mirror of
https://github.com/davidalves04/Trabalho-Pratico-SD.git
synced 2025-12-08 12:33:31 +00:00
Compare commits
8 Commits
v0.7.6
...
ea33d61a9e
| Author | SHA1 | Date | |
|---|---|---|---|
| ea33d61a9e | |||
| 240563419b | |||
| 90db380f61 | |||
| d28a77b6a4 | |||
| 173d9e54ce | |||
| 5202032471 | |||
| 46d148c9d5 | |||
| 0d85d010bf |
69
.github/workflows/maven.yml
vendored
69
.github/workflows/maven.yml
vendored
@@ -1,8 +1,9 @@
|
|||||||
name: Java CI with Maven
|
name: Java CI with Maven
|
||||||
|
|
||||||
on:
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
push:
|
push:
|
||||||
branches: [ "main" ]
|
branches: [ "dev", "cleanup" ]
|
||||||
tags:
|
tags:
|
||||||
- 'v*.*.*'
|
- 'v*.*.*'
|
||||||
pull_request:
|
pull_request:
|
||||||
@@ -11,51 +12,93 @@ on:
|
|||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up JDK 17
|
- name: Set up JDK 17
|
||||||
uses: actions/setup-java@v4
|
uses: actions/setup-java@v4
|
||||||
with:
|
with:
|
||||||
java-version: '17'
|
java-version: '17'
|
||||||
distribution: 'temurin'
|
distribution: 'temurin'
|
||||||
cache: maven
|
cache: maven
|
||||||
|
|
||||||
- name: Build with Maven
|
- name: Build with Maven
|
||||||
run: mvn -B package
|
run: mvn -B package
|
||||||
working-directory: main
|
working-directory: main
|
||||||
|
|
||||||
- name: Upload built JAR
|
- name: Upload built JAR
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: package
|
name: package
|
||||||
path: main/target/*.jar
|
path: main/target/*.jar
|
||||||
|
|
||||||
- name: Generate dependency graph
|
- name: Generate dependency graph
|
||||||
run: mvn -B -f main/pom.xml com.github.ferstl:depgraph-maven-plugin:4.0.1:graph
|
run: mvn -B -f main/pom.xml com.github.ferstl:depgraph-maven-plugin:4.0.1:graph
|
||||||
|
|
||||||
- name: Upload dependency graph artifact
|
- name: Upload dependency graph artifact
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: dependency-graph
|
name: dependency-graph
|
||||||
path: main/target/**
|
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:
|
publish-release:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: [build]
|
needs: [build, build-windows]
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
if: startsWith(github.ref, 'refs/tags/') || github.event_name == 'workflow_dispatch'
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Download built JAR
|
- name: Download Linux JAR
|
||||||
uses: actions/download-artifact@v4
|
uses: actions/download-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: package
|
name: package
|
||||||
path: main/target/
|
path: main/target/
|
||||||
|
- name: Download Windows Zip
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: windows-package
|
||||||
|
path: windows-dist/
|
||||||
- name: Create GitHub Release
|
- name: Create GitHub Release
|
||||||
uses: softprops/action-gh-release@v2
|
uses: softprops/action-gh-release@v2
|
||||||
with:
|
with:
|
||||||
files: main/target/*.jar
|
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
|
||||||
|
|||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -3,6 +3,9 @@
|
|||||||
|
|
||||||
# Log files
|
# Log files
|
||||||
*.log
|
*.log
|
||||||
|
*.trace
|
||||||
|
logs
|
||||||
|
*.md
|
||||||
|
|
||||||
# BlueJ files
|
# BlueJ files
|
||||||
*.ctxt
|
*.ctxt
|
||||||
|
|||||||
620
README.md
620
README.md
@@ -1,620 +0,0 @@
|
|||||||
# Sistema de Simulação de Tráfego Distribuído
|
|
||||||
|
|
||||||
Sistema distribuído de simulação de tráfego.
|
|
||||||
---
|
|
||||||
|
|
||||||
## Índice
|
|
||||||
|
|
||||||
- [Visão Geral](#visão-geral)
|
|
||||||
- [Arquitetura](#arquitetura)
|
|
||||||
- [Protocolo de Comunicação](#protocolo-de-comunicação)
|
|
||||||
- [Estrutura do Projeto](#estrutura-do-projeto)
|
|
||||||
- [Instalação e Execução](#instalação-e-execução)
|
|
||||||
- [Documentação](#documentação)
|
|
||||||
- [Desenvolvimento](#desenvolvimento)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Visão Geral
|
|
||||||
|
|
||||||
Este projeto implementa uma simulação distribuída de tráfego veicular numa rede de cruzamentos. O sistema utiliza:
|
|
||||||
|
|
||||||
- **Processos independentes** para cada cruzamento
|
|
||||||
- **Threads** para controlar os semáforos dentro de cada cruzamento
|
|
||||||
- **Comunicação via sockets** para transferência de veículos entre cruzamentos
|
|
||||||
- **Simulação de eventos discretos** (DES) para gerir o tempo de simulação
|
|
||||||
|
|
||||||
### Características Principais
|
|
||||||
|
|
||||||
- Simulação determinística e reproduzível
|
|
||||||
- Comunicação assíncrona entre processos
|
|
||||||
- Protocolo de mensagens baseado em JSON
|
|
||||||
- Dashboard em tempo real (planeado)
|
|
||||||
- Estatísticas detalhadas de desempenho
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Arquitetura
|
|
||||||
|
|
||||||
### Visão Geral do Sistema
|
|
||||||
|
|
||||||
```
|
|
||||||
┌─────────────────────────────────────────────────────────────────┐
|
|
||||||
│ SISTEMA DISTRIBUÍDO │
|
|
||||||
├─────────────────────────────────────────────────────────────────┤
|
|
||||||
│ │
|
|
||||||
│ ┌──────────────┐ ┌──────────────┐ │
|
|
||||||
│ │ Coordenador │ ────────────────────────>│ Dashboard │ │
|
|
||||||
│ │ / Gerador │ │ │
|
|
||||||
│ └──────┬───────┘ └──────▲───────┘ │
|
|
||||||
│ │ │ │
|
|
||||||
│ │ Gera veículos Stats │ │
|
|
||||||
│ │ │ │
|
|
||||||
│ ▼ │ │
|
|
||||||
│ ┌─────────────────────────────────────────────────┴──────┐ │
|
|
||||||
│ │ Rede de Cruzamentos (Processos) │ │
|
|
||||||
│ │ │ │
|
|
||||||
│ │ ┌────┐ ┌────┐ ┌────┐ │ │
|
|
||||||
│ │ │Cr1 │◄───────►│Cr2 │◄───────►│Cr3 │ │ │
|
|
||||||
│ │ └─┬──┘ └─┬──┘ └─┬──┘ │ │
|
|
||||||
│ │ │ │ │ │ │
|
|
||||||
│ │ │ ┌────▼────┐ │ │ │
|
|
||||||
│ │ └────────►│ Cr4 │◄────────┘ │ │
|
|
||||||
│ │ └────┬────┘ │ │
|
|
||||||
│ │ │ │ │
|
|
||||||
│ │ ┌────▼────┐ │ │
|
|
||||||
│ │ │ Cr5 │ │ │
|
|
||||||
│ │ └────┬────┘ │ │
|
|
||||||
│ └───────────────────┼─────────────────────────────────────┤ │
|
|
||||||
│ │ │ │
|
|
||||||
│ ▼ │ │
|
|
||||||
│ ┌──────────────┐ │ │
|
|
||||||
│ │ Nó de Saída │ │ │
|
|
||||||
│ │ (S) │ │ │
|
|
||||||
│ └──────────────┘ │ │
|
|
||||||
│ │ │
|
|
||||||
└────────────────────────────────────────────────────────────┘ │
|
|
||||||
```
|
|
||||||
|
|
||||||
### Componentes
|
|
||||||
|
|
||||||
1. **Coordenador/Gerador**: Gera veículos e injeta no sistema
|
|
||||||
2. **Cruzamentos (Cr1-Cr5)**: Processos independentes que gerem tráfego local
|
|
||||||
3. **Nó de Saída (S)**: Recolhe estatísticas de veículos que saem do sistema
|
|
||||||
4. **Dashboard Server**: Agrega e exibe dados em tempo real
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Protocolo de Comunicação
|
|
||||||
|
|
||||||
### Formato de Serialização: JSON (Gson)
|
|
||||||
|
|
||||||
O sistema utiliza JSON como formato de serialização por ser mais rápido, seguro e legível que a serialização em Java.
|
|
||||||
|
|
||||||
### Estrutura de Mensagens
|
|
||||||
|
|
||||||
Todas as mensagens seguem o formato base:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"messageId": "uuid",
|
|
||||||
"type": "MESSAGE_TYPE",
|
|
||||||
"senderId": "sender_id",
|
|
||||||
"destinationId": "destination_id",
|
|
||||||
"timestamp": 1729595234567,
|
|
||||||
"payload": { ... }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Tipos de Mensagens
|
|
||||||
|
|
||||||
#### 1. VEHICLE_TRANSFER
|
|
||||||
|
|
||||||
Transfere um veículo entre cruzamentos.
|
|
||||||
|
|
||||||
**Estrutura:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"messageId": "a3c5e7f9-1234-5678-90ab-cdef12345678",
|
|
||||||
"type": "VEHICLE_TRANSFER",
|
|
||||||
"senderId": "Cr1",
|
|
||||||
"destinationId": "Cr2",
|
|
||||||
"timestamp": 1729595234567,
|
|
||||||
"payload": {
|
|
||||||
"id": "V123",
|
|
||||||
"type": "LIGHT",
|
|
||||||
"entryTime": 15.7,
|
|
||||||
"route": ["Cr1", "Cr2", "Cr5", "S"],
|
|
||||||
"currentRouteIndex": 1,
|
|
||||||
"totalWaitingTime": 3.2,
|
|
||||||
"totalCrossingTime": 1.8
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Fluxo:**
|
|
||||||
1. Veículo completa travessia no Cr1
|
|
||||||
2. Cr1 serializa mensagem VEHICLE_TRANSFER
|
|
||||||
3. Envia para Cr2 via socket
|
|
||||||
4. Cr2 desserializa e adiciona veículo à fila
|
|
||||||
|
|
||||||
#### 2. STATS_UPDATE
|
|
||||||
|
|
||||||
Envia estatísticas de um cruzamento para o Dashboard.
|
|
||||||
|
|
||||||
**Estrutura:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"messageId": "b4d6e8f0-2345-6789-01bc-def123456789",
|
|
||||||
"type": "STATS_UPDATE",
|
|
||||||
"senderId": "Cr3",
|
|
||||||
"destinationId": "Dashboard",
|
|
||||||
"timestamp": 1729595234789,
|
|
||||||
"payload": {
|
|
||||||
"intersectionId": "Cr3",
|
|
||||||
"queueLengths": {
|
|
||||||
"North": 5,
|
|
||||||
"South": 3,
|
|
||||||
"East": 7,
|
|
||||||
"West": 2
|
|
||||||
},
|
|
||||||
"vehiclesProcessed": 142,
|
|
||||||
"averageWaitTime": 4.5,
|
|
||||||
"currentTime": 123.45
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Frequência:** A cada 10 segundos (configurável)
|
|
||||||
|
|
||||||
#### 3. VEHICLE_EXIT
|
|
||||||
|
|
||||||
Notifica quando um veículo sai do sistema.
|
|
||||||
|
|
||||||
**Estrutura:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"messageId": "c5e7f9a1-3456-7890-12bc-def123456789",
|
|
||||||
"type": "VEHICLE_EXIT",
|
|
||||||
"senderId": "Cr5",
|
|
||||||
"destinationId": "ExitNode",
|
|
||||||
"timestamp": 1729595234890,
|
|
||||||
"payload": {
|
|
||||||
"id": "V123",
|
|
||||||
"type": "LIGHT",
|
|
||||||
"entryTime": 15.7,
|
|
||||||
"exitTime": 45.2,
|
|
||||||
"totalSystemTime": 29.5,
|
|
||||||
"totalWaitingTime": 8.3,
|
|
||||||
"totalCrossingTime": 4.8,
|
|
||||||
"routeTaken": ["Cr1", "Cr2", "Cr5", "S"]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 4. HEARTBEAT
|
|
||||||
|
|
||||||
Mantém a ligação ativa e monitoriza a saúde dos processos.
|
|
||||||
|
|
||||||
**Estrutura:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"messageId": "d6e8f0a2-4567-8901-23cd-ef1234567890",
|
|
||||||
"type": "HEARTBEAT",
|
|
||||||
"senderId": "Cr1",
|
|
||||||
"destinationId": "Coordinator",
|
|
||||||
"timestamp": 1729595235000,
|
|
||||||
"payload": {
|
|
||||||
"status": "RUNNING",
|
|
||||||
"uptime": 120.5,
|
|
||||||
"vehiclesInQueue": 12
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Frequência:** A cada 5 segundos
|
|
||||||
|
|
||||||
#### 5. LIGHT_CHANGE
|
|
||||||
|
|
||||||
Notifica mudança de estado de semáforo (para logging/debugging).
|
|
||||||
|
|
||||||
**Estrutura:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"messageId": "e7f9a1b3-5678-9012-34de-f12345678901",
|
|
||||||
"type": "LIGHT_CHANGE",
|
|
||||||
"senderId": "Cr1-North",
|
|
||||||
"destinationId": "Dashboard",
|
|
||||||
"timestamp": 1729595235100,
|
|
||||||
"payload": {
|
|
||||||
"lightId": "Cr1-North",
|
|
||||||
"previousState": "RED",
|
|
||||||
"newState": "GREEN",
|
|
||||||
"queueSize": 5
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Tipos de Veículos
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"BIKE": {
|
|
||||||
"probability": 0.20,
|
|
||||||
"crossingTime": 1.5
|
|
||||||
},
|
|
||||||
"LIGHT": {
|
|
||||||
"probability": 0.60,
|
|
||||||
"crossingTime": 2.0
|
|
||||||
},
|
|
||||||
"HEAVY": {
|
|
||||||
"probability": 0.20,
|
|
||||||
"crossingTime": 4.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Estados dos Semáforos
|
|
||||||
|
|
||||||
```
|
|
||||||
RED → Veículos aguardam na fila
|
|
||||||
GREEN → Veículos podem atravessar
|
|
||||||
```
|
|
||||||
|
|
||||||
### Exemplo de Comunicação Completa
|
|
||||||
|
|
||||||
```
|
|
||||||
Tempo Processo Ação Mensagem
|
|
||||||
------ --------- ------------------------------------- ------------------
|
|
||||||
15.7s Gerador Gera veículo V123 -
|
|
||||||
15.7s Gerador → Injeta V123 em Cr1 VEHICLE_TRANSFER
|
|
||||||
18.2s Cr1 V123 inicia travessia -
|
|
||||||
20.2s Cr1 V123 completa travessia -
|
|
||||||
20.2s Cr1 → Cr2 Transfere V123 para Cr2 VEHICLE_TRANSFER
|
|
||||||
23.5s Cr2 V123 inicia travessia -
|
|
||||||
25.5s Cr2 V123 completa travessia -
|
|
||||||
25.5s Cr2 → Cr5 Transfere V123 para Cr5 VEHICLE_TRANSFER
|
|
||||||
28.0s Cr5 V123 inicia travessia -
|
|
||||||
30.0s Cr5 V123 completa travessia -
|
|
||||||
30.0s Cr5 → Exit V123 sai do sistema VEHICLE_EXIT
|
|
||||||
30.0s Exit → Dash Estatísticas de V123 STATS_UPDATE
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Estrutura do Projeto
|
|
||||||
|
|
||||||
```
|
|
||||||
Trabalho-Pratico-SD/
|
|
||||||
├── README.md # Este ficheiro
|
|
||||||
├── TODO.md # Plano de desenvolvimento
|
|
||||||
├── main/
|
|
||||||
│ ├── pom.xml # Configuração do Maven
|
|
||||||
│ ├── docs/
|
|
||||||
│ │ ├── README.md # Índice da documentação
|
|
||||||
│ │ ├── SERIALIZATION_SPECIFICATION.md
|
|
||||||
│ │ ├── SERIALIZATION_DECISION.md
|
|
||||||
│ │ ├── SERIALIZATION_SUMMARY.md
|
|
||||||
│ │ └── SERIALIZATION_ARCHITECTURE.md
|
|
||||||
│ ├── src/
|
|
||||||
│ │ ├── main/java/sd/
|
|
||||||
│ │ │ ├── Entry.java # Ponto de entrada
|
|
||||||
│ │ │ ├── config/
|
|
||||||
│ │ │ │ └── SimulationConfig.java
|
|
||||||
│ │ │ ├── engine/
|
|
||||||
│ │ │ │ └── SimulationEngine.java
|
|
||||||
│ │ │ ├── model/
|
|
||||||
│ │ │ │ ├── Event.java
|
|
||||||
│ │ │ │ ├── EventType.java
|
|
||||||
│ │ │ │ ├── Intersection.java
|
|
||||||
│ │ │ │ ├── Message.java # Estrutura de mensagens
|
|
||||||
│ │ │ │ ├── MessageType.java # Tipos de mensagens
|
|
||||||
│ │ │ │ ├── TrafficLight.java
|
|
||||||
│ │ │ │ ├── Vehicle.java
|
|
||||||
│ │ │ │ └── VehicleType.java
|
|
||||||
│ │ │ ├── serialization/ # Sistema de serialização
|
|
||||||
│ │ │ │ ├── MessageSerializer.java
|
|
||||||
│ │ │ │ ├── SerializationException.java
|
|
||||||
│ │ │ │ ├── JsonMessageSerializer.java
|
|
||||||
│ │ │ │ ├── SerializerFactory.java
|
|
||||||
│ │ │ │ ├── SerializationExample.java
|
|
||||||
│ │ │ │ └── README.md
|
|
||||||
│ │ │ └── util/
|
|
||||||
│ │ │ ├── RandomGenerator.java
|
|
||||||
│ │ │ ├── StatisticsCollector.java
|
|
||||||
│ │ │ └── VehicleGenerator.java
|
|
||||||
│ │ └── test/java/
|
|
||||||
│ │ ├── SimulationTest.java
|
|
||||||
│ │ └── sd/serialization/
|
|
||||||
│ │ └── SerializationTest.java
|
|
||||||
│ └── target/ # Ficheiros compilados
|
|
||||||
└── .vscode/ # Configuração do VS Code
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Instalação e Execução
|
|
||||||
|
|
||||||
### Pré-requisitos
|
|
||||||
|
|
||||||
- **Java 17** ou superior
|
|
||||||
- **Maven 3.8+**
|
|
||||||
- **Git**
|
|
||||||
|
|
||||||
### Instalação
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Clonar o repositório
|
|
||||||
git clone https://github.com/davidalves04/Trabalho-Pratico-SD.git
|
|
||||||
cd Trabalho-Pratico-SD/main
|
|
||||||
|
|
||||||
# Compilar o projeto
|
|
||||||
mvn clean compile
|
|
||||||
|
|
||||||
# Executar os testes
|
|
||||||
mvn test
|
|
||||||
```
|
|
||||||
|
|
||||||
### Execução
|
|
||||||
|
|
||||||
#### Simulação Básica (Single Process)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
mvn exec:java -Dexec.mainClass="sd.Entry"
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Exemplo de Serialização
|
|
||||||
|
|
||||||
```bash
|
|
||||||
mvn exec:java -Dexec.mainClass="sd.serialization.SerializationExample"
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Configuração
|
|
||||||
|
|
||||||
Editar `src/main/resources/simulation.properties`:
|
|
||||||
|
|
||||||
```properties
|
|
||||||
# Duração da simulação (segundos)
|
|
||||||
simulation.duration=60.0
|
|
||||||
|
|
||||||
# Modelo de chegada: FIXED ou POISSON
|
|
||||||
arrival.model=POISSON
|
|
||||||
|
|
||||||
# Taxa de chegada (veículos/segundo)
|
|
||||||
arrival.rate=0.5
|
|
||||||
|
|
||||||
# Intervalo de atualização de estatísticas (segundos)
|
|
||||||
stats.update.interval=10.0
|
|
||||||
|
|
||||||
# Distribuição de tipos de veículos
|
|
||||||
vehicle.type.bike.probability=0.20
|
|
||||||
vehicle.type.light.probability=0.60
|
|
||||||
vehicle.type.heavy.probability=0.20
|
|
||||||
|
|
||||||
# Tempos de travessia por tipo (segundos)
|
|
||||||
vehicle.type.bike.crossing.time=1.5
|
|
||||||
vehicle.type.light.crossing.time=2.0
|
|
||||||
vehicle.type.heavy.crossing.time=4.0
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Documentação
|
|
||||||
|
|
||||||
### Documentação de Serialização
|
|
||||||
|
|
||||||
A documentação completa sobre o protocolo de serialização está disponível em:
|
|
||||||
|
|
||||||
- **[Índice Completo](./main/docs/README.md)** - Navegação da documentação
|
|
||||||
- **[Especificação](./main/docs/SERIALIZATION_SPECIFICATION.md)** - Design detalhado
|
|
||||||
- **[Guia de Decisão](./main/docs/SERIALIZATION_DECISION.md)** - Porquê JSON?
|
|
||||||
- **[Resumo](./main/docs/SERIALIZATION_SUMMARY.md)** - Estado de implementação
|
|
||||||
- **[Arquitetura](./main/docs/SERIALIZATION_ARCHITECTURE.md)** - Diagramas visuais
|
|
||||||
|
|
||||||
### Guias de Utilização
|
|
||||||
|
|
||||||
- **[Serialization README](./main/src/main/java/sd/serialization/README.md)** - Como utilizar os serializers
|
|
||||||
|
|
||||||
### Exemplos de Código
|
|
||||||
|
|
||||||
```java
|
|
||||||
// Criar serializer
|
|
||||||
MessageSerializer serializer = SerializerFactory.createDefault();
|
|
||||||
|
|
||||||
// Serializar mensagem
|
|
||||||
Vehicle vehicle = new Vehicle("V123", VehicleType.LIGHT, 10.5, route);
|
|
||||||
Message message = new Message(
|
|
||||||
MessageType.VEHICLE_TRANSFER,
|
|
||||||
"Cr1",
|
|
||||||
"Cr2",
|
|
||||||
vehicle
|
|
||||||
);
|
|
||||||
byte[] data = serializer.serialize(message);
|
|
||||||
|
|
||||||
// Enviar via socket
|
|
||||||
outputStream.write(data);
|
|
||||||
|
|
||||||
// Receber e desserializar
|
|
||||||
byte[] received = inputStream.readAllBytes();
|
|
||||||
Message msg = serializer.deserialize(received, Message.class);
|
|
||||||
Vehicle v = msg.getPayloadAs(Vehicle.class);
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Desenvolvimento
|
|
||||||
|
|
||||||
### Estado do Projeto
|
|
||||||
|
|
||||||
| Componente | Estado | Notas |
|
|
||||||
|------------|--------|-------|
|
|
||||||
| Modelo de Dados | Completo | Vehicle, Message, Event, etc. |
|
|
||||||
| Simulação DES | Completo | Single-process funcional |
|
|
||||||
| Serialização | Completo | JSON e Java implementados |
|
|
||||||
| Testes | 14/14 | Suite de serialização |
|
|
||||||
| Processos Distribuídos | Planeado | Próxima etapa |
|
|
||||||
| Comunicação Sockets | Planeado | Em design |
|
|
||||||
| Dashboard | Planeado | UI web |
|
|
||||||
|
|
||||||
### Roteiro de Desenvolvimento
|
|
||||||
|
|
||||||
#### Fase 1: Fundações (Concluído)
|
|
||||||
- Modelação de classes
|
|
||||||
- Simulação DES single-process
|
|
||||||
- Design de protocolo de serialização
|
|
||||||
- Implementação JSON/Java serialization
|
|
||||||
- Testes unitários
|
|
||||||
|
|
||||||
#### Fase 2: Distribuição (Em Curso)
|
|
||||||
- Implementar comunicação via sockets
|
|
||||||
- Separar cruzamentos em processos
|
|
||||||
- Implementar threads de semáforos
|
|
||||||
- Testar comunicação entre processos
|
|
||||||
|
|
||||||
#### Fase 3: Dashboard e Monitorização
|
|
||||||
- Dashboard server
|
|
||||||
- UI web em tempo real
|
|
||||||
- Visualização de estatísticas
|
|
||||||
- Logs estruturados
|
|
||||||
|
|
||||||
#### Fase 4: Optimização e Análise
|
|
||||||
- Testes de carga
|
|
||||||
- Análise de diferentes políticas
|
|
||||||
- Recolha de métricas
|
|
||||||
- Relatório final
|
|
||||||
|
|
||||||
### Executar Testes
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Todos os testes
|
|
||||||
mvn test
|
|
||||||
|
|
||||||
# Apenas testes de serialização
|
|
||||||
mvn test -Dtest=SerializationTest
|
|
||||||
|
|
||||||
# Com relatório de cobertura
|
|
||||||
mvn test jacoco:report
|
|
||||||
```
|
|
||||||
|
|
||||||
### Contribuir
|
|
||||||
|
|
||||||
1. Fork o projeto
|
|
||||||
2. Criar uma branch para a funcionalidade (`git checkout -b feature/MinhaFuncionalidade`)
|
|
||||||
3. Commit das alterações (`git commit -m 'Adiciona MinhaFuncionalidade'`)
|
|
||||||
4. Push para a branch (`git push origin feature/MinhaFuncionalidade`)
|
|
||||||
5. Abrir um Pull Request
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Métricas de Desempenho
|
|
||||||
|
|
||||||
### Serialização
|
|
||||||
|
|
||||||
| Formato | Tamanho | Latência | Throughput |
|
|
||||||
|---------|---------|----------|------------|
|
|
||||||
| JSON | 300 bytes | 40.79 μs | ~24k msgs/s |
|
|
||||||
| Java | 657 bytes | 33.34 μs | ~30k msgs/s |
|
|
||||||
|
|
||||||
**Conclusão**: JSON é 54% menor com overhead desprezível (7 μs)
|
|
||||||
|
|
||||||
### Simulação
|
|
||||||
|
|
||||||
- **Veículos gerados/s**: ~0.5-1.0 (configurável)
|
|
||||||
- **Throughput**: ~0.2 veículos/s (saída)
|
|
||||||
- **Tempo de execução**: 140ms para 60s de simulação
|
|
||||||
- **Overhead**: < 0.25% do tempo simulado
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Protocolo de Mensagens - Resumo
|
|
||||||
|
|
||||||
### Formato Base
|
|
||||||
|
|
||||||
```
|
|
||||||
+------------------+
|
|
||||||
| Message Header |
|
|
||||||
|------------------|
|
|
||||||
| messageId | UUID único
|
|
||||||
| type | Enum MessageType
|
|
||||||
| senderId | ID do processo remetente
|
|
||||||
| destinationId | ID do processo destino (null = broadcast)
|
|
||||||
| timestamp | Tempo de criação (ms)
|
|
||||||
+------------------+
|
|
||||||
| Payload |
|
|
||||||
|------------------|
|
|
||||||
| Object | Dados específicos do tipo de mensagem
|
|
||||||
+------------------+
|
|
||||||
```
|
|
||||||
|
|
||||||
### Serialização
|
|
||||||
|
|
||||||
- **Formato**: JSON (UTF-8)
|
|
||||||
- **Biblioteca**: Gson 2.10.1
|
|
||||||
- **Codificação**: UTF-8
|
|
||||||
- **Compressão**: Opcional (gzip)
|
|
||||||
|
|
||||||
### Transporte
|
|
||||||
|
|
||||||
- **Protocolo**: TCP/IP
|
|
||||||
- **Porta base**: 5000+ (configurável)
|
|
||||||
- **Timeout**: 30s
|
|
||||||
- **Keep-alive**: Heartbeat a cada 5s
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Segurança
|
|
||||||
|
|
||||||
### Considerações
|
|
||||||
|
|
||||||
1. **Validação de Mensagens**
|
|
||||||
- Verificar tipos esperados
|
|
||||||
- Validar intervalos de valores
|
|
||||||
- Rejeitar mensagens malformadas
|
|
||||||
|
|
||||||
2. **Autenticação** (Planeado)
|
|
||||||
- Autenticação baseada em token
|
|
||||||
- Whitelist de processos
|
|
||||||
|
|
||||||
3. **Encriptação** (Opcional)
|
|
||||||
- TLS/SSL para produção
|
|
||||||
- Não necessário para ambiente de desenvolvimento local
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Licença
|
|
||||||
|
|
||||||
Este projeto é desenvolvido para fins académicos no âmbito da disciplina de Sistemas Distribuídos (SD) do Instituto Politécnico do Porto.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Equipa
|
|
||||||
|
|
||||||
**Instituição**: Instituto Politécnico do Porto
|
|
||||||
**Curso**: Sistemas Distribuídos
|
|
||||||
**Ano Letivo**: 2025-2026 (1º Semestre)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Suporte
|
|
||||||
|
|
||||||
Para questões ou problemas:
|
|
||||||
|
|
||||||
1. Consultar a [documentação](./main/docs/README.md)
|
|
||||||
2. Ver [exemplos de código](./main/src/main/java/sd/serialization/SerializationExample.java)
|
|
||||||
3. Executar testes: `mvn test`
|
|
||||||
4. Abrir issue no GitHub
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Ligações Úteis
|
|
||||||
|
|
||||||
- [Documentação do Projeto](./main/docs/README.md)
|
|
||||||
- [Plano de Desenvolvimento](./TODO.md)
|
|
||||||
- [Especificação de Serialização](./main/docs/SERIALIZATION_SPECIFICATION.md)
|
|
||||||
- [Guia de Serialização](./main/src/main/java/sd/serialization/README.md)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**Última actualização**: 23 de outubro de 2025
|
|
||||||
**Versão**: 1.0.0
|
|
||||||
**Estado**: Em Desenvolvimento Activo
|
|
||||||
134
STEP2_SUMMARY.md
134
STEP2_SUMMARY.md
@@ -1,134 +0,0 @@
|
|||||||
# 🏁 Single-Process Prototype — Implementation Summary
|
|
||||||
|
|
||||||
**Status:** ✅ Complete
|
|
||||||
**Date:** October 22, 2025
|
|
||||||
**Branch:** `8-single-process-prototype`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Overview
|
|
||||||
|
|
||||||
The single-process prototype implements a **discrete event simulation (DES)** of a 3×3 urban grid with five intersections, realistic vehicle behavior, and fully synchronized traffic lights. Everything runs under one process, laying the groundwork for the distributed architecture in Phase 3.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Core Architecture
|
|
||||||
|
|
||||||
### **SimulationEngine**
|
|
||||||
|
|
||||||
Drives the DES loop with a priority queue of timestamped events — vehicles, lights, crossings, and periodic stats updates. Handles five intersections (Cr1–Cr5) and six event types.
|
|
||||||
|
|
||||||
**Main loop:**
|
|
||||||
|
|
||||||
```
|
|
||||||
while (events && time < duration):
|
|
||||||
event = nextEvent()
|
|
||||||
time = event.timestamp
|
|
||||||
handle(event)
|
|
||||||
```
|
|
||||||
|
|
||||||
### **VehicleGenerator**
|
|
||||||
|
|
||||||
Spawns vehicles via:
|
|
||||||
|
|
||||||
* **Poisson arrivals** (λ = 0.5 veh/s) or fixed intervals
|
|
||||||
* **Probabilistic routes** from E1–E3
|
|
||||||
* **Type distribution**: 20% BIKE, 60% LIGHT, 20% HEAVY
|
|
||||||
|
|
||||||
### **StatisticsCollector**
|
|
||||||
|
|
||||||
Tracks system-wide and per-type metrics: throughput, avg. wait, queue sizes, light cycles — updated every 10 s and at simulation end.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Model Highlights
|
|
||||||
|
|
||||||
* **Vehicle** – type, route, timings, lifecycle.
|
|
||||||
* **Intersection** – routing tables, traffic lights, queues.
|
|
||||||
* **TrafficLight** – red/green cycles with FIFO queues.
|
|
||||||
* **Event** – timestamped, comparable; 6 types for all DES actions.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Configuration (`simulation.properties`)
|
|
||||||
|
|
||||||
```properties
|
|
||||||
simulation.duration=60.0
|
|
||||||
simulation.arrival.model=POISSON
|
|
||||||
simulation.arrival.rate=0.5
|
|
||||||
|
|
||||||
vehicle.bike.crossingTime=1.5
|
|
||||||
vehicle.light.crossingTime=2.0
|
|
||||||
vehicle.heavy.crossingTime=4.0
|
|
||||||
|
|
||||||
statistics.update.interval=10.0
|
|
||||||
```
|
|
||||||
|
|
||||||
**Speed logic:**
|
|
||||||
`t_bike = 0.5×t_car`, `t_heavy = 2×t_car`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Topology
|
|
||||||
|
|
||||||
```
|
|
||||||
E1→Cr1→Cr4→Cr5→S
|
|
||||||
E2→Cr2→Cr5→S
|
|
||||||
E3→Cr3→S
|
|
||||||
Bi-dir: Cr1↔Cr2, Cr2↔Cr3
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Results
|
|
||||||
|
|
||||||
**Unit Tests:** 7/7 ✅
|
|
||||||
**60-Second Simulation:**
|
|
||||||
|
|
||||||
* Generated: 22 vehicles
|
|
||||||
* Completed: 5 (22.7%)
|
|
||||||
* Avg system time: 15.47 s
|
|
||||||
* Throughput: 0.08 veh/s
|
|
||||||
* All lights & intersections operational
|
|
||||||
|
|
||||||
**Performance:**
|
|
||||||
~0.03 s real-time run (≈2000× speed-up), < 50 MB RAM.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Code Structure
|
|
||||||
|
|
||||||
```
|
|
||||||
sd/
|
|
||||||
├── engine/SimulationEngine.java
|
|
||||||
├── model/{Vehicle,Intersection,TrafficLight,Event}.java
|
|
||||||
├── util/{VehicleGenerator,StatisticsCollector}.java
|
|
||||||
└── config/SimulationConfig.java
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Key Flow
|
|
||||||
|
|
||||||
1. Initialize intersections, lights, first events.
|
|
||||||
2. Process events chronologically.
|
|
||||||
3. Vehicles follow routes → queue → cross → exit.
|
|
||||||
4. Lights toggle, queues drain, stats update.
|
|
||||||
5. Print summary and performance metrics.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Next Steps — Phase 3
|
|
||||||
|
|
||||||
* Split intersections into independent **processes**.
|
|
||||||
* Add **socket-based communication**.
|
|
||||||
* Run **traffic lights as threads**.
|
|
||||||
* Enable **distributed synchronization** and fault handling.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## TL;DR
|
|
||||||
|
|
||||||
Solid single-process DES ✅
|
|
||||||
Everything’s working — traffic lights, routing, vehicles, stats.
|
|
||||||
Ready to go distributed next.
|
|
||||||
198
TODO.md
198
TODO.md
@@ -1,198 +0,0 @@
|
|||||||
## ✅ SINGLE-PROCESS PROTOTYPE - COMPLETED
|
|
||||||
|
|
||||||
### Phase 2 Status: DONE ✅
|
|
||||||
|
|
||||||
All components for the single-process prototype have been successfully implemented and tested:
|
|
||||||
|
|
||||||
- ✅ **SimulationEngine** - Priority queue-based discrete event simulation
|
|
||||||
- ✅ **VehicleGenerator** - Poisson and Fixed arrival models
|
|
||||||
- ✅ **StatisticsCollector** - Comprehensive metrics tracking
|
|
||||||
- ✅ **Entry point** - Main simulation runner
|
|
||||||
- ✅ **60s test simulation** - Successfully validated event processing and routing
|
|
||||||
|
|
||||||
### Test Results:
|
|
||||||
- All 7 unit tests passing
|
|
||||||
- 60-second simulation completed successfully
|
|
||||||
- Generated 22 vehicles with 5 completing their routes
|
|
||||||
- Traffic light state changes working correctly
|
|
||||||
- Vehicle routing through intersections validated
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## NEXT: Distributed Architecture Implementation
|
|
||||||
|
|
||||||
### 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.
|
|
||||||
@@ -12,6 +12,13 @@ import java.util.concurrent.TimeUnit;
|
|||||||
import sd.config.SimulationConfig;
|
import sd.config.SimulationConfig;
|
||||||
import sd.coordinator.SocketClient;
|
import sd.coordinator.SocketClient;
|
||||||
import sd.dashboard.StatsUpdatePayload;
|
import sd.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.Message;
|
||||||
import sd.model.MessageType;
|
import sd.model.MessageType;
|
||||||
import sd.model.Vehicle;
|
import sd.model.Vehicle;
|
||||||
@@ -20,16 +27,17 @@ import sd.protocol.MessageProtocol;
|
|||||||
import sd.protocol.SocketConnection;
|
import sd.protocol.SocketConnection;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Processo responsável pelo nó de saída do sistema de simulação de tráfego
|
* Destino final de todos os veículos da simulação (nó de saída S).
|
||||||
* distribuído.
|
|
||||||
*
|
*
|
||||||
* Este processo representa o ponto final ("S") onde os veículos completam as
|
* <p>Opera como sumidouro da rede:
|
||||||
* suas rotas.
|
* <ol>
|
||||||
* As suas principais responsabilidades são:
|
* <li>Recebe veículos que completaram a viagem
|
||||||
* - Receber veículos que terminam a sua rota vindos das interseções
|
* <li>Regista estatísticas finais (tempo total, espera, travessia)
|
||||||
* - Calcular e agregar estatísticas finais dos veículos
|
* <li>Envia métricas ao dashboard em tempo real
|
||||||
* - Enviar estatísticas periódicas para o dashboard
|
* </ol>
|
||||||
* - Gerar relatórios finais ao terminar a simulação
|
*
|
||||||
|
* <p>Participa no DES rastreando eventos, mas opera principalmente
|
||||||
|
* de forma reativa, aguardando chegadas via socket.
|
||||||
*/
|
*/
|
||||||
public class ExitNodeProcess {
|
public class ExitNodeProcess {
|
||||||
|
|
||||||
@@ -37,41 +45,43 @@ public class ExitNodeProcess {
|
|||||||
private ServerSocket serverSocket;
|
private ServerSocket serverSocket;
|
||||||
private final ExecutorService connectionHandlerPool;
|
private final ExecutorService connectionHandlerPool;
|
||||||
|
|
||||||
/**
|
// DES components
|
||||||
* Flag para controlar a execução do processo (volatile para visibilidade entre
|
private final SimulationClock clock;
|
||||||
* threads)
|
private final EventQueue eventQueue;
|
||||||
*/
|
private final EventLogger eventLogger;
|
||||||
|
private Thread eventProcessorThread;
|
||||||
|
|
||||||
|
/** Flag de controlo (volatile para visibilidade entre threads) */
|
||||||
private volatile boolean running;
|
private volatile boolean running;
|
||||||
|
|
||||||
/** Simulation start time (milliseconds) to calculate relative times */
|
/** Instante de início da simulação (milissegundos) */
|
||||||
private long simulationStartMillis;
|
private long simulationStartMillis;
|
||||||
|
|
||||||
/** Counter de veículos que completaram a rota */
|
/** Contador de veículos que completaram a rota */
|
||||||
private int totalVehiclesReceived;
|
private int totalVehiclesReceived;
|
||||||
|
|
||||||
/** Soma dos tempos no sistema de todos os veículos */
|
/** Tempo acumulado no sistema de todos os veículos */
|
||||||
private double totalSystemTime;
|
private double totalSystemTime;
|
||||||
|
|
||||||
/** Soma dos tempos de espera de todos os veículos */
|
/** Tempo acumulado em espera de todos os veículos */
|
||||||
private double totalWaitingTime;
|
private double totalWaitingTime;
|
||||||
|
|
||||||
/** Soma dos tempos de travessia de todos os veículos */
|
/** Tempo acumulado em travessia de todos os veículos */
|
||||||
private double totalCrossingTime;
|
private double totalCrossingTime;
|
||||||
|
|
||||||
/** Contagem de veículos por tipo */
|
/** Contagem de veículos por tipo */
|
||||||
private final Map<VehicleType, Integer> vehicleTypeCount;
|
private final Map<VehicleType, Integer> vehicleTypeCount;
|
||||||
|
|
||||||
/** Tempo total de espera acumulado por tipo de veículo */
|
/** Tempo de espera acumulado por tipo de veículo */
|
||||||
private final Map<VehicleType, Double> vehicleTypeWaitTime;
|
private final Map<VehicleType, Double> vehicleTypeWaitTime;
|
||||||
|
|
||||||
/** Socket para comunicação com o dashboard */
|
/** Cliente socket para envio de estatísticas ao dashboard */
|
||||||
private SocketClient dashboardClient;
|
private SocketClient dashboardClient;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Método para iniciar o processo
|
* Ponto de entrada do processo.
|
||||||
*
|
*
|
||||||
* @param args Argumentos da linha de comandos. Se fornecido, args[0] deve ser
|
* @param args args[0] (opcional) = caminho do ficheiro de configuração
|
||||||
* o caminho para um ficheiro de configuração personalizado.
|
|
||||||
*/
|
*/
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
System.out.println("=".repeat(60));
|
System.out.println("=".repeat(60));
|
||||||
@@ -79,6 +89,8 @@ public class ExitNodeProcess {
|
|||||||
System.out.println("=".repeat(60));
|
System.out.println("=".repeat(60));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
EventLogger.getInstance().log(EventType.PROCESS_STARTED, "ExitNode", "Exit node process started");
|
||||||
|
|
||||||
String configFile = args.length > 0 ? args[0] : "src/main/resources/simulation.properties";
|
String configFile = args.length > 0 ? args[0] : "src/main/resources/simulation.properties";
|
||||||
System.out.println("Loading configuration from: " + configFile);
|
System.out.println("Loading configuration from: " + configFile);
|
||||||
|
|
||||||
@@ -93,22 +105,25 @@ public class ExitNodeProcess {
|
|||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
System.err.println("Failed to start exit node: " + e.getMessage());
|
System.err.println("Failed to start exit node: " + e.getMessage());
|
||||||
|
EventLogger.getInstance().logError("ExitNode", "Failed to start", e);
|
||||||
System.exit(1);
|
System.exit(1);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.err.println("Exit node error: " + e.getMessage());
|
System.err.println("Exit node error: " + e.getMessage());
|
||||||
|
EventLogger.getInstance().logError("ExitNode", "Exit node error", e);
|
||||||
System.exit(1);
|
System.exit(1);
|
||||||
|
} finally {
|
||||||
|
EventLogger.getInstance().log(EventType.PROCESS_STOPPED, "ExitNode", "Exit node process stopped");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constrói um novo processo de nó de saída.
|
* Configura o Nó de Saída.
|
||||||
*
|
*
|
||||||
* Inicializa todas as estruturas de dados necessárias para recolher
|
* Inicializamos os nossos contadores, preparamos a pool de threads para tratar
|
||||||
* estatísticas
|
* das ligações de veículos recebidas,
|
||||||
* e configura o pool de threads para processar as ligações concorrentes.
|
* e configuramos os componentes DES para rastreio de eventos.
|
||||||
*
|
*
|
||||||
* @param config Configuração da simulação contendo portas e endereços dos
|
* @param config A configuração da simulação.
|
||||||
* serviços
|
|
||||||
*/
|
*/
|
||||||
public ExitNodeProcess(SimulationConfig config) {
|
public ExitNodeProcess(SimulationConfig config) {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
@@ -128,17 +143,23 @@ public class ExitNodeProcess {
|
|||||||
vehicleTypeWaitTime.put(type, 0.0);
|
vehicleTypeWaitTime.put(type, 0.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println("Exit node initialized");
|
// 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(" - Exit port: " + config.getExitPort());
|
||||||
System.out.println(" - Dashboard: " + config.getDashboardHost() + ":" + config.getDashboardPort());
|
System.out.println(" - Dashboard: " + config.getDashboardHost() + ":" + config.getDashboardPort());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Inicializa o processo de ligação ao dashboard.
|
* Tenta estabelecer uma ligação ao dashboard.
|
||||||
*
|
* Se for bem-sucedido, poderemos enviar estatísticas em tempo real. Se não,
|
||||||
* Tenta conectar-se ao dashboard. Se a ligação falhar, o processo
|
* apenas registamos localmente.
|
||||||
* continua a funcionar normalmente, mas sem enviar estatísticas.
|
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public void initialize() {
|
public void initialize() {
|
||||||
System.out.println("Connecting to dashboard...");
|
System.out.println("Connecting to dashboard...");
|
||||||
@@ -158,23 +179,141 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Inicia o socket e começa a aceitar ligações.
|
* 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.
|
||||||
*
|
*
|
||||||
* Este é o loop principal do processo que:
|
* @param endTime The simulation time when the simulation should end
|
||||||
* 1. Cria um socket na porta definida
|
*/
|
||||||
* 2. Aguarda pelas ligações das interseções
|
public void scheduleSimulationEnd(double endTime) {
|
||||||
* 3. Delega cada ligação a uma thread da pool para processamento assíncrono
|
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.
|
||||||
*
|
*
|
||||||
* @throws IOException Se o socket não puder ser criado ou houver erro na
|
* Este é o loop principal. Aceitamos ligações das interseções (de onde vêm os
|
||||||
* aceitação
|
* 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 {
|
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();
|
int port = config.getExitPort();
|
||||||
serverSocket = new ServerSocket(port);
|
serverSocket = new ServerSocket(port);
|
||||||
running = true;
|
running = true;
|
||||||
simulationStartMillis = System.currentTimeMillis();
|
simulationStartMillis = System.currentTimeMillis();
|
||||||
|
|
||||||
System.out.println("Exit node started on port " + port);
|
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");
|
System.out.println("Waiting for vehicles...\\n");
|
||||||
|
|
||||||
while (running) {
|
while (running) {
|
||||||
@@ -190,13 +329,12 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Processa uma ligação recebida de uma interseção.
|
* Trata uma ligação de uma interseção.
|
||||||
*
|
*
|
||||||
* Mantém a ligação aberta e processa continuamente mensagens do tipo
|
* Mantemos a ligação aberta e escutamos por mensagens `VEHICLE_TRANSFER`.
|
||||||
* VEHICLE_TRANSFER. Cada mensagem representa um veículo que chegou ao nó de
|
* Cada mensagem contém um veículo que acabou de terminar a sua viagem.
|
||||||
* saída.
|
|
||||||
*
|
*
|
||||||
* @param clientSocket Socket da ligação estabelecida com a interseção
|
* @param clientSocket O socket ligado à interseção.
|
||||||
*/
|
*/
|
||||||
private void handleIncomingConnection(Socket clientSocket) {
|
private void handleIncomingConnection(Socket clientSocket) {
|
||||||
String clientAddress = clientSocket.getInetAddress().getHostAddress();
|
String clientAddress = clientSocket.getInetAddress().getHostAddress();
|
||||||
@@ -252,25 +390,24 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Processa um veículo que chegou ao nó de saída.
|
* Processa um veículo que acabou de sair do sistema.
|
||||||
*
|
*
|
||||||
* Método sincronizado para garantir thread-safety ao atualizar as estatísticas.
|
* Calculamos quanto tempo demorou, atualizamos as nossas estatísticas globais e
|
||||||
* Calcula as métricas finais do veículo e atualiza:
|
* notificamos o dashboard.
|
||||||
* - Counters globais;
|
* Este método é sincronizado porque múltiplos veículos podem chegar ao mesmo
|
||||||
* - Estatísticas por tipo de veículo;
|
* tempo.
|
||||||
* - Faz update ao dashboard a cada 10 veículos.
|
|
||||||
*
|
*
|
||||||
* @param vehicle Veículo que completou a sua rota
|
* @param vehicle O veículo que completou a sua rota.
|
||||||
*/
|
*/
|
||||||
private synchronized void processExitingVehicle(Vehicle vehicle) {
|
private synchronized void processExitingVehicle(Vehicle vehicle) {
|
||||||
totalVehiclesReceived++;
|
totalVehiclesReceived++;
|
||||||
|
|
||||||
// Calculate relative simulation time (seconds since simulation start)
|
// Use simulation time instead of wall-clock time
|
||||||
double currentSimTime = (System.currentTimeMillis() - simulationStartMillis) / 1000.0;
|
// System time = total time vehicle spent in system (wait + crossing times)
|
||||||
// System time = time vehicle spent in system (current time - entry time)
|
// This represents the actual simulation time elapsed, not real-time
|
||||||
double systemTime = currentSimTime - vehicle.getEntryTime();
|
|
||||||
double waitTime = vehicle.getTotalWaitingTime();
|
double waitTime = vehicle.getTotalWaitingTime();
|
||||||
double crossingTime = vehicle.getTotalCrossingTime();
|
double crossingTime = vehicle.getTotalCrossingTime();
|
||||||
|
double systemTime = waitTime + crossingTime;
|
||||||
|
|
||||||
// Store times in seconds, will be converted to ms when sending to dashboard
|
// Store times in seconds, will be converted to ms when sending to dashboard
|
||||||
totalSystemTime += systemTime;
|
totalSystemTime += systemTime;
|
||||||
@@ -284,18 +421,23 @@ public class ExitNodeProcess {
|
|||||||
System.out.printf("[Exit] Vehicle %s completed (type=%s, system_time=%.2fs, wait=%.2fs, crossing=%.2fs)%n",
|
System.out.printf("[Exit] Vehicle %s completed (type=%s, system_time=%.2fs, wait=%.2fs, crossing=%.2fs)%n",
|
||||||
vehicle.getId(), vehicle.getType(), systemTime, waitTime, crossingTime);
|
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
|
// Send stats after every vehicle to ensure dashboard updates quickly
|
||||||
sendStatsToDashboard();
|
sendStatsToDashboard();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Envia as estatísticas para o dashboard.
|
* Envia as estatísticas mais recentes para o dashboard.
|
||||||
*
|
|
||||||
* Prepara e envia uma mensagem STATS_UPDATE com:
|
|
||||||
* - O total de veículos processados;
|
|
||||||
* - A média dos tempos (sistema, espera, travessia);
|
|
||||||
* - As contagens e médias por cada tipo de veículo.
|
|
||||||
*
|
*
|
||||||
|
* Empacotamos as contagens totais e os tempos médios num `StatsUpdatePayload`
|
||||||
|
* e enviamo-lo.
|
||||||
*/
|
*/
|
||||||
private void sendStatsToDashboard() {
|
private void sendStatsToDashboard() {
|
||||||
if (dashboardClient == null || !dashboardClient.isConnected()) {
|
if (dashboardClient == null || !dashboardClient.isConnected()) {
|
||||||
@@ -347,14 +489,9 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Termina o processo
|
* Encerra graciosamente o processo.
|
||||||
*
|
*
|
||||||
* Executa a seguinte sequência:
|
* Imprimimos as estatísticas finais, fechamos ligações e limpamos threads.
|
||||||
* Imprime as estatísticas finais no terminal;
|
|
||||||
* Envia a última atualização de estatísticas ao dashboard;
|
|
||||||
* Fecha o socket;
|
|
||||||
* Aguarda pela finalização das threads;
|
|
||||||
* Fecha a ligação com o dashboard;
|
|
||||||
*/
|
*/
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
System.out.println("\n[Exit] Shutting down...");
|
System.out.println("\n[Exit] Shutting down...");
|
||||||
@@ -390,15 +527,9 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Imprime as estatísticas finais detalhadas no terminal
|
* 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
|
||||||
* Gera um relatório com:
|
* veículos, etc.).
|
||||||
* Total de veículos que completaram a rota;
|
|
||||||
* Médias de tempo no sistema, espera e travessia;
|
|
||||||
* Distribuição e médias pelo tipo de veículo (BIKE, LIGHT, HEAVY);
|
|
||||||
*
|
|
||||||
* Este método é chamado durante o shutdown para fornecer um resumo
|
|
||||||
* da simulação antes de terminar o processo.
|
|
||||||
*/
|
*/
|
||||||
private void printFinalStatistics() {
|
private void printFinalStatistics() {
|
||||||
System.out.println("\n=== EXIT NODE STATISTICS ===");
|
System.out.println("\n=== EXIT NODE STATISTICS ===");
|
||||||
|
|||||||
@@ -16,21 +16,36 @@ import java.util.concurrent.locks.ReentrantLock;
|
|||||||
import sd.config.SimulationConfig;
|
import sd.config.SimulationConfig;
|
||||||
import sd.coordinator.SocketClient;
|
import sd.coordinator.SocketClient;
|
||||||
import sd.dashboard.StatsUpdatePayload;
|
import sd.dashboard.StatsUpdatePayload;
|
||||||
import sd.engine.TrafficLightThread;
|
import sd.des.DESEventType;
|
||||||
|
import sd.des.EventQueue;
|
||||||
|
import sd.des.SimulationClock;
|
||||||
|
import sd.des.SimulationEvent;
|
||||||
|
import sd.des.TrafficLightEvent;
|
||||||
|
import sd.logging.EventLogger;
|
||||||
import sd.model.Intersection;
|
import sd.model.Intersection;
|
||||||
import sd.model.Message;
|
import sd.model.Message;
|
||||||
import sd.model.MessageType;
|
import sd.model.MessageType;
|
||||||
import sd.model.TrafficLight;
|
import sd.model.TrafficLight;
|
||||||
|
import sd.model.TrafficLightState;
|
||||||
import sd.model.Vehicle;
|
import sd.model.Vehicle;
|
||||||
import sd.protocol.MessageProtocol;
|
import sd.protocol.MessageProtocol;
|
||||||
import sd.protocol.SocketConnection;
|
import sd.protocol.SocketConnection;
|
||||||
import sd.serialization.SerializationException;
|
import sd.serialization.SerializationException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Main class for an Intersection Process in the distributed traffic simulation.
|
* Representa uma única interseção na nossa simulação de tráfego distribuída.
|
||||||
* * Each IntersectionProcess runs as an independent Java application (JVM
|
*
|
||||||
* instance)
|
* Esta classe opera como um processo independente (uma aplicação Java autónoma)
|
||||||
* representing one of the five intersections (Cr1-Cr5) in the network.
|
* e é responsável por:
|
||||||
|
* 1. Gerir os semáforos e a sua temporização.
|
||||||
|
* 2. Processar as chegadas e partidas de veículos.
|
||||||
|
* 3. Comunicar com outras interseções e com o dashboard.
|
||||||
|
*
|
||||||
|
* Utiliza uma abordagem de Simulação de Eventos Discretos (DES), onde as
|
||||||
|
* mudanças de estado (como semáforos a mudar para verde)
|
||||||
|
* são agendadas como eventos numa fila de prioridade, em vez de depender de
|
||||||
|
* loops contínuos ou threads em espera.
|
||||||
|
* Isto garante uma temporização precisa e uma execução eficiente.
|
||||||
*/
|
*/
|
||||||
public class IntersectionProcess {
|
public class IntersectionProcess {
|
||||||
|
|
||||||
@@ -46,24 +61,31 @@ public class IntersectionProcess {
|
|||||||
|
|
||||||
private final ExecutorService connectionHandlerPool;
|
private final ExecutorService connectionHandlerPool;
|
||||||
|
|
||||||
private final ExecutorService trafficLightPool;
|
|
||||||
|
|
||||||
private ScheduledExecutorService statsExecutor;
|
private ScheduledExecutorService statsExecutor;
|
||||||
|
private ScheduledExecutorService departureExecutor;
|
||||||
|
|
||||||
private volatile boolean running; // Quando uma thread escreve um valor volatile, todas as outras
|
private volatile boolean running;
|
||||||
// threads veem a mudança imediatamente.
|
/** Escala temporal para visualização: tempo_real = tempo_simulado * escala */
|
||||||
|
private double timeScale;
|
||||||
|
|
||||||
|
/** Relógio central da simulação */
|
||||||
|
private final SimulationClock clock;
|
||||||
|
/** Fila de eventos discretos agendados */
|
||||||
|
private final EventQueue eventQueue;
|
||||||
|
/** Sistema de registo de eventos */
|
||||||
|
private final EventLogger eventLogger;
|
||||||
|
/** Thread dedicada ao processamento sequencial de eventos DES */
|
||||||
|
private Thread eventProcessorThread;
|
||||||
|
|
||||||
// Traffic Light Coordination
|
|
||||||
/**
|
/**
|
||||||
* Lock to ensure mutual exclusion between traffic lights.
|
* Lock para exclusão mútua entre semáforos.
|
||||||
* Only one traffic light can be green at any given time within this
|
* Garante que apenas um semáforo pode estar verde de cada vez nesta interseção.
|
||||||
* intersection.
|
|
||||||
*/
|
*/
|
||||||
private final Lock trafficCoordinationLock;
|
private final Lock trafficCoordinationLock;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tracks which direction currently has the green light.
|
* Regista qual direção tem atualmente o sinal verde.
|
||||||
* null means no direction is currently green (all are red).
|
* {@code null} significa que todos os semáforos estão vermelhos.
|
||||||
*/
|
*/
|
||||||
private volatile String currentGreenDirection;
|
private volatile String currentGreenDirection;
|
||||||
|
|
||||||
@@ -72,11 +94,11 @@ public class IntersectionProcess {
|
|||||||
private volatile int totalDepartures = 0;
|
private volatile int totalDepartures = 0;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new IntersectionProcess.
|
* Inicializa o processo da interseção.
|
||||||
*
|
*
|
||||||
* @param intersectionId The ID of this intersection (e.g., "Cr1").
|
* @param intersectionId O identificador único para esta interseção (ex: "Cr1").
|
||||||
* @param configFilePath Path to the simulation.properties file.
|
* @param configFilePath O caminho para o ficheiro de configuração.
|
||||||
* @throws IOException If configuration cannot be loaded.
|
* @throws IOException Se houver algum problema ao ler a configuração.
|
||||||
*/
|
*/
|
||||||
public IntersectionProcess(String intersectionId, String configFilePath) throws IOException {
|
public IntersectionProcess(String intersectionId, String configFilePath) throws IOException {
|
||||||
this.intersectionId = intersectionId;
|
this.intersectionId = intersectionId;
|
||||||
@@ -84,17 +106,327 @@ public class IntersectionProcess {
|
|||||||
this.intersection = new Intersection(intersectionId);
|
this.intersection = new Intersection(intersectionId);
|
||||||
this.outgoingConnections = new HashMap<>();
|
this.outgoingConnections = new HashMap<>();
|
||||||
this.connectionHandlerPool = Executors.newCachedThreadPool();
|
this.connectionHandlerPool = Executors.newCachedThreadPool();
|
||||||
this.trafficLightPool = Executors.newFixedThreadPool(4); // Max 4 directions
|
|
||||||
this.statsExecutor = Executors.newSingleThreadScheduledExecutor();
|
this.statsExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||||
|
this.departureExecutor = Executors.newScheduledThreadPool(4);
|
||||||
this.running = false;
|
this.running = false;
|
||||||
this.trafficCoordinationLock = new ReentrantLock(true); // Fair lock to prevent starvation
|
this.trafficCoordinationLock = new ReentrantLock(true); // Fair lock to prevent starvation
|
||||||
this.currentGreenDirection = null;
|
this.currentGreenDirection = null;
|
||||||
|
this.timeScale = config.getTimeScale();
|
||||||
|
|
||||||
|
// Initialize DES components
|
||||||
|
this.clock = new SimulationClock();
|
||||||
|
this.eventQueue = new EventQueue(true); // Track history for debugging
|
||||||
|
this.eventLogger = EventLogger.getInstance();
|
||||||
|
|
||||||
|
eventLogger.log(sd.logging.EventType.PROCESS_STARTED, intersectionId,
|
||||||
|
"Intersection process initialized with DES architecture");
|
||||||
|
|
||||||
System.out.println("=".repeat(60));
|
System.out.println("=".repeat(60));
|
||||||
System.out.println("INTERSECTION PROCESS: " + intersectionId);
|
System.out.println("INTERSECTION PROCESS: " + intersectionId + " (DES Mode)");
|
||||||
System.out.println("=".repeat(60));
|
System.out.println("=".repeat(60));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inicia o ciclo de processamento de eventos.
|
||||||
|
*
|
||||||
|
* Esta thread é o coração do modelo DES para esta interseção. Retira eventos da
|
||||||
|
* fila
|
||||||
|
* e executa-os por ordem cronológica. Enquanto a thread principal trata das
|
||||||
|
* operações de I/O de rede (receção de veículos),
|
||||||
|
* esta thread trata da lógica da simulação (semáforos, travessias de veículos).
|
||||||
|
*/
|
||||||
|
private void startEventProcessor() {
|
||||||
|
eventProcessorThread = new Thread(() -> {
|
||||||
|
eventLogger.log(sd.logging.EventType.SIMULATION_STARTED, intersectionId,
|
||||||
|
"Event processor thread started");
|
||||||
|
|
||||||
|
// Keep running while the process is active
|
||||||
|
double lastTime = 0.0;
|
||||||
|
while (running) {
|
||||||
|
SimulationEvent event = eventQueue.poll();
|
||||||
|
if (event == null) {
|
||||||
|
// No events currently, wait a bit before checking again
|
||||||
|
try {
|
||||||
|
Thread.sleep(50); // Short sleep to avoid busy-waiting
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 clock to event time
|
||||||
|
clock.advanceTo(event.getTimestamp());
|
||||||
|
|
||||||
|
// Process the event
|
||||||
|
processEvent(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
eventLogger.log(sd.logging.EventType.SIMULATION_STOPPED, intersectionId,
|
||||||
|
String.format("Event processor thread terminated at time %.2f", clock.getCurrentTime()));
|
||||||
|
}, "EventProcessor-" + intersectionId);
|
||||||
|
|
||||||
|
eventProcessorThread.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processa um evento da fila de simulação.
|
||||||
|
* Cada tipo de evento é encaminhado para o seu tratador específico.
|
||||||
|
*
|
||||||
|
* @param event o evento a processar
|
||||||
|
*/
|
||||||
|
private void processEvent(SimulationEvent event) {
|
||||||
|
try {
|
||||||
|
switch (event.getType()) {
|
||||||
|
case TRAFFIC_LIGHT_CHANGE:
|
||||||
|
handleTrafficLightChangeEvent(event);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case VEHICLE_ARRIVAL:
|
||||||
|
// Vehicle arrivals are still handled via network messages
|
||||||
|
// This event type is for internal scheduling if needed
|
||||||
|
break;
|
||||||
|
|
||||||
|
case VEHICLE_CROSSING_START:
|
||||||
|
handleVehicleCrossingStartEvent(event);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case VEHICLE_CROSSING_END:
|
||||||
|
handleVehicleCrossingEndEvent(event);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case SIMULATION_END:
|
||||||
|
handleSimulationEndEvent(event);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
System.err.println("[" + intersectionId + "] Unknown event type: " + event.getType());
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.err.println("[" + intersectionId + "] Error processing event " + event.getType() +
|
||||||
|
" at time " + event.getTimestamp() + ": " + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trata da mudança dos semáforos.
|
||||||
|
*
|
||||||
|
* Quando um semáforo muda de estado, registamos o evento, atualizamos o modelo
|
||||||
|
* e, se tiver mudado para VERDE,
|
||||||
|
* verificamos imediatamente se há veículos à espera para atravessar.
|
||||||
|
* Também agendamos aqui o *próximo* evento de mudança, mantendo o ciclo ativo.
|
||||||
|
*/
|
||||||
|
private void handleTrafficLightChangeEvent(SimulationEvent event) {
|
||||||
|
TrafficLightEvent tlEvent = (TrafficLightEvent) event.getPayload();
|
||||||
|
TrafficLight light = tlEvent.getLight();
|
||||||
|
String direction = tlEvent.getDirection();
|
||||||
|
|
||||||
|
// Toggle state
|
||||||
|
TrafficLightState oldState = light.getState();
|
||||||
|
TrafficLightState newState = (oldState == TrafficLightState.GREEN) ? TrafficLightState.RED
|
||||||
|
: TrafficLightState.GREEN;
|
||||||
|
|
||||||
|
light.changeState(newState);
|
||||||
|
|
||||||
|
sd.logging.EventType logEventType = (newState == TrafficLightState.GREEN)
|
||||||
|
? sd.logging.EventType.LIGHT_CHANGED_GREEN
|
||||||
|
: sd.logging.EventType.LIGHT_CHANGED_RED;
|
||||||
|
|
||||||
|
eventLogger.log(logEventType, intersectionId,
|
||||||
|
String.format("Direction %s changed to %s at time %.2f",
|
||||||
|
direction, newState, event.getTimestamp()));
|
||||||
|
|
||||||
|
// If light turned GREEN, process queued vehicles
|
||||||
|
if (newState == TrafficLightState.GREEN) {
|
||||||
|
processQueuedVehiclesForLight(light, event.getTimestamp());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Schedule next state change
|
||||||
|
double nextChangeTime = event.getTimestamp() +
|
||||||
|
(newState == TrafficLightState.GREEN ? light.getGreenTime() : light.getRedTime());
|
||||||
|
|
||||||
|
SimulationEvent nextEvent = new SimulationEvent(
|
||||||
|
nextChangeTime,
|
||||||
|
DESEventType.TRAFFIC_LIGHT_CHANGE,
|
||||||
|
tlEvent);
|
||||||
|
eventQueue.schedule(nextEvent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processa a fila de veículos quando um semáforo fica verde.
|
||||||
|
*
|
||||||
|
* <p>Para cada veículo na fila:</p>
|
||||||
|
* <ol>
|
||||||
|
* <li>Calcula o tempo de travessia com base no tipo de veículo</li>
|
||||||
|
* <li>Verifica se cabe na duração restante do sinal verde</li>
|
||||||
|
* <li>Agenda o evento de partida do veículo</li>
|
||||||
|
* </ol>
|
||||||
|
*
|
||||||
|
* <p>Os veículos que não couberem no tempo verde ficam à espera do próximo ciclo.</p>
|
||||||
|
*
|
||||||
|
* @param light o semáforo que acabou de ficar verde
|
||||||
|
* @param currentTime o tempo atual da simulação em segundos
|
||||||
|
*/
|
||||||
|
private void processQueuedVehiclesForLight(TrafficLight light, double currentTime) {
|
||||||
|
double greenDuration = light.getGreenTime();
|
||||||
|
double timeOffset = 0.0;
|
||||||
|
|
||||||
|
int queueSize = light.getQueueSize();
|
||||||
|
System.out.printf("[%s] Processing queue for %s (GREEN for %.2fs, queue size: %d, currentTime=%.2f)%n",
|
||||||
|
intersectionId, light.getId(), greenDuration, queueSize, currentTime);
|
||||||
|
|
||||||
|
// Process vehicles while queue not empty and within green light duration
|
||||||
|
while (light.getQueueSize() > 0) {
|
||||||
|
// Calculate crossing time for next vehicle (peek at queue size to estimate)
|
||||||
|
// We'll use LIGHT vehicle as default for estimation
|
||||||
|
double crossingTime = config.getLightVehicleCrossingTime();
|
||||||
|
|
||||||
|
// Check if another vehicle can fit in remaining green time
|
||||||
|
if (timeOffset + crossingTime > greenDuration) {
|
||||||
|
break; // No more vehicles can cross this green phase
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove vehicle from queue
|
||||||
|
Vehicle vehicle = light.removeVehicle();
|
||||||
|
if (vehicle == null)
|
||||||
|
break;
|
||||||
|
|
||||||
|
// Get actual crossing time for this vehicle
|
||||||
|
crossingTime = getCrossingTimeForVehicle(vehicle);
|
||||||
|
|
||||||
|
// Schedule crossing
|
||||||
|
double crossingStartTime = currentTime + timeOffset;
|
||||||
|
scheduleVehicleCrossing(vehicle, crossingStartTime, crossingTime);
|
||||||
|
|
||||||
|
// Update offset for next vehicle
|
||||||
|
timeOffset += crossingTime;
|
||||||
|
|
||||||
|
System.out.printf("[%s] Scheduled vehicle %s to cross at t=%.2f (duration=%.2fs)%n",
|
||||||
|
intersectionId, vehicle.getId(), crossingStartTime, crossingTime);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Agenda a travessia e partida de um veículo.
|
||||||
|
* Cria um evento de fim de travessia agendado para o tempo correto.
|
||||||
|
*
|
||||||
|
* @param vehicle o veículo que vai atravessar
|
||||||
|
* @param startTime quando a travessia começa (segundos de simulação)
|
||||||
|
* @param crossingDuration quanto tempo demora a atravessar (segundos)
|
||||||
|
*/
|
||||||
|
private void scheduleVehicleCrossing(Vehicle vehicle, double startTime, double crossingDuration) {
|
||||||
|
// Schedule crossing end (when vehicle departs)
|
||||||
|
double departureTime = startTime + crossingDuration;
|
||||||
|
|
||||||
|
// Create event with vehicle as payload
|
||||||
|
SimulationEvent departureEvent = new SimulationEvent(
|
||||||
|
departureTime,
|
||||||
|
DESEventType.VEHICLE_CROSSING_END,
|
||||||
|
vehicle);
|
||||||
|
eventQueue.schedule(departureEvent);
|
||||||
|
|
||||||
|
eventLogger.log(sd.logging.EventType.VEHICLE_QUEUED, intersectionId,
|
||||||
|
String.format("Vehicle %s crossing scheduled: %.2fs to %.2fs",
|
||||||
|
vehicle.getId(), startTime, departureTime));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calcula o tempo de travessia com base no tipo de veículo.
|
||||||
|
* Bicicletas são mais rápidas, veículos pesados mais lentos.
|
||||||
|
*
|
||||||
|
* @param vehicle o veículo para calcular o tempo
|
||||||
|
* @return tempo de travessia em segundos
|
||||||
|
*/
|
||||||
|
private double getCrossingTimeForVehicle(Vehicle vehicle) {
|
||||||
|
return switch (vehicle.getType()) {
|
||||||
|
case BIKE -> config.getBikeVehicleCrossingTime();
|
||||||
|
case LIGHT -> config.getLightVehicleCrossingTime();
|
||||||
|
case HEAVY -> config.getHeavyVehicleCrossingTime();
|
||||||
|
default -> config.getLightVehicleCrossingTime();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trata o evento de início de travessia de um veículo.
|
||||||
|
* (Implementação futura - atualmente apenas regista o evento)
|
||||||
|
*
|
||||||
|
* @param event o evento de início de travessia
|
||||||
|
*/
|
||||||
|
private void handleVehicleCrossingStartEvent(SimulationEvent event) {
|
||||||
|
// Implementation will depend on how vehicle crossing is modeled
|
||||||
|
// For now, log the event
|
||||||
|
eventLogger.log(sd.logging.EventType.VEHICLE_DEPARTED, intersectionId,
|
||||||
|
"Vehicle crossing started at time " + event.getTimestamp());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trata o fim da travessia de um veículo pela interseção.
|
||||||
|
* Atualiza estatísticas, regista o tempo de travessia e envia o veículo
|
||||||
|
* para o próximo destino na sua rota.
|
||||||
|
*
|
||||||
|
* @param event evento contendo o veículo que terminou a travessia
|
||||||
|
*/
|
||||||
|
private void handleVehicleCrossingEndEvent(SimulationEvent event) {
|
||||||
|
Vehicle vehicle = (Vehicle) event.getPayload();
|
||||||
|
|
||||||
|
// Add crossing time to vehicle stats
|
||||||
|
double crossingTime = getCrossingTimeForVehicle(vehicle);
|
||||||
|
vehicle.addCrossingTime(crossingTime);
|
||||||
|
|
||||||
|
// Update intersection statistics
|
||||||
|
intersection.incrementVehiclesSent();
|
||||||
|
|
||||||
|
// Send vehicle to next destination
|
||||||
|
sendVehicleToNextDestination(vehicle);
|
||||||
|
|
||||||
|
eventLogger.log(sd.logging.EventType.VEHICLE_DEPARTED, intersectionId,
|
||||||
|
String.format("Vehicle %s departed at time %.2f", vehicle.getId(), event.getTimestamp()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trata o evento de fim da simulação.
|
||||||
|
* Define a flag de execução como falsa para terminar o processamento.
|
||||||
|
*
|
||||||
|
* @param event o evento de fim de simulação
|
||||||
|
*/
|
||||||
|
private void handleSimulationEndEvent(SimulationEvent event) {
|
||||||
|
eventLogger.log(sd.logging.EventType.SIMULATION_STOPPED, intersectionId,
|
||||||
|
String.format("Simulation ended at time %.2f", event.getTimestamp()));
|
||||||
|
running = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exporta o histórico completo de eventos para um ficheiro.
|
||||||
|
* Útil para análise posterior e debugging da simulação.
|
||||||
|
*
|
||||||
|
* @param outputPath caminho do ficheiro onde guardar o histórico
|
||||||
|
*/
|
||||||
|
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("[" + intersectionId + "] Event history exported to: " + outputPath);
|
||||||
|
} catch (java.io.FileNotFoundException e) {
|
||||||
|
System.err.println("[" + intersectionId + "] Failed to export event history: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Main entry point for running an intersection process
|
// Main entry point for running an intersection process
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
if (args.length < 1) {
|
if (args.length < 1) {
|
||||||
@@ -137,7 +469,7 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Establishes connection to the dashboard server for statistics reporting.
|
* Estabelece ligação ao servidor do dashboard para reportar estatísticas.
|
||||||
*/
|
*/
|
||||||
private void connectToDashboard() {
|
private void connectToDashboard() {
|
||||||
try {
|
try {
|
||||||
@@ -161,10 +493,9 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates traffic lights for this intersection based on its physical
|
* Cria os semáforos para esta interseção com base nas suas ligações físicas.
|
||||||
* connections.
|
* Cada interseção tem um número e direções de semáforos diferentes de acordo
|
||||||
* Each intersection has different number and directions of traffic lights
|
* com a topologia da rede.
|
||||||
* according to the network topology.
|
|
||||||
*/
|
*/
|
||||||
private void createTrafficLights() {
|
private void createTrafficLights() {
|
||||||
System.out.println("\n[" + intersectionId + "] Creating traffic lights...");
|
System.out.println("\n[" + intersectionId + "] Creating traffic lights...");
|
||||||
@@ -224,10 +555,11 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Requests permission for a traffic light to turn green.
|
* Solicita permissão para um semáforo ficar verde.
|
||||||
* Blocks until permission is granted (no other light is green).
|
* Bloqueia até que a permissão seja concedida (nenhum outro semáforo está
|
||||||
|
* verde).
|
||||||
*
|
*
|
||||||
* @param direction The direction requesting green light
|
* @param direction A direção que solicita o sinal verde
|
||||||
*/
|
*/
|
||||||
public void requestGreenLight(String direction) {
|
public void requestGreenLight(String direction) {
|
||||||
trafficCoordinationLock.lock();
|
trafficCoordinationLock.lock();
|
||||||
@@ -235,9 +567,10 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Releases the green light permission, allowing another light to turn green.
|
* Liberta a permissão de sinal verde, permitindo que outro semáforo fique
|
||||||
|
* verde.
|
||||||
*
|
*
|
||||||
* @param direction The direction releasing green light
|
* @param direction A direção que liberta o sinal verde
|
||||||
*/
|
*/
|
||||||
public void releaseGreenLight(String direction) {
|
public void releaseGreenLight(String direction) {
|
||||||
if (direction.equals(currentGreenDirection)) {
|
if (direction.equals(currentGreenDirection)) {
|
||||||
@@ -247,29 +580,77 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Starts all traffic light threads.
|
* Modo DES: Agenda os eventos iniciais de mudança de semáforo.
|
||||||
|
* Isto substitui a antiga abordagem baseada em threads startTrafficLights().
|
||||||
*/
|
*/
|
||||||
private void startTrafficLights() {
|
private void scheduleInitialTrafficLightEvents() {
|
||||||
System.out.println("\n[" + intersectionId + "] Starting traffic light threads...");
|
System.out.println("\n[" + intersectionId + "] Scheduling initial traffic light events (DES mode)...");
|
||||||
|
|
||||||
|
double currentTime = clock.getCurrentTime();
|
||||||
|
System.out.printf("[%s] Initial clock time: %.2f%n", intersectionId, currentTime);
|
||||||
|
|
||||||
for (TrafficLight light : intersection.getTrafficLights()) {
|
for (TrafficLight light : intersection.getTrafficLights()) {
|
||||||
|
String direction = light.getDirection();
|
||||||
|
|
||||||
TrafficLightThread lightTask = new TrafficLightThread(light, this, config);
|
// Set initial state (first light starts green, others red)
|
||||||
|
boolean isFirstLight = intersection.getTrafficLights().indexOf(light) == 0;
|
||||||
|
TrafficLightState initialState = isFirstLight ? TrafficLightState.GREEN : TrafficLightState.RED;
|
||||||
|
light.changeState(initialState);
|
||||||
|
|
||||||
trafficLightPool.submit(lightTask);
|
// Schedule first state change
|
||||||
|
double firstChangeTime = currentTime +
|
||||||
|
(initialState == TrafficLightState.GREEN ? light.getGreenTime() : light.getRedTime());
|
||||||
|
|
||||||
System.out.println(" Started thread for: " + light.getDirection());
|
TrafficLightEvent tlEvent = new TrafficLightEvent(light, direction, intersectionId);
|
||||||
|
SimulationEvent event = new SimulationEvent(
|
||||||
|
firstChangeTime,
|
||||||
|
DESEventType.TRAFFIC_LIGHT_CHANGE,
|
||||||
|
tlEvent);
|
||||||
|
eventQueue.schedule(event);
|
||||||
|
|
||||||
|
System.out.println(" Scheduled first event for direction " + direction +
|
||||||
|
" (initial: " + initialState + ", change at t=" + firstChangeTime + ")");
|
||||||
|
|
||||||
|
eventLogger.log(
|
||||||
|
initialState == TrafficLightState.GREEN ? sd.logging.EventType.LIGHT_CHANGED_GREEN
|
||||||
|
: sd.logging.EventType.LIGHT_CHANGED_RED,
|
||||||
|
intersectionId,
|
||||||
|
"Direction " + direction + " initialized to " + initialState);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends a vehicle to its next destination via socket connection.
|
* Envia um veículo para o seu próximo destino via ligação socket.
|
||||||
*
|
*
|
||||||
* @param vehicle The vehicle that has crossed this intersection.
|
* @param vehicle O veículo que atravessou esta interseção.
|
||||||
*/
|
*/
|
||||||
public void sendVehicleToNextDestination(Vehicle vehicle) {
|
public void sendVehicleToNextDestination(Vehicle vehicle) {
|
||||||
String nextDestination = vehicle.getCurrentDestination();
|
String nextDestination = vehicle.getCurrentDestination();
|
||||||
|
|
||||||
|
// Calculate travel time
|
||||||
|
double baseTime = config.getBaseTravelTime();
|
||||||
|
double multiplier = 1.0;
|
||||||
|
switch (vehicle.getType()) {
|
||||||
|
case BIKE -> multiplier = config.getBikeTravelTimeMultiplier();
|
||||||
|
case HEAVY -> multiplier = config.getHeavyTravelTimeMultiplier();
|
||||||
|
default -> multiplier = 1.0;
|
||||||
|
}
|
||||||
|
double travelTime = baseTime * multiplier;
|
||||||
|
|
||||||
|
System.out.printf("[%s] Vehicle %s departing to %s. Travel time: %.2fs%n",
|
||||||
|
intersectionId, vehicle.getId(), nextDestination, travelTime);
|
||||||
|
|
||||||
|
// Record departure immediately as it leaves the intersection
|
||||||
|
recordVehicleDeparture();
|
||||||
|
|
||||||
|
// In DES mode, send immediately (no real-time delay)
|
||||||
|
sendVehicleImmediately(vehicle, nextDestination);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Envia imediatamente um veículo para o seu destino via rede.
|
||||||
|
*/
|
||||||
|
private void sendVehicleImmediately(Vehicle vehicle, String nextDestination) {
|
||||||
try {
|
try {
|
||||||
// Get or create connection to next destination
|
// Get or create connection to next destination
|
||||||
SocketConnection connection = getOrCreateConnection(nextDestination);
|
SocketConnection connection = getOrCreateConnection(nextDestination);
|
||||||
@@ -284,11 +665,8 @@ public class IntersectionProcess {
|
|||||||
|
|
||||||
connection.sendMessage(message);
|
connection.sendMessage(message);
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Sent vehicle " + vehicle.getId() +
|
System.out.println("[" + intersectionId + "] Vehicle " + vehicle.getId() +
|
||||||
" to " + nextDestination);
|
" arrived at " + nextDestination + " (msg sent)");
|
||||||
|
|
||||||
// Record departure for statistics
|
|
||||||
recordVehicleDeparture();
|
|
||||||
|
|
||||||
// Note: vehicle route is advanced when it arrives at the next intersection
|
// Note: vehicle route is advanced when it arrives at the next intersection
|
||||||
|
|
||||||
@@ -299,12 +677,12 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets an existing connection to a destination or creates a new one.
|
* Obtém uma ligação existente para um destino ou cria uma nova.
|
||||||
*
|
*
|
||||||
* @param destinationId The ID of the destination node.
|
* @param destinationId O ID do nó de destino.
|
||||||
* @return The SocketConnection to that destination.
|
* @return A SocketConnection para esse destino.
|
||||||
* @throws IOException If connection cannot be established.
|
* @throws IOException Se a ligação não puder ser estabelecida.
|
||||||
* @throws InterruptedException If connection attempt is interrupted.
|
* @throws InterruptedException Se a tentativa de ligação for interrompida.
|
||||||
*/
|
*/
|
||||||
private synchronized SocketConnection getOrCreateConnection(String destinationId)
|
private synchronized SocketConnection getOrCreateConnection(String destinationId)
|
||||||
throws IOException, InterruptedException {
|
throws IOException, InterruptedException {
|
||||||
@@ -324,10 +702,10 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the host address for a destination node from configuration.
|
* Obtém o endereço host para um nó de destino a partir da configuração.
|
||||||
*
|
*
|
||||||
* @param destinationId The destination node ID.
|
* @param destinationId O ID do nó de destino.
|
||||||
* @return The host address.
|
* @return O endereço host.
|
||||||
*/
|
*/
|
||||||
private String getHostForDestination(String destinationId) {
|
private String getHostForDestination(String destinationId) {
|
||||||
if (destinationId.equals("S")) {
|
if (destinationId.equals("S")) {
|
||||||
@@ -338,10 +716,10 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the port number for a destination node from configuration.
|
* Obtém o número da porta para um nó de destino a partir da configuração.
|
||||||
*
|
*
|
||||||
* @param destinationId The destination node ID.
|
* @param destinationId O ID do nó de destino.
|
||||||
* @return The port number.
|
* @return O número da porta.
|
||||||
*/
|
*/
|
||||||
private int getPortForDestination(String destinationId) {
|
private int getPortForDestination(String destinationId) {
|
||||||
if (destinationId.equals("S")) {
|
if (destinationId.equals("S")) {
|
||||||
@@ -352,10 +730,10 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Starts the server socket and begins accepting incoming connections.
|
* Inicia o socket do servidor e começa a aceitar ligações recebidas.
|
||||||
* This is the main listening loop of the process.
|
* Este é o loop principal de escuta do processo.
|
||||||
*
|
*
|
||||||
* @throws IOException If the server socket cannot be created.
|
* @throws IOException Se o socket do servidor não puder ser criado.
|
||||||
*/
|
*/
|
||||||
public void start() throws IOException {
|
public void start() throws IOException {
|
||||||
int port = config.getIntersectionPort(intersectionId);
|
int port = config.getIntersectionPort(intersectionId);
|
||||||
@@ -364,8 +742,10 @@ public class IntersectionProcess {
|
|||||||
|
|
||||||
System.out.println("\n[" + intersectionId + "] Server started on port " + port);
|
System.out.println("\n[" + intersectionId + "] Server started on port " + port);
|
||||||
|
|
||||||
// Start traffic light threads when running is true
|
// DES Mode: Schedule initial events and start event processor
|
||||||
startTrafficLights();
|
scheduleInitialTrafficLightEvents();
|
||||||
|
startEventProcessor();
|
||||||
|
System.out.println("[" + intersectionId + "] Running in DES mode");
|
||||||
|
|
||||||
// Start stats updater
|
// Start stats updater
|
||||||
statsExecutor.scheduleAtFixedRate(this::sendStatsToDashboard, 1, 1, TimeUnit.SECONDS);
|
statsExecutor.scheduleAtFixedRate(this::sendStatsToDashboard, 1, 1, TimeUnit.SECONDS);
|
||||||
@@ -410,10 +790,10 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles an incoming connection from another process.
|
* Trata uma ligação recebida de outro processo.
|
||||||
* Continuously listens for vehicle transfer messages.
|
* Escuta continuamente mensagens de transferência de veículos.
|
||||||
*
|
*
|
||||||
* @param clientSocket The accepted socket connection.
|
* @param clientSocket A ligação socket aceite.
|
||||||
*/
|
*/
|
||||||
private void handleIncomingConnection(Socket clientSocket) {
|
private void handleIncomingConnection(Socket clientSocket) {
|
||||||
try {
|
try {
|
||||||
@@ -467,6 +847,10 @@ public class IntersectionProcess {
|
|||||||
// Add vehicle to appropriate queue
|
// Add vehicle to appropriate queue
|
||||||
intersection.receiveVehicle(vehicle);
|
intersection.receiveVehicle(vehicle);
|
||||||
|
|
||||||
|
// Log queue status after adding vehicle
|
||||||
|
System.out.printf("[%s] Vehicle %s queued. Total queue size: %d%n",
|
||||||
|
intersectionId, vehicle.getId(), intersection.getTotalQueueSize());
|
||||||
|
|
||||||
// Record arrival for statistics
|
// Record arrival for statistics
|
||||||
recordVehicleArrival();
|
recordVehicleArrival();
|
||||||
} else if (message.getType() == MessageType.SHUTDOWN) {
|
} else if (message.getType() == MessageType.SHUTDOWN) {
|
||||||
@@ -531,27 +915,29 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 2. Shutdown thread pools with force
|
// 2. Shutdown thread pools with force
|
||||||
if (trafficLightPool != null && !trafficLightPool.isShutdown()) {
|
|
||||||
trafficLightPool.shutdownNow();
|
|
||||||
}
|
|
||||||
if (connectionHandlerPool != null && !connectionHandlerPool.isShutdown()) {
|
if (connectionHandlerPool != null && !connectionHandlerPool.isShutdown()) {
|
||||||
connectionHandlerPool.shutdownNow();
|
connectionHandlerPool.shutdownNow();
|
||||||
}
|
}
|
||||||
if (statsExecutor != null && !statsExecutor.isShutdown()) {
|
if (statsExecutor != null && !statsExecutor.isShutdown()) {
|
||||||
statsExecutor.shutdownNow();
|
statsExecutor.shutdownNow();
|
||||||
}
|
}
|
||||||
|
if (departureExecutor != null && !departureExecutor.isShutdown()) {
|
||||||
|
departureExecutor.shutdownNow();
|
||||||
|
}
|
||||||
|
|
||||||
// 3. Wait briefly for termination (don't block forever)
|
// 3. Wait briefly for termination (don't block forever)
|
||||||
try {
|
try {
|
||||||
if (trafficLightPool != null) {
|
|
||||||
trafficLightPool.awaitTermination(1, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
if (connectionHandlerPool != null) {
|
if (connectionHandlerPool != null) {
|
||||||
connectionHandlerPool.awaitTermination(1, TimeUnit.SECONDS);
|
connectionHandlerPool.awaitTermination(1, TimeUnit.SECONDS);
|
||||||
}
|
}
|
||||||
if (statsExecutor != null) {
|
if (statsExecutor != null) {
|
||||||
statsExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
statsExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||||
}
|
}
|
||||||
|
if (departureExecutor != null) {
|
||||||
|
departureExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
}
|
}
|
||||||
|
|||||||
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()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,16 +14,14 @@ import java.util.Properties;
|
|||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class to load and manage simulation configurations.
|
* Carrega e gere configurações da simulação.
|
||||||
* Configurations are read from a .properties file. This class provides
|
*
|
||||||
* type-safe getter methods for all expected configuration parameters,
|
* <p>Lê propriedades de um ficheiro .properties e fornece getters
|
||||||
* with default values to ensure robustness.
|
* type-safe com valores padrão para robustez.
|
||||||
*/
|
*/
|
||||||
public class SimulationConfig {
|
public class SimulationConfig {
|
||||||
|
|
||||||
/**
|
/** Propriedades carregadas do ficheiro */
|
||||||
* Holds all properties loaded from the file.
|
|
||||||
*/
|
|
||||||
private final Properties properties;
|
private final Properties properties;
|
||||||
private NetworkConfig networkConfig;
|
private NetworkConfig networkConfig;
|
||||||
|
|
||||||
@@ -54,18 +52,17 @@ public class SimulationConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new SimulationConfig object by loading properties
|
* Carrega propriedades do ficheiro especificado.
|
||||||
* from the specified file path.
|
|
||||||
*
|
*
|
||||||
* This constructor attempts to load the configuration file using multiple
|
* <p>Tenta múltiplas estratégias:
|
||||||
* strategies:
|
* <ol>
|
||||||
* 1. Direct file system path
|
* <li>Caminho direto no sistema de ficheiros
|
||||||
* 2. Classpath resource (with automatic path normalization)
|
* <li>Recurso no classpath (com normalização automática)
|
||||||
* 3. Classpath resource with leading slash
|
* <li>Recurso no classpath com barra inicial
|
||||||
|
* </ol>
|
||||||
*
|
*
|
||||||
* @param filePath The path to the .properties file (e.g.,
|
* @param filePath caminho do ficheiro .properties
|
||||||
* "src/main/resources/simulation.properties").
|
* @throws IOException se o ficheiro não for encontrado
|
||||||
* @throws IOException If the file cannot be found or read from any location.
|
|
||||||
*/
|
*/
|
||||||
public SimulationConfig(String filePath) throws IOException {
|
public SimulationConfig(String filePath) throws IOException {
|
||||||
properties = new Properties();
|
properties = new Properties();
|
||||||
@@ -224,7 +221,15 @@ public class SimulationConfig {
|
|||||||
* @return The simulation duration.
|
* @return The simulation duration.
|
||||||
*/
|
*/
|
||||||
public double getSimulationDuration() {
|
public double getSimulationDuration() {
|
||||||
return Double.parseDouble(properties.getProperty("simulation.duration", "3600.0"));
|
return Double.parseDouble(properties.getProperty("simulation.duration", "3600"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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"));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -373,7 +378,7 @@ public class SimulationConfig {
|
|||||||
* @return The multiplier for heavy vehicle travel time.
|
* @return The multiplier for heavy vehicle travel time.
|
||||||
*/
|
*/
|
||||||
public double getHeavyTravelTimeMultiplier() {
|
public double getHeavyTravelTimeMultiplier() {
|
||||||
return Double.parseDouble(properties.getProperty("vehicle.travel.time.heavy.multiplier", "2.0"));
|
return Double.parseDouble(properties.getProperty("vehicle.travel.time.heavy.multiplier", "4.0"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Statistics ---
|
// --- Statistics ---
|
||||||
|
|||||||
@@ -6,6 +6,11 @@ import java.util.Map;
|
|||||||
|
|
||||||
import sd.config.SimulationConfig;
|
import sd.config.SimulationConfig;
|
||||||
import sd.dashboard.StatsUpdatePayload;
|
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.Message;
|
||||||
import sd.model.MessageType;
|
import sd.model.MessageType;
|
||||||
import sd.model.Vehicle;
|
import sd.model.Vehicle;
|
||||||
@@ -13,12 +18,17 @@ import sd.serialization.SerializationException;
|
|||||||
import sd.util.VehicleGenerator;
|
import sd.util.VehicleGenerator;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Coordinator process responsible for:
|
* Coordenador central da simulação distribuída.
|
||||||
* 1. Vehicle generation (using VehicleGenerator)
|
|
||||||
* 2. Distributing vehicles to intersection processes via sockets
|
|
||||||
* 3. Managing simulation timing and shutdown
|
|
||||||
*
|
*
|
||||||
* This is the main entry point for the distributed simulation architecture.
|
* <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 {
|
public class CoordinatorProcess {
|
||||||
|
|
||||||
@@ -26,10 +36,14 @@ public class CoordinatorProcess {
|
|||||||
private final VehicleGenerator vehicleGenerator;
|
private final VehicleGenerator vehicleGenerator;
|
||||||
private final Map<String, SocketClient> intersectionClients;
|
private final Map<String, SocketClient> intersectionClients;
|
||||||
private SocketClient dashboardClient;
|
private SocketClient dashboardClient;
|
||||||
private double currentTime;
|
|
||||||
|
private final SimulationClock clock;
|
||||||
|
private final EventQueue eventQueue;
|
||||||
|
private final EventLogger eventLogger;
|
||||||
|
|
||||||
private int vehicleCounter;
|
private int vehicleCounter;
|
||||||
private boolean running;
|
private boolean running;
|
||||||
private double nextGenerationTime;
|
private double timeScale;
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
System.out.println("=".repeat(60));
|
System.out.println("=".repeat(60));
|
||||||
@@ -65,15 +79,22 @@ public class CoordinatorProcess {
|
|||||||
this.config = config;
|
this.config = config;
|
||||||
this.vehicleGenerator = new VehicleGenerator(config);
|
this.vehicleGenerator = new VehicleGenerator(config);
|
||||||
this.intersectionClients = new HashMap<>();
|
this.intersectionClients = new HashMap<>();
|
||||||
this.currentTime = 0.0;
|
|
||||||
this.vehicleCounter = 0;
|
this.vehicleCounter = 0;
|
||||||
this.running = false;
|
this.running = false;
|
||||||
this.nextGenerationTime = 0.0;
|
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("Coordinator initialized with configuration:");
|
||||||
System.out.println(" - Simulation duration: " + config.getSimulationDuration() + "s");
|
System.out.println(" - Simulation duration: " + config.getSimulationDuration() + "s");
|
||||||
System.out.println(" - Arrival model: " + config.getArrivalModel());
|
System.out.println(" - Arrival model: " + config.getArrivalModel());
|
||||||
System.out.println(" - Arrival rate: " + config.getArrivalRate() + " vehicles/s");
|
System.out.println(" - Arrival rate: " + config.getArrivalRate() + " vehicles/s");
|
||||||
|
System.out.println(" - DES Mode: ENABLED (Event-driven, no time-stepping)");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void initialize() {
|
public void initialize() {
|
||||||
@@ -107,58 +128,151 @@ public class CoordinatorProcess {
|
|||||||
|
|
||||||
public void run() {
|
public void run() {
|
||||||
double duration = config.getSimulationDuration();
|
double duration = config.getSimulationDuration();
|
||||||
|
double drainTime = config.getDrainTime();
|
||||||
|
double totalDuration = duration + drainTime;
|
||||||
running = true;
|
running = true;
|
||||||
|
|
||||||
System.out.println("Starting vehicle generation simulation...");
|
System.out.println("Starting DES-based vehicle generation simulation...");
|
||||||
System.out.println("Duration: " + duration + " seconds");
|
System.out.println("Duration: " + duration + "s (+ " + drainTime + "s drain)");
|
||||||
System.out.println();
|
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
|
// Send simulation start time to all processes for synchronization
|
||||||
sendSimulationStartTime();
|
sendSimulationStartTime();
|
||||||
|
|
||||||
nextGenerationTime = vehicleGenerator.getNextArrivalTime(currentTime);
|
// Schedule first vehicle generation event
|
||||||
final double TIME_STEP = 0.1;
|
double firstArrivalTime = vehicleGenerator.getNextArrivalTime(clock.getCurrentTime());
|
||||||
|
eventQueue.schedule(new SimulationEvent(
|
||||||
|
firstArrivalTime,
|
||||||
|
DESEventType.VEHICLE_GENERATION,
|
||||||
|
null,
|
||||||
|
"Coordinator"));
|
||||||
|
|
||||||
double drainTime = config.getDrainTime();
|
// Schedule simulation end event
|
||||||
double totalDuration = duration + drainTime;
|
eventQueue.schedule(new SimulationEvent(
|
||||||
boolean draining = false;
|
totalDuration,
|
||||||
|
DESEventType.SIMULATION_END,
|
||||||
|
null,
|
||||||
|
"Coordinator"));
|
||||||
|
|
||||||
while (running && currentTime < totalDuration) {
|
System.out.printf("Initial event scheduled at t=%.3fs\n", firstArrivalTime);
|
||||||
// Only generate vehicles during the main duration
|
System.out.println("Entering DES event loop...\n");
|
||||||
if (currentTime < duration) {
|
|
||||||
if (currentTime >= nextGenerationTime) {
|
// Main DES loop - process events in chronological order
|
||||||
generateAndSendVehicle();
|
double lastTime = 0.0;
|
||||||
nextGenerationTime = vehicleGenerator.getNextArrivalTime(currentTime);
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else if (!draining) {
|
lastTime = event.getTimestamp();
|
||||||
draining = true;
|
|
||||||
System.out.println("\n[t=" + String.format("%.2f", currentTime)
|
|
||||||
+ "] Generation complete. Entering DRAIN MODE for " + drainTime + "s...");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
// Advance simulation time to event time
|
||||||
Thread.sleep((long) (TIME_STEP * 1000));
|
clock.advanceTo(event.getTimestamp());
|
||||||
} catch (InterruptedException e) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
currentTime += TIME_STEP;
|
// Process the event
|
||||||
|
processEvent(event, duration);
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println();
|
System.out.println();
|
||||||
System.out.println("Simulation complete at t=" + String.format("%.2f", currentTime) + "s");
|
System.out.printf("Simulation complete at t=%.2fs\n", clock.getCurrentTime());
|
||||||
System.out.println("Total vehicles generated: " + vehicleCounter);
|
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();
|
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() {
|
private void generateAndSendVehicle() {
|
||||||
|
double currentTime = clock.getCurrentTime();
|
||||||
Vehicle vehicle = vehicleGenerator.generateVehicle("V" + (++vehicleCounter), currentTime);
|
Vehicle vehicle = vehicleGenerator.generateVehicle("V" + (++vehicleCounter), currentTime);
|
||||||
|
|
||||||
System.out.printf("[t=%.2f] Vehicle %s generated (type=%s, route=%s)%n",
|
System.out.printf("[t=%.2f] Vehicle %s generated (type=%s, route=%s)%n",
|
||||||
currentTime, vehicle.getId(), vehicle.getType(), vehicle.getRoute());
|
currentTime, vehicle.getId(), vehicle.getType(), vehicle.getRoute());
|
||||||
|
|
||||||
|
// 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
|
// Send generation count to dashboard
|
||||||
sendGenerationStatsToDashboard();
|
sendGenerationStatsToDashboard();
|
||||||
|
|
||||||
|
|||||||
@@ -10,10 +10,10 @@ import sd.serialization.SerializationException;
|
|||||||
import sd.serialization.SerializerFactory;
|
import sd.serialization.SerializerFactory;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Socket client for communication with a single intersection process.
|
* Cliente socket para comunicação com um processo de interseção.
|
||||||
*
|
*
|
||||||
* Handles a persistent TCP connection to one intersection,
|
* <p>Gere uma ligação TCP persistente para uma interseção,
|
||||||
* providing a simple way to send serialized messages.
|
* fornecendo uma forma simples de enviar mensagens serializadas.</p>
|
||||||
*/
|
*/
|
||||||
public class SocketClient {
|
public class SocketClient {
|
||||||
|
|
||||||
@@ -25,11 +25,11 @@ public class SocketClient {
|
|||||||
private MessageSerializer serializer;
|
private MessageSerializer serializer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new SocketClient for a given intersection.
|
* Cria um novo cliente socket para uma interseção.
|
||||||
*
|
*
|
||||||
* @param intersectionId Intersection ID (ex. "Cr1")
|
* @param intersectionId ID da interseção (ex: "Cr1")
|
||||||
* @param host Host address (ex. "localhost")
|
* @param host endereço do host (ex: "localhost")
|
||||||
* @param port Port number
|
* @param port número da porta
|
||||||
*/
|
*/
|
||||||
public SocketClient(String intersectionId, String host, int port) {
|
public SocketClient(String intersectionId, String host, int port) {
|
||||||
this.intersectionId = intersectionId;
|
this.intersectionId = intersectionId;
|
||||||
@@ -39,11 +39,10 @@ public class SocketClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connects to the intersection process via TCP.
|
* Liga-se ao processo da interseção via TCP.
|
||||||
*
|
*
|
||||||
* @throws IOException if the connection cannot be established
|
* @throws IOException se a ligação não puder ser estabelecida
|
||||||
*/
|
*/
|
||||||
|
|
||||||
public void connect() throws IOException {
|
public void connect() throws IOException {
|
||||||
try {
|
try {
|
||||||
socket = new Socket(host, port);
|
socket = new Socket(host, port);
|
||||||
@@ -56,12 +55,12 @@ public class SocketClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends a message to the connected intersection.
|
* Envia uma mensagem para a interseção ligada.
|
||||||
* The message is serialized and written over the socket.
|
* A mensagem é serializada e enviada pelo socket.
|
||||||
*
|
*
|
||||||
* @param message The message to send
|
* @param message mensagem a enviar
|
||||||
* @throws SerializationException if serialization fails
|
* @throws SerializationException se a serialização falhar
|
||||||
* @throws IOException if the socket write fails
|
* @throws IOException se a escrita no socket falhar
|
||||||
*/
|
*/
|
||||||
public void send(Message message) throws SerializationException, IOException {
|
public void send(Message message) throws SerializationException, IOException {
|
||||||
if (socket == null || socket.isClosed()) {
|
if (socket == null || socket.isClosed()) {
|
||||||
@@ -71,7 +70,6 @@ public class SocketClient {
|
|||||||
try {
|
try {
|
||||||
byte[] data = serializer.serialize(message);
|
byte[] data = serializer.serialize(message);
|
||||||
|
|
||||||
// Prefix with message length (so receiver knows how much to read)
|
|
||||||
int length = data.length;
|
int length = data.length;
|
||||||
outputStream.write((length >> 24) & 0xFF);
|
outputStream.write((length >> 24) & 0xFF);
|
||||||
outputStream.write((length >> 16) & 0xFF);
|
outputStream.write((length >> 16) & 0xFF);
|
||||||
|
|||||||
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,8 +10,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
|||||||
import sd.config.SimulationConfig;
|
import sd.config.SimulationConfig;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Aggregates and displays real-time statistics from all simulation processes.
|
* Agrega e apresenta estatísticas em tempo real de todos os processos da simulação.
|
||||||
* Uses a thread pool to handle concurrent client connections.
|
* Usa um thread pool para gerir ligações concorrentes de clientes.
|
||||||
*/
|
*/
|
||||||
public class DashboardServer {
|
public class DashboardServer {
|
||||||
|
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ import java.util.concurrent.atomic.AtomicLong;
|
|||||||
import sd.model.VehicleType;
|
import sd.model.VehicleType;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Thread-safe storage for aggregated simulation statistics.
|
* Armazenamento thread-safe de estatísticas agregadas da simulação.
|
||||||
* Uses atomic types and concurrent collections for lock-free updates.
|
* Usa tipos atómicos e coleções concorrentes para atualizações sem locks.
|
||||||
*/
|
*/
|
||||||
public class DashboardStatistics {
|
public class DashboardStatistics {
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import javafx.geometry.Pos;
|
|||||||
import javafx.scene.Scene;
|
import javafx.scene.Scene;
|
||||||
import javafx.scene.control.Alert;
|
import javafx.scene.control.Alert;
|
||||||
import javafx.scene.control.Button;
|
import javafx.scene.control.Button;
|
||||||
|
import javafx.scene.control.ComboBox;
|
||||||
import javafx.scene.control.Label;
|
import javafx.scene.control.Label;
|
||||||
import javafx.scene.control.TableColumn;
|
import javafx.scene.control.TableColumn;
|
||||||
import javafx.scene.control.TableView;
|
import javafx.scene.control.TableView;
|
||||||
@@ -54,6 +55,11 @@ public class DashboardUI extends Application {
|
|||||||
// Update scheduler
|
// Update scheduler
|
||||||
private ScheduledExecutorService updateScheduler;
|
private ScheduledExecutorService updateScheduler;
|
||||||
|
|
||||||
|
// Configuration controls
|
||||||
|
private ComboBox<String> configFileSelector;
|
||||||
|
private String selectedConfigFile = "simulation.properties";
|
||||||
|
private Label configInfoLabel;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void start(Stage primaryStage) {
|
public void start(Stage primaryStage) {
|
||||||
try {
|
try {
|
||||||
@@ -122,6 +128,9 @@ public class DashboardUI extends Application {
|
|||||||
Label subtitle = new Label("Real-time Statistics and Monitoring");
|
Label subtitle = new Label("Real-time Statistics and Monitoring");
|
||||||
subtitle.getStyleClass().add("header-subtitle");
|
subtitle.getStyleClass().add("header-subtitle");
|
||||||
|
|
||||||
|
// Configuration Panel
|
||||||
|
VBox configPanel = createConfigurationPanel();
|
||||||
|
|
||||||
// Control Buttons
|
// Control Buttons
|
||||||
HBox controls = new HBox(15);
|
HBox controls = new HBox(15);
|
||||||
controls.setAlignment(Pos.CENTER);
|
controls.setAlignment(Pos.CENTER);
|
||||||
@@ -137,9 +146,12 @@ public class DashboardUI extends Application {
|
|||||||
|
|
||||||
btnStart.setOnAction(e -> {
|
btnStart.setOnAction(e -> {
|
||||||
try {
|
try {
|
||||||
|
// Passar o ficheiro de configuração selecionado
|
||||||
|
processManager.setConfigFile(selectedConfigFile);
|
||||||
processManager.startSimulation();
|
processManager.startSimulation();
|
||||||
btnStart.setDisable(true);
|
btnStart.setDisable(true);
|
||||||
btnStop.setDisable(false);
|
btnStop.setDisable(false);
|
||||||
|
configFileSelector.setDisable(true); // Bloquear mudanças durante simulação
|
||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
showErrorAlert("Start Failed", "Could not start simulation processes: " + ex.getMessage());
|
showErrorAlert("Start Failed", "Could not start simulation processes: " + ex.getMessage());
|
||||||
}
|
}
|
||||||
@@ -149,15 +161,74 @@ public class DashboardUI extends Application {
|
|||||||
processManager.stopSimulation();
|
processManager.stopSimulation();
|
||||||
btnStart.setDisable(false);
|
btnStart.setDisable(false);
|
||||||
btnStop.setDisable(true);
|
btnStop.setDisable(true);
|
||||||
|
configFileSelector.setDisable(false); // Desbloquear para nova simulação
|
||||||
});
|
});
|
||||||
|
|
||||||
controls.getChildren().addAll(btnStart, btnStop);
|
controls.getChildren().addAll(btnStart, btnStop);
|
||||||
|
|
||||||
header.getChildren().addAll(title, subtitle, controls);
|
header.getChildren().addAll(title, subtitle, configPanel, controls);
|
||||||
|
|
||||||
return header;
|
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() {
|
private VBox createMainContent() {
|
||||||
VBox mainContent = new VBox(20);
|
VBox mainContent = new VBox(20);
|
||||||
mainContent.setPadding(new Insets(20));
|
mainContent.setPadding(new Insets(20));
|
||||||
@@ -333,7 +404,7 @@ public class DashboardUI extends Application {
|
|||||||
updateScheduler = Executors.newSingleThreadScheduledExecutor();
|
updateScheduler = Executors.newSingleThreadScheduledExecutor();
|
||||||
updateScheduler.scheduleAtFixedRate(() -> {
|
updateScheduler.scheduleAtFixedRate(() -> {
|
||||||
Platform.runLater(this::updateUI);
|
Platform.runLater(this::updateUI);
|
||||||
}, 0, 5, TimeUnit.SECONDS);
|
}, 0, 100, TimeUnit.MILLISECONDS);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void updateUI() {
|
private void updateUI() {
|
||||||
@@ -367,6 +438,28 @@ public class DashboardUI extends Application {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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() {
|
private void shutdown() {
|
||||||
System.out.println("Shutting down Dashboard UI...");
|
System.out.println("Shutting down Dashboard UI...");
|
||||||
|
|
||||||
|
|||||||
@@ -6,25 +6,36 @@ import java.util.ArrayList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Manages the lifecycle of simulation processes (Intersections, Exit Node,
|
* Gere o ciclo de vida dos processos de simulação (Intersections, Exit Node,
|
||||||
* Coordinator).
|
* Coordinator).
|
||||||
* Allows starting and stopping the distributed simulation from within the Java
|
* Permite iniciar e parar a simulação distribuída dentro da aplicação Java.
|
||||||
* application.
|
|
||||||
*/
|
*/
|
||||||
public class SimulationProcessManager {
|
public class SimulationProcessManager {
|
||||||
|
|
||||||
private final List<Process> runningProcesses;
|
private final List<Process> runningProcesses;
|
||||||
private final String classpath;
|
private final String classpath;
|
||||||
|
private String configFile;
|
||||||
|
|
||||||
public SimulationProcessManager() {
|
public SimulationProcessManager() {
|
||||||
this.runningProcesses = new ArrayList<>();
|
this.runningProcesses = new ArrayList<>();
|
||||||
this.classpath = System.getProperty("java.class.path");
|
this.classpath = System.getProperty("java.class.path");
|
||||||
|
this.configFile = "src/main/resources/simulation.properties";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Starts the full simulation: 5 Intersections, 1 Exit Node, and 1 Coordinator.
|
* Define o ficheiro de configuração a usar.
|
||||||
*
|
*
|
||||||
* @throws IOException If a process fails to start.
|
* @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 {
|
public void startSimulation() throws IOException {
|
||||||
if (!runningProcesses.isEmpty()) {
|
if (!runningProcesses.isEmpty()) {
|
||||||
@@ -83,30 +94,36 @@ public class SimulationProcessManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper to start a single Java process.
|
* Helper para iniciar um único processo Java.
|
||||||
*/
|
*/
|
||||||
private void startProcess(String className, String arg) throws IOException {
|
private void startProcess(String className, String arg) throws IOException {
|
||||||
String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
|
String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
|
||||||
|
|
||||||
ProcessBuilder builder;
|
ProcessBuilder builder;
|
||||||
if (arg != null) {
|
if (arg != null) {
|
||||||
builder = new ProcessBuilder(javaBin, "-cp", classpath, className, arg);
|
builder = new ProcessBuilder(javaBin, "-cp", classpath, className, arg, configFile);
|
||||||
} else {
|
} else {
|
||||||
builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
|
builder = new ProcessBuilder(javaBin, "-cp", classpath, className, configFile);
|
||||||
}
|
}
|
||||||
|
|
||||||
// this is a linux thing - not sure about windows
|
// 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";
|
String logName = className.substring(className.lastIndexOf('.') + 1) + (arg != null ? "-" + arg : "") + ".log";
|
||||||
File logFile = new File("/tmp/" + logName);
|
|
||||||
|
// use the (File parent, String child) constructor to handle slash/backslash
|
||||||
|
// automatically
|
||||||
|
File logFile = new File(tempDir, logName);
|
||||||
|
|
||||||
builder.redirectOutput(logFile);
|
builder.redirectOutput(logFile);
|
||||||
builder.redirectError(logFile);
|
builder.redirectError(logFile);
|
||||||
|
|
||||||
Process process = builder.start();
|
Process process = builder.start();
|
||||||
runningProcesses.add(process);
|
runningProcesses.add(process);
|
||||||
System.out.println("Started " + className + (arg != null ? " " + arg : ""));
|
System.out.println("Started " + className + (arg != null ? " " + arg : ""));
|
||||||
}
|
// print where the logs are actually going
|
||||||
|
System.out.println("Logs redirected to: " + logFile.getAbsolutePath());
|
||||||
public boolean isSimulationRunning() {
|
|
||||||
return !runningProcesses.isEmpty() && runningProcesses.stream().anyMatch(Process::isAlive);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ import java.util.Map;
|
|||||||
import sd.model.VehicleType;
|
import sd.model.VehicleType;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Data transfer object for statistics updates to the dashboard.
|
* DTO para atualizações de estatísticas ao dashboard.
|
||||||
* Use -1 for fields not being updated in this message.
|
* Campos com valor -1 não são atualizados nesta mensagem.
|
||||||
*/
|
*/
|
||||||
public class StatsUpdatePayload implements Serializable {
|
public class StatsUpdatePayload implements Serializable {
|
||||||
|
|
||||||
|
|||||||
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
package sd.engine;
|
|
||||||
|
|
||||||
import sd.IntersectionProcess;
|
|
||||||
import sd.config.SimulationConfig;
|
|
||||||
import sd.model.TrafficLight;
|
|
||||||
import sd.model.TrafficLightState;
|
|
||||||
import sd.model.Vehicle;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Implements the control logic for a single TrafficLight
|
|
||||||
* as a Runnable task that runs in its own Thread.
|
|
||||||
*/
|
|
||||||
public class TrafficLightThread implements Runnable {
|
|
||||||
|
|
||||||
private final TrafficLight light;
|
|
||||||
private final IntersectionProcess process;
|
|
||||||
private final SimulationConfig config;
|
|
||||||
private volatile boolean running;
|
|
||||||
|
|
||||||
// Store the thread reference for proper interruption
|
|
||||||
private Thread currentThread;
|
|
||||||
|
|
||||||
public TrafficLightThread(TrafficLight light, IntersectionProcess process, SimulationConfig config) {
|
|
||||||
this.light = light;
|
|
||||||
this.process = process;
|
|
||||||
this.config = config;
|
|
||||||
this.running = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
this.currentThread = Thread.currentThread();
|
|
||||||
this.running = true;
|
|
||||||
System.out.println("[" + light.getId() + "] Traffic light thread started.");
|
|
||||||
|
|
||||||
try {
|
|
||||||
while (running && !Thread.currentThread().isInterrupted()) {
|
|
||||||
|
|
||||||
// Request permission to turn green (blocks until granted)
|
|
||||||
process.requestGreenLight(light.getDirection());
|
|
||||||
|
|
||||||
try {
|
|
||||||
// --- GREEN Phase ---
|
|
||||||
light.changeState(TrafficLightState.GREEN);
|
|
||||||
System.out.println("[" + light.getId() + "] State: GREEN");
|
|
||||||
|
|
||||||
// Process queue for the duration of the green light
|
|
||||||
long greenDurationMs = (long) (light.getGreenTime() * 1000);
|
|
||||||
processGreenLightQueue(greenDurationMs);
|
|
||||||
|
|
||||||
if (!running || Thread.currentThread().isInterrupted())
|
|
||||||
break;
|
|
||||||
|
|
||||||
// --- RED Phase ---
|
|
||||||
light.changeState(TrafficLightState.RED);
|
|
||||||
System.out.println("[" + light.getId() + "] State: RED");
|
|
||||||
|
|
||||||
} finally {
|
|
||||||
// Always release the green light permission
|
|
||||||
process.releaseGreenLight(light.getDirection());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wait for red duration
|
|
||||||
Thread.sleep((long) (light.getRedTime() * 1000));
|
|
||||||
}
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
System.out.println("[" + light.getId() + "] Traffic light thread interrupted.");
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
} finally {
|
|
||||||
this.running = false;
|
|
||||||
System.out.println("[" + light.getId() + "] Traffic light thread stopped.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void processGreenLightQueue(long greenDurationMs) throws InterruptedException {
|
|
||||||
long startTime = System.currentTimeMillis();
|
|
||||||
|
|
||||||
while (running && !Thread.currentThread().isInterrupted()
|
|
||||||
&& light.getState() == TrafficLightState.GREEN) {
|
|
||||||
|
|
||||||
// Check if green time has expired
|
|
||||||
long elapsed = System.currentTimeMillis() - startTime;
|
|
||||||
if (elapsed >= greenDurationMs) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (light.getQueueSize() > 0) {
|
|
||||||
Vehicle vehicle = light.removeVehicle();
|
|
||||||
|
|
||||||
if (vehicle != null) {
|
|
||||||
double crossingTime = getCrossingTimeForVehicle(vehicle);
|
|
||||||
long crossingTimeMs = (long) (crossingTime * 1000);
|
|
||||||
|
|
||||||
Thread.sleep(crossingTimeMs);
|
|
||||||
|
|
||||||
vehicle.addCrossingTime(crossingTime);
|
|
||||||
process.getIntersection().incrementVehiclesSent();
|
|
||||||
process.sendVehicleToNextDestination(vehicle);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Queue is empty, wait briefly for new vehicles or until time expires
|
|
||||||
Thread.sleep(50);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private double getCrossingTimeForVehicle(Vehicle vehicle) {
|
|
||||||
return switch (vehicle.getType()) {
|
|
||||||
case BIKE -> config.getBikeVehicleCrossingTime();
|
|
||||||
case LIGHT -> config.getLightVehicleCrossingTime();
|
|
||||||
case HEAVY -> config.getHeavyVehicleCrossingTime();
|
|
||||||
default -> config.getLightVehicleCrossingTime();
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Requests the thread to stop gracefully.
|
|
||||||
* Sets the running flag and interrupts the thread to unblock any sleep() calls.
|
|
||||||
*/
|
|
||||||
public void shutdown() {
|
|
||||||
this.running = false;
|
|
||||||
if (currentThread != null && currentThread.isAlive()) {
|
|
||||||
currentThread.interrupt();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,65 +6,51 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents an intersection in the traffic simulation.
|
* Representa uma interseção na simulação de tráfego.
|
||||||
* * An Intersection acts as a central hub. It does not control logic itself,
|
*
|
||||||
* but it *owns* and *manages* a set of {@link TrafficLight} objects.
|
* <p>Uma interseção funciona como um nó central da rede. Não controla lógica diretamente,
|
||||||
* * Its primary responsibilities are:
|
* mas gere um conjunto de semáforos ({@link TrafficLight}).</p>
|
||||||
* 1. Holding a {@link TrafficLight} for each direction ("North", "East", etc.).
|
*
|
||||||
* 2. Maintaining a {@code routing} table that maps a vehicle's *next*
|
* <p>Responsabilidades principais:</p>
|
||||||
* destination (e.g., "Cr3") to a specific *direction* at *this*
|
* <ul>
|
||||||
* intersection (e.g., "East").
|
* <li>Manter um {@link TrafficLight} para cada direção (Norte, Este, etc.)</li>
|
||||||
* 3. Receiving incoming vehicles and placing them in the correct
|
* <li>Gerir uma tabela de encaminhamento que mapeia destinos para direções</li>
|
||||||
* traffic light's queue based on the routing table.
|
* <li>Receber veículos e colocá-los na fila do semáforo correto</li>
|
||||||
* 4. Tracking aggregate statistics for all traffic passing through it.
|
* <li>Acompanhar estatísticas agregadas do tráfego</li>
|
||||||
|
* </ul>
|
||||||
*/
|
*/
|
||||||
public class Intersection {
|
public class Intersection {
|
||||||
|
|
||||||
// --- Identity and configuration ---
|
/** Identificador único da interseção (ex: "Cr1", "Cr2") */
|
||||||
|
|
||||||
/**
|
|
||||||
* Unique identifier for the intersection (e.g., "Cr1", "Cr2").
|
|
||||||
*/
|
|
||||||
private final String id;
|
private final String id;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A map holding all traffic lights managed by this intersection.
|
* Mapa com todos os semáforos desta interseção.
|
||||||
* Key: Direction (String, e.g., "North", "East").
|
* Chave: Direção (String, ex: "Norte", "Este")
|
||||||
* Value: The {@link TrafficLight} object for that direction.
|
* Valor: Objeto {@link TrafficLight} correspondente
|
||||||
*/
|
*/
|
||||||
private final Map<String, TrafficLight> trafficLights;
|
private final Map<String, TrafficLight> trafficLights;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The routing table for this intersection.
|
* Tabela de encaminhamento da interseção.
|
||||||
* Key: The *next* destination ID (String, e.g., "Cr3", "S" for exit).
|
* Chave: Próximo destino (String, ex: "Cr3", "S" para saída)
|
||||||
* Value: The *direction* (String, e.g., "East") a vehicle must take
|
* Valor: Direção que o veículo deve tomar nesta interseção
|
||||||
* at *this* intersection to reach that destination.
|
|
||||||
*/
|
*/
|
||||||
private final Map<String, String> routing;
|
private final Map<String, String> routing;
|
||||||
|
/** Número total de veículos recebidos por esta interseção */
|
||||||
// --- Statistics ---
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Total number of vehicles that have been received by this intersection.
|
|
||||||
*/
|
|
||||||
private int totalVehiclesReceived;
|
private int totalVehiclesReceived;
|
||||||
|
|
||||||
/**
|
/** Número total de veículos que partiram desta interseção */
|
||||||
* Total number of vehicles that have successfully passed through (sent from) this intersection.
|
|
||||||
*/
|
|
||||||
private int totalVehiclesSent;
|
private int totalVehiclesSent;
|
||||||
|
|
||||||
/**
|
/** Média acumulada do tempo de espera dos veículos nesta interseção */
|
||||||
* A running average of the waiting time for vehicles at this intersection.
|
|
||||||
* Note: This calculation might be simplified.
|
|
||||||
*/
|
|
||||||
private double averageWaitingTime;
|
private double averageWaitingTime;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new Intersection with a given ID.
|
* Cria uma nova interseção.
|
||||||
* Initializes empty maps for traffic lights and routing.
|
* Inicializa mapas vazios para semáforos e encaminhamento.
|
||||||
*
|
*
|
||||||
* @param id The unique identifier for this intersection (e.g., "Cr1").
|
* @param id identificador único da interseção (ex: "Cr1")
|
||||||
*/
|
*/
|
||||||
public Intersection(String id) {
|
public Intersection(String id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
@@ -76,40 +62,41 @@ public class Intersection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Registers a new {@link TrafficLight} with this intersection.
|
* Regista um novo semáforo nesta interseção.
|
||||||
* The light is mapped by its direction.
|
* O semáforo é mapeado pela sua direção.
|
||||||
*
|
*
|
||||||
* @param trafficLight The {@link TrafficLight} object to add.
|
* @param trafficLight o semáforo a adicionar
|
||||||
*/
|
*/
|
||||||
public void addTrafficLight(TrafficLight trafficLight) {
|
public void addTrafficLight(TrafficLight trafficLight) {
|
||||||
trafficLights.put(trafficLight.getDirection(), trafficLight);
|
trafficLights.put(trafficLight.getDirection(), trafficLight);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Defines a routing rule for this intersection.
|
* Define uma regra de encaminhamento para esta interseção.
|
||||||
* * This method builds the routing table. For example, calling
|
*
|
||||||
* {@code configureRoute("Cr3", "East")} means "Any vehicle
|
* <p>Por exemplo, {@code configureRoute("Cr3", "Este")} significa:
|
||||||
* arriving here whose next destination is 'Cr3' should be sent to
|
* "Qualquer veículo que chegue aqui com destino 'Cr3' deve ser enviado
|
||||||
* the 'East' traffic light queue."
|
* para a fila do semáforo da direção Este."</p>
|
||||||
*
|
*
|
||||||
* @param nextDestination The ID of the *next* intersection or exit (e.g., "Cr3", "S").
|
* @param nextDestination ID da próxima interseção ou saída (ex: "Cr3", "S")
|
||||||
* @param direction The direction (and thus, the traffic light)
|
* @param direction direção (e respetivo semáforo) a usar nesta interseção
|
||||||
* at *this* intersection to use (e.g., "East").
|
|
||||||
*/
|
*/
|
||||||
public void configureRoute(String nextDestination, String direction) {
|
public void configureRoute(String nextDestination, String direction) {
|
||||||
routing.put(nextDestination, direction);
|
routing.put(nextDestination, direction);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Accepts an incoming vehicle and places it in the correct queue.
|
* Recebe um veículo e coloca-o na fila correta.
|
||||||
* * This method:
|
*
|
||||||
* 1. Increments the {@link #totalVehiclesReceived} counter.
|
* <p>Passos executados:</p>
|
||||||
* 2. Advances the vehicle's route (since it just arrived here)
|
* <ol>
|
||||||
* 3. Gets the vehicle's *next* destination (from {@link Vehicle#getCurrentDestination()}).
|
* <li>Incrementa o contador de veículos recebidos</li>
|
||||||
* 4. Uses the {@link #routing} map to find the correct *direction* for that destination.
|
* <li>Obtém o próximo destino do veículo</li>
|
||||||
* 5. Adds the vehicle to the queue of the {@link TrafficLight} for that direction.
|
* <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 The {@link Vehicle} arriving at the intersection.
|
* @param vehicle o veículo que chega à interseção
|
||||||
*/
|
*/
|
||||||
public void receiveVehicle(Vehicle vehicle) {
|
public void receiveVehicle(Vehicle vehicle) {
|
||||||
totalVehiclesReceived++;
|
totalVehiclesReceived++;
|
||||||
@@ -141,115 +128,99 @@ public class Intersection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the direction a vehicle should take to reach a given destination.
|
* Retorna a direção que um veículo deve tomar para alcançar um destino.
|
||||||
*
|
*
|
||||||
* @param destination The next destination (e.g., "Cr3", "S").
|
* @param destination o próximo destino (ex: "Cr3", "S")
|
||||||
* @return The direction (e.g., "East"), or null if no route is configured.
|
* @return a direção (ex: "Este"), ou null se não houver rota configurada
|
||||||
*/
|
*/
|
||||||
public String getDirectionForDestination(String destination) {
|
public String getDirectionForDestination(String destination) {
|
||||||
return routing.get(destination);
|
return routing.get(destination);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the traffic light controlling the given direction.
|
* Retorna o semáforo que controla uma determinada direção.
|
||||||
*
|
*
|
||||||
* @param direction The direction (e.g., "North").
|
* @param direction a direção (ex: "Norte")
|
||||||
* @return The {@link TrafficLight} object, or null if no light exists
|
* @return o objeto {@link TrafficLight}, ou null se não existir
|
||||||
* for that direction.
|
|
||||||
*/
|
*/
|
||||||
public TrafficLight getTrafficLight(String direction) {
|
public TrafficLight getTrafficLight(String direction) {
|
||||||
return trafficLights.get(direction);
|
return trafficLights.get(direction);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a list of all traffic lights managed by this intersection.
|
* Retorna uma lista com todos os semáforos desta interseção.
|
||||||
*
|
*
|
||||||
* @return A new {@link List} containing all {@link TrafficLight} objects.
|
* @return uma nova {@link List} com todos os semáforos
|
||||||
*/
|
*/
|
||||||
public List<TrafficLight> getTrafficLights() {
|
public List<TrafficLight> getTrafficLights() {
|
||||||
// Return a copy to prevent external modification of the internal map's values
|
|
||||||
return new ArrayList<>(trafficLights.values());
|
return new ArrayList<>(trafficLights.values());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the total number of vehicles currently queued across *all*
|
* Retorna o número total de veículos em fila em todos os semáforos.
|
||||||
* traffic lights at this intersection.
|
* Usa Java Stream API para somar os tamanhos de todas as filas.
|
||||||
*
|
*
|
||||||
* @return The sum of all queue sizes.
|
* @return a soma dos tamanhos de todas as filas
|
||||||
*/
|
*/
|
||||||
public int getTotalQueueSize() {
|
public int getTotalQueueSize() {
|
||||||
// Uses Java Stream API:
|
|
||||||
// 1. trafficLights.values().stream() - Get a stream of TrafficLight objects
|
|
||||||
// 2. .mapToInt(TrafficLight::getQueueSize) - Convert each light to its queue size (an int)
|
|
||||||
// 3. .sum() - Sum all the integers
|
|
||||||
return trafficLights.values().stream()
|
return trafficLights.values().stream()
|
||||||
.mapToInt(TrafficLight::getQueueSize)
|
.mapToInt(TrafficLight::getQueueSize)
|
||||||
.sum();
|
.sum();
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Stats and getters ---
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return The unique ID of this intersection.
|
* @return o identificador único desta interseção
|
||||||
*/
|
*/
|
||||||
public String getId() {
|
public String getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return The total number of vehicles that have arrived at this intersection.
|
* @return o número total de veículos que chegaram a esta interseção
|
||||||
*/
|
*/
|
||||||
public int getTotalVehiclesReceived() {
|
public int getTotalVehiclesReceived() {
|
||||||
return totalVehiclesReceived;
|
return totalVehiclesReceived;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return The total number of vehicles that have successfully
|
* @return o número total de veículos que partiram desta interseção
|
||||||
* departed from this intersection.
|
|
||||||
*/
|
*/
|
||||||
public int getTotalVehiclesSent() {
|
public int getTotalVehiclesSent() {
|
||||||
return totalVehiclesSent;
|
return totalVehiclesSent;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Increments the counter for vehicles that have successfully departed.
|
* Incrementa o contador de veículos que partiram com sucesso.
|
||||||
* This is typically called by the {@link sd.engine.SimulationEngine}
|
* Tipicamente chamado após um veículo completar a travessia.
|
||||||
* after a vehicle finishes crossing.
|
|
||||||
*/
|
*/
|
||||||
public void incrementVehiclesSent() {
|
public void incrementVehiclesSent() {
|
||||||
totalVehiclesSent++;
|
totalVehiclesSent++;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return The running average of vehicle waiting time at this intersection.
|
* @return a média do tempo de espera dos veículos nesta interseção
|
||||||
*/
|
*/
|
||||||
public double getAverageWaitingTime() {
|
public double getAverageWaitingTime() {
|
||||||
return averageWaitingTime;
|
return averageWaitingTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates the running average waiting time with a new sample (a new
|
* Atualiza a média do tempo de espera com uma nova amostra.
|
||||||
* vehicle's wait time).
|
* Usa a fórmula: Nova Média = (Média Antiga * (N-1) + Novo Valor) / N
|
||||||
* * Uses an incremental/weighted average formula:
|
|
||||||
* NewAvg = (OldAvg * (N-1) + NewValue) / N
|
|
||||||
* where N is the total number of vehicles sent.
|
|
||||||
*
|
*
|
||||||
* @param newTime The waiting time (in seconds) of the vehicle that just
|
* @param newTime tempo de espera (em segundos) do veículo que acabou de partir
|
||||||
* departed.
|
|
||||||
*/
|
*/
|
||||||
public void updateAverageWaitingTime(double newTime) {
|
public void updateAverageWaitingTime(double newTime) {
|
||||||
// Avoid division by zero if this is called before any vehicle is sent
|
|
||||||
if (totalVehiclesSent > 0) {
|
if (totalVehiclesSent > 0) {
|
||||||
averageWaitingTime = (averageWaitingTime * (totalVehiclesSent - 1) + newTime)
|
averageWaitingTime = (averageWaitingTime * (totalVehiclesSent - 1) + newTime)
|
||||||
/ totalVehiclesSent;
|
/ totalVehiclesSent;
|
||||||
} else if (totalVehiclesSent == 1) {
|
} else if (totalVehiclesSent == 1) {
|
||||||
// This is the first vehicle
|
|
||||||
averageWaitingTime = newTime;
|
averageWaitingTime = newTime;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return A string summary of the intersection's current state.
|
* @return representação textual do estado atual da interseção
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
|
|||||||
@@ -5,52 +5,41 @@ import java.util.UUID;
|
|||||||
import sd.protocol.MessageProtocol;
|
import sd.protocol.MessageProtocol;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents a message exchanged between processes in the distributed simulation.
|
* Representa uma mensagem trocada entre processos na simulação distribuída.
|
||||||
* Each message has a unique ID, a type, a sender, a destination, and a payload.
|
*
|
||||||
* This class implements {@link MessageProtocol} which extends Serializable for network transmission.
|
* <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 {
|
public class Message implements MessageProtocol {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
/**
|
/** Identificador único desta mensagem */
|
||||||
* Unique identifier for this message.
|
|
||||||
*/
|
|
||||||
private final String messageId;
|
private final String messageId;
|
||||||
|
|
||||||
/**
|
/** Tipo desta mensagem (ex: VEHICLE_TRANSFER, STATS_UPDATE) */
|
||||||
* The type of this message (e.g., VEHICLE_TRANSFER, STATS_UPDATE).
|
|
||||||
*/
|
|
||||||
private final MessageType type;
|
private final MessageType type;
|
||||||
|
|
||||||
/**
|
/** Identificador do processo que enviou esta mensagem */
|
||||||
* Identifier of the process that sent this message.
|
|
||||||
*/
|
|
||||||
private final String senderId;
|
private final String senderId;
|
||||||
|
|
||||||
/**
|
/** Identificador do processo de destino (pode ser null para broadcast) */
|
||||||
* Identifier of the destination process. Can be null for broadcast messages.
|
|
||||||
*/
|
|
||||||
private final String destinationId;
|
private final String destinationId;
|
||||||
|
|
||||||
/**
|
/** Dados a serem transmitidos (o tipo depende do tipo de mensagem) */
|
||||||
* The actual data being transmitted. Type depends on the message type.
|
|
||||||
*/
|
|
||||||
private final Object payload;
|
private final Object payload;
|
||||||
|
|
||||||
/**
|
/** Timestamp de criação da mensagem (tempo de simulação ou real) */
|
||||||
* Timestamp when this message was created (simulation time or real time).
|
|
||||||
*/
|
|
||||||
private final long timestamp;
|
private final long timestamp;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new message with all parameters.
|
* Cria uma nova mensagem com todos os parâmetros.
|
||||||
*
|
*
|
||||||
* @param type The message type
|
* @param type tipo da mensagem
|
||||||
* @param senderId The ID of the sending process
|
* @param senderId ID do processo remetente
|
||||||
* @param destinationId The ID of the destination process (null for broadcast)
|
* @param destinationId ID do processo de destino (null para broadcast)
|
||||||
* @param payload The message payload
|
* @param payload conteúdo da mensagem
|
||||||
* @param timestamp The timestamp of message creation
|
* @param timestamp timestamp de criação da mensagem
|
||||||
*/
|
*/
|
||||||
public Message(MessageType type, String senderId, String destinationId,
|
public Message(MessageType type, String senderId, String destinationId,
|
||||||
Object payload, long timestamp) {
|
Object payload, long timestamp) {
|
||||||
@@ -63,23 +52,23 @@ public class Message implements MessageProtocol {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new message with current system time as timestamp.
|
* Cria uma nova mensagem usando o tempo atual do sistema como timestamp.
|
||||||
*
|
*
|
||||||
* @param type The message type
|
* @param type tipo da mensagem
|
||||||
* @param senderId The ID of the sending process
|
* @param senderId ID do processo remetente
|
||||||
* @param destinationId The ID of the destination process
|
* @param destinationId ID do processo de destino
|
||||||
* @param payload The message payload
|
* @param payload conteúdo da mensagem
|
||||||
*/
|
*/
|
||||||
public Message(MessageType type, String senderId, String destinationId, Object payload) {
|
public Message(MessageType type, String senderId, String destinationId, Object payload) {
|
||||||
this(type, senderId, destinationId, payload, System.currentTimeMillis());
|
this(type, senderId, destinationId, payload, System.currentTimeMillis());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a broadcast message (no specific destination).
|
* Cria uma mensagem de broadcast (sem destino específico).
|
||||||
*
|
*
|
||||||
* @param type The message type
|
* @param type tipo da mensagem
|
||||||
* @param senderId The ID of the sending process
|
* @param senderId ID do processo remetente
|
||||||
* @param payload The message payload
|
* @param payload conteúdo da mensagem
|
||||||
*/
|
*/
|
||||||
public Message(MessageType type, String senderId, Object payload) {
|
public Message(MessageType type, String senderId, Object payload) {
|
||||||
this(type, senderId, null, payload, System.currentTimeMillis());
|
this(type, senderId, null, payload, System.currentTimeMillis());
|
||||||
|
|||||||
@@ -1,87 +1,43 @@
|
|||||||
package sd.model;
|
package sd.model;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enumeration representing all possible message types for distributed communication.
|
* Enumeração que representa todos os tipos de mensagens possíveis para
|
||||||
* These types are used for inter-process communication between different components
|
* comunicação distribuída.
|
||||||
* of the distributed traffic simulation system.
|
* 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 {
|
public enum MessageType {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Message to transfer a vehicle between intersections or processes.
|
* Mensagem para transferir um veículo entre interseções ou processos.
|
||||||
* Payload: Vehicle object with current state
|
* Payload: Objeto Vehicle com o estado atual
|
||||||
*/
|
*/
|
||||||
VEHICLE_TRANSFER,
|
VEHICLE_TRANSFER,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Message to update statistics across the distributed system.
|
* Mensagem para atualizar estatísticas em todo o sistema distribuído.
|
||||||
* Payload: Statistics data (waiting times, queue sizes, etc.)
|
* Payload: Dados estatísticos (tempos de espera, tamanhos de fila, etc.)
|
||||||
*/
|
*/
|
||||||
STATS_UPDATE,
|
STATS_UPDATE,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Message to synchronize simulation start time across all processes.
|
* Mensagem para sincronizar a hora de início da simulação em todos os
|
||||||
* Payload: Start timestamp (long milliseconds)
|
* processos.
|
||||||
|
* Payload: Timestamp de início (long milissegundos)
|
||||||
*/
|
*/
|
||||||
SIMULATION_START,
|
SIMULATION_START,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Message to synchronize traffic light states between processes.
|
* Mensagem para notificar sobre a geração de um novo veículo.
|
||||||
* Payload: TrafficLight state and timing information
|
* Payload: Parâmetros de geração do veículo
|
||||||
*/
|
|
||||||
TRAFFIC_LIGHT_SYNC,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Heartbeat message to check if a process is alive.
|
|
||||||
* Payload: Process ID and timestamp
|
|
||||||
*/
|
|
||||||
HEARTBEAT,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Request to join the distributed simulation.
|
|
||||||
* Payload: Process information and capabilities
|
|
||||||
*/
|
|
||||||
JOIN_REQUEST,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Response to a join request.
|
|
||||||
* Payload: Acceptance status and configuration
|
|
||||||
*/
|
|
||||||
JOIN_RESPONSE,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Message to notify about a new vehicle generation.
|
|
||||||
* Payload: Vehicle generation parameters
|
|
||||||
*/
|
*/
|
||||||
VEHICLE_SPAWN,
|
VEHICLE_SPAWN,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Message to request the current state of an intersection.
|
* Mensagem para sinalizar o encerramento de um processo.
|
||||||
* Payload: Intersection ID
|
* Payload: ID do processo e motivo
|
||||||
*/
|
|
||||||
STATE_REQUEST,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Response containing the current state of an intersection.
|
|
||||||
* Payload: Complete intersection state
|
|
||||||
*/
|
|
||||||
STATE_RESPONSE,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Message to signal shutdown of a process.
|
|
||||||
* Payload: Process ID and reason
|
|
||||||
*/
|
*/
|
||||||
SHUTDOWN,
|
SHUTDOWN,
|
||||||
|
|
||||||
/**
|
|
||||||
* Acknowledgment message for reliable communication.
|
|
||||||
* Payload: Message ID being acknowledged
|
|
||||||
*/
|
|
||||||
ACK,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Error message to report problems in the distributed system.
|
|
||||||
* Payload: Error description and context
|
|
||||||
*/
|
|
||||||
ERROR
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,114 +9,69 @@ import java.util.concurrent.locks.Lock;
|
|||||||
import java.util.concurrent.locks.ReentrantLock;
|
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 {@link Vehicle} objects and
|
*
|
||||||
* alternates between {@link TrafficLightState#GREEN} and
|
* <p>Cada semáforo controla uma direção específica e mantém uma fila de veículos à espera.
|
||||||
* {@link TrafficLightState#RED} states.
|
* Alterna entre os estados VERDE e VERMELHO de acordo com a temporização configurada.</p>
|
||||||
* * This class is designed to be thread-safe for a potential concurrent
|
*
|
||||||
* simulation (though the current engine {@link sd.engine.SimulationEngine}
|
* <p><strong>Thread-safety:</strong> Usa locks para permitir acesso concorrente seguro entre
|
||||||
* is single-threaded). It uses a {@link ReentrantLock} to protect its
|
* a thread de processamento de eventos e as threads de I/O de rede.</p>
|
||||||
* internal state (the queue and the light state) from simultaneous access.
|
|
||||||
* * The {@link Condition} variables ({@code vehicleAdded}, {@code lightGreen})
|
|
||||||
* are included for a concurrent model where:
|
|
||||||
* - A "vehicle" thread might wait on {@code lightGreen} until the light changes.
|
|
||||||
* - A "controller" thread might wait on {@code vehicleAdded} to know when to
|
|
||||||
* process a queue.
|
|
||||||
* (Note: These Conditions are *not* used by the current discrete-event engine).
|
|
||||||
*/
|
*/
|
||||||
public class TrafficLight {
|
public class TrafficLight {
|
||||||
|
|
||||||
// --- Identity and configuration ---
|
/** Identificador único do semáforo (ex: "Cr1-N") */
|
||||||
|
|
||||||
/**
|
|
||||||
* Unique identifier for the light (e.g., "Cr1-N").
|
|
||||||
*/
|
|
||||||
private final String id;
|
private final String id;
|
||||||
|
|
||||||
/**
|
/** Direção que este semáforo controla (ex: "Norte", "Sul") */
|
||||||
* The direction this light controls (e.g., "North", "South").
|
|
||||||
*/
|
|
||||||
private final String direction;
|
private final String direction;
|
||||||
|
|
||||||
/**
|
/** Estado atual do semáforo (VERDE ou VERMELHO) */
|
||||||
* The current state of the light (GREEN or RED).
|
|
||||||
*/
|
|
||||||
private TrafficLightState state;
|
private TrafficLightState state;
|
||||||
|
|
||||||
// --- Vehicle management ---
|
/** Fila de veículos à espera neste semáforo */
|
||||||
|
|
||||||
/**
|
|
||||||
* The queue of vehicles waiting at this light.
|
|
||||||
* {@link LinkedList} is used as it's a standard {@link Queue} implementation.
|
|
||||||
*/
|
|
||||||
private final Queue<Vehicle> queue;
|
private final Queue<Vehicle> queue;
|
||||||
|
|
||||||
// --- Synchronization primitives (for thread-safety) ---
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A lock to protect all mutable state ({@link #queue} and {@link #state})
|
* Lock para proteger o estado mutável ({@link #queue} e {@link #state})
|
||||||
* from concurrent access. Any method reading or writing these fields
|
* de acesso concorrente.
|
||||||
* *must* acquire this lock first.
|
|
||||||
*/
|
*/
|
||||||
private final Lock lock;
|
private final Lock lock;
|
||||||
|
|
||||||
/**
|
/** Variável de condição para sinalizar adição de veículos (uso futuro) */
|
||||||
* A condition variable for a potential concurrent model.
|
|
||||||
* It could be used to signal threads (e.g., a controller) that
|
|
||||||
* a new vehicle has been added to the queue.
|
|
||||||
* (Not used in the current discrete-event engine).
|
|
||||||
*/
|
|
||||||
private final Condition vehicleAdded;
|
private final Condition vehicleAdded;
|
||||||
|
|
||||||
/**
|
/** Variável de condição para sinalizar que o semáforo ficou verde (uso futuro) */
|
||||||
* A condition variable for a potential concurrent model.
|
|
||||||
* It could be used to signal waiting vehicle threads that the
|
|
||||||
* light has just turned GREEN.
|
|
||||||
* (Not used in the current discrete-event engine).
|
|
||||||
*/
|
|
||||||
private final Condition lightGreen;
|
private final Condition lightGreen;
|
||||||
|
|
||||||
// --- Timing configuration ---
|
/** Duração (segundos) que o semáforo permanece VERDE */
|
||||||
|
|
||||||
/**
|
|
||||||
* The duration (in seconds) this light stays GREEN.
|
|
||||||
*/
|
|
||||||
private double greenTime;
|
private double greenTime;
|
||||||
|
|
||||||
/**
|
/** Duração (segundos) que o semáforo permanece VERMELHO */
|
||||||
* The duration (in seconds) this light stays RED.
|
|
||||||
*/
|
|
||||||
private double redTime;
|
private double redTime;
|
||||||
|
|
||||||
// --- Statistics ---
|
/** Número total de veículos processados por este semáforo */
|
||||||
|
|
||||||
/**
|
|
||||||
* Counter for the total number of vehicles that have
|
|
||||||
* been dequeued (processed) by this light.
|
|
||||||
*/
|
|
||||||
private int totalVehiclesProcessed;
|
private int totalVehiclesProcessed;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Track when vehicles arrive at this light for wait time calculation.
|
* Regista quando os veículos chegam ao semáforo para cálculo do tempo de espera.
|
||||||
* Maps vehicle ID to arrival timestamp (milliseconds).
|
* Mapeia ID do veículo para timestamp de chegada (milissegundos).
|
||||||
*/
|
*/
|
||||||
private final Map<String, Long> vehicleArrivalTimes;
|
private final Map<String, Long> vehicleArrivalTimes;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new TrafficLight.
|
* Cria um novo semáforo.
|
||||||
*
|
*
|
||||||
* @param id The unique ID (e.g., "Cr1-N").
|
* @param id identificador único (ex: "Cr1-N")
|
||||||
* @param direction The direction (e.g., "North").
|
* @param direction direção controlada (ex: "Norte")
|
||||||
* @param greenTime The duration of the GREEN state in seconds.
|
* @param greenTime duração do estado VERDE em segundos
|
||||||
* @param redTime The duration of the RED state in seconds.
|
* @param redTime duração do estado VERMELHO em segundos
|
||||||
*/
|
*/
|
||||||
public TrafficLight(String id, String direction, double greenTime, double redTime) {
|
public TrafficLight(String id, String direction, double greenTime, double redTime) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
this.direction = direction;
|
this.direction = direction;
|
||||||
this.state = TrafficLightState.RED; // All lights start RED
|
this.state = TrafficLightState.RED;
|
||||||
this.queue = new LinkedList<>();
|
this.queue = new LinkedList<>();
|
||||||
|
|
||||||
// Initialize synchronization objects
|
|
||||||
this.lock = new ReentrantLock();
|
this.lock = new ReentrantLock();
|
||||||
this.vehicleAdded = lock.newCondition();
|
this.vehicleAdded = lock.newCondition();
|
||||||
this.lightGreen = lock.newCondition();
|
this.lightGreen = lock.newCondition();
|
||||||
@@ -128,42 +83,45 @@ public class TrafficLight {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds a vehicle to the *end* of the waiting queue.
|
* Coloca um veículo na fila deste semáforo.
|
||||||
* This method is thread-safe.
|
*
|
||||||
*
|
* Registamos a hora de chegada para podermos calcular mais tarde quanto tempo o
|
||||||
* @param vehicle The {@link Vehicle} to add.
|
* veículo esperou.
|
||||||
|
*
|
||||||
|
* @param vehicle O veículo que chega ao semáforo.
|
||||||
*/
|
*/
|
||||||
public void addVehicle(Vehicle vehicle) {
|
public void addVehicle(Vehicle vehicle) {
|
||||||
lock.lock(); // Acquire the lock
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
queue.offer(vehicle); // Add vehicle to queue
|
queue.offer(vehicle);
|
||||||
vehicleArrivalTimes.put(vehicle.getId(), System.currentTimeMillis());
|
vehicleArrivalTimes.put(vehicle.getId(), System.currentTimeMillis());
|
||||||
vehicleAdded.signalAll(); // Signal (for concurrent models)
|
vehicleAdded.signalAll();
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock(); // Always release the lock
|
lock.unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Removes and returns the {@link Vehicle} from the *front* of the queue.
|
* Remove um veículo da fila para travessia.
|
||||||
* * This only succeeds if:
|
*
|
||||||
* 1. The light's state is {@link TrafficLightState#GREEN}.
|
* <p>Só remove se:</p>
|
||||||
* 2. The queue is not empty.
|
* <ul>
|
||||||
* * If these conditions are not met, it returns {@code null}.
|
* <li>O semáforo estiver VERDE</li>
|
||||||
* This method is thread-safe.
|
* <li>Existir pelo menos um veículo na fila</li>
|
||||||
*
|
* </ul>
|
||||||
* @return The {@link Vehicle} at the front of the queue, or {@code null}
|
*
|
||||||
* if the light is RED or the queue is empty.
|
* <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() {
|
public Vehicle removeVehicle() {
|
||||||
lock.lock(); // Acquire the lock
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
if (state == TrafficLightState.GREEN && !queue.isEmpty()) {
|
if (state == TrafficLightState.GREEN && !queue.isEmpty()) {
|
||||||
Vehicle vehicle = queue.poll(); // Remove vehicle from queue
|
Vehicle vehicle = queue.poll();
|
||||||
if (vehicle != null) {
|
if (vehicle != null) {
|
||||||
totalVehiclesProcessed++;
|
totalVehiclesProcessed++;
|
||||||
|
|
||||||
// Calculate wait time (time spent in queue)
|
|
||||||
Long arrivalTime = vehicleArrivalTimes.remove(vehicle.getId());
|
Long arrivalTime = vehicleArrivalTimes.remove(vehicle.getId());
|
||||||
if (arrivalTime != null) {
|
if (arrivalTime != null) {
|
||||||
double waitTimeSeconds = (System.currentTimeMillis() - arrivalTime) / 1000.0;
|
double waitTimeSeconds = (System.currentTimeMillis() - arrivalTime) / 1000.0;
|
||||||
@@ -172,161 +130,138 @@ public class TrafficLight {
|
|||||||
}
|
}
|
||||||
return vehicle;
|
return vehicle;
|
||||||
}
|
}
|
||||||
return null; // Light is RED or queue is empty
|
return null;
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock(); // Always release the lock
|
lock.unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Changes the light’s state (e.g., RED -> GREEN).
|
* Muda o estado do semáforo.
|
||||||
* If the new state is GREEN, it signals any waiting threads
|
*
|
||||||
* (for a potential concurrent model).
|
* @param newState novo estado (VERDE ou VERMELHO)
|
||||||
* This method is thread-safe.
|
|
||||||
*
|
|
||||||
* @param newState The {@link TrafficLightState} to set.
|
|
||||||
*/
|
*/
|
||||||
public void changeState(TrafficLightState newState) {
|
public void changeState(TrafficLightState newState) {
|
||||||
lock.lock(); // Acquire the lock
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
this.state = newState;
|
this.state = newState;
|
||||||
if (newState == TrafficLightState.GREEN) {
|
if (newState == TrafficLightState.GREEN) {
|
||||||
lightGreen.signalAll(); // Signal (for concurrent models)
|
lightGreen.signalAll();
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock(); // Always release the lock
|
lock.unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns how many vehicles are currently in the queue.
|
* Retorna quantos veículos estão atualmente na fila.
|
||||||
* This method is thread-safe.
|
* Método thread-safe.
|
||||||
* * @return The size of the queue.
|
*
|
||||||
|
* @return tamanho da fila
|
||||||
*/
|
*/
|
||||||
public int getQueueSize() {
|
public int getQueueSize() {
|
||||||
lock.lock(); // Acquire the lock
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
return queue.size();
|
return queue.size();
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock(); // Always release the lock
|
lock.unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks whether the queue is empty.
|
* Verifica se a fila está vazia.
|
||||||
* This method is thread-safe.
|
* Método thread-safe.
|
||||||
*
|
*
|
||||||
* @return {@code true} if the queue has no vehicles, {@code false} otherwise.
|
* @return {@code true} se não houver veículos, {@code false} caso contrário
|
||||||
*/
|
*/
|
||||||
public boolean isQueueEmpty() {
|
public boolean isQueueEmpty() {
|
||||||
lock.lock(); // Acquire the lock
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
return queue.isEmpty();
|
return queue.isEmpty();
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock(); // Always release the lock
|
lock.unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Getters & Setters ---
|
/** @return identificador único do semáforo */
|
||||||
|
|
||||||
/**
|
|
||||||
* @return The unique ID of this light (e.g., "Cr1-N").
|
|
||||||
*/
|
|
||||||
public String getId() {
|
public String getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return direção controlada por este semáforo */
|
||||||
* @return The direction this light controls (e.g., "North").
|
|
||||||
*/
|
|
||||||
public String getDirection() {
|
public String getDirection() {
|
||||||
return direction;
|
return direction;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the current state of the light (GREEN or RED).
|
* Obtém o estado atual do semáforo.
|
||||||
* This method is thread-safe.
|
* Método thread-safe.
|
||||||
*
|
*
|
||||||
* @return The current {@link TrafficLightState}.
|
* @return estado atual (VERDE ou VERMELHO)
|
||||||
*/
|
*/
|
||||||
public TrafficLightState getState() {
|
public TrafficLightState getState() {
|
||||||
lock.lock(); // Acquire the lock
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
return state;
|
return state;
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock(); // Always release the lock
|
lock.unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return duração configurada do sinal verde em segundos */
|
||||||
* @return The configured GREEN light duration in seconds.
|
|
||||||
*/
|
|
||||||
public double getGreenTime() {
|
public double getGreenTime() {
|
||||||
return greenTime;
|
return greenTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the GREEN light duration.
|
* Define a duração do sinal verde.
|
||||||
* @param greenTime The new duration in seconds.
|
*
|
||||||
|
* @param greenTime nova duração em segundos
|
||||||
*/
|
*/
|
||||||
public void setGreenTime(double greenTime) {
|
public void setGreenTime(double greenTime) {
|
||||||
this.greenTime = greenTime;
|
this.greenTime = greenTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return duração configurada do sinal vermelho em segundos */
|
||||||
* @return The configured RED light duration in seconds.
|
|
||||||
*/
|
|
||||||
public double getRedTime() {
|
public double getRedTime() {
|
||||||
return redTime;
|
return redTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the RED light duration.
|
* Define a duração do sinal vermelho.
|
||||||
* @param redTime The new duration in seconds.
|
*
|
||||||
|
* @param redTime nova duração em segundos
|
||||||
*/
|
*/
|
||||||
public void setRedTime(double redTime) {
|
public void setRedTime(double redTime) {
|
||||||
this.redTime = redTime;
|
this.redTime = redTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return número total de veículos processados por este semáforo */
|
||||||
* @return The total number of vehicles processed (dequeued) by this light.
|
|
||||||
*/
|
|
||||||
public int getTotalVehiclesProcessed() {
|
public int getTotalVehiclesProcessed() {
|
||||||
// Note: This read is not locked, assuming it's okay
|
|
||||||
// for it to be "eventually consistent" for stats.
|
|
||||||
// For strict accuracy, it should also be locked.
|
|
||||||
return totalVehiclesProcessed;
|
return totalVehiclesProcessed;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return objeto {@link Lock} para sincronização avançada */
|
||||||
* @return The {@link Lock} object for advanced synchronization.
|
|
||||||
*/
|
|
||||||
public Lock getLock() {
|
public Lock getLock() {
|
||||||
return lock;
|
return lock;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return condição para adição de veículos */
|
||||||
* @return The {@link Condition} for vehicle additions.
|
|
||||||
*/
|
|
||||||
public Condition getVehicleAdded() {
|
public Condition getVehicleAdded() {
|
||||||
return vehicleAdded;
|
return vehicleAdded;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return condição para semáforo ficar verde */
|
||||||
* @return The {@link Condition} for the light turning green.
|
|
||||||
*/
|
|
||||||
public Condition getLightGreen() {
|
public Condition getLightGreen() {
|
||||||
return lightGreen;
|
return lightGreen;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return representação textual do estado atual do semáforo */
|
||||||
* @return A string summary of the light's current state.
|
|
||||||
*/
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return String.format(
|
return String.format(
|
||||||
"TrafficLight{id='%s', direction='%s', state=%s, queueSize=%d}",
|
"TrafficLight{id='%s', direction='%s', state=%s, queueSize=%d}",
|
||||||
id, direction, getState(), getQueueSize() // Use getters for thread-safety
|
id, direction, getState(), getQueueSize()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,17 +1,13 @@
|
|||||||
package sd.model;
|
package sd.model;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enumeration representing the two possible states of a {@link TrafficLight}.
|
* Estados possíveis de um semáforo ({@link TrafficLight}).
|
||||||
*/
|
*/
|
||||||
public enum TrafficLightState {
|
public enum TrafficLightState {
|
||||||
|
|
||||||
/**
|
/** Sinal verde - veículos podem passar */
|
||||||
* The light is GREEN, allowing vehicles to pass (be dequeued).
|
|
||||||
*/
|
|
||||||
GREEN,
|
GREEN,
|
||||||
|
|
||||||
/**
|
/** Sinal vermelho - veículos aguardam na fila */
|
||||||
* The light is RED, blocking vehicles (they remain in the queue).
|
|
||||||
*/
|
|
||||||
RED
|
RED
|
||||||
}
|
}
|
||||||
@@ -5,94 +5,74 @@ import java.util.ArrayList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents a single vehicle moving through the simulation.
|
* Representa um veículo que se move pela rede de interseções.
|
||||||
*
|
*
|
||||||
* This class is a data object that holds the state of a vehicle, including:
|
* <p>Esta classe é o "gémeo digital" de um carro, mota ou camião.
|
||||||
* - Its unique ID, type, and entry time.
|
* Mantém toda a informação necessária:</p>
|
||||||
* - Its complete, pre-determined {@code route} (a list of intersection IDs).
|
* <ul>
|
||||||
* - Its current position in the route ({@code currentRouteIndex}).
|
* <li>Identificação e tipo do veículo</li>
|
||||||
* - Metrics for total time spent waiting at red lights and time spent crossing.
|
* <li>Rota completa a percorrer</li>
|
||||||
* * This object is passed around the simulation, primarily inside message
|
* <li>Métricas de tempo (espera, travessia, total)</li>
|
||||||
* payloads and stored in {@link TrafficLight} queues.
|
* </ul>
|
||||||
* * Implements {@link Serializable} so it can be sent between processes
|
*
|
||||||
* or nodes (e.g., over a socket in a distributed version of the simulation).
|
* <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 {
|
public class Vehicle implements Serializable {
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
// --- Identity and configuration ---
|
/** Identificador único do veículo (ex: "V1", "V2") */
|
||||||
|
|
||||||
/**
|
|
||||||
* Unique identifier for the vehicle (e.g., "V1", "V2").
|
|
||||||
*/
|
|
||||||
private final String id;
|
private final String id;
|
||||||
|
|
||||||
/**
|
/** Tipo de veículo (BIKE, LIGHT, HEAVY) */
|
||||||
* The type of vehicle (BIKE, LIGHT, HEAVY).
|
|
||||||
*/
|
|
||||||
private final VehicleType type;
|
private final VehicleType type;
|
||||||
|
|
||||||
/**
|
/** Tempo de simulação (em segundos) em que o veículo foi gerado */
|
||||||
* The simulation time (in seconds) when the vehicle was generated.
|
|
||||||
*/
|
|
||||||
private final double entryTime;
|
private final double entryTime;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The complete, ordered list of destinations (intersection IDs and the
|
* Lista ordenada completa de destinos (IDs de interseções e saída "S").
|
||||||
* final exit "S"). Example: ["Cr1", "Cr3", "S"].
|
* Exemplo: ["Cr1", "Cr3", "S"]
|
||||||
*/
|
*/
|
||||||
private final List<String> route;
|
private final List<String> route;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An index that tracks the vehicle's progress along its {@link #route}.
|
* Índice que acompanha o progresso do veículo ao longo da {@link #route}.
|
||||||
* {@code route.get(currentRouteIndex)} is the vehicle's *current*
|
* {@code route.get(currentRouteIndex)} é o destino *atual* do veículo.
|
||||||
* destination (i.e., the one it is traveling *towards* or *arriving at*).
|
|
||||||
*/
|
*/
|
||||||
private int currentRouteIndex;
|
private int currentRouteIndex;
|
||||||
|
|
||||||
// --- Metrics ---
|
/** Tempo total acumulado (segundos) que o veículo passou à espera em semáforos vermelhos */
|
||||||
|
|
||||||
/**
|
|
||||||
* The total accumulated time (in seconds) this vehicle has spent
|
|
||||||
* waiting at red lights.
|
|
||||||
*/
|
|
||||||
private double totalWaitingTime;
|
private double totalWaitingTime;
|
||||||
|
|
||||||
/**
|
/** Tempo total acumulado (segundos) que o veículo passou a atravessar interseções */
|
||||||
* The total accumulated time (in seconds) this vehicle has spent
|
|
||||||
* actively crossing intersections.
|
|
||||||
*/
|
|
||||||
private double totalCrossingTime;
|
private double totalCrossingTime;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new Vehicle.
|
* Cria um novo veículo pronto para se fazer à estrada.
|
||||||
*
|
*
|
||||||
* @param id The unique ID for the vehicle.
|
* @param id Identificador único (ex: "V1").
|
||||||
* @param type The {@link VehicleType}.
|
* @param type O tipo de veículo (determina velocidade/tamanho).
|
||||||
* @param entryTime The simulation time when the vehicle is created.
|
* @param entryTime Quando este veículo entrou na simulação (segundos).
|
||||||
* @param route The complete list of destination IDs (e.t., ["Cr1", "Cr2",
|
* @param route A lista ordenada de paragens (Interseções -> Saída).
|
||||||
* "S"]).
|
|
||||||
*/
|
*/
|
||||||
public Vehicle(String id, VehicleType type, double entryTime, List<String> route) {
|
public Vehicle(String id, VehicleType type, double entryTime, List<String> route) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
this.type = type;
|
this.type = type;
|
||||||
this.entryTime = entryTime;
|
this.entryTime = entryTime;
|
||||||
// Create a copy of the route list to ensure immutability
|
|
||||||
this.route = new ArrayList<>(route);
|
this.route = new ArrayList<>(route);
|
||||||
this.currentRouteIndex = 0; // Starts at the first destination
|
this.currentRouteIndex = 0;
|
||||||
this.totalWaitingTime = 0.0;
|
this.totalWaitingTime = 0.0;
|
||||||
this.totalCrossingTime = 0.0;
|
this.totalCrossingTime = 0.0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Advances the vehicle to the next stop in its route by
|
* Move o GPS interno do veículo para o próximo destino.
|
||||||
* incrementing the {@link #currentRouteIndex}.
|
*
|
||||||
* * This is typically called *after* a vehicle *arrives* at an intersection,
|
* Chame isto quando um veículo chega a uma interseção para atualizar para onde
|
||||||
* to set its *next* destination before it is queued.
|
* deve ir a seguir.
|
||||||
*
|
*
|
||||||
* @return {@code true} if there is still at least one more destination
|
* @return true se houver mais paragens, false se a viagem terminou.
|
||||||
* in the route, {@code false} if the vehicle has passed its
|
|
||||||
* final destination.
|
|
||||||
*/
|
*/
|
||||||
public boolean advanceRoute() {
|
public boolean advanceRoute() {
|
||||||
currentRouteIndex++;
|
currentRouteIndex++;
|
||||||
@@ -100,116 +80,89 @@ public class Vehicle implements Serializable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the current destination (the next intersection or exit) that
|
* Obtém o destino atual (próxima interseção ou saída) para onde o veículo se dirige.
|
||||||
* the vehicle is heading towards.
|
|
||||||
*
|
*
|
||||||
* @return The ID of the current destination (e.g., "Cr1"), or
|
* @return ID do destino atual (ex: "Cr1"), ou {@code null} se a rota terminou
|
||||||
* {@code null} if the route is complete.
|
|
||||||
*/
|
*/
|
||||||
public String getCurrentDestination() {
|
public String getCurrentDestination() {
|
||||||
return (currentRouteIndex < route.size()) ? route.get(currentRouteIndex) : null;
|
return (currentRouteIndex < route.size()) ? route.get(currentRouteIndex) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if the vehicle has completed its entire route.
|
* Verifica se o veículo completou toda a sua rota.
|
||||||
*
|
*
|
||||||
* @return {@code true} if the route index is at or past the end
|
* @return {@code true} se chegou ao fim da rota, {@code false} caso contrário
|
||||||
* of the route list, {@code false} otherwise.
|
|
||||||
*/
|
*/
|
||||||
public boolean hasReachedEnd() {
|
public boolean hasReachedEnd() {
|
||||||
return currentRouteIndex >= route.size();
|
return currentRouteIndex >= route.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Getters and metrics management ---
|
/** @return identificador único do veículo */
|
||||||
|
|
||||||
/**
|
|
||||||
* @return The vehicle's unique ID.
|
|
||||||
*/
|
|
||||||
public String getId() {
|
public String getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return tipo do veículo */
|
||||||
* @return The vehicle's {@link VehicleType}.
|
|
||||||
*/
|
|
||||||
public VehicleType getType() {
|
public VehicleType getType() {
|
||||||
return type;
|
return type;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return tempo de simulação em que o veículo entrou no sistema */
|
||||||
* @return The simulation time when the vehicle entered the system.
|
|
||||||
*/
|
|
||||||
public double getEntryTime() {
|
public double getEntryTime() {
|
||||||
return entryTime;
|
return entryTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return cópia da rota completa do veículo */
|
||||||
* @return A *copy* of the vehicle's complete route.
|
|
||||||
*/
|
|
||||||
public List<String> getRoute() {
|
public List<String> getRoute() {
|
||||||
// Return a copy to prevent external modification
|
|
||||||
return new ArrayList<>(route);
|
return new ArrayList<>(route);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return índice atual apontando para o destino do veículo na sua rota */
|
||||||
* @return The current index pointing to the vehicle's destination in its route
|
|
||||||
* list.
|
|
||||||
*/
|
|
||||||
public int getCurrentRouteIndex() {
|
public int getCurrentRouteIndex() {
|
||||||
return currentRouteIndex;
|
return currentRouteIndex;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return tempo total acumulado de espera em segundos */
|
||||||
* @return The total accumulated waiting time in seconds.
|
|
||||||
*/
|
|
||||||
public double getTotalWaitingTime() {
|
public double getTotalWaitingTime() {
|
||||||
return totalWaitingTime;
|
return totalWaitingTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds a duration to the vehicle's total waiting time.
|
* Adiciona uma duração ao tempo total de espera do veículo.
|
||||||
* This is called by the simulation engine when a vehicle
|
* Chamado quando um veículo começa a atravessar uma interseção.
|
||||||
* starts crossing an intersection.
|
|
||||||
*
|
*
|
||||||
* @param time The duration (in seconds) to add.
|
* @param time duração (em segundos) a adicionar
|
||||||
*/
|
*/
|
||||||
public void addWaitingTime(double time) {
|
public void addWaitingTime(double time) {
|
||||||
totalWaitingTime += time;
|
totalWaitingTime += time;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return tempo total acumulado de travessia em segundos */
|
||||||
* @return The total accumulated crossing time in seconds.
|
|
||||||
*/
|
|
||||||
public double getTotalCrossingTime() {
|
public double getTotalCrossingTime() {
|
||||||
return totalCrossingTime;
|
return totalCrossingTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds a duration to the vehicle's total crossing time.
|
* Adiciona uma duração ao tempo total de travessia do veículo.
|
||||||
* This is called by the simulation engine when a vehicle
|
* Chamado quando um veículo termina de atravessar uma interseção.
|
||||||
* finishes crossing an intersection.
|
|
||||||
*
|
*
|
||||||
* @param time The duration (in seconds) to add.
|
* @param time duração (em segundos) a adicionar
|
||||||
*/
|
*/
|
||||||
public void addCrossingTime(double time) {
|
public void addCrossingTime(double time) {
|
||||||
totalCrossingTime += time;
|
totalCrossingTime += time;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Calculates the vehicle's total time spent in the system so far.
|
* Calcula o tempo total que o veículo passou no sistema até agora.
|
||||||
* This is a "live" calculation.
|
|
||||||
*
|
*
|
||||||
* @param currentTime The current simulation time.
|
* @param currentTime tempo atual da simulação
|
||||||
* @return The total elapsed time (in seconds) since the vehicle
|
* @return tempo total decorrido (em segundos) desde que o veículo foi gerado
|
||||||
* was generated ({@code currentTime - entryTime}).
|
|
||||||
*/
|
*/
|
||||||
public double getTotalTravelTime(double currentTime) {
|
public double getTotalTravelTime(double currentTime) {
|
||||||
return currentTime - entryTime;
|
return currentTime - entryTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return representação textual do estado atual do veículo */
|
||||||
* @return A string summary of the vehicle's current state.
|
|
||||||
*/
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return String.format(
|
return String.format(
|
||||||
|
|||||||
@@ -1,27 +1,19 @@
|
|||||||
package sd.model;
|
package sd.model;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enumeration representing the different types of vehicles in the simulation.
|
* Enumeração dos diferentes tipos de veículos na simulação.
|
||||||
* Each type can have different properties, such as crossing time
|
*
|
||||||
* and generation probability, defined in {@link sd.config.SimulationConfig}.
|
* <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 {
|
public enum VehicleType {
|
||||||
|
|
||||||
/**
|
/** Bicicleta ou motocicleta - tempo de travessia curto */
|
||||||
* A bike or motorcycle.
|
|
||||||
* Typically has a short crossing time.
|
|
||||||
*/
|
|
||||||
BIKE,
|
BIKE,
|
||||||
|
|
||||||
/**
|
/** Veículo ligeiro padrão (carro) - tipo mais comum */
|
||||||
* A standard light vehicle, such as a car.
|
|
||||||
* This is usually the most common type.
|
|
||||||
*/
|
|
||||||
LIGHT,
|
LIGHT,
|
||||||
|
|
||||||
/**
|
/** Veículo pesado (camião ou autocarro) - tempo de travessia longo */
|
||||||
* A heavy vehicle, such as a truck or bus.
|
|
||||||
* Typically has a long crossing time.
|
|
||||||
*/
|
|
||||||
HEAVY
|
HEAVY
|
||||||
}
|
}
|
||||||
@@ -1,41 +1,45 @@
|
|||||||
package sd.protocol;
|
package sd.protocol;
|
||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
import sd.model.MessageType; // Assuming MessageType is in sd.model or sd.protocol
|
import sd.model.MessageType; // Assuming MessageType is in sd.model or sd.protocol
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Interface defining the contract for all messages exchanged in the simulator.
|
* Contrato para todas as mensagens trocadas no simulador.
|
||||||
* Ensures that any message can be identified and routed.
|
*
|
||||||
* * This interface extends Serializable to allow objects that implement it
|
* <p>Garante que mensagens podem ser identificadas e encaminhadas.
|
||||||
* to be sent over Sockets (ObjectOutputStream).
|
* Extende Serializable para permitir envio via sockets.
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public interface MessageProtocol extends Serializable {
|
public interface MessageProtocol extends Serializable {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the type of the message, indicating its purpose.
|
* Tipo da mensagem, indicando o seu propósito.
|
||||||
* @return The MessageType (e.g., VEHICLE_TRANSFER, STATS_UPDATE).
|
* @return tipo (ex: VEHICLE_TRANSFER, STATS_UPDATE)
|
||||||
*/
|
*/
|
||||||
MessageType getType();
|
MessageType getType();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the data object (payload) that this message carries.
|
* Dados (payload) que esta mensagem transporta.
|
||||||
* The type of object will depend on the MessageType.
|
*
|
||||||
* * - If getType() == VEHICLE_TRANSFER, the payload will be a {@link sd.model.Vehicle} object.
|
* <p>Tipo depende do MessageType:
|
||||||
* - If getType() == STATS_UPDATE, the payload will be a statistics object.
|
* <ul>
|
||||||
* * @return The data object (payload), which must also be Serializable.
|
* <li>VEHICLE_TRANSFER → objeto Vehicle
|
||||||
|
* <li>STATS_UPDATE → objeto de estatísticas
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* @return payload (deve ser Serializable)
|
||||||
*/
|
*/
|
||||||
Object getPayload();
|
Object getPayload();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the ID of the node (Process) that sent this message.
|
* ID do nó (processo) que enviou a mensagem.
|
||||||
* @return String (e.g., "Cr1", "Cr5", "S").
|
* @return ID de origem (ex: "Cr1", "Cr5", "S")
|
||||||
*/
|
*/
|
||||||
String getSourceNode();
|
String getSourceNode();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the ID of the destination node (Process) for this message.
|
* ID do nó de destino.
|
||||||
* @return String (e.g., "Cr2", "DashboardServer").
|
* @return ID de destino (ex: "Cr2", "DashboardServer")
|
||||||
*/
|
*/
|
||||||
String getDestinationNode();
|
String getDestinationNode();
|
||||||
}
|
}
|
||||||
@@ -18,8 +18,8 @@ import sd.serialization.SerializerFactory;
|
|||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Wrapper class that simplifies communication via Sockets.
|
* Simplifica comunicação via sockets.
|
||||||
* Includes connection retry logic for robustness.
|
* Inclui lógica de retry para robustez.
|
||||||
*/
|
*/
|
||||||
public class SocketConnection implements Closeable {
|
public class SocketConnection implements Closeable {
|
||||||
|
|
||||||
@@ -28,22 +28,20 @@ public class SocketConnection implements Closeable {
|
|||||||
private final InputStream inputStream;
|
private final InputStream inputStream;
|
||||||
private final MessageSerializer serializer;
|
private final MessageSerializer serializer;
|
||||||
|
|
||||||
// --- Configuration for Retry Logic ---
|
/** Número máximo de tentativas de ligação */
|
||||||
/** Maximum number of connection attempts. */
|
|
||||||
private static final int MAX_RETRIES = 5;
|
private static final int MAX_RETRIES = 5;
|
||||||
/** Delay between retry attempts in milliseconds. */
|
/** Atraso entre tentativas (milissegundos) */
|
||||||
private static final long RETRY_DELAY_MS = 1000;
|
private static final long RETRY_DELAY_MS = 1000;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor for the "Client" (who initiates the connection).
|
* Construtor do cliente que inicia a ligação.
|
||||||
* Tries to connect to a process that is already listening (Server).
|
* Tenta ligar a um servidor já em escuta, com retry.
|
||||||
* Includes retry logic in case of initial connection failure.
|
|
||||||
*
|
*
|
||||||
* @param host The host address (e.g., "localhost" from your simulation.properties)
|
* @param host endereço do host (ex: "localhost")
|
||||||
* @param port The port (e.g., 8001 from your simulation.properties)
|
* @param port número da porta
|
||||||
* @throws IOException If connection fails after all retries.
|
* @throws IOException se falhar após todas as tentativas
|
||||||
* @throws UnknownHostException If the host is not found (this error usually doesn't need retry).
|
* @throws UnknownHostException se o host não for encontrado
|
||||||
* @throws InterruptedException If the thread is interrupted while waiting between retries.
|
* @throws InterruptedException se a thread for interrompida
|
||||||
*/
|
*/
|
||||||
public SocketConnection(String host, int port) throws IOException, UnknownHostException, InterruptedException {
|
public SocketConnection(String host, int port) throws IOException, UnknownHostException, InterruptedException {
|
||||||
Socket tempSocket = null;
|
Socket tempSocket = null;
|
||||||
|
|||||||
@@ -3,84 +3,82 @@ package sd.util;
|
|||||||
import java.util.Random;
|
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.
|
||||||
* * Provides static methods for:
|
*
|
||||||
* - Generating exponentially distributed intervals (for Poisson processes).
|
* <p>Fornece métodos estáticos para:</p>
|
||||||
* - Generating random integers and doubles in a range.
|
* <ul>
|
||||||
* - Making decisions based on probability.
|
* <li>Gerar intervalos exponencialmente distribuídos (processos de Poisson)</li>
|
||||||
* - Choosing random elements from an array.
|
* <li>Gerar inteiros e doubles aleatórios num intervalo</li>
|
||||||
* * It uses a single, static {@link Random} instance.
|
* <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 {
|
public class RandomGenerator {
|
||||||
|
|
||||||
/**
|
/** Instância partilhada de Random para toda a simulação */
|
||||||
* The single, shared Random instance for the entire simulation.
|
|
||||||
*/
|
|
||||||
private static final Random random = new Random();
|
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.
|
||||||
* * This is a key component for modeling a Poisson process, where the
|
*
|
||||||
* *inter-arrival times* (time between events) are exponentially distributed.
|
* <p>Componente essencial para modelar processos de Poisson, onde os
|
||||||
* The formula used is the inverse transform sampling method:
|
* tempos entre chegadas seguem uma distribuição exponencial.</p>
|
||||||
* {@code Time = -ln(1 - U) / λ}
|
*
|
||||||
* where U is a uniform random number [0, 1) and λ (lambda) is the
|
* <p>Fórmula: {@code Time = -ln(1 - U) / λ}<br>
|
||||||
* average arrival rate.
|
* onde U é um número aleatório uniforme [0, 1) e λ (lambda) é a taxa média de chegada.</p>
|
||||||
*
|
*
|
||||||
* @param lambda The average arrival rate (λ) (e.g., 0.5 vehicles per second).
|
* @param lambda taxa média de chegada λ (ex: 0.5 veículos por segundo)
|
||||||
* @return The time interval (in seconds) until the next arrival.
|
* @return intervalo de tempo (segundos) até à próxima chegada
|
||||||
*/
|
*/
|
||||||
public static double generateExponentialInterval(double lambda) {
|
public static double generateExponentialInterval(double lambda) {
|
||||||
// Math.log is the natural logarithm (ln)
|
|
||||||
// random.nextDouble() returns a value in [0.0, 1.0)
|
|
||||||
return Math.log(1 - random.nextDouble()) / -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 The minimum possible value.
|
* @param min valor mínimo possível
|
||||||
* @param max The maximum possible value.
|
* @param max valor máximo possível
|
||||||
* @return A random integer in the range [min, max].
|
* @return inteiro aleatório no intervalo [min, max]
|
||||||
*/
|
*/
|
||||||
public static int generateRandomInt(int min, int max) {
|
public static int generateRandomInt(int min, int max) {
|
||||||
// random.nextInt(N) returns a value from 0 to N-1
|
|
||||||
// (max - min + 1) is the total number of integers in the range
|
|
||||||
// + min offsets the range
|
|
||||||
return random.nextInt(max - min + 1) + min;
|
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 The minimum possible value.
|
* @param min valor mínimo possível
|
||||||
* @param max The maximum possible value.
|
* @param max valor máximo possível
|
||||||
* @return A random double in the range [min, max).
|
* @return double aleatório no intervalo [min, max)
|
||||||
*/
|
*/
|
||||||
public static double generateRandomDouble(double min, double max) {
|
public static double generateRandomDouble(double min, double max) {
|
||||||
return min + (max - min) * random.nextDouble();
|
return min + (max - min) * random.nextDouble();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns {@code true} with a given probability.
|
* Retorna {@code true} com uma dada probabilidade.
|
||||||
* * This is useful for making weighted decisions. For example,
|
*
|
||||||
* {@code occursWithProbability(0.3)} will return {@code true}
|
* <p>Útil para tomar decisões ponderadas. Por exemplo,
|
||||||
* approximately 30% of the time.
|
* {@code occursWithProbability(0.3)} retorna {@code true}
|
||||||
|
* aproximadamente 30% das vezes.</p>
|
||||||
*
|
*
|
||||||
* @param probability A value between 0.0 (never) and 1.0 (always).
|
* @param probability valor entre 0.0 (nunca) e 1.0 (sempre)
|
||||||
* @return {@code true} or {@code false}, based on the probability.
|
* @return {@code true} ou {@code false}, baseado na probabilidade
|
||||||
*/
|
*/
|
||||||
public static boolean occursWithProbability(double probability) {
|
public static boolean occursWithProbability(double probability) {
|
||||||
return random.nextDouble() < probability;
|
return random.nextDouble() < probability;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Picks a random element from the given array.
|
* Escolhe um elemento aleatório do array fornecido.
|
||||||
*
|
*
|
||||||
* @param <T> The generic type of the array.
|
* @param <T> tipo genérico do array
|
||||||
* @param array The array to choose from.
|
* @param array array de onde escolher
|
||||||
* @return A randomly selected element from the array.
|
* @return elemento selecionado aleatoriamente
|
||||||
* @throws IllegalArgumentException if the array is null or empty.
|
* @throws IllegalArgumentException se o array for null ou vazio
|
||||||
*/
|
*/
|
||||||
public static <T> T chooseRandom(T[] array) {
|
public static <T> T chooseRandom(T[] array) {
|
||||||
if (array == null || array.length == 0) {
|
if (array == null || array.length == 0) {
|
||||||
@@ -90,12 +88,13 @@ public class RandomGenerator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the seed of the shared random number generator.
|
* Define a seed do gerador de números aleatórios partilhado.
|
||||||
* This is extremely useful for debugging and testing, as it allows
|
*
|
||||||
* the simulation to be run multiple times with the *exact same*
|
* <p>Extremamente útil para debugging e testes, pois permite executar
|
||||||
* sequence of "random" events, making the results reproducible.
|
* a simulação múltiplas vezes com a mesma sequência de eventos "aleatórios",
|
||||||
|
* tornando os resultados reproduzíveis.</p>
|
||||||
*
|
*
|
||||||
* @param seed The seed to use.
|
* @param seed seed a usar
|
||||||
*/
|
*/
|
||||||
public static void setSeed(long seed) {
|
public static void setSeed(long seed) {
|
||||||
random.setSeed(seed);
|
random.setSeed(seed);
|
||||||
|
|||||||
@@ -9,37 +9,38 @@ import sd.model.Vehicle;
|
|||||||
import sd.model.VehicleType;
|
import sd.model.VehicleType;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generates vehicles for the simulation.
|
* Gera veículos para a simulação.
|
||||||
* * This class is responsible for two key tasks:
|
*
|
||||||
* 1. Determining *when* the next vehicle should arrive, based on the
|
* <p>Esta classe é responsável por duas tarefas principais:</p>
|
||||||
* arrival model (POISSON or FIXED) from the {@link SimulationConfig}.
|
* <ol>
|
||||||
* 2. Creating a new {@link Vehicle} object with a randomly selected
|
* <li>Determinar <em>quando</em> o próximo veículo deve chegar, baseado no
|
||||||
* type (e.g., BIKE, LIGHT) and a randomly selected route.
|
* modelo de chegada (POISSON ou FIXED) da {@link SimulationConfig}</li>
|
||||||
* * Routes are predefined and organized by entry point (E1, E2, E3).
|
* <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 {
|
public class VehicleGenerator {
|
||||||
|
|
||||||
private final SimulationConfig config;
|
private final SimulationConfig config;
|
||||||
private final String arrivalModel;
|
private final String arrivalModel;
|
||||||
private final double arrivalRate; // Lambda (λ) for POISSON
|
/** Lambda (λ) para modelo POISSON */
|
||||||
private final double fixedInterval; // Interval for FIXED
|
private final double arrivalRate;
|
||||||
|
/** Intervalo para modelo FIXED */
|
||||||
|
private final double fixedInterval;
|
||||||
|
|
||||||
// --- Predefined Routes ---
|
/** Rotas possíveis a partir do ponto de entrada E1 */
|
||||||
// These lists store all possible routes, grouped by where they start.
|
|
||||||
|
|
||||||
/** Routes starting from entry point E1. */
|
|
||||||
private final List<RouteWithProbability> e1Routes;
|
private final List<RouteWithProbability> e1Routes;
|
||||||
/** Routes starting from entry point E2. */
|
/** Rotas possíveis a partir do ponto de entrada E2 */
|
||||||
private final List<RouteWithProbability> e2Routes;
|
private final List<RouteWithProbability> e2Routes;
|
||||||
/** Routes starting from entry point E3. */
|
/** Rotas possíveis a partir do ponto de entrada E3 */
|
||||||
private final List<RouteWithProbability> e3Routes;
|
private final List<RouteWithProbability> e3Routes;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new VehicleGenerator.
|
* Cria um novo gerador de veículos.
|
||||||
* It reads the necessary configuration and initializes the
|
* Lê a configuração necessária e inicializa as rotas predefinidas.
|
||||||
* predefined routes.
|
|
||||||
*
|
*
|
||||||
* @param config The {@link SimulationConfig} object.
|
* @param config objeto de {@link SimulationConfig}
|
||||||
*/
|
*/
|
||||||
public VehicleGenerator(SimulationConfig config) {
|
public VehicleGenerator(SimulationConfig config) {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
@@ -57,64 +58,62 @@ public class VehicleGenerator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Defines all possible routes that vehicles can take, organized by
|
* Define todas as rotas possíveis que os veículos podem tomar.
|
||||||
* their entry point (E1, E2, E3). Each route is given a
|
* As rotas são organizadas por ponto de entrada (E1, E2, E3).
|
||||||
* probability, which determines how often it's chosen.
|
* Cada rota tem uma probabilidade que determina a frequência com que é escolhida.
|
||||||
*/
|
*/
|
||||||
private void initializePossibleRoutes() {
|
private void initializePossibleRoutes() {
|
||||||
// E1 routes (Starts at Cr1)
|
|
||||||
e1Routes.add(new RouteWithProbability(
|
e1Routes.add(new RouteWithProbability(
|
||||||
Arrays.asList("Cr1", "Cr4", "Cr5", "S"), 0.34)); // E1 -> Cr1 -> Cr4 -> Cr5 -> Exit
|
Arrays.asList("Cr1", "Cr4", "Cr5", "S"), 0.34));
|
||||||
e1Routes.add(new RouteWithProbability(
|
e1Routes.add(new RouteWithProbability(
|
||||||
Arrays.asList("Cr1", "Cr2", "Cr5", "S"), 0.33)); // E1 -> Cr1 -> Cr2 -> Cr5 -> Exit
|
Arrays.asList("Cr1", "Cr2", "Cr5", "S"), 0.33));
|
||||||
e1Routes.add(new RouteWithProbability(
|
e1Routes.add(new RouteWithProbability(
|
||||||
Arrays.asList("Cr1", "Cr2", "Cr3", "S"), 0.33)); // E1 -> Cr1 -> Cr2 -> Cr3 -> Exit
|
Arrays.asList("Cr1", "Cr2", "Cr3", "S"), 0.33));
|
||||||
|
|
||||||
// E2 routes (Starts at Cr2)
|
|
||||||
e2Routes.add(new RouteWithProbability(
|
e2Routes.add(new RouteWithProbability(
|
||||||
Arrays.asList("Cr2", "Cr5", "S"), 0.34)); // E2 -> Cr2 -> Cr5 -> Exit
|
Arrays.asList("Cr2", "Cr5", "S"), 0.34));
|
||||||
e2Routes.add(new RouteWithProbability(
|
e2Routes.add(new RouteWithProbability(
|
||||||
Arrays.asList("Cr2", "Cr3", "S"), 0.33)); // E2 -> Cr2 -> Cr3 -> Exit
|
Arrays.asList("Cr2", "Cr3", "S"), 0.33));
|
||||||
e2Routes.add(new RouteWithProbability(
|
e2Routes.add(new RouteWithProbability(
|
||||||
Arrays.asList("Cr2", "Cr1", "Cr4", "Cr5", "S"), 0.33)); // E2 -> Cr2 -> ... -> Exit
|
Arrays.asList("Cr2", "Cr1", "Cr4", "Cr5", "S"), 0.33));
|
||||||
|
|
||||||
// E3 routes (Starts at Cr3)
|
|
||||||
e3Routes.add(new RouteWithProbability(
|
e3Routes.add(new RouteWithProbability(
|
||||||
Arrays.asList("Cr3", "S"), 0.34)); // E3 -> Cr3 -> Exit
|
Arrays.asList("Cr3", "S"), 0.34));
|
||||||
e3Routes.add(new RouteWithProbability(
|
e3Routes.add(new RouteWithProbability(
|
||||||
Arrays.asList("Cr3", "Cr2", "Cr5", "S"), 0.33)); // E3 -> Cr3 -> Cr2 -> Cr5 -> Exit
|
Arrays.asList("Cr3", "Cr2", "Cr5", "S"), 0.33));
|
||||||
e3Routes.add(new RouteWithProbability(
|
e3Routes.add(new RouteWithProbability(
|
||||||
Arrays.asList("Cr3", "Cr2", "Cr1", "Cr4", "Cr5", "S"), 0.33)); // E3 -> Cr3 -> ... -> Exit
|
Arrays.asList("Cr3", "Cr2", "Cr1", "Cr4", "Cr5", "S"), 0.33));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Calculates the *absolute* time of the next vehicle arrival
|
* Calcula o tempo <em>absoluto</em> da próxima chegada de veículo
|
||||||
* based on the configured model.
|
* baseado no modelo configurado.
|
||||||
* * @param currentTime The current simulation time, used as the base.
|
*
|
||||||
* @return The absolute time (e.g., {@code currentTime + interval})
|
* @param currentTime tempo atual da simulação, usado como base
|
||||||
* when the next vehicle should be generated.
|
* @return tempo absoluto (ex: {@code currentTime + intervalo})
|
||||||
|
* em que o próximo veículo deve ser gerado
|
||||||
*/
|
*/
|
||||||
public double getNextArrivalTime(double currentTime) {
|
public double getNextArrivalTime(double currentTime) {
|
||||||
if ("POISSON".equalsIgnoreCase(arrivalModel)) {
|
if ("POISSON".equalsIgnoreCase(arrivalModel)) {
|
||||||
// For a Poisson process, the time *between* arrivals
|
|
||||||
// follows an exponential distribution.
|
|
||||||
double interval = RandomGenerator.generateExponentialInterval(arrivalRate);
|
double interval = RandomGenerator.generateExponentialInterval(arrivalRate);
|
||||||
return currentTime + interval;
|
return currentTime + interval;
|
||||||
} else {
|
} else {
|
||||||
// For a Fixed model, the interval is constant.
|
|
||||||
return currentTime + fixedInterval;
|
return currentTime + fixedInterval;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generates a new {@link Vehicle} object.
|
* Gera um novo objeto {@link Vehicle}.
|
||||||
* This involves:
|
*
|
||||||
* 1. Selecting a random {@link VehicleType} based on probabilities.
|
* <p>Passos executados:</p>
|
||||||
* 2. Selecting a random route (entry point + path) based on probabilities.
|
* <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 The unique identifier for the new vehicle (e.g., "V123").
|
* @param vehicleId identificador único do novo veículo (ex: "V123")
|
||||||
* @param entryTime The simulation time when this vehicle is being created.
|
* @param entryTime tempo de simulação em que o veículo é criado
|
||||||
* @return A new, configured {@link Vehicle} object.
|
* @return novo objeto {@link Vehicle} configurado
|
||||||
*/
|
*/
|
||||||
public Vehicle generateVehicle(String vehicleId, double entryTime) {
|
public Vehicle generateVehicle(String vehicleId, double entryTime) {
|
||||||
VehicleType type = selectVehicleType();
|
VehicleType type = selectVehicleType();
|
||||||
@@ -124,22 +123,24 @@ public class VehicleGenerator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Selects a {@link VehicleType} (BIKE, LIGHT, HEAVY) based on the
|
* Seleciona um {@link VehicleType} (BIKE, LIGHT, HEAVY) baseado nas
|
||||||
* probabilities defined in the {@link SimulationConfig}.
|
* probabilidades definidas na {@link SimulationConfig}.
|
||||||
* * Uses a standard "cumulative probability" technique:
|
*
|
||||||
* 1. Get a random number {@code rand} from [0, 1).
|
* <p>Usa técnica de "probabilidade cumulativa":</p>
|
||||||
* 2. If {@code rand < P(Bike)}, return BIKE.
|
* <ol>
|
||||||
* 3. Else if {@code rand < P(Bike) + P(Light)}, return LIGHT.
|
* <li>Obtém número aleatório {@code rand} de [0, 1)</li>
|
||||||
* 4. Else, return HEAVY.
|
* <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 The selected {@link VehicleType}.
|
* @return tipo de veículo selecionado
|
||||||
*/
|
*/
|
||||||
private VehicleType selectVehicleType() {
|
private VehicleType selectVehicleType() {
|
||||||
double bikeProbability = config.getBikeVehicleProbability();
|
double bikeProbability = config.getBikeVehicleProbability();
|
||||||
double lightProbability = config.getLightVehicleProbability();
|
double lightProbability = config.getLightVehicleProbability();
|
||||||
double heavyProbability = config.getHeavyVehicleProbability();
|
double heavyProbability = config.getHeavyVehicleProbability();
|
||||||
|
|
||||||
// Normalize probabilities in case they don't sum to exactly 1.0
|
|
||||||
double total = bikeProbability + lightProbability + heavyProbability;
|
double total = bikeProbability + lightProbability + heavyProbability;
|
||||||
if (total == 0) return VehicleType.LIGHT; // Avoid division by zero
|
if (total == 0) return VehicleType.LIGHT; // Avoid division by zero
|
||||||
bikeProbability /= total;
|
bikeProbability /= total;
|
||||||
|
|||||||
@@ -27,15 +27,18 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "Cr4",
|
"id": "Cr4",
|
||||||
"lights": ["East"],
|
"lights": ["East", "West"],
|
||||||
"routes": {
|
"routes": {
|
||||||
|
"Cr1": "North",
|
||||||
"Cr5": "East"
|
"Cr5": "East"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "Cr5",
|
"id": "Cr5",
|
||||||
"lights": ["East"],
|
"lights": ["East", "West", "North"],
|
||||||
"routes": {
|
"routes": {
|
||||||
|
"Cr2": "North",
|
||||||
|
"Cr4": "West",
|
||||||
"S": "East"
|
"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 ===
|
# === SIMULATION CONFIGURATION ===
|
||||||
|
|
||||||
# Total duration in seconds (3600 = 1 hour)
|
# Total duration in seconds (3600 = 1 hour)
|
||||||
simulation.duration=60.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
|
# Vehicle arrival model: FIXED or POISSON
|
||||||
simulation.arrival.model=POISSON
|
simulation.arrival.model=POISSON
|
||||||
@@ -47,44 +51,33 @@ simulation.arrival.fixed.interval=2.0
|
|||||||
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
|
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
|
||||||
|
|
||||||
# Intersection 1 (Entry point - balanced)
|
# Intersection 1 (Entry point - balanced)
|
||||||
trafficlight.Cr1.South.green=20.0
|
trafficlight.Cr1.South.green=60.0
|
||||||
trafficlight.Cr1.South.red=40.0
|
trafficlight.Cr1.South.red=5.0
|
||||||
trafficlight.Cr1.East.green=20.0
|
trafficlight.Cr1.East.green=60.0
|
||||||
trafficlight.Cr1.East.red=40.0
|
trafficlight.Cr1.East.red=5.0
|
||||||
trafficlight.Cr1.West.green=20.0
|
|
||||||
trafficlight.Cr1.West.red=40.0
|
|
||||||
|
|
||||||
# Intersection 2 (Main hub - shorter cycles, favor East-West)
|
# Intersection 2 (Main hub - shorter cycles, favor East-West)
|
||||||
trafficlight.Cr2.South.green=12.0
|
trafficlight.Cr2.South.green=60.0
|
||||||
trafficlight.Cr2.South.red=36.0
|
trafficlight.Cr2.South.red=5.0
|
||||||
trafficlight.Cr2.East.green=18.0
|
trafficlight.Cr2.East.green=60.0
|
||||||
trafficlight.Cr2.East.red=30.0
|
trafficlight.Cr2.East.red=5.0
|
||||||
trafficlight.Cr2.West.green=18.0
|
trafficlight.Cr2.West.green=60.0
|
||||||
trafficlight.Cr2.West.red=30.0
|
trafficlight.Cr2.West.red=5.0
|
||||||
|
|
||||||
# Intersection 3 (Path to exit - favor East)
|
# Intersection 3 (Path to exit - favor East)
|
||||||
trafficlight.Cr3.South.green=15.0
|
trafficlight.Cr3.South.green=60.0
|
||||||
trafficlight.Cr3.South.red=30.0
|
trafficlight.Cr3.South.red=5.0
|
||||||
trafficlight.Cr3.East.green=20.0
|
trafficlight.Cr3.West.green=60.0
|
||||||
trafficlight.Cr3.East.red=25.0
|
trafficlight.Cr3.West.red=5.0
|
||||||
trafficlight.Cr3.West.green=15.0
|
|
||||||
trafficlight.Cr3.West.red=30.0
|
|
||||||
|
|
||||||
# Intersection 4 (Favor East toward Cr5)
|
# Intersection 4 (Favor East toward Cr5)
|
||||||
trafficlight.Cr4.South.green=15.0
|
trafficlight.Cr4.East.green=60.0
|
||||||
trafficlight.Cr4.South.red=30.0
|
trafficlight.Cr4.East.red=5.0
|
||||||
trafficlight.Cr4.East.green=20.0
|
|
||||||
trafficlight.Cr4.East.red=25.0
|
|
||||||
trafficlight.Cr4.West.green=15.0
|
|
||||||
trafficlight.Cr4.West.red=30.0
|
|
||||||
|
|
||||||
# Intersection 5 (Near exit - favor East)
|
# Intersection 5 (Near exit - favor East)
|
||||||
trafficlight.Cr5.South.green=15.0
|
trafficlight.Cr5.East.green=60.0
|
||||||
trafficlight.Cr5.South.red=30.0
|
trafficlight.Cr5.East.red=5.0
|
||||||
trafficlight.Cr5.East.green=22.0
|
|
||||||
trafficlight.Cr5.East.red=23.0
|
|
||||||
trafficlight.Cr5.West.green=15.0
|
|
||||||
trafficlight.Cr5.West.red=30.0
|
|
||||||
|
|
||||||
# === VEHICLE CONFIGURATION ===
|
# === VEHICLE CONFIGURATION ===
|
||||||
# Probability distribution for vehicle types (must sum to 1.0)
|
# Probability distribution for vehicle types (must sum to 1.0)
|
||||||
@@ -99,13 +92,13 @@ vehicle.crossing.time.heavy=4.0
|
|||||||
|
|
||||||
# Travel times between intersections (in seconds)
|
# Travel times between intersections (in seconds)
|
||||||
# Base time for light vehicles (cars)
|
# Base time for light vehicles (cars)
|
||||||
vehicle.travel.time.base=8.0
|
vehicle.travel.time.base=1.0
|
||||||
# Bike travel time = 0.5 × car travel time
|
# Bike travel time = 0.5 × car travel time
|
||||||
vehicle.travel.time.bike.multiplier=0.5
|
vehicle.travel.time.bike.multiplier=0.5
|
||||||
# Heavy vehicle travel time = 4 × bike travel time
|
# Heavy vehicle travel time = 4.0 x base travel time
|
||||||
vehicle.travel.time.heavy.multiplier=2.0
|
vehicle.travel.time.heavy.multiplier=4.0
|
||||||
|
|
||||||
# === STATISTICS ===
|
# === STATISTICS ===
|
||||||
|
|
||||||
# Interval between dashboard updates (seconds)
|
# Interval between dashboard updates (seconds)
|
||||||
statistics.update.interval=1.0
|
statistics.update.interval=0.1
|
||||||
|
|||||||
@@ -1,527 +0,0 @@
|
|||||||
import java.io.IOException;
|
|
||||||
import java.net.InetSocketAddress;
|
|
||||||
import java.net.Socket;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.util.Arrays;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.AfterEach;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.junit.jupiter.api.Timeout;
|
|
||||||
import org.junit.jupiter.api.io.TempDir;
|
|
||||||
|
|
||||||
import sd.IntersectionProcess;
|
|
||||||
import sd.model.MessageType;
|
|
||||||
import sd.model.Vehicle;
|
|
||||||
import sd.model.VehicleType;
|
|
||||||
import sd.protocol.SocketConnection;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tests for IntersectionProcess - covers initialization, traffic lights,
|
|
||||||
* vehicle transfer and network stuff
|
|
||||||
*/
|
|
||||||
public class IntersectionProcessTest {
|
|
||||||
|
|
||||||
@TempDir
|
|
||||||
Path tempDir;
|
|
||||||
|
|
||||||
private Path configFile;
|
|
||||||
private IntersectionProcess intersectionProcess;
|
|
||||||
|
|
||||||
// setup test config before each test
|
|
||||||
@BeforeEach
|
|
||||||
public void setUp() throws IOException {
|
|
||||||
// create temp config file
|
|
||||||
configFile = tempDir.resolve("test-simulation.properties");
|
|
||||||
|
|
||||||
String configContent = """
|
|
||||||
# Test Simulation Configuration
|
|
||||||
|
|
||||||
# Intersection Network Configuration
|
|
||||||
intersection.Cr1.host=localhost
|
|
||||||
intersection.Cr1.port=18001
|
|
||||||
intersection.Cr2.host=localhost
|
|
||||||
intersection.Cr2.port=18002
|
|
||||||
intersection.Cr3.host=localhost
|
|
||||||
intersection.Cr3.port=18003
|
|
||||||
intersection.Cr4.host=localhost
|
|
||||||
intersection.Cr4.port=18004
|
|
||||||
intersection.Cr5.host=localhost
|
|
||||||
intersection.Cr5.port=18005
|
|
||||||
|
|
||||||
# Exit Configuration
|
|
||||||
exit.host=localhost
|
|
||||||
exit.port=18099
|
|
||||||
|
|
||||||
# Dashboard Configuration
|
|
||||||
dashboard.host=localhost
|
|
||||||
dashboard.port=18100
|
|
||||||
|
|
||||||
# Traffic Light Timing (seconds)
|
|
||||||
trafficLight.Cr1.East.greenTime=5.0
|
|
||||||
trafficLight.Cr1.East.redTime=5.0
|
|
||||||
trafficLight.Cr1.South.greenTime=5.0
|
|
||||||
trafficLight.Cr1.South.redTime=5.0
|
|
||||||
trafficLight.Cr1.West.greenTime=5.0
|
|
||||||
trafficLight.Cr1.West.redTime=5.0
|
|
||||||
|
|
||||||
trafficLight.Cr2.West.greenTime=4.0
|
|
||||||
trafficLight.Cr2.West.redTime=6.0
|
|
||||||
trafficLight.Cr2.East.greenTime=4.0
|
|
||||||
trafficLight.Cr2.East.redTime=6.0
|
|
||||||
trafficLight.Cr2.South.greenTime=4.0
|
|
||||||
trafficLight.Cr2.South.redTime=6.0
|
|
||||||
|
|
||||||
trafficLight.Cr3.West.greenTime=3.0
|
|
||||||
trafficLight.Cr3.West.redTime=7.0
|
|
||||||
trafficLight.Cr3.East.greenTime=3.0
|
|
||||||
trafficLight.Cr3.East.redTime=7.0
|
|
||||||
|
|
||||||
trafficLight.Cr4.East.greenTime=6.0
|
|
||||||
trafficLight.Cr4.East.redTime=4.0
|
|
||||||
|
|
||||||
trafficLight.Cr5.East.greenTime=5.0
|
|
||||||
trafficLight.Cr5.East.redTime=5.0
|
|
||||||
|
|
||||||
# Vehicle Crossing Times (seconds)
|
|
||||||
vehicle.bike.crossingTime=2.0
|
|
||||||
vehicle.light.crossingTime=3.0
|
|
||||||
vehicle.heavy.crossingTime=5.0
|
|
||||||
""";
|
|
||||||
|
|
||||||
Files.writeString(configFile, configContent);
|
|
||||||
}
|
|
||||||
|
|
||||||
@AfterEach
|
|
||||||
public void tearDown() {
|
|
||||||
if (intersectionProcess != null) {
|
|
||||||
try {
|
|
||||||
// Only shutdown if still running
|
|
||||||
intersectionProcess.shutdown();
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.err.println("Error in tearDown: " + e.getMessage());
|
|
||||||
} finally {
|
|
||||||
intersectionProcess = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ==================== Initialization Tests ====================
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testConstructor_Success() throws IOException {
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
|
||||||
assertNotNull(intersectionProcess);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testConstructor_InvalidConfig() {
|
|
||||||
Exception exception = assertThrows(IOException.class, () -> {
|
|
||||||
new IntersectionProcess("Cr1", "non-existent-config.properties");
|
|
||||||
});
|
|
||||||
assertNotNull(exception);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testInitialize_Cr1() throws IOException {
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
|
||||||
assertDoesNotThrow(() -> intersectionProcess.initialize());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testInitialize_Cr2() throws IOException {
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr2", configFile.toString());
|
|
||||||
assertDoesNotThrow(() -> intersectionProcess.initialize());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testInitialize_Cr3() throws IOException {
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr3", configFile.toString());
|
|
||||||
assertDoesNotThrow(() -> intersectionProcess.initialize());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testInitialize_Cr4() throws IOException {
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr4", configFile.toString());
|
|
||||||
assertDoesNotThrow(() -> intersectionProcess.initialize());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testInitialize_Cr5() throws IOException {
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr5", configFile.toString());
|
|
||||||
assertDoesNotThrow(() -> intersectionProcess.initialize());
|
|
||||||
}
|
|
||||||
|
|
||||||
// traffic light creation tests
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testTrafficLightCreation_Cr1_HasCorrectDirections() throws IOException {
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
|
||||||
intersectionProcess.initialize();
|
|
||||||
|
|
||||||
// cant access private fields but initialization succeds
|
|
||||||
assertNotNull(intersectionProcess);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testTrafficLightCreation_Cr3_HasCorrectDirections() throws IOException {
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr3", configFile.toString());
|
|
||||||
intersectionProcess.initialize();
|
|
||||||
|
|
||||||
// Cr3 has west and south only
|
|
||||||
assertNotNull(intersectionProcess);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testTrafficLightCreation_Cr4_HasSingleDirection() throws IOException {
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr4", configFile.toString());
|
|
||||||
intersectionProcess.initialize();
|
|
||||||
|
|
||||||
// Cr4 only has east direction
|
|
||||||
assertNotNull(intersectionProcess);
|
|
||||||
}
|
|
||||||
|
|
||||||
// server startup tests
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Timeout(5)
|
|
||||||
public void testServerStart_BindsToCorrectPort() throws IOException, InterruptedException {
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
|
||||||
intersectionProcess.initialize();
|
|
||||||
|
|
||||||
// start server in separate thread
|
|
||||||
Thread serverThread = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
intersectionProcess.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
// expected on shutdown
|
|
||||||
}
|
|
||||||
});
|
|
||||||
serverThread.start();
|
|
||||||
|
|
||||||
// Wait for server to actually start with retries
|
|
||||||
boolean serverReady = false;
|
|
||||||
for (int i = 0; i < 20; i++) {
|
|
||||||
Thread.sleep(100);
|
|
||||||
try (Socket testSocket = new Socket()) {
|
|
||||||
testSocket.connect(new java.net.InetSocketAddress("localhost", 18001), 500);
|
|
||||||
serverReady = true;
|
|
||||||
break;
|
|
||||||
} catch (IOException e) {
|
|
||||||
// Server not ready yet, continue waiting
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
assertTrue(serverReady, "Server should start and bind to port 18001");
|
|
||||||
|
|
||||||
// Shutdown immediately after confirming server is running
|
|
||||||
intersectionProcess.shutdown();
|
|
||||||
serverThread.join(2000);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Timeout(5)
|
|
||||||
public void testServerStart_MultipleIntersections() throws IOException, InterruptedException {
|
|
||||||
// test 2 intersections on diferent ports
|
|
||||||
IntersectionProcess cr1 = new IntersectionProcess("Cr1", configFile.toString());
|
|
||||||
IntersectionProcess cr2 = new IntersectionProcess("Cr2", configFile.toString());
|
|
||||||
|
|
||||||
cr1.initialize();
|
|
||||||
cr2.initialize();
|
|
||||||
|
|
||||||
Thread thread1 = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
cr1.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Thread thread2 = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
cr2.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
thread1.start();
|
|
||||||
thread2.start();
|
|
||||||
|
|
||||||
Thread.sleep(500);
|
|
||||||
|
|
||||||
// check both are running
|
|
||||||
try (Socket socket1 = new Socket("localhost", 18001);
|
|
||||||
Socket socket2 = new Socket("localhost", 18002)) {
|
|
||||||
assertTrue(socket1.isConnected());
|
|
||||||
assertTrue(socket2.isConnected());
|
|
||||||
}
|
|
||||||
|
|
||||||
cr1.shutdown();
|
|
||||||
cr2.shutdown();
|
|
||||||
thread1.join(2000);
|
|
||||||
thread2.join(2000);
|
|
||||||
}
|
|
||||||
|
|
||||||
// vehicle transfer tests
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Timeout(10)
|
|
||||||
public void testVehicleTransfer_ReceiveVehicle() throws IOException, InterruptedException {
|
|
||||||
// setup reciever intersection
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr2", configFile.toString());
|
|
||||||
intersectionProcess.initialize();
|
|
||||||
|
|
||||||
Thread serverThread = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
intersectionProcess.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
}
|
|
||||||
});
|
|
||||||
serverThread.start();
|
|
||||||
|
|
||||||
Thread.sleep(500);
|
|
||||||
|
|
||||||
try {
|
|
||||||
// create test vehicle - FIXED: use 4-parameter constructor
|
|
||||||
java.util.List<String> route = Arrays.asList("Cr2", "Cr3", "S");
|
|
||||||
Vehicle vehicle = new Vehicle("V001", VehicleType.LIGHT, 0.0, route);
|
|
||||||
|
|
||||||
// send vehicle from Cr1 to Cr2 - FIXED: use SocketConnection
|
|
||||||
try (Socket socket = new Socket("localhost", 18002);
|
|
||||||
SocketConnection conn = new SocketConnection(socket)) {
|
|
||||||
|
|
||||||
TestVehicleMessage message = new TestVehicleMessage("Cr1", "Cr2", vehicle);
|
|
||||||
conn.sendMessage(message);
|
|
||||||
|
|
||||||
Thread.sleep(1000); // wait for processing
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
intersectionProcess.shutdown();
|
|
||||||
serverThread.join(2000);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// routing config tests
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testRoutingConfiguration_Cr1() throws IOException {
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
|
||||||
intersectionProcess.initialize();
|
|
||||||
|
|
||||||
// indirect test - if init works routing should be ok
|
|
||||||
assertNotNull(intersectionProcess);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testRoutingConfiguration_Cr5() throws IOException {
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr5", configFile.toString());
|
|
||||||
intersectionProcess.initialize();
|
|
||||||
|
|
||||||
// Cr5 routes to exit
|
|
||||||
assertNotNull(intersectionProcess);
|
|
||||||
}
|
|
||||||
|
|
||||||
// shutdown tests
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Timeout(5)
|
|
||||||
public void testShutdown_GracefulTermination() throws IOException, InterruptedException {
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
|
||||||
intersectionProcess.initialize();
|
|
||||||
|
|
||||||
Thread serverThread = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
intersectionProcess.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
}
|
|
||||||
});
|
|
||||||
serverThread.start();
|
|
||||||
|
|
||||||
Thread.sleep(500);
|
|
||||||
|
|
||||||
// shutdown should be fast
|
|
||||||
assertDoesNotThrow(() -> intersectionProcess.shutdown());
|
|
||||||
|
|
||||||
serverThread.join(2000);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Timeout(5)
|
|
||||||
public void testShutdown_ClosesServerSocket() throws IOException, InterruptedException {
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
|
||||||
intersectionProcess.initialize();
|
|
||||||
|
|
||||||
// Start server in separate thread
|
|
||||||
Thread serverThread = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
intersectionProcess.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
// Expected on shutdown
|
|
||||||
}
|
|
||||||
});
|
|
||||||
serverThread.start();
|
|
||||||
|
|
||||||
// Wait for server to start
|
|
||||||
Thread.sleep(500);
|
|
||||||
|
|
||||||
// Shutdown
|
|
||||||
intersectionProcess.shutdown();
|
|
||||||
serverThread.join(2000);
|
|
||||||
|
|
||||||
// Give shutdown time to complete
|
|
||||||
Thread.sleep(200);
|
|
||||||
|
|
||||||
// Verify we cannot connect (server socket is closed)
|
|
||||||
boolean connectionFailed = false;
|
|
||||||
try (Socket testSocket = new Socket()) {
|
|
||||||
testSocket.connect(new InetSocketAddress("localhost", 18001), 500);
|
|
||||||
} catch (IOException e) {
|
|
||||||
connectionFailed = true; // Expected - server should be closed
|
|
||||||
}
|
|
||||||
|
|
||||||
assertTrue(connectionFailed, "Server socket should be closed after shutdown");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Timeout(5)
|
|
||||||
public void testShutdown_StopsTrafficLightThreads() throws IOException, InterruptedException {
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
|
||||||
intersectionProcess.initialize();
|
|
||||||
|
|
||||||
Thread serverThread = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
intersectionProcess.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
}
|
|
||||||
});
|
|
||||||
serverThread.start();
|
|
||||||
|
|
||||||
Thread.sleep(500);
|
|
||||||
|
|
||||||
int threadCountBefore = Thread.activeCount();
|
|
||||||
|
|
||||||
intersectionProcess.shutdown();
|
|
||||||
serverThread.join(2000);
|
|
||||||
|
|
||||||
Thread.sleep(500); // wait for threads to die
|
|
||||||
|
|
||||||
// thread count should decrese (traffic light threads stop)
|
|
||||||
int threadCountAfter = Thread.activeCount();
|
|
||||||
assertTrue(threadCountAfter <= threadCountBefore);
|
|
||||||
}
|
|
||||||
|
|
||||||
// integration tests
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Timeout(15)
|
|
||||||
public void testIntegration_TwoIntersectionsVehicleTransfer() throws IOException, InterruptedException {
|
|
||||||
IntersectionProcess cr1 = null;
|
|
||||||
IntersectionProcess cr2 = null;
|
|
||||||
Thread thread1 = null;
|
|
||||||
Thread thread2 = null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
// setup 2 intersections
|
|
||||||
cr1 = new IntersectionProcess("Cr1", configFile.toString());
|
|
||||||
cr2 = new IntersectionProcess("Cr2", configFile.toString());
|
|
||||||
|
|
||||||
cr1.initialize();
|
|
||||||
cr2.initialize();
|
|
||||||
|
|
||||||
// start both
|
|
||||||
final IntersectionProcess cr1Final = cr1;
|
|
||||||
thread1 = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
cr1Final.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
final IntersectionProcess cr2Final = cr2;
|
|
||||||
thread2 = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
cr2Final.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
thread1.start();
|
|
||||||
thread2.start();
|
|
||||||
|
|
||||||
Thread.sleep(1000); // wait for servers
|
|
||||||
|
|
||||||
// send vehicle to Cr1 that goes to Cr2 - FIXED: use 4-parameter constructor
|
|
||||||
java.util.List<String> route = Arrays.asList("Cr1", "Cr2", "S");
|
|
||||||
Vehicle vehicle = new Vehicle("V001", VehicleType.LIGHT, 0.0, route);
|
|
||||||
|
|
||||||
// FIXED: use SocketConnection
|
|
||||||
try (Socket socket = new Socket("localhost", 18001);
|
|
||||||
SocketConnection conn = new SocketConnection(socket)) {
|
|
||||||
|
|
||||||
TestVehicleMessage message = new TestVehicleMessage("Entry", "Cr1", vehicle);
|
|
||||||
conn.sendMessage(message);
|
|
||||||
|
|
||||||
Thread.sleep(2000); // time for processing
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
if (cr1 != null) {
|
|
||||||
cr1.shutdown();
|
|
||||||
}
|
|
||||||
if (cr2 != null) {
|
|
||||||
cr2.shutdown();
|
|
||||||
}
|
|
||||||
if (thread1 != null) {
|
|
||||||
thread1.join(2000);
|
|
||||||
}
|
|
||||||
if (thread2 != null) {
|
|
||||||
thread2.join(2000);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testMain_MissingArguments() {
|
|
||||||
// main needs intersection ID as argument
|
|
||||||
// cant test System.exit easily in modern java
|
|
||||||
assertTrue(true, "Main method expects intersection ID as first argument");
|
|
||||||
}
|
|
||||||
|
|
||||||
// helper class for testing vehicle messages
|
|
||||||
private static class TestVehicleMessage implements sd.protocol.MessageProtocol {
|
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
|
|
||||||
private final String sourceNode;
|
|
||||||
private final String destinationNode;
|
|
||||||
private final Vehicle payload;
|
|
||||||
|
|
||||||
public TestVehicleMessage(String sourceNode, String destinationNode, Vehicle vehicle) {
|
|
||||||
this.sourceNode = sourceNode;
|
|
||||||
this.destinationNode = destinationNode;
|
|
||||||
this.payload = vehicle;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public MessageType getType() {
|
|
||||||
return MessageType.VEHICLE_TRANSFER;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object getPayload() {
|
|
||||||
return payload;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getSourceNode() {
|
|
||||||
return sourceNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getDestinationNode() {
|
|
||||||
return destinationNode;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import sd.config.SimulationConfig;
|
|
||||||
import sd.model.Intersection;
|
|
||||||
import sd.model.TrafficLight;
|
|
||||||
import sd.model.TrafficLightState;
|
|
||||||
import sd.model.Vehicle;
|
|
||||||
import sd.model.VehicleType;
|
|
||||||
import sd.util.VehicleGenerator;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Basic tests for the simulation components.
|
|
||||||
*/
|
|
||||||
class SimulationTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testConfigurationLoading() throws IOException {
|
|
||||||
SimulationConfig config = new SimulationConfig("src/main/resources/simulation.properties");
|
|
||||||
|
|
||||||
assertEquals(60.0, config.getSimulationDuration());
|
|
||||||
assertEquals("POISSON", config.getArrivalModel());
|
|
||||||
assertEquals(0.5, config.getArrivalRate());
|
|
||||||
assertEquals(1.0, config.getStatisticsUpdateInterval());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testVehicleGeneration() throws IOException {
|
|
||||||
SimulationConfig config = new SimulationConfig("src/main/resources/simulation.properties");
|
|
||||||
VehicleGenerator generator = new VehicleGenerator(config);
|
|
||||||
|
|
||||||
Vehicle vehicle = generator.generateVehicle("TEST1", 0.0);
|
|
||||||
|
|
||||||
assertNotNull(vehicle);
|
|
||||||
assertEquals("TEST1", vehicle.getId());
|
|
||||||
assertNotNull(vehicle.getType());
|
|
||||||
assertNotNull(vehicle.getRoute());
|
|
||||||
assertTrue(!vehicle.getRoute().isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testIntersectionVehicleQueue() {
|
|
||||||
Intersection intersection = new Intersection("TestCr");
|
|
||||||
TrafficLight light = new TrafficLight("TestCr-N", "North", 30.0, 30.0);
|
|
||||||
|
|
||||||
intersection.addTrafficLight(light);
|
|
||||||
|
|
||||||
Vehicle v1 = new Vehicle("V1", VehicleType.LIGHT, 0.0,
|
|
||||||
java.util.Arrays.asList("TestCr", "S"));
|
|
||||||
|
|
||||||
intersection.configureRoute("S", "North");
|
|
||||||
|
|
||||||
// Advance route to next destination
|
|
||||||
v1.advanceRoute();
|
|
||||||
|
|
||||||
intersection.receiveVehicle(v1);
|
|
||||||
|
|
||||||
assertEquals(1, intersection.getTotalQueueSize());
|
|
||||||
assertEquals(1, intersection.getTotalVehiclesReceived());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testTrafficLightStateChange() {
|
|
||||||
TrafficLight light = new TrafficLight("Test-Light", "North", 30.0, 30.0);
|
|
||||||
|
|
||||||
assertEquals(TrafficLightState.RED, light.getState());
|
|
||||||
|
|
||||||
light.changeState(TrafficLightState.GREEN);
|
|
||||||
assertEquals(TrafficLightState.GREEN, light.getState());
|
|
||||||
|
|
||||||
light.changeState(TrafficLightState.RED);
|
|
||||||
assertEquals(TrafficLightState.RED, light.getState());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Removed testSimulationEngineInitialization as SimulationEngine has been
|
|
||||||
// removed.
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,327 +0,0 @@
|
|||||||
package sd;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.Socket;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.util.concurrent.CountDownLatch;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.AfterEach;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.junit.jupiter.api.Timeout;
|
|
||||||
import org.junit.jupiter.api.io.TempDir;
|
|
||||||
|
|
||||||
import sd.config.SimulationConfig;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Testes unitários para a classe ExitNodeProcess.
|
|
||||||
*
|
|
||||||
* Esta classe de testes verifica:
|
|
||||||
* - Construção e inicialização do processo
|
|
||||||
* - Criação e aceitação de conexões do servidor socket
|
|
||||||
* - Gestão do ciclo de vida (start/shutdown)
|
|
||||||
* - Processamento concorrente de múltiplas conexões
|
|
||||||
* - Impressão de estatísticas finais
|
|
||||||
*
|
|
||||||
* Os testes utilizam configurações temporárias e portas dedicadas (19001)
|
|
||||||
* para evitar conflitos com outros testes ou processos em execução.
|
|
||||||
*/
|
|
||||||
public class ExitNodeProcessTest {
|
|
||||||
|
|
||||||
@TempDir
|
|
||||||
Path tempDir;
|
|
||||||
|
|
||||||
private Path configFile;
|
|
||||||
private ExitNodeProcess exitNodeProcess;
|
|
||||||
private Thread exitNodeThread;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Configura o ambiente de teste antes de cada teste.
|
|
||||||
* Cria um ficheiro de configuração temporário com as definições necessárias.
|
|
||||||
*/
|
|
||||||
@BeforeEach
|
|
||||||
public void setUp() throws IOException {
|
|
||||||
configFile = tempDir.resolve("test-simulation.properties");
|
|
||||||
|
|
||||||
String configContent = """
|
|
||||||
# Test Exit Node Configuration
|
|
||||||
|
|
||||||
# Exit Configuration
|
|
||||||
exit.host=localhost
|
|
||||||
exit.port=19001
|
|
||||||
|
|
||||||
# Dashboard Configuration (will not be running in tests)
|
|
||||||
dashboard.host=localhost
|
|
||||||
dashboard.port=19000
|
|
||||||
|
|
||||||
# Vehicle Crossing Times
|
|
||||||
vehicle.bike.crossingTime=2.0
|
|
||||||
vehicle.light.crossingTime=3.0
|
|
||||||
vehicle.heavy.crossingTime=5.0
|
|
||||||
|
|
||||||
# Simulation Duration
|
|
||||||
simulation.duration=60.0
|
|
||||||
""";
|
|
||||||
|
|
||||||
Files.writeString(configFile, configContent);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Limpa os recursos após cada teste.
|
|
||||||
* Garante que o processo e threads são terminados corretamente.
|
|
||||||
*/
|
|
||||||
@AfterEach
|
|
||||||
public void tearDown() {
|
|
||||||
if (exitNodeProcess != null) {
|
|
||||||
exitNodeProcess.shutdown();
|
|
||||||
}
|
|
||||||
if (exitNodeThread != null && exitNodeThread.isAlive()) {
|
|
||||||
exitNodeThread.interrupt();
|
|
||||||
try {
|
|
||||||
exitNodeThread.join(1000);
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Testa a construção bem-sucedida do ExitNodeProcess com configuração válida.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
public void testConstructor_Success() throws IOException {
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile.toString());
|
|
||||||
exitNodeProcess = new ExitNodeProcess(config);
|
|
||||||
assertNotNull(exitNodeProcess);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Testa que uma exceção é lançada quando a configuração é inválida.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
public void testConstructor_InvalidConfig() {
|
|
||||||
Exception exception = assertThrows(IOException.class, () -> {
|
|
||||||
new SimulationConfig("non-existent-config.properties");
|
|
||||||
});
|
|
||||||
assertNotNull(exception);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Testa a inicialização sem dashboard disponível.
|
|
||||||
* Verifica que o processo continua a funcionar mesmo sem conexão ao dashboard.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
public void testInitialize_WithoutDashboard() throws IOException {
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile.toString());
|
|
||||||
exitNodeProcess = new ExitNodeProcess(config);
|
|
||||||
assertDoesNotThrow(() -> exitNodeProcess.initialize());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Testa que o servidor socket é criado corretamente na porta configurada.
|
|
||||||
* Verifica que é possível estabelecer uma conexão ao socket do servidor.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
@Timeout(value = 3, unit = TimeUnit.SECONDS)
|
|
||||||
public void testStart_ServerSocketCreated() throws IOException {
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile.toString());
|
|
||||||
exitNodeProcess = new ExitNodeProcess(config);
|
|
||||||
exitNodeProcess.initialize();
|
|
||||||
|
|
||||||
CountDownLatch latch = new CountDownLatch(1);
|
|
||||||
|
|
||||||
exitNodeThread = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
latch.countDown();
|
|
||||||
exitNodeProcess.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
// expected when shutdown
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
exitNodeThread.start();
|
|
||||||
|
|
||||||
try {
|
|
||||||
assertTrue(latch.await(2, TimeUnit.SECONDS), "Exit node should start within timeout");
|
|
||||||
Thread.sleep(100);
|
|
||||||
|
|
||||||
assertDoesNotThrow(() -> {
|
|
||||||
try (Socket testSocket = new Socket("localhost", 19001)) {
|
|
||||||
assertTrue(testSocket.isConnected());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Testa que o servidor aceita conexões de clientes.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
@Timeout(value = 3, unit = TimeUnit.SECONDS)
|
|
||||||
public void testStart_AcceptsConnection() throws IOException, InterruptedException {
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile.toString());
|
|
||||||
exitNodeProcess = new ExitNodeProcess(config);
|
|
||||||
exitNodeProcess.initialize();
|
|
||||||
|
|
||||||
CountDownLatch latch = new CountDownLatch(1);
|
|
||||||
|
|
||||||
exitNodeThread = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
latch.countDown();
|
|
||||||
exitNodeProcess.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
// expected
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
exitNodeThread.start();
|
|
||||||
|
|
||||||
assertTrue(latch.await(2, TimeUnit.SECONDS));
|
|
||||||
Thread.sleep(200);
|
|
||||||
|
|
||||||
assertDoesNotThrow(() -> {
|
|
||||||
try (Socket socket = new Socket("localhost", 19001)) {
|
|
||||||
assertTrue(socket.isConnected());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Testa múltiplas inicializações e encerramentos do processo.
|
|
||||||
* Verifica que o processo pode ser iniciado e parado múltiplas vezes,
|
|
||||||
* permitindo reutilização da porta.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
@Timeout(value = 3, unit = TimeUnit.SECONDS)
|
|
||||||
public void testMultipleStartStop() throws IOException, InterruptedException {
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile.toString());
|
|
||||||
exitNodeProcess = new ExitNodeProcess(config);
|
|
||||||
exitNodeProcess.initialize();
|
|
||||||
|
|
||||||
CountDownLatch latch = new CountDownLatch(1);
|
|
||||||
|
|
||||||
exitNodeThread = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
latch.countDown();
|
|
||||||
exitNodeProcess.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
// expected
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
exitNodeThread.start();
|
|
||||||
assertTrue(latch.await(2, TimeUnit.SECONDS));
|
|
||||||
Thread.sleep(100);
|
|
||||||
|
|
||||||
exitNodeProcess.shutdown();
|
|
||||||
Thread.sleep(100);
|
|
||||||
|
|
||||||
assertDoesNotThrow(() -> {
|
|
||||||
SimulationConfig config2 = new SimulationConfig(configFile.toString());
|
|
||||||
ExitNodeProcess exitNode2 = new ExitNodeProcess(config2);
|
|
||||||
exitNode2.initialize();
|
|
||||||
exitNode2.shutdown();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Testa que o shutdown fecha corretamente o servidor socket.
|
|
||||||
* Após o shutdown, novas conexões ao socket devem falhar.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
@Timeout(value = 3, unit = TimeUnit.SECONDS)
|
|
||||||
public void testShutdown_ClosesServerSocket() throws IOException, InterruptedException {
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile.toString());
|
|
||||||
exitNodeProcess = new ExitNodeProcess(config);
|
|
||||||
exitNodeProcess.initialize();
|
|
||||||
|
|
||||||
CountDownLatch startLatch = new CountDownLatch(1);
|
|
||||||
|
|
||||||
exitNodeThread = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
startLatch.countDown();
|
|
||||||
exitNodeProcess.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
// expected
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
exitNodeThread.start();
|
|
||||||
assertTrue(startLatch.await(2, TimeUnit.SECONDS));
|
|
||||||
Thread.sleep(200);
|
|
||||||
|
|
||||||
exitNodeProcess.shutdown();
|
|
||||||
Thread.sleep(200);
|
|
||||||
|
|
||||||
assertThrows(IOException.class, () -> {
|
|
||||||
Socket socket = new Socket("localhost", 19001);
|
|
||||||
socket.close();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Testa que as estatísticas finais são impressas corretamente durante o shutdown.
|
|
||||||
* Verifica que o método não lança exceções mesmo sem dados processados.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
public void testPrintFinalStatistics() throws IOException {
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile.toString());
|
|
||||||
exitNodeProcess = new ExitNodeProcess(config);
|
|
||||||
exitNodeProcess.initialize();
|
|
||||||
|
|
||||||
assertDoesNotThrow(() -> exitNodeProcess.shutdown());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Testa o processamento de múltiplas conexões concorrentes.
|
|
||||||
* Verifica que o servidor consegue lidar com vários clientes simultaneamente
|
|
||||||
* usando o pool de threads.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
@Timeout(value = 3, unit = TimeUnit.SECONDS)
|
|
||||||
public void testMultipleConcurrentConnections() throws IOException, InterruptedException {
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile.toString());
|
|
||||||
exitNodeProcess = new ExitNodeProcess(config);
|
|
||||||
exitNodeProcess.initialize();
|
|
||||||
|
|
||||||
CountDownLatch latch = new CountDownLatch(1);
|
|
||||||
|
|
||||||
exitNodeThread = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
latch.countDown();
|
|
||||||
exitNodeProcess.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
// expected
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
exitNodeThread.start();
|
|
||||||
assertTrue(latch.await(2, TimeUnit.SECONDS));
|
|
||||||
Thread.sleep(200);
|
|
||||||
|
|
||||||
Thread[] clients = new Thread[3];
|
|
||||||
for (int i = 0; i < 3; i++) {
|
|
||||||
clients[i] = new Thread(() -> {
|
|
||||||
try (Socket socket = new Socket("localhost", 19001)) {
|
|
||||||
assertTrue(socket.isConnected());
|
|
||||||
Thread.sleep(100);
|
|
||||||
} catch (IOException | InterruptedException e) {
|
|
||||||
// ignore
|
|
||||||
}
|
|
||||||
});
|
|
||||||
clients[i].start();
|
|
||||||
}
|
|
||||||
|
|
||||||
for (Thread client : clients) {
|
|
||||||
client.join(1000);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,207 +0,0 @@
|
|||||||
package sd;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.AfterEach;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import sd.model.TrafficLight;
|
|
||||||
import sd.model.TrafficLightState;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Test class to verify traffic light coordination within an intersection.
|
|
||||||
* Ensures that only ONE traffic light can be GREEN at any given time.
|
|
||||||
*/
|
|
||||||
public class TrafficLightCoordinationTest {
|
|
||||||
|
|
||||||
private IntersectionProcess intersectionProcess;
|
|
||||||
|
|
||||||
@BeforeEach
|
|
||||||
public void setUp() throws IOException {
|
|
||||||
// Create an intersection with multiple traffic lights
|
|
||||||
intersectionProcess = new IntersectionProcess("Cr2", "src/main/resources/simulation.properties");
|
|
||||||
intersectionProcess.initialize();
|
|
||||||
}
|
|
||||||
|
|
||||||
@AfterEach
|
|
||||||
public void tearDown() throws InterruptedException {
|
|
||||||
if (intersectionProcess != null) {
|
|
||||||
intersectionProcess.shutdown();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Test that verifies mutual exclusion between traffic lights.
|
|
||||||
* Monitors all traffic lights for 10 seconds and ensures that
|
|
||||||
* at most ONE light is GREEN at any point in time.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
public void testOnlyOneGreenLightAtATime() throws InterruptedException {
|
|
||||||
System.out.println("\n=== Testing Traffic Light Mutual Exclusion ===");
|
|
||||||
|
|
||||||
// Start the intersection
|
|
||||||
Thread intersectionThread = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
intersectionProcess.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
intersectionThread.start();
|
|
||||||
|
|
||||||
// Monitor traffic lights for violations
|
|
||||||
AtomicInteger maxGreenSimultaneously = new AtomicInteger(0);
|
|
||||||
AtomicInteger violationCount = new AtomicInteger(0);
|
|
||||||
List<String> violations = new ArrayList<>();
|
|
||||||
|
|
||||||
// Monitor for 10 seconds
|
|
||||||
long endTime = System.currentTimeMillis() + 10000;
|
|
||||||
|
|
||||||
while (System.currentTimeMillis() < endTime) {
|
|
||||||
int greenCount = 0;
|
|
||||||
StringBuilder currentState = new StringBuilder("States: ");
|
|
||||||
|
|
||||||
for (TrafficLight light : intersectionProcess.getIntersection().getTrafficLights()) {
|
|
||||||
TrafficLightState state = light.getState();
|
|
||||||
currentState.append(light.getDirection()).append("=").append(state).append(" ");
|
|
||||||
|
|
||||||
if (state == TrafficLightState.GREEN) {
|
|
||||||
greenCount++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update maximum simultaneous green lights
|
|
||||||
if (greenCount > maxGreenSimultaneously.get()) {
|
|
||||||
maxGreenSimultaneously.set(greenCount);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for violations (more than one green)
|
|
||||||
if (greenCount > 1) {
|
|
||||||
violationCount.incrementAndGet();
|
|
||||||
String violation = String.format("[VIOLATION] %d lights GREEN simultaneously: %s",
|
|
||||||
greenCount, currentState.toString());
|
|
||||||
violations.add(violation);
|
|
||||||
System.err.println(violation);
|
|
||||||
}
|
|
||||||
|
|
||||||
Thread.sleep(50); // Check every 50ms
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("\n=== Test Results ===");
|
|
||||||
System.out.println("Maximum simultaneous GREEN lights: " + maxGreenSimultaneously.get());
|
|
||||||
System.out.println("Total violations detected: " + violationCount.get());
|
|
||||||
|
|
||||||
if (!violations.isEmpty()) {
|
|
||||||
System.err.println("\nViolation details:");
|
|
||||||
violations.forEach(System.err::println);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Assert that we never had more than one green light
|
|
||||||
assertEquals(0, violationCount.get(),
|
|
||||||
"Traffic light coordination violated! Multiple lights were GREEN simultaneously.");
|
|
||||||
assertTrue(maxGreenSimultaneously.get() <= 1,
|
|
||||||
"At most ONE light should be GREEN at any time. Found: " + maxGreenSimultaneously.get());
|
|
||||||
|
|
||||||
System.out.println("\nTraffic light coordination working correctly!");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Test that verifies all traffic lights get a chance to be GREEN.
|
|
||||||
* Ensures fairness in the coordination mechanism.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
public void testAllLightsGetGreenTime() throws InterruptedException {
|
|
||||||
System.out.println("\n=== Testing Traffic Light Fairness ===");
|
|
||||||
|
|
||||||
// Start the intersection
|
|
||||||
Thread intersectionThread = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
intersectionProcess.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
intersectionThread.start();
|
|
||||||
|
|
||||||
// Track which lights have been green
|
|
||||||
List<TrafficLight> lights = intersectionProcess.getIntersection().getTrafficLights();
|
|
||||||
boolean[] hasBeenGreen = new boolean[lights.size()];
|
|
||||||
|
|
||||||
// Monitor for 60 seconds (enough time for all lights to cycle: 18+18+12 = 48s)
|
|
||||||
long endTime = System.currentTimeMillis() + 60000;
|
|
||||||
|
|
||||||
while (System.currentTimeMillis() < endTime) {
|
|
||||||
for (int i = 0; i < lights.size(); i++) {
|
|
||||||
if (lights.get(i).getState() == TrafficLightState.GREEN) {
|
|
||||||
hasBeenGreen[i] = true;
|
|
||||||
System.out.println("✓ " + lights.get(i).getDirection() + " has been GREEN");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Thread.sleep(100);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if all lights got green time
|
|
||||||
int greenCount = 0;
|
|
||||||
System.out.println("\n=== Fairness Results ===");
|
|
||||||
for (int i = 0; i < lights.size(); i++) {
|
|
||||||
String status = hasBeenGreen[i] ? "✓ YES" : "✗ NO";
|
|
||||||
System.out.println(lights.get(i).getDirection() + " got GREEN time: " + status);
|
|
||||||
if (hasBeenGreen[i])
|
|
||||||
greenCount++;
|
|
||||||
}
|
|
||||||
|
|
||||||
assertTrue(greenCount > 0, "At least one light should have been GREEN during the test");
|
|
||||||
System.out.println("\n" + greenCount + "/" + lights.size() + " lights were GREEN during test period");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Test that verifies the state transitions are consistent.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
public void testStateTransitionsAreConsistent() throws InterruptedException {
|
|
||||||
System.out.println("\n=== Testing State Transition Consistency ===");
|
|
||||||
|
|
||||||
Thread intersectionThread = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
intersectionProcess.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
intersectionThread.start();
|
|
||||||
|
|
||||||
List<TrafficLight> lights = intersectionProcess.getIntersection().getTrafficLights();
|
|
||||||
TrafficLightState[] previousStates = new TrafficLightState[lights.size()];
|
|
||||||
|
|
||||||
// Initialize previous states
|
|
||||||
for (int i = 0; i < lights.size(); i++) {
|
|
||||||
previousStates[i] = lights.get(i).getState();
|
|
||||||
}
|
|
||||||
|
|
||||||
int transitionCount = 0;
|
|
||||||
long endTime = System.currentTimeMillis() + 8000;
|
|
||||||
|
|
||||||
while (System.currentTimeMillis() < endTime) {
|
|
||||||
for (int i = 0; i < lights.size(); i++) {
|
|
||||||
TrafficLightState currentState = lights.get(i).getState();
|
|
||||||
|
|
||||||
if (currentState != previousStates[i]) {
|
|
||||||
transitionCount++;
|
|
||||||
System.out.println(lights.get(i).getDirection() + " transitioned: " +
|
|
||||||
previousStates[i] + " → " + currentState);
|
|
||||||
previousStates[i] = currentState;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Thread.sleep(100);
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("\nTotal state transitions observed: " + transitionCount);
|
|
||||||
assertTrue(transitionCount > 0, "There should be state transitions during the test period");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,302 +0,0 @@
|
|||||||
package sd.coordinator;
|
|
||||||
|
|
||||||
import java.io.DataInputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.ServerSocket;
|
|
||||||
import java.net.Socket;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.AfterEach;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.junit.jupiter.api.Timeout;
|
|
||||||
|
|
||||||
import sd.model.Message;
|
|
||||||
import sd.model.MessageType;
|
|
||||||
import sd.model.Vehicle;
|
|
||||||
import sd.serialization.MessageSerializer;
|
|
||||||
import sd.serialization.SerializerFactory;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Integration tests for the Coordinator-side networking.
|
|
||||||
*
|
|
||||||
* What we’re checking here:
|
|
||||||
* 1. A SocketClient can actually connect to something listening
|
|
||||||
* 2. Messages go over the wire and can be deserialized
|
|
||||||
* 3. Vehicle payloads survive the trip
|
|
||||||
* 4. Shutdown messages can be broadcast to multiple intersections
|
|
||||||
*
|
|
||||||
* We do this by spinning up a tiny mock intersection server in-process.
|
|
||||||
*/
|
|
||||||
class CoordinatorIntegrationTest {
|
|
||||||
|
|
||||||
private List<MockIntersectionServer> mockServers;
|
|
||||||
private static final int BASE_PORT = 9001; // keep clear of real ports
|
|
||||||
|
|
||||||
@BeforeEach
|
|
||||||
void setUp() {
|
|
||||||
mockServers = new ArrayList<>();
|
|
||||||
}
|
|
||||||
|
|
||||||
@AfterEach
|
|
||||||
void tearDown() {
|
|
||||||
// Stop all mock servers
|
|
||||||
for (MockIntersectionServer server : mockServers) {
|
|
||||||
server.stop();
|
|
||||||
}
|
|
||||||
mockServers.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Can the client open a TCP connection to our fake intersection?
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
@Timeout(5)
|
|
||||||
void testSocketClientConnection() throws IOException, InterruptedException {
|
|
||||||
MockIntersectionServer server = new MockIntersectionServer("Cr1", BASE_PORT);
|
|
||||||
server.start();
|
|
||||||
mockServers.add(server);
|
|
||||||
|
|
||||||
// tiny pause to let the server bind
|
|
||||||
Thread.sleep(100);
|
|
||||||
|
|
||||||
SocketClient client = new SocketClient("Cr1", "localhost", BASE_PORT);
|
|
||||||
client.connect();
|
|
||||||
|
|
||||||
assertTrue(client.isConnected(), "Client should be connected to mock intersection");
|
|
||||||
|
|
||||||
client.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* End-to-end: send a message, make sure the server actually receives it.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
@Timeout(5)
|
|
||||||
void testMessageTransmission() throws Exception {
|
|
||||||
MockIntersectionServer server = new MockIntersectionServer("Cr1", BASE_PORT);
|
|
||||||
server.start();
|
|
||||||
mockServers.add(server);
|
|
||||||
|
|
||||||
Thread.sleep(100);
|
|
||||||
|
|
||||||
SocketClient client = new SocketClient("Cr1", "localhost", BASE_PORT);
|
|
||||||
client.connect();
|
|
||||||
|
|
||||||
Message testMessage = new Message(
|
|
||||||
MessageType.VEHICLE_SPAWN,
|
|
||||||
"COORDINATOR",
|
|
||||||
"Cr1",
|
|
||||||
"Test payload"
|
|
||||||
);
|
|
||||||
|
|
||||||
client.send(testMessage);
|
|
||||||
|
|
||||||
// give the server a moment to read and deserialize
|
|
||||||
Thread.sleep(200);
|
|
||||||
|
|
||||||
assertFalse(
|
|
||||||
server.getReceivedMessages().isEmpty(),
|
|
||||||
"Mock server should have received at least one message"
|
|
||||||
);
|
|
||||||
|
|
||||||
Message receivedMsg = server.getReceivedMessages().poll();
|
|
||||||
assertNotNull(receivedMsg, "Server should have actually received a message");
|
|
||||||
assertEquals(MessageType.VEHICLE_SPAWN, receivedMsg.getType(), "Message type should match what we sent");
|
|
||||||
assertEquals("COORDINATOR", receivedMsg.getSenderId(), "Sender ID should be preserved");
|
|
||||||
assertEquals("Cr1", receivedMsg.getDestinationId(), "Destination ID should be preserved");
|
|
||||||
|
|
||||||
client.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Make sure vehicle payloads survive the trip and arrive non-null.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
@Timeout(5)
|
|
||||||
void testVehicleSpawnMessage() throws Exception {
|
|
||||||
MockIntersectionServer server = new MockIntersectionServer("Cr1", BASE_PORT);
|
|
||||||
server.start();
|
|
||||||
mockServers.add(server);
|
|
||||||
|
|
||||||
Thread.sleep(100);
|
|
||||||
|
|
||||||
SocketClient client = new SocketClient("Cr1", "localhost", BASE_PORT);
|
|
||||||
client.connect();
|
|
||||||
|
|
||||||
// fake a vehicle like the coordinator would send
|
|
||||||
List<String> route = List.of("Cr1", "Cr4", "Cr5", "S");
|
|
||||||
Vehicle vehicle = new Vehicle("V1", sd.model.VehicleType.LIGHT, 0.0, route);
|
|
||||||
|
|
||||||
Message spawnMessage = new Message(
|
|
||||||
MessageType.VEHICLE_SPAWN,
|
|
||||||
"COORDINATOR",
|
|
||||||
"Cr1",
|
|
||||||
vehicle
|
|
||||||
);
|
|
||||||
|
|
||||||
client.send(spawnMessage);
|
|
||||||
|
|
||||||
Thread.sleep(200);
|
|
||||||
|
|
||||||
Message receivedMsg = server.getReceivedMessages().poll();
|
|
||||||
assertNotNull(receivedMsg, "Mock server should receive the spawn message");
|
|
||||||
assertEquals(MessageType.VEHICLE_SPAWN, receivedMsg.getType(), "Message should be of type VEHICLE_SPAWN");
|
|
||||||
assertNotNull(receivedMsg.getPayload(), "Payload should not be null (vehicle must arrive)");
|
|
||||||
|
|
||||||
client.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Broadcast shutdown to multiple mock intersections and see if all of them get it.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
@Timeout(5)
|
|
||||||
void testShutdownMessageBroadcast() throws Exception {
|
|
||||||
// Start a couple of fake intersections
|
|
||||||
for (int i = 1; i <= 3; i++) {
|
|
||||||
MockIntersectionServer server = new MockIntersectionServer("Cr" + i, BASE_PORT + i - 1);
|
|
||||||
server.start();
|
|
||||||
mockServers.add(server);
|
|
||||||
}
|
|
||||||
|
|
||||||
Thread.sleep(200);
|
|
||||||
|
|
||||||
// Connect to all of them
|
|
||||||
List<SocketClient> clients = new ArrayList<>();
|
|
||||||
for (int i = 1; i <= 3; i++) {
|
|
||||||
SocketClient client = new SocketClient("Cr" + i, "localhost", BASE_PORT + i - 1);
|
|
||||||
client.connect();
|
|
||||||
clients.add(client);
|
|
||||||
}
|
|
||||||
|
|
||||||
Message shutdownMessage = new Message(
|
|
||||||
MessageType.SHUTDOWN,
|
|
||||||
"COORDINATOR",
|
|
||||||
"ALL",
|
|
||||||
"Simulation complete"
|
|
||||||
);
|
|
||||||
|
|
||||||
for (SocketClient client : clients) {
|
|
||||||
client.send(shutdownMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
Thread.sleep(200);
|
|
||||||
|
|
||||||
for (MockIntersectionServer server : mockServers) {
|
|
||||||
assertFalse(
|
|
||||||
server.getReceivedMessages().isEmpty(),
|
|
||||||
"Server " + server.getIntersectionId() + " should have received the shutdown message"
|
|
||||||
);
|
|
||||||
|
|
||||||
Message msg = server.getReceivedMessages().poll();
|
|
||||||
assertEquals(MessageType.SHUTDOWN, msg.getType(), "Server should receive a SHUTDOWN message");
|
|
||||||
}
|
|
||||||
|
|
||||||
for (SocketClient client : clients) {
|
|
||||||
client.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tiny TCP server that pretends to be an intersection.
|
|
||||||
* It:
|
|
||||||
* - listens on a port
|
|
||||||
* - accepts connections
|
|
||||||
* - reads length-prefixed messages
|
|
||||||
* - deserializes them and stores them for the test to inspect
|
|
||||||
*/
|
|
||||||
private static class MockIntersectionServer {
|
|
||||||
private final String intersectionId;
|
|
||||||
private final int port;
|
|
||||||
private ServerSocket serverSocket;
|
|
||||||
private Thread serverThread;
|
|
||||||
private volatile boolean running;
|
|
||||||
private final ConcurrentLinkedQueue<Message> receivedMessages;
|
|
||||||
private final MessageSerializer serializer;
|
|
||||||
|
|
||||||
public MockIntersectionServer(String intersectionId, int port) {
|
|
||||||
this.intersectionId = intersectionId;
|
|
||||||
this.port = port;
|
|
||||||
this.receivedMessages = new ConcurrentLinkedQueue<>();
|
|
||||||
this.serializer = SerializerFactory.createDefault();
|
|
||||||
this.running = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void start() throws IOException {
|
|
||||||
serverSocket = new ServerSocket(port);
|
|
||||||
running = true;
|
|
||||||
|
|
||||||
System.out.printf("Mock %s listening on port %d%n", intersectionId, port);
|
|
||||||
|
|
||||||
serverThread = new Thread(() -> {
|
|
||||||
try {
|
|
||||||
while (running) {
|
|
||||||
Socket clientSocket = serverSocket.accept();
|
|
||||||
handleClient(clientSocket);
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
if (running) {
|
|
||||||
System.err.println("Mock " + intersectionId + " server error: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, "mock-" + intersectionId + "-listener");
|
|
||||||
|
|
||||||
serverThread.start();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleClient(Socket clientSocket) {
|
|
||||||
new Thread(() -> {
|
|
||||||
try (DataInputStream input = new DataInputStream(clientSocket.getInputStream())) {
|
|
||||||
while (running) {
|
|
||||||
// Read length prefix (4 bytes, big-endian)
|
|
||||||
int length = input.readInt();
|
|
||||||
byte[] data = new byte[length];
|
|
||||||
input.readFully(data);
|
|
||||||
|
|
||||||
Message message = serializer.deserialize(data, Message.class);
|
|
||||||
receivedMessages.offer(message);
|
|
||||||
|
|
||||||
System.out.println("Mock " + intersectionId + " received: " + message.getType());
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
if (running) {
|
|
||||||
System.err.println("Mock " + intersectionId + " client handler error: " + e.getMessage());
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.err.println("Mock " + intersectionId + " deserialization error: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}, "mock-" + intersectionId + "-client").start();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void stop() {
|
|
||||||
running = false;
|
|
||||||
try {
|
|
||||||
if (serverSocket != null && !serverSocket.isClosed()) {
|
|
||||||
serverSocket.close();
|
|
||||||
}
|
|
||||||
if (serverThread != null) {
|
|
||||||
serverThread.interrupt();
|
|
||||||
serverThread.join(1000);
|
|
||||||
}
|
|
||||||
System.out.printf("Mock %s stopped%n", intersectionId);
|
|
||||||
} catch (IOException | InterruptedException e) {
|
|
||||||
System.err.println("Error stopping mock server " + intersectionId + ": " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public ConcurrentLinkedQueue<Message> getReceivedMessages() {
|
|
||||||
return receivedMessages;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getIntersectionId() {
|
|
||||||
return intersectionId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,194 +0,0 @@
|
|||||||
package sd.coordinator;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.AfterEach;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import sd.config.SimulationConfig;
|
|
||||||
import sd.model.Vehicle;
|
|
||||||
import sd.util.VehicleGenerator;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tests for the Coordinator/vehicle-generation layer.
|
|
||||||
*
|
|
||||||
* What we’re checking here:
|
|
||||||
* 1. Coordinator can be created with a valid config
|
|
||||||
* 2. Vehicle arrival times are monotonic and sane
|
|
||||||
* 3. Vehicle IDs are created in the format we expect (V1, V2, ...)
|
|
||||||
* 4. Generated vehicles have proper routes (start at CrX, end at S)
|
|
||||||
* 5. Config actually has intersection info
|
|
||||||
* 6. Duration in config is not something crazy
|
|
||||||
*/
|
|
||||||
class CoordinatorProcessTest {
|
|
||||||
|
|
||||||
private SimulationConfig config;
|
|
||||||
private static final String TEST_CONFIG = "src/main/resources/simulation.properties";
|
|
||||||
|
|
||||||
@BeforeEach
|
|
||||||
void setUp() throws IOException {
|
|
||||||
config = new SimulationConfig(TEST_CONFIG);
|
|
||||||
}
|
|
||||||
|
|
||||||
@AfterEach
|
|
||||||
void tearDown() {
|
|
||||||
config = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Basic smoke test: can we build a coordinator with this config?
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
void testCoordinatorInitialization() {
|
|
||||||
CoordinatorProcess coordinator = new CoordinatorProcess(config);
|
|
||||||
assertNotNull(coordinator, "Coordinator should be created with a valid config");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Make sure the VehicleGenerator is giving us increasing arrival times,
|
|
||||||
* i.e. time doesn’t go backwards and intervals look reasonable.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
void testVehicleGenerationTiming() {
|
|
||||||
VehicleGenerator generator = new VehicleGenerator(config);
|
|
||||||
|
|
||||||
double currentTime = 0.0;
|
|
||||||
List<Double> arrivalTimes = new ArrayList<>();
|
|
||||||
|
|
||||||
// generate a small batch to inspect
|
|
||||||
for (int i = 0; i < 10; i++) {
|
|
||||||
double nextArrival = generator.getNextArrivalTime(currentTime);
|
|
||||||
arrivalTimes.add(nextArrival);
|
|
||||||
currentTime = nextArrival;
|
|
||||||
}
|
|
||||||
|
|
||||||
// times should strictly increase
|
|
||||||
for (int i = 1; i < arrivalTimes.size(); i++) {
|
|
||||||
assertTrue(
|
|
||||||
arrivalTimes.get(i) > arrivalTimes.get(i - 1),
|
|
||||||
"Arrival times must increase — got " + arrivalTimes.get(i - 1) + " then " + arrivalTimes.get(i)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// and they shouldn't be nonsense
|
|
||||||
for (double time : arrivalTimes) {
|
|
||||||
assertTrue(time >= 0, "Arrival time should not be negative (got " + time + ")");
|
|
||||||
assertTrue(time < 1000, "Arrival time looks suspiciously large: " + time);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* We generate V1..V5 manually and make sure the IDs are exactly those.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
void testVehicleIdGeneration() {
|
|
||||||
VehicleGenerator generator = new VehicleGenerator(config);
|
|
||||||
|
|
||||||
List<Vehicle> vehicles = new ArrayList<>();
|
|
||||||
for (int i = 1; i <= 5; i++) {
|
|
||||||
Vehicle v = generator.generateVehicle("V" + i, 0.0);
|
|
||||||
vehicles.add(v);
|
|
||||||
assertEquals("V" + i, v.getId(), "Vehicle ID should be 'V" + i + "' but got " + v.getId());
|
|
||||||
}
|
|
||||||
|
|
||||||
// just to be safe, no duplicates in that small set
|
|
||||||
long distinctCount = vehicles.stream().map(Vehicle::getId).distinct().count();
|
|
||||||
assertEquals(5, distinctCount, "Vehicle IDs in this batch should all be unique");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A generated vehicle should:
|
|
||||||
* - have a non-empty route
|
|
||||||
* - start in a known intersection (Cr1..Cr5)
|
|
||||||
* - end in S (exit)
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
void testVehicleRouteValidity() {
|
|
||||||
VehicleGenerator generator = new VehicleGenerator(config);
|
|
||||||
|
|
||||||
for (int i = 0; i < 20; i++) {
|
|
||||||
Vehicle vehicle = generator.generateVehicle("V" + i, 0.0);
|
|
||||||
|
|
||||||
assertNotNull(vehicle.getRoute(), "Vehicle route should not be null");
|
|
||||||
assertFalse(vehicle.getRoute().isEmpty(), "Vehicle route should not be empty");
|
|
||||||
|
|
||||||
String firstHop = vehicle.getRoute().get(0);
|
|
||||||
assertTrue(
|
|
||||||
firstHop.matches("Cr[1-5]"),
|
|
||||||
"First hop should be a valid intersection (Cr1..Cr5), got: " + firstHop
|
|
||||||
);
|
|
||||||
|
|
||||||
String lastHop = vehicle.getRoute().get(vehicle.getRoute().size() - 1);
|
|
||||||
assertEquals("S", lastHop, "Last hop should be exit 'S' but got: " + lastHop);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whatever is in simulation.properties should give us a sane duration.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
void testSimulationDuration() {
|
|
||||||
double duration = config.getSimulationDuration();
|
|
||||||
assertTrue(duration > 0, "Simulation duration must be positive");
|
|
||||||
assertTrue(duration >= 1.0, "Simulation should run at least 1 second (got " + duration + ")");
|
|
||||||
assertTrue(duration <= 86400.0, "Simulation should not run more than a day (got " + duration + ")");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check that the 5 intersections defined in the architecture
|
|
||||||
* actually exist in the config and have valid network data.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
void testIntersectionConfiguration() {
|
|
||||||
String[] intersectionIds = {"Cr1", "Cr2", "Cr3", "Cr4", "Cr5"};
|
|
||||||
|
|
||||||
for (String id : intersectionIds) {
|
|
||||||
String host = config.getIntersectionHost(id);
|
|
||||||
int port = config.getIntersectionPort(id);
|
|
||||||
|
|
||||||
assertNotNull(host, "Host should not be null for " + id);
|
|
||||||
assertFalse(host.isEmpty(), "Host should not be empty for " + id);
|
|
||||||
assertTrue(port > 0, "Port should be > 0 for " + id + " (got " + port + ")");
|
|
||||||
assertTrue(port < 65536, "Port should be a valid TCP port for " + id + " (got " + port + ")");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Quick sanity check: over a bunch of generated vehicles,
|
|
||||||
* we should eventually see the different vehicle types appear.
|
|
||||||
*
|
|
||||||
* Note: this is probabilistic, so we're not being super strict.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
void testVehicleTypeDistribution() {
|
|
||||||
VehicleGenerator generator = new VehicleGenerator(config);
|
|
||||||
|
|
||||||
boolean hasBike = false;
|
|
||||||
boolean hasLight = false;
|
|
||||||
boolean hasHeavy = false;
|
|
||||||
|
|
||||||
// 50 is enough for a "we're probably fine" test
|
|
||||||
for (int i = 0; i < 50; i++) {
|
|
||||||
Vehicle vehicle = generator.generateVehicle("V" + i, 0.0);
|
|
||||||
|
|
||||||
switch (vehicle.getType()) {
|
|
||||||
case BIKE -> hasBike = true;
|
|
||||||
case LIGHT -> hasLight = true;
|
|
||||||
case HEAVY -> hasHeavy = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// at least one of them should have shown up — if not, RNG is cursed
|
|
||||||
assertTrue(
|
|
||||||
hasBike || hasLight || hasHeavy,
|
|
||||||
"Expected to see at least one vehicle type after 50 generations"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,164 +0,0 @@
|
|||||||
package sd.dashboard;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.AfterEach;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import sd.config.SimulationConfig;
|
|
||||||
import sd.model.VehicleType;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Unit tests for Dashboard Server components.
|
|
||||||
*/
|
|
||||||
class DashboardTest {
|
|
||||||
|
|
||||||
private DashboardStatistics statistics;
|
|
||||||
|
|
||||||
@BeforeEach
|
|
||||||
void setUp() {
|
|
||||||
statistics = new DashboardStatistics();
|
|
||||||
}
|
|
||||||
|
|
||||||
@AfterEach
|
|
||||||
void tearDown() {
|
|
||||||
statistics = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testInitialStatistics() {
|
|
||||||
assertEquals(0, statistics.getTotalVehiclesGenerated(),
|
|
||||||
"Initial vehicles generated should be 0");
|
|
||||||
assertEquals(0, statistics.getTotalVehiclesCompleted(),
|
|
||||||
"Initial vehicles completed should be 0");
|
|
||||||
assertEquals(0.0, statistics.getAverageSystemTime(),
|
|
||||||
"Initial average system time should be 0.0");
|
|
||||||
assertEquals(0.0, statistics.getAverageWaitingTime(),
|
|
||||||
"Initial average waiting time should be 0.0");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testVehicleCounters() {
|
|
||||||
statistics.incrementVehiclesGenerated();
|
|
||||||
assertEquals(1, statistics.getTotalVehiclesGenerated());
|
|
||||||
|
|
||||||
statistics.updateVehiclesGenerated(10);
|
|
||||||
assertEquals(10, statistics.getTotalVehiclesGenerated());
|
|
||||||
|
|
||||||
statistics.incrementVehiclesCompleted();
|
|
||||||
assertEquals(1, statistics.getTotalVehiclesCompleted());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testAverageCalculations() {
|
|
||||||
// Add 3 completed vehicles with known times
|
|
||||||
statistics.updateVehiclesCompleted(3);
|
|
||||||
statistics.addSystemTime(3000); // 3000ms total
|
|
||||||
statistics.addWaitingTime(1500); // 1500ms total
|
|
||||||
|
|
||||||
assertEquals(1000.0, statistics.getAverageSystemTime(), 0.01,
|
|
||||||
"Average system time should be 1000ms");
|
|
||||||
assertEquals(500.0, statistics.getAverageWaitingTime(), 0.01,
|
|
||||||
"Average waiting time should be 500ms");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testVehicleTypeStatistics() {
|
|
||||||
statistics.incrementVehicleType(VehicleType.LIGHT);
|
|
||||||
statistics.incrementVehicleType(VehicleType.LIGHT);
|
|
||||||
statistics.incrementVehicleType(VehicleType.HEAVY);
|
|
||||||
|
|
||||||
assertEquals(2, statistics.getVehicleTypeCount(VehicleType.LIGHT));
|
|
||||||
assertEquals(1, statistics.getVehicleTypeCount(VehicleType.HEAVY));
|
|
||||||
assertEquals(0, statistics.getVehicleTypeCount(VehicleType.BIKE));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testIntersectionStatistics() {
|
|
||||||
statistics.updateIntersectionStats("Cr1", 10, 8, 2);
|
|
||||||
|
|
||||||
DashboardStatistics.IntersectionStats stats =
|
|
||||||
statistics.getIntersectionStats("Cr1");
|
|
||||||
|
|
||||||
assertNotNull(stats, "Intersection stats should not be null");
|
|
||||||
assertEquals("Cr1", stats.getIntersectionId());
|
|
||||||
assertEquals(10, stats.getTotalArrivals());
|
|
||||||
assertEquals(8, stats.getTotalDepartures());
|
|
||||||
assertEquals(2, stats.getCurrentQueueSize());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testMultipleIntersections() {
|
|
||||||
statistics.updateIntersectionStats("Cr1", 10, 8, 2);
|
|
||||||
statistics.updateIntersectionStats("Cr2", 15, 12, 3);
|
|
||||||
statistics.updateIntersectionStats("Cr3", 5, 5, 0);
|
|
||||||
|
|
||||||
assertEquals(3, statistics.getAllIntersectionStats().size(),
|
|
||||||
"Should have 3 intersections");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testStatsUpdatePayload() {
|
|
||||||
StatsUpdatePayload payload = new StatsUpdatePayload()
|
|
||||||
.setTotalVehiclesGenerated(50)
|
|
||||||
.setTotalVehiclesCompleted(20)
|
|
||||||
.setIntersectionArrivals(30)
|
|
||||||
.setIntersectionDepartures(25)
|
|
||||||
.setIntersectionQueueSize(5);
|
|
||||||
|
|
||||||
assertEquals(50, payload.getTotalVehiclesGenerated());
|
|
||||||
assertEquals(20, payload.getTotalVehiclesCompleted());
|
|
||||||
assertEquals(30, payload.getIntersectionArrivals());
|
|
||||||
assertEquals(25, payload.getIntersectionDepartures());
|
|
||||||
assertEquals(5, payload.getIntersectionQueueSize());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testStatsMessage() {
|
|
||||||
StatsUpdatePayload payload = new StatsUpdatePayload()
|
|
||||||
.setIntersectionArrivals(10);
|
|
||||||
|
|
||||||
StatsMessage message = new StatsMessage("Cr1", payload);
|
|
||||||
|
|
||||||
assertEquals("Cr1", message.getSourceNode());
|
|
||||||
assertEquals("DashboardServer", message.getDestinationNode());
|
|
||||||
assertEquals(sd.model.MessageType.STATS_UPDATE, message.getType());
|
|
||||||
assertNotNull(message.getPayload());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testThreadSafety() throws InterruptedException {
|
|
||||||
// Test concurrent updates
|
|
||||||
Thread t1 = new Thread(() -> {
|
|
||||||
for (int i = 0; i < 100; i++) {
|
|
||||||
statistics.incrementVehiclesGenerated();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Thread t2 = new Thread(() -> {
|
|
||||||
for (int i = 0; i < 100; i++) {
|
|
||||||
statistics.incrementVehiclesGenerated();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
t1.start();
|
|
||||||
t2.start();
|
|
||||||
t1.join();
|
|
||||||
t2.join();
|
|
||||||
|
|
||||||
assertEquals(200, statistics.getTotalVehiclesGenerated(),
|
|
||||||
"Concurrent increments should total 200");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testDashboardServerCreation() throws Exception {
|
|
||||||
SimulationConfig config = new SimulationConfig("simulation.properties");
|
|
||||||
DashboardServer server = new DashboardServer(config);
|
|
||||||
|
|
||||||
assertNotNull(server, "Server should be created successfully");
|
|
||||||
assertNotNull(server.getStatistics(), "Statistics should be initialized");
|
|
||||||
assertFalse(server.isRunning(), "Server should not be running initially");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,140 +0,0 @@
|
|||||||
package sd.serialization;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.junit.jupiter.api.DisplayName;
|
|
||||||
import sd.model.Message;
|
|
||||||
import sd.model.Vehicle;
|
|
||||||
import sd.model.VehicleType;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Test suite for JSON serialization.
|
|
||||||
*
|
|
||||||
* Tests JSON serialization to ensure:
|
|
||||||
* - Correct serialization and deserialization
|
|
||||||
* - Data integrity during round-trip conversion
|
|
||||||
* - Proper error handling
|
|
||||||
*/
|
|
||||||
class SerializationTest {
|
|
||||||
|
|
||||||
private MessageSerializer jsonSerializer = new JsonMessageSerializer();
|
|
||||||
|
|
||||||
private Vehicle testVehicle = new Vehicle("V001", VehicleType.LIGHT, 10.5,
|
|
||||||
Arrays.asList("Cr1", "Cr2", "Cr5", "S"));
|
|
||||||
private Message testMessage = new Message(
|
|
||||||
sd.model.MessageType.VEHICLE_TRANSFER,
|
|
||||||
"Cr1",
|
|
||||||
"Cr2",
|
|
||||||
testVehicle
|
|
||||||
);
|
|
||||||
|
|
||||||
|
|
||||||
// ===== JSON Serialization Tests =====
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@DisplayName("JSON: Should serialize and deserialize Vehicle correctly")
|
|
||||||
void testJsonVehicleRoundTrip() throws SerializationException {
|
|
||||||
// Serialize
|
|
||||||
byte[] data = jsonSerializer.serialize(testVehicle);
|
|
||||||
assertNotNull(data);
|
|
||||||
assertTrue(data.length > 0);
|
|
||||||
|
|
||||||
// Print JSON for inspection
|
|
||||||
System.out.println("JSON Vehicle:");
|
|
||||||
System.out.println(new String(data));
|
|
||||||
|
|
||||||
// Deserialize
|
|
||||||
Vehicle deserialized = jsonSerializer.deserialize(data, Vehicle.class);
|
|
||||||
|
|
||||||
// Verify
|
|
||||||
assertNotNull(deserialized);
|
|
||||||
assertEquals(testVehicle.getId(), deserialized.getId());
|
|
||||||
assertEquals(testVehicle.getType(), deserialized.getType());
|
|
||||||
assertEquals(testVehicle.getEntryTime(), deserialized.getEntryTime());
|
|
||||||
assertEquals(testVehicle.getRoute(), deserialized.getRoute());
|
|
||||||
assertEquals(testVehicle.getTotalWaitingTime(), deserialized.getTotalWaitingTime());
|
|
||||||
assertEquals(testVehicle.getTotalCrossingTime(), deserialized.getTotalCrossingTime());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@DisplayName("JSON: Should serialize and deserialize Message correctly")
|
|
||||||
void testJsonMessageRoundTrip() throws SerializationException {
|
|
||||||
// Serialize
|
|
||||||
byte[] data = jsonSerializer.serialize(testMessage);
|
|
||||||
assertNotNull(data);
|
|
||||||
|
|
||||||
// Print JSON for inspection
|
|
||||||
System.out.println("\nJSON Message:");
|
|
||||||
System.out.println(new String(data));
|
|
||||||
|
|
||||||
// Deserialize
|
|
||||||
Message deserialized = jsonSerializer.deserialize(data, Message.class);
|
|
||||||
|
|
||||||
// Verify
|
|
||||||
assertNotNull(deserialized);
|
|
||||||
assertEquals(testMessage.getType(), deserialized.getType());
|
|
||||||
assertEquals(testMessage.getSenderId(), deserialized.getSenderId());
|
|
||||||
assertEquals(testMessage.getDestinationId(), deserialized.getDestinationId());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@DisplayName("JSON: Should throw exception on null object")
|
|
||||||
void testJsonSerializeNull() {
|
|
||||||
assertThrows(IllegalArgumentException.class, () -> {
|
|
||||||
jsonSerializer.serialize(null);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@DisplayName("JSON: Should throw exception on null data")
|
|
||||||
void testJsonDeserializeNull() {
|
|
||||||
assertThrows(IllegalArgumentException.class, () -> {
|
|
||||||
jsonSerializer.deserialize(null, Vehicle.class);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@DisplayName("JSON: Should throw exception on invalid JSON")
|
|
||||||
void testJsonDeserializeInvalid() {
|
|
||||||
byte[] invalidData = "{ invalid json }".getBytes();
|
|
||||||
assertThrows(SerializationException.class, () -> {
|
|
||||||
jsonSerializer.deserialize(invalidData, Vehicle.class);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@DisplayName("JSON: Should preserve data integrity for complex objects")
|
|
||||||
void testDataIntegrity() throws SerializationException {
|
|
||||||
// Create a more complex vehicle
|
|
||||||
Vehicle vehicle = new Vehicle("V999", VehicleType.HEAVY, 100.5,
|
|
||||||
Arrays.asList("Cr1", "Cr2", "Cr3", "Cr4", "Cr5", "S"));
|
|
||||||
vehicle.addWaitingTime(10.5);
|
|
||||||
vehicle.addWaitingTime(5.3);
|
|
||||||
vehicle.addCrossingTime(2.1);
|
|
||||||
vehicle.advanceRoute();
|
|
||||||
vehicle.advanceRoute();
|
|
||||||
|
|
||||||
// Serialize and deserialize
|
|
||||||
byte[] jsonData = jsonSerializer.serialize(vehicle);
|
|
||||||
Vehicle deserialized = jsonSerializer.deserialize(jsonData, Vehicle.class);
|
|
||||||
|
|
||||||
// Verify all fields match
|
|
||||||
assertEquals(vehicle.getId(), deserialized.getId());
|
|
||||||
assertEquals(vehicle.getType(), deserialized.getType());
|
|
||||||
assertEquals(vehicle.getTotalWaitingTime(), deserialized.getTotalWaitingTime());
|
|
||||||
assertEquals(vehicle.getCurrentRouteIndex(), deserialized.getCurrentRouteIndex());
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===== Factory Tests =====
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@DisplayName("Factory: Should create JSON serializer by default")
|
|
||||||
void testFactoryDefault() {
|
|
||||||
MessageSerializer serializer = SerializerFactory.createDefault();
|
|
||||||
assertNotNull(serializer);
|
|
||||||
assertEquals("JSON (Gson)", serializer.getName());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user