mirror of
https://github.com/davidalves04/Trabalho-Pratico-SD.git
synced 2025-12-08 20:43:32 +00:00
Compare commits
12 Commits
dev-ui-tem
...
24fe1c1d67
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
24fe1c1d67 | ||
|
|
766eabbbe4 | ||
|
|
d7b1de1fe3 | ||
|
|
96b3a66b96 | ||
|
|
29848b04a6 | ||
| 043ba7d185 | |||
| 25f2876c34 | |||
| 7cbecc4fab | |||
| 72db59415f | |||
| 60b4f0c2b6 | |||
| 81f842e2bb | |||
|
|
108d2e544c |
110
.$Diagrama de arquitetura - SD.drawio.bkp
Normal file
110
.$Diagrama de arquitetura - SD.drawio.bkp
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
<mxfile host="Electron" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/29.0.3 Chrome/140.0.7339.249 Electron/38.7.0 Safari/537.36" version="29.0.3">
|
||||||
|
<diagram name="Arquitetura SD" id="QKeTeUWuUs8JeLsq44d-">
|
||||||
|
<mxGraphModel dx="1426" dy="841" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1654" pageHeight="1169" math="0" shadow="0">
|
||||||
|
<root>
|
||||||
|
<mxCell id="0" />
|
||||||
|
<mxCell id="1" parent="0" />
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-1" value="<b>CoordinatorProcess</b><br>(Cliente Socket)<hr>• VehicleGenerator<br>• Modelo Poisson (λ=0.5)<br>• Liga a Cr1-Cr5" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="560" y="40" width="240" height="100" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-2" value="<b>Cr1</b> (IntersectionProcess)<br>Porta: 8001<br>Servidor + Cliente<hr>• ServerSocket (8001)<br>• Thread Semáforo Sul<br>• Thread Semáforo Este<br>• Thread Semáforo Oeste<br>• Fila Eventos (DES)<br>• ReentrantLock" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="280" y="200" width="180" height="160" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-3" value="<b>Cr2</b> (IntersectionProcess)<br>Porta: 8002<br>Servidor + Cliente<hr>• ServerSocket (8002)<br>• Thread Semáforo Sul<br>• Thread Semáforo Este<br>• Thread Semáforo Oeste<br>• Fila Eventos (DES)<br>• ReentrantLock" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="590" y="190" width="180" height="160" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-5" value="<b>Cr4</b> (IntersectionProcess)<br>Porta: 8004<br>Servidor + Cliente<hr>• ServerSocket (8004)<br>• Thread Semáforo Sul<br>• Thread Semáforo Este<br>• Thread Semáforo Oeste<br>• Fila Eventos (DES)<br>• ReentrantLock" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="440" y="530" width="180" height="160" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-6" value="<b>Cr5</b> (IntersectionProcess)<br>Porta: 8005<br>Servidor + Cliente<hr>• ServerSocket (8005)<br>• Thread Semáforo Sul<br>• Thread Semáforo Este<br>• Thread Semáforo Oeste<br>• Fila Eventos (DES)<br>• ReentrantLock" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="910" y="430" width="180" height="160" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-7" value="<b>ExitNode (S)</b><br>Porta: 9001<br>Servidor Socket<hr>• Recebe veículos finais<br>• Calcula estatísticas:<br> - Tempo no sistema<br> - Tempo de espera<br> - Métricas por tipo<br>• Envia para Dashboard" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#ffe6cc;strokeColor=#d79b00;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="727" y="810" width="200" height="170" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-8" value="<b>DashboardServer</b><br>Porta: 9000<br>Servidor Socket<hr>• Thread Pool (10 threads)<br>• ConcurrentHashMap<br>• Agrega estatísticas<br>• Display a cada 5s:<br> - Throughput<br> - Tempos médios<br> - Tamanhos de filas" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="1210" y="585" width="200" height="160" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-9" value="VEHICLE_SPAWN<br>(Vehicle)" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#0000FF;strokeWidth=2;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-1" target="0K4eb2koB2xQ8duQ1-_a-2" edge="1">
|
||||||
|
<mxGeometry x="-0.2105" relative="1" as="geometry">
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-10" value="VEHICLE_SPAWN<br>(Vehicle)" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#0000FF;strokeWidth=2;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-1" target="0K4eb2koB2xQ8duQ1-_a-3" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-11" value="VEHICLE_SPAWN<br>(Vehicle)" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#0000FF;strokeWidth=2;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-1" target="0K4eb2koB2xQ8duQ1-_a-4" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-12" value="VEHICLE_TRANSFER" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=classic;startArrow=classic;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-2" target="0K4eb2koB2xQ8duQ1-_a-3" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-13" value="VEHICLE_TRANSFER" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=classic;startArrow=classic;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-3" target="0K4eb2koB2xQ8duQ1-_a-4" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-14" value="VEHICLE_TRANSFER" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=classic;startArrow=classic;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-2" target="0K4eb2koB2xQ8duQ1-_a-5" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-15" value="VEHICLE_TRANSFER" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=classic;startArrow=classic;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-3" target="0K4eb2koB2xQ8duQ1-_a-5" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-16" value="VEHICLE_TRANSFER" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=classic;startArrow=classic;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-5" target="0K4eb2koB2xQ8duQ1-_a-6" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-17" value="VEHICLE_TRANSFER" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=classic;startArrow=none;startFill=0;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-4" target="0K4eb2koB2xQ8duQ1-_a-6" edge="1">
|
||||||
|
<mxGeometry x="0.3659" relative="1" as="geometry">
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-18" value="VEHICLE_TRANSFER" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#FF6600;strokeWidth=2;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-5" target="0K4eb2koB2xQ8duQ1-_a-7" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-19" value="VEHICLE_TRANSFER" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#FF6600;strokeWidth=2;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-6" target="0K4eb2koB2xQ8duQ1-_a-7" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-20" value="STATS_UPDATE<br>(periódico 5s)" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-2" target="0K4eb2koB2xQ8duQ1-_a-8" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-21" value="STATS_UPDATE<br>(periódico 5s)" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-4" target="0K4eb2koB2xQ8duQ1-_a-8" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-22" value="STATS_UPDATE<br>(periódico 5s)" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-4" target="0K4eb2koB2xQ8duQ1-_a-8" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-23" value="STATS_UPDATE<br>(periódico 5s)" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-5" target="0K4eb2koB2xQ8duQ1-_a-8" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-24" value="STATS_UPDATE<br>(periódico 5s)" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-6" target="0K4eb2koB2xQ8duQ1-_a-8" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-25" value="STATS_UPDATE<br>(periódico 5s)" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-26" target="0K4eb2koB2xQ8duQ1-_a-8" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-27" value="<b>MessageProtocol</b><hr>interface:<br>• getType()<br>• getPayload()<br>• getSourceNode()<br>• getDestinationNode()" style="rounded=0;whiteSpace=wrap;html=1;align=left;verticalAlign=top;fillColor=#fff2cc;strokeColor=#d6b656;spacing=10;fontColor=#000000;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="30" y="30" width="180" height="120" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-28" value="<b>Tipos de Mensagens</b><hr>• VEHICLE_TRANSFER<br>• VEHICLE_SPAWN<br>• STATS_UPDATE<br>• TRAFFIC_LIGHT_SYNC<br>• HEARTBEAT" style="rounded=0;whiteSpace=wrap;html=1;align=left;verticalAlign=top;fillColor=#fff2cc;strokeColor=#d6b656;spacing=10;fontColor=#000000;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="20" y="170" width="200" height="120" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-29" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-3" target="0K4eb2koB2xQ8duQ1-_a-4" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<mxPoint x="480" y="280" as="sourcePoint" />
|
||||||
|
<mxPoint x="990" y="440" as="targetPoint" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-4" value="<b>Cr3</b> (IntersectionProcess)<br>Porta: 8003<br>Servidor + Cliente<hr>• ServerSocket (8003)<br>• Thread Semáforo Sul<br>• Thread Semáforo Este<br>• Thread Semáforo Oeste<br>• Fila Eventos (DES)<br>• ReentrantLock" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="910" y="200" width="180" height="160" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-30" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;" parent="1" source="0K4eb2koB2xQ8duQ1-_a-7" target="0K4eb2koB2xQ8duQ1-_a-26" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<mxPoint x="500" y="710" as="sourcePoint" />
|
||||||
|
<mxPoint x="1090" y="520" as="targetPoint" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-26" value="<b>LEGENDA</b><hr>━━━► Comunicação síncrona<br>╌╌╌► Comunicação periódica<br><br><b>Cores:</b><br>🔵 Azul = Geração<br>🟢 Verde = Transferência<br>🟠 Laranja = Finalização<br>🟣 Roxo = Monitorização<br><br><b>Serialização:</b> JSON (Gson)<br><b>Protocolo:</b> TCP/IP" style="rounded=0;whiteSpace=wrap;html=1;align=left;verticalAlign=top;fillColor=#f5f5f5;strokeColor=#666666;fontColor=#333333;spacing=10;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="1210" y="825" width="200" height="220" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
</root>
|
||||||
|
</mxGraphModel>
|
||||||
|
</diagram>
|
||||||
|
</mxfile>
|
||||||
62
.github/workflows/maven.yml
vendored
62
.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,88 @@ 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/')
|
||||||
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
|
files: |
|
||||||
|
main/target/*.jar
|
||||||
|
windows-dist/*.zip
|
||||||
|
|||||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -47,7 +47,5 @@ build/
|
|||||||
|
|
||||||
# Other
|
# Other
|
||||||
*.swp
|
*.swp
|
||||||
*.pdf
|
.$Diagrama de arquitetura - SD.drawio.bkp
|
||||||
|
Diagrama de arquitetura.jpg
|
||||||
# JAR built pom file
|
|
||||||
dependency-reduced-pom.xml
|
|
||||||
|
|||||||
@@ -1,24 +1,168 @@
|
|||||||
<mxfile host="app.diagrams.net" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 Edg/141.0.0.0" version="28.2.7">
|
<mxfile host="Electron" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/29.0.3 Chrome/140.0.7339.249 Electron/38.7.0 Safari/537.36" version="29.0.3">
|
||||||
<diagram name="Página-1" id="B1_hHcevBzWlEwI7FSV6">
|
<diagram name="Arquitetura SD" id="QKeTeUWuUs8JeLsq44d-">
|
||||||
<mxGraphModel dx="778" dy="476" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
|
<mxGraphModel dx="1426" dy="841" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1169" pageHeight="827" math="0" shadow="0">
|
||||||
<root>
|
<root>
|
||||||
<mxCell id="0" />
|
<mxCell id="0" />
|
||||||
<mxCell id="1" parent="0" />
|
<mxCell id="1" parent="0" />
|
||||||
<mxCell id="vcp7vux32DhQR4tKQhnF-8" value="Dashboard" style="sketch=0;pointerEvents=1;shadow=0;dashed=0;html=1;strokeColor=#C73500;labelPosition=center;verticalLabelPosition=bottom;verticalAlign=top;align=center;fillColor=#fa6800;shape=mxgraph.mscae.oms.dashboard;fontColor=#000000;" vertex="1" parent="1">
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-27" value="<b>MessageProtocol</b><hr>interface:<br>• getType()<br>• getPayload()<br>• getSourceNode()<br>• getDestinationNode()" style="rounded=0;whiteSpace=wrap;html=1;align=left;verticalAlign=top;fillColor=#fff2cc;strokeColor=#d6b656;spacing=10;fontColor=#000000;" parent="1" vertex="1">
|
||||||
<mxGeometry x="389" y="230" width="50" height="41" as="geometry" />
|
<mxGeometry x="30" y="30" width="180" height="120" as="geometry" />
|
||||||
</mxCell>
|
</mxCell>
|
||||||
<mxCell id="vcp7vux32DhQR4tKQhnF-12" value="Semaforo.java" style="shape=image;html=1;verticalAlign=top;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;imageAspect=0;aspect=fixed;image=https://icons.diagrams.net/icon-cache1/Strabo-2829/traffic_light-1068.png" vertex="1" parent="1">
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-28" value="<b>Tipos de Mensagens</b><hr>• VEHICLE_TRANSFER<br>• VEHICLE_SPAWN<br>• STATS_UPDATE<br>• TRAFFIC_LIGHT_SYNC<br>• HEARTBEAT" style="rounded=0;whiteSpace=wrap;html=1;align=left;verticalAlign=top;fillColor=#fff2cc;strokeColor=#d6b656;spacing=10;fontColor=#000000;" parent="1" vertex="1">
|
||||||
<mxGeometry x="230" y="350" width="53" height="53" as="geometry" />
|
<mxGeometry x="20" y="170" width="200" height="120" as="geometry" />
|
||||||
</mxCell>
|
</mxCell>
|
||||||
<mxCell id="vcp7vux32DhQR4tKQhnF-13" value="" style="endArrow=classic;startArrow=classic;html=1;rounded=0;movable=1;resizable=1;rotatable=1;deletable=1;editable=1;locked=0;connectable=1;" edge="1" parent="1">
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-26" value="<b>LEGENDA</b><hr>━━━► Comunicação síncrona<br>╌╌╌► Comunicação periódica<br><br><b>Cores:</b><br>🔵 Azul =&nbsp;<span style="background-color: transparent;">Criação do veículo</span><div>🟢 Verde = Transferência do veículo<br>🟠 Laranja = Chegada ao destino<br>🟣 Roxo =&nbsp;<span style="background-color: transparent;">Envio das estatísticas</span></div><div><br><b>Serialização:</b> JSON (Gson)<br><b>Protocolo:</b> TCP/IP</div>" style="rounded=0;whiteSpace=wrap;html=1;align=left;verticalAlign=top;fillColor=#f5f5f5;strokeColor=#666666;fontColor=#333333;spacing=10;" parent="1" vertex="1">
|
||||||
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
<mxGeometry x="10" y="320" width="220" height="220" as="geometry" />
|
||||||
<mxPoint x="310" y="330" as="sourcePoint" />
|
</mxCell>
|
||||||
<mxPoint x="360" y="280" as="targetPoint" />
|
<mxCell id="L62mICw2ZrYi1D68OOFe-13" value="" style="group" parent="1" vertex="1" connectable="0">
|
||||||
|
<mxGeometry x="280" y="40" width="850" height="730" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-20" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;exitX=0.616;exitY=-0.011;exitDx=0;exitDy=0;entryX=0.661;entryY=-0.002;entryDx=0;entryDy=0;entryPerimeter=0;exitPerimeter=0;" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-2" target="0K4eb2koB2xQ8duQ1-_a-8" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<mxPoint x="794" y="530" as="targetPoint" />
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="99" y="122" />
|
||||||
|
<mxPoint x="793" y="122" />
|
||||||
|
</Array>
|
||||||
</mxGeometry>
|
</mxGeometry>
|
||||||
</mxCell>
|
</mxCell>
|
||||||
<mxCell id="vcp7vux32DhQR4tKQhnF-14" value="CruzamentoServer.java" style="edgeLabel;html=1;align=center;verticalAlign=middle;resizable=1;points=[];movable=1;rotatable=1;deletable=1;editable=1;locked=0;connectable=1;" vertex="1" connectable="0" parent="vcp7vux32DhQR4tKQhnF-13">
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-1" value="<b>CoordinatorProcess</b><br>(Cliente Socket)<hr>• VehicleGenerator<br>• Modelo Poisson<br>• Liga a Cr1-Cr5" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="L62mICw2ZrYi1D68OOFe-13" vertex="1">
|
||||||
<mxGeometry x="-0.3933" relative="1" as="geometry">
|
<mxGeometry x="205.6637168141593" width="176.28318584070794" height="101.38888888888889" as="geometry" />
|
||||||
<mxPoint x="25" y="25" as="offset" />
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-2" value="<b>Cr1</b> (IntersectionProcess)<br>Porta: 8001<br>Servidor + Cliente<hr>• ServerSocket (8001)<br>• Thread Semáforo - Sul<br>• Thread Semáforo - Este<br>• Fila Eventos (DES)<br>• ReentrantLock" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="L62mICw2ZrYi1D68OOFe-13" vertex="1">
|
||||||
|
<mxGeometry y="162.22" width="160" height="162.22" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-3" value="<b>Cr2</b> (IntersectionProcess)<br>Porta: 8002<br>Servidor + Cliente<hr>• ServerSocket (8002)<br>• Thread Semáforo - Sul<br>• Thread Semáforo - Este<br>• Thread Semáforo - Oeste<br>• Fila Eventos (DES)<br>• ReentrantLock" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="L62mICw2ZrYi1D68OOFe-13" vertex="1">
|
||||||
|
<mxGeometry x="227.7" y="162.22" width="162.3" height="162.22" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-5" value="<b>Cr4</b> (IntersectionProcess)<br>Porta: 8004<br>Servidor + Cliente<hr>• ServerSocket (8004)<br>• Thread Semáforo - Este<br>• Fila Eventos (DES)<br>• ReentrantLock" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="L62mICw2ZrYi1D68OOFe-13" vertex="1">
|
||||||
|
<mxGeometry y="486.67" width="160" height="133.33" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-6" value="<b>Cr5</b> (IntersectionProcess)<br>Porta: 8005<br>Servidor + Cliente<hr>• ServerSocket (8005)<br>• Thread Semáforo - Este<br>• Fila Eventos (DES)<br>• ReentrantLock" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="L62mICw2ZrYi1D68OOFe-13" vertex="1">
|
||||||
|
<mxGeometry x="220.35" y="486.67" width="169.65" height="162.22" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-7" value="<b>ExitNode (S)</b><br>Porta: 9001<br>Servidor Socket<hr>• Recebe veículos finais<br>• Calcula estatísticas:<br> - Tempo no sistema<br> - Tempo de espera<br> - Métricas por tipo<br>• Envia para o Dashboard" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#ffe6cc;strokeColor=#d79b00;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="L62mICw2ZrYi1D68OOFe-13" vertex="1">
|
||||||
|
<mxGeometry x="464.07" y="476.53" width="154.6" height="172.36" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-8" value="<b>DashboardServer</b><br>Porta: 9000<br>Servidor Socket<hr>• Thread Pool (10 threads)<br>• ConcurrentHashMap<br>• Agrega estatísticas<br>• Display a cada 5s:<br> - Throughput<br> - Tempos médios<br> - Tamanhos de filas" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="L62mICw2ZrYi1D68OOFe-13" vertex="1">
|
||||||
|
<mxGeometry x="683.1" y="540" width="166.9" height="180" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-9" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#0000FF;strokeWidth=2;" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-1" target="0K4eb2koB2xQ8duQ1-_a-2" edge="1">
|
||||||
|
<mxGeometry x="-0.2105" relative="1" as="geometry">
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-10" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#0000FF;strokeWidth=2;" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-1" target="0K4eb2koB2xQ8duQ1-_a-3" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="309" y="120" />
|
||||||
|
<mxPoint x="309" y="120" />
|
||||||
|
</Array>
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-11" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#0000FF;strokeWidth=2;" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-1" target="0K4eb2koB2xQ8duQ1-_a-4" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-12" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=classic;startArrow=classic;" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-2" target="0K4eb2koB2xQ8duQ1-_a-3" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-13" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=classic;startArrow=classic;" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-3" target="0K4eb2koB2xQ8duQ1-_a-4" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-14" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=classic;startArrow=none;startFill=0;" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-2" target="0K4eb2koB2xQ8duQ1-_a-5" edge="1">
|
||||||
|
<mxGeometry x="0.125" y="100" relative="1" as="geometry">
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="66.10619469026548" y="446.11111111111114" />
|
||||||
|
<mxPoint x="66.10619469026548" y="446.11111111111114" />
|
||||||
|
</Array>
|
||||||
|
<mxPoint y="-1" as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-16" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=classic;startArrow=none;startFill=0;exitX=1.005;exitY=0.63;exitDx=0;exitDy=0;exitPerimeter=0;align=center;" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-5" edge="1">
|
||||||
|
<mxGeometry x="-0.0178" y="-49" relative="1" as="geometry">
|
||||||
|
<mxPoint x="139.55752212389382" y="588.0555555555555" as="sourcePoint" />
|
||||||
|
<mxPoint x="220" y="571" as="targetPoint" />
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="220" y="571" />
|
||||||
|
</Array>
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-19" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#b46504;strokeWidth=2;fillColor=#fad7ac;" parent="L62mICw2ZrYi1D68OOFe-13" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<mxPoint x="390" y="580" as="sourcePoint" />
|
||||||
|
<mxPoint x="462.74" y="580.22" as="targetPoint" />
|
||||||
|
<Array as="points" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-22" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;exitX=0.981;exitY=0.08;exitDx=0;exitDy=0;exitPerimeter=0;" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-4" target="0K4eb2koB2xQ8duQ1-_a-8" edge="1">
|
||||||
|
<mxGeometry x="0.1427" y="-60" relative="1" as="geometry">
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="593" y="175" />
|
||||||
|
<mxPoint x="593" y="140" />
|
||||||
|
<mxPoint x="764" y="140" />
|
||||||
|
</Array>
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-4" value="<b>Cr3</b> (IntersectionProcess)<br>Porta: 8003<br>Servidor + Cliente<hr>• ServerSocket (8003)<br>• Thread Semáforo - Sul<br>• Thread Semáforo - Oeste<br>• Fila Eventos (DES)<br>• ReentrantLock" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" parent="L62mICw2ZrYi1D68OOFe-13" vertex="1">
|
||||||
|
<mxGeometry x="462.74" y="162.22" width="167.26" height="162.22" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-30" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;entryX=0.186;entryY=0.998;entryDx=0;entryDy=0;entryPerimeter=0;" parent="L62mICw2ZrYi1D68OOFe-13" target="0K4eb2koB2xQ8duQ1-_a-8" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<mxPoint x="103" y="620" as="sourcePoint" />
|
||||||
|
<mxPoint x="710" y="730" as="targetPoint" />
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="103" y="730" />
|
||||||
|
<mxPoint x="714" y="730" />
|
||||||
|
</Array>
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="L62mICw2ZrYi1D68OOFe-2" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=none;startArrow=classic;startFill=1;endFill=0;" parent="L62mICw2ZrYi1D68OOFe-13" edge="1">
|
||||||
|
<mxGeometry x="-0.2214" y="26" relative="1" as="geometry">
|
||||||
|
<mxPoint x="293.8053097345133" y="486.6666666666666" as="sourcePoint" />
|
||||||
|
<mxPoint x="293.8053097345133" y="324.44444444444446" as="targetPoint" />
|
||||||
|
<Array as="points" />
|
||||||
|
<mxPoint x="-17" y="6" as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="L62mICw2ZrYi1D68OOFe-3" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#b46504;strokeWidth=2;endArrow=classic;startArrow=none;startFill=0;fillColor=#fad7ac;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" parent="L62mICw2ZrYi1D68OOFe-13" target="0K4eb2koB2xQ8duQ1-_a-7" edge="1">
|
||||||
|
<mxGeometry x="0.3659" relative="1" as="geometry">
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
<mxPoint x="541" y="324" as="sourcePoint" />
|
||||||
|
<mxPoint x="528.8495575221239" y="435.9722222222221" as="targetPoint" />
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="541" y="360" />
|
||||||
|
<mxPoint x="541" y="360" />
|
||||||
|
</Array>
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="L62mICw2ZrYi1D68OOFe-10" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;exitX=0.621;exitY=-0.003;exitDx=0;exitDy=0;exitPerimeter=0;" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-3" edge="1">
|
||||||
|
<mxGeometry x="0.1427" y="-60" relative="1" as="geometry">
|
||||||
|
<mxPoint x="330.53097345132744" y="141.94444444444443" as="sourcePoint" />
|
||||||
|
<mxPoint x="780" y="540" as="targetPoint" />
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="329" y="130" />
|
||||||
|
<mxPoint x="780" y="130" />
|
||||||
|
</Array>
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="L62mICw2ZrYi1D68OOFe-11" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;" parent="L62mICw2ZrYi1D68OOFe-13" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<mxPoint x="326" y="654" as="sourcePoint" />
|
||||||
|
<mxPoint x="683.1" y="700" as="targetPoint" />
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="326.1" y="700" />
|
||||||
|
</Array>
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="L62mICw2ZrYi1D68OOFe-12" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;" parent="L62mICw2ZrYi1D68OOFe-13" edge="1">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<mxPoint x="556" y="650" as="sourcePoint" />
|
||||||
|
<mxPoint x="683.0973451327434" y="663.0833333333331" as="targetPoint" />
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="556" y="663" />
|
||||||
|
</Array>
|
||||||
</mxGeometry>
|
</mxGeometry>
|
||||||
</mxCell>
|
</mxCell>
|
||||||
</root>
|
</root>
|
||||||
|
|||||||
BIN
Enunciado.pdf
Normal file
BIN
Enunciado.pdf
Normal file
Binary file not shown.
21
main/pom.xml
21
main/pom.xml
@@ -29,18 +29,6 @@
|
|||||||
<artifactId>gson</artifactId>
|
<artifactId>gson</artifactId>
|
||||||
<version>2.10.1</version>
|
<version>2.10.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- JavaFX for UI -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.openjfx</groupId>
|
|
||||||
<artifactId>javafx-controls</artifactId>
|
|
||||||
<version>17.0.2</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.openjfx</groupId>
|
|
||||||
<artifactId>javafx-fxml</artifactId>
|
|
||||||
<version>17.0.2</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@@ -54,15 +42,6 @@
|
|||||||
<mainClass>sd.Entry</mainClass>
|
<mainClass>sd.Entry</mainClass>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<!-- JavaFX Maven Plugin -->
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.openjfx</groupId>
|
|
||||||
<artifactId>javafx-maven-plugin</artifactId>
|
|
||||||
<version>0.0.8</version>
|
|
||||||
<configuration>
|
|
||||||
<mainClass>sd.dashboard.DashboardUI</mainClass>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-shade-plugin</artifactId>
|
<artifactId>maven-shade-plugin</artifactId>
|
||||||
|
|||||||
@@ -1,426 +0,0 @@
|
|||||||
package sd;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.ServerSocket;
|
|
||||||
import java.net.Socket;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import sd.config.SimulationConfig;
|
|
||||||
import sd.coordinator.SocketClient;
|
|
||||||
import sd.dashboard.StatsUpdatePayload;
|
|
||||||
import sd.model.Message;
|
|
||||||
import sd.model.MessageType;
|
|
||||||
import sd.model.Vehicle;
|
|
||||||
import sd.model.VehicleType;
|
|
||||||
import sd.protocol.MessageProtocol;
|
|
||||||
import sd.protocol.SocketConnection;
|
|
||||||
import sd.serialization.SerializationException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Processo responsável pelo nó de saída do sistema de simulação de tráfego distribuído.
|
|
||||||
*
|
|
||||||
* Este processo representa o ponto final ("S") onde os veículos completam as suas rotas.
|
|
||||||
* As suas principais responsabilidades são:
|
|
||||||
* - Receber veículos que terminam a sua rota vindos das interseções
|
|
||||||
* - Calcular e agregar estatísticas finais dos veículos
|
|
||||||
* - Enviar estatísticas periódicas para o dashboard
|
|
||||||
* - Gerar relatórios finais ao terminar a simulação
|
|
||||||
*/
|
|
||||||
public class ExitNodeProcess {
|
|
||||||
|
|
||||||
private final SimulationConfig config;
|
|
||||||
private ServerSocket serverSocket;
|
|
||||||
private final ExecutorService connectionHandlerPool;
|
|
||||||
|
|
||||||
/** Flag para controlar a execução do processo (volatile para visibilidade entre threads) */
|
|
||||||
private volatile boolean running;
|
|
||||||
|
|
||||||
/** Simulation start time (milliseconds) to calculate relative times */
|
|
||||||
private long simulationStartMillis;
|
|
||||||
|
|
||||||
/** Counter de veículos que completaram a rota */
|
|
||||||
private int totalVehiclesReceived;
|
|
||||||
|
|
||||||
/** Soma dos tempos no sistema de todos os veículos */
|
|
||||||
private double totalSystemTime;
|
|
||||||
|
|
||||||
/** Soma dos tempos de espera de todos os veículos */
|
|
||||||
private double totalWaitingTime;
|
|
||||||
|
|
||||||
/** Soma dos tempos de travessia de todos os veículos */
|
|
||||||
private double totalCrossingTime;
|
|
||||||
|
|
||||||
/** Contagem de veículos por tipo */
|
|
||||||
private final Map<VehicleType, Integer> vehicleTypeCount;
|
|
||||||
|
|
||||||
/** Tempo total de espera acumulado por tipo de veículo */
|
|
||||||
private final Map<VehicleType, Double> vehicleTypeWaitTime;
|
|
||||||
|
|
||||||
/** Socket para comunicação com o dashboard */
|
|
||||||
private SocketClient dashboardClient;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Método para iniciar o processo
|
|
||||||
*
|
|
||||||
* @param args Argumentos da linha de comandos. Se fornecido, args[0] deve ser
|
|
||||||
* o caminho para um ficheiro de configuração personalizado.
|
|
||||||
*/
|
|
||||||
public static void main(String[] args) {
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
System.out.println("EXIT NODE PROCESS");
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
|
|
||||||
try {
|
|
||||||
String configFile = args.length > 0 ? args[0] : "src/main/resources/simulation.properties";
|
|
||||||
System.out.println("Loading configuration from: " + configFile);
|
|
||||||
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile);
|
|
||||||
ExitNodeProcess exitNode = new ExitNodeProcess(config);
|
|
||||||
|
|
||||||
System.out.println("\n" + "=".repeat(60));
|
|
||||||
exitNode.initialize();
|
|
||||||
|
|
||||||
System.out.println("\n" + "=".repeat(60));
|
|
||||||
exitNode.start();
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("Failed to start exit node: " + e.getMessage());
|
|
||||||
System.exit(1);
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.err.println("Exit node error: " + e.getMessage());
|
|
||||||
System.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constrói um novo processo de nó de saída.
|
|
||||||
*
|
|
||||||
* Inicializa todas as estruturas de dados necessárias para recolher estatísticas
|
|
||||||
* e configura o pool de threads para processar as ligações concorrentes.
|
|
||||||
*
|
|
||||||
* @param config Configuração da simulação contendo portas e endereços dos serviços
|
|
||||||
*/
|
|
||||||
public ExitNodeProcess(SimulationConfig config) {
|
|
||||||
this.config = config;
|
|
||||||
this.connectionHandlerPool = Executors.newCachedThreadPool();
|
|
||||||
this.running = false;
|
|
||||||
|
|
||||||
this.totalVehiclesReceived = 0;
|
|
||||||
this.totalSystemTime = 0.0;
|
|
||||||
this.totalWaitingTime = 0.0;
|
|
||||||
this.totalCrossingTime = 0.0;
|
|
||||||
this.vehicleTypeCount = new HashMap<>();
|
|
||||||
this.vehicleTypeWaitTime = new HashMap<>();
|
|
||||||
|
|
||||||
// Inicializa os counters para cada tipo de veículo
|
|
||||||
for (VehicleType type : VehicleType.values()) {
|
|
||||||
vehicleTypeCount.put(type, 0);
|
|
||||||
vehicleTypeWaitTime.put(type, 0.0);
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("Exit node initialized");
|
|
||||||
System.out.println(" - Exit port: " + config.getExitPort());
|
|
||||||
System.out.println(" - Dashboard: " + config.getDashboardHost() + ":" + config.getDashboardPort());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Inicializa o processo de ligação ao dashboard.
|
|
||||||
*
|
|
||||||
* Tenta conectar-se ao dashboard. Se a ligação falhar, o processo
|
|
||||||
* continua a funcionar normalmente, mas sem enviar estatísticas.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public void initialize() {
|
|
||||||
System.out.println("Connecting to dashboard...");
|
|
||||||
|
|
||||||
try {
|
|
||||||
String host = config.getDashboardHost();
|
|
||||||
int port = config.getDashboardPort();
|
|
||||||
|
|
||||||
dashboardClient = new SocketClient("Dashboard", host, port);
|
|
||||||
dashboardClient.connect();
|
|
||||||
|
|
||||||
System.out.println("Successfully connected to dashboard");
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("WARNING: Failed to connect to dashboard: " + e.getMessage());
|
|
||||||
System.err.println("Exit node will continue without dashboard connection");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Inicia o socket e começa a aceitar ligações.
|
|
||||||
*
|
|
||||||
* Este é o loop principal do processo que:
|
|
||||||
* 1. Cria um socket na porta definida
|
|
||||||
* 2. Aguarda pelas ligações das interseções
|
|
||||||
* 3. Delega cada ligação a uma thread da pool para processamento assíncrono
|
|
||||||
*
|
|
||||||
* @throws IOException Se o socket não puder ser criado ou houver erro na aceitação
|
|
||||||
*/
|
|
||||||
public void start() throws IOException {
|
|
||||||
int port = config.getExitPort();
|
|
||||||
serverSocket = new ServerSocket(port);
|
|
||||||
running = true;
|
|
||||||
simulationStartMillis = System.currentTimeMillis();
|
|
||||||
|
|
||||||
System.out.println("Exit node started on port " + port);
|
|
||||||
System.out.println("Waiting for vehicles...\\n");
|
|
||||||
|
|
||||||
while (running) {
|
|
||||||
try {
|
|
||||||
Socket clientSocket = serverSocket.accept();
|
|
||||||
connectionHandlerPool.submit(() -> handleIncomingConnection(clientSocket));
|
|
||||||
} catch (IOException e) {
|
|
||||||
if (running) {
|
|
||||||
System.err.println("Error accepting connection: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Processa uma ligação recebida de uma interseção.
|
|
||||||
*
|
|
||||||
* Mantém a ligação aberta e processa continuamente mensagens do tipo
|
|
||||||
* VEHICLE_TRANSFER. Cada mensagem representa um veículo que chegou ao nó de saída.
|
|
||||||
*
|
|
||||||
* @param clientSocket Socket da ligação estabelecida com a interseção
|
|
||||||
*/
|
|
||||||
private void handleIncomingConnection(Socket clientSocket) {
|
|
||||||
String clientAddress = clientSocket.getInetAddress().getHostAddress();
|
|
||||||
System.out.println("New connection accepted from " + clientAddress);
|
|
||||||
|
|
||||||
try (SocketConnection connection = new SocketConnection(clientSocket)) {
|
|
||||||
|
|
||||||
while (running && connection.isConnected()) {
|
|
||||||
try {
|
|
||||||
System.out.println("[Exit] Waiting for message from " + clientAddress);
|
|
||||||
MessageProtocol message = connection.receiveMessage();
|
|
||||||
System.out.println("[Exit] Received message type: " + message.getType() +
|
|
||||||
" from " + message.getSourceNode());
|
|
||||||
|
|
||||||
if (message.getType() == MessageType.SIMULATION_START) {
|
|
||||||
// Coordinator sends start time - use it instead of our local start
|
|
||||||
simulationStartMillis = ((Number) message.getPayload()).longValue();
|
|
||||||
System.out.println("[Exit] Simulation start time synchronized");
|
|
||||||
} else if (message.getType() == MessageType.VEHICLE_TRANSFER) {
|
|
||||||
Object payload = message.getPayload();
|
|
||||||
System.out.println("[Exit] Payload type: " + payload.getClass().getName());
|
|
||||||
|
|
||||||
// Handle Gson LinkedHashMap
|
|
||||||
Vehicle vehicle;
|
|
||||||
if (payload instanceof com.google.gson.internal.LinkedTreeMap ||
|
|
||||||
payload instanceof java.util.LinkedHashMap) {
|
|
||||||
String json = new com.google.gson.Gson().toJson(payload);
|
|
||||||
vehicle = new com.google.gson.Gson().fromJson(json, Vehicle.class);
|
|
||||||
} else {
|
|
||||||
vehicle = (Vehicle) payload;
|
|
||||||
}
|
|
||||||
|
|
||||||
processExitingVehicle(vehicle);
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (ClassNotFoundException e) {
|
|
||||||
System.err.println("[Exit] Unknown message type: " + e.getMessage());
|
|
||||||
e.printStackTrace();
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.err.println("[Exit] Error processing message: " + e.getMessage());
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("[Exit] Connection closed from " + clientAddress);
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
if (running) {
|
|
||||||
System.err.println("[Exit] Connection error from " + clientAddress + ": " + e.getMessage());
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Processa um veículo que chegou ao nó de saída.
|
|
||||||
*
|
|
||||||
* Método sincronizado para garantir thread-safety ao atualizar as estatísticas.
|
|
||||||
* Calcula as métricas finais do veículo e atualiza:
|
|
||||||
* - Counters globais;
|
|
||||||
* - Estatísticas por tipo de veículo;
|
|
||||||
* - Faz update ao dashboard a cada 10 veículos.
|
|
||||||
*
|
|
||||||
* @param vehicle Veículo que completou a sua rota
|
|
||||||
*/
|
|
||||||
private synchronized void processExitingVehicle(Vehicle vehicle) {
|
|
||||||
totalVehiclesReceived++;
|
|
||||||
|
|
||||||
// Calculate relative simulation time (seconds since simulation start)
|
|
||||||
double currentSimTime = (System.currentTimeMillis() - simulationStartMillis) / 1000.0;
|
|
||||||
// System time = time vehicle spent in system (current time - entry time)
|
|
||||||
double systemTime = currentSimTime - vehicle.getEntryTime();
|
|
||||||
double waitTime = vehicle.getTotalWaitingTime();
|
|
||||||
double crossingTime = vehicle.getTotalCrossingTime();
|
|
||||||
|
|
||||||
// Store times in seconds, will be converted to ms when sending to dashboard
|
|
||||||
totalSystemTime += systemTime;
|
|
||||||
totalWaitingTime += waitTime;
|
|
||||||
totalCrossingTime += crossingTime;
|
|
||||||
|
|
||||||
VehicleType type = vehicle.getType();
|
|
||||||
vehicleTypeCount.put(type, vehicleTypeCount.get(type) + 1);
|
|
||||||
vehicleTypeWaitTime.put(type, vehicleTypeWaitTime.get(type) + waitTime);
|
|
||||||
|
|
||||||
System.out.printf("[Exit] Vehicle %s completed (type=%s, system_time=%.2fs, wait=%.2fs, crossing=%.2fs)%n",
|
|
||||||
vehicle.getId(), vehicle.getType(), systemTime, waitTime, crossingTime);
|
|
||||||
|
|
||||||
// Send stats after every vehicle to ensure dashboard updates quickly
|
|
||||||
sendStatsToDashboard();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Obtém o tempo atual da simulação em segundos.
|
|
||||||
*
|
|
||||||
* @return Tempo atual em segundos desde "epoch"
|
|
||||||
*
|
|
||||||
* "Epoch" é um ponto de referência temporal Unix (1 de janeiro de 1970).
|
|
||||||
* Este método retorna os segundos decorridos desde esse momento.
|
|
||||||
*/
|
|
||||||
private double getCurrentTime() {
|
|
||||||
return System.currentTimeMillis() / 1000.0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Envia as estatísticas para o dashboard.
|
|
||||||
*
|
|
||||||
* 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.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
private void sendStatsToDashboard() {
|
|
||||||
if (dashboardClient == null || !dashboardClient.isConnected()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Create stats payload
|
|
||||||
StatsUpdatePayload payload = new StatsUpdatePayload();
|
|
||||||
|
|
||||||
// Set global stats - convert seconds to milliseconds
|
|
||||||
payload.setTotalVehiclesCompleted(totalVehiclesReceived);
|
|
||||||
payload.setTotalSystemTime((long)(totalSystemTime * 1000.0)); // s -> ms
|
|
||||||
payload.setTotalWaitingTime((long)(totalWaitingTime * 1000.0)); // s -> ms
|
|
||||||
|
|
||||||
// Set vehicle type stats
|
|
||||||
Map<VehicleType, Integer> typeCounts = new HashMap<>();
|
|
||||||
Map<VehicleType, Long> typeWaitTimes = new HashMap<>();
|
|
||||||
|
|
||||||
for (VehicleType type : VehicleType.values()) {
|
|
||||||
typeCounts.put(type, vehicleTypeCount.get(type));
|
|
||||||
typeWaitTimes.put(type, (long)(vehicleTypeWaitTime.get(type) * 1000.0)); // s -> ms
|
|
||||||
}
|
|
||||||
|
|
||||||
payload.setVehicleTypeCounts(typeCounts);
|
|
||||||
payload.setVehicleTypeWaitTimes(typeWaitTimes);
|
|
||||||
|
|
||||||
// Send message
|
|
||||||
Message message = new Message(
|
|
||||||
MessageType.STATS_UPDATE,
|
|
||||||
"ExitNode",
|
|
||||||
"Dashboard",
|
|
||||||
payload
|
|
||||||
);
|
|
||||||
|
|
||||||
dashboardClient.send(message);
|
|
||||||
|
|
||||||
double avgWait = totalVehiclesReceived > 0 ? totalWaitingTime / totalVehiclesReceived : 0.0;
|
|
||||||
System.out.printf("[Exit] Sent stats to dashboard (total=%d, avg_wait=%.2fs)%n",
|
|
||||||
totalVehiclesReceived, avgWait);
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.err.println("[Exit] Failed to send stats to dashboard: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Termina o processo
|
|
||||||
*
|
|
||||||
* Executa a seguinte sequência:
|
|
||||||
* 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() {
|
|
||||||
System.out.println("\n[Exit] Shutting down...");
|
|
||||||
running = false;
|
|
||||||
|
|
||||||
printFinalStatistics();
|
|
||||||
|
|
||||||
sendStatsToDashboard();
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (serverSocket != null && !serverSocket.isClosed()) {
|
|
||||||
serverSocket.close();
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("Error closing server socket: " + e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
connectionHandlerPool.shutdown();
|
|
||||||
try {
|
|
||||||
if (!connectionHandlerPool.awaitTermination(5, TimeUnit.SECONDS)) {
|
|
||||||
connectionHandlerPool.shutdownNow();
|
|
||||||
}
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
connectionHandlerPool.shutdownNow();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (dashboardClient != null) {
|
|
||||||
dashboardClient.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("[Exit] Shutdown complete.");
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Imprime as estatísticas finais detalhadas no terminal
|
|
||||||
*
|
|
||||||
* Gera um relatório com:
|
|
||||||
* 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() {
|
|
||||||
System.out.println("\n=== EXIT NODE STATISTICS ===");
|
|
||||||
System.out.printf("Total Vehicles Completed: %d%n", totalVehiclesReceived);
|
|
||||||
|
|
||||||
if (totalVehiclesReceived > 0) {
|
|
||||||
System.out.printf("%nAVERAGE METRICS:%n");
|
|
||||||
System.out.printf(" System Time: %.2f seconds%n", totalSystemTime / totalVehiclesReceived);
|
|
||||||
System.out.printf(" Waiting Time: %.2f seconds%n", totalWaitingTime / totalVehiclesReceived);
|
|
||||||
System.out.printf(" Crossing Time: %.2f seconds%n", totalCrossingTime / totalVehiclesReceived);
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("\nVEHICLE TYPE DISTRIBUTION:");
|
|
||||||
for (VehicleType type : VehicleType.values()) {
|
|
||||||
int count = vehicleTypeCount.get(type);
|
|
||||||
if (count > 0) {
|
|
||||||
double percentage = (count * 100.0) / totalVehiclesReceived;
|
|
||||||
double avgWait = vehicleTypeWaitTime.get(type) / count;
|
|
||||||
System.out.printf(" %s: %d (%.1f%%), Avg Wait: %.2fs%n",
|
|
||||||
type, count, percentage, avgWait);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,692 +0,0 @@
|
|||||||
package sd;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.ServerSocket;
|
|
||||||
import java.net.Socket;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
import java.util.concurrent.locks.Lock;
|
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
|
||||||
|
|
||||||
import sd.config.SimulationConfig;
|
|
||||||
import sd.coordinator.SocketClient;
|
|
||||||
import sd.dashboard.StatsUpdatePayload;
|
|
||||||
import sd.engine.TrafficLightThread;
|
|
||||||
import sd.model.Intersection;
|
|
||||||
import sd.model.Message;
|
|
||||||
import sd.model.MessageType;
|
|
||||||
import sd.model.TrafficLight;
|
|
||||||
import sd.model.Vehicle;
|
|
||||||
import sd.protocol.MessageProtocol;
|
|
||||||
import sd.protocol.SocketConnection;
|
|
||||||
import sd.serialization.SerializationException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Main class for an Intersection Process in the distributed traffic simulation.
|
|
||||||
* * Each IntersectionProcess runs as an independent Java application (JVM
|
|
||||||
* instance)
|
|
||||||
* representing one of the five intersections (Cr1-Cr5) in the network.
|
|
||||||
*/
|
|
||||||
public class IntersectionProcess {
|
|
||||||
|
|
||||||
private final String intersectionId;
|
|
||||||
|
|
||||||
private final SimulationConfig config;
|
|
||||||
|
|
||||||
private final Intersection intersection;
|
|
||||||
|
|
||||||
private ServerSocket serverSocket;
|
|
||||||
|
|
||||||
private final Map<String, SocketConnection> outgoingConnections;
|
|
||||||
|
|
||||||
private final ExecutorService connectionHandlerPool;
|
|
||||||
|
|
||||||
private final ExecutorService trafficLightPool;
|
|
||||||
|
|
||||||
private volatile boolean running; // Quando uma thread escreve um valor volatile, todas as outras
|
|
||||||
// threads veem a mudança imediatamente.
|
|
||||||
|
|
||||||
// Traffic Light Coordination
|
|
||||||
/**
|
|
||||||
* Lock to ensure mutual exclusion between traffic lights.
|
|
||||||
* Only one traffic light can be green at any given time within this
|
|
||||||
* intersection.
|
|
||||||
*/
|
|
||||||
private final Lock trafficCoordinationLock;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tracks which direction currently has the green light.
|
|
||||||
* null means no direction is currently green (all are red).
|
|
||||||
*/
|
|
||||||
private volatile String currentGreenDirection;
|
|
||||||
|
|
||||||
private SocketClient dashboardClient;
|
|
||||||
private long simulationStartMillis;
|
|
||||||
private volatile int totalArrivals = 0;
|
|
||||||
private volatile int totalDepartures = 0;
|
|
||||||
private long lastStatsUpdateTime;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a new IntersectionProcess.
|
|
||||||
*
|
|
||||||
* @param intersectionId The ID of this intersection (e.g., "Cr1").
|
|
||||||
* @param configFilePath Path to the simulation.properties file.
|
|
||||||
* @throws IOException If configuration cannot be loaded.
|
|
||||||
*/
|
|
||||||
public IntersectionProcess(String intersectionId, String configFilePath) throws IOException {
|
|
||||||
this.intersectionId = intersectionId;
|
|
||||||
this.config = new SimulationConfig(configFilePath);
|
|
||||||
this.intersection = new Intersection(intersectionId);
|
|
||||||
this.outgoingConnections = new HashMap<>();
|
|
||||||
this.connectionHandlerPool = Executors.newCachedThreadPool();
|
|
||||||
this.trafficLightPool = Executors.newFixedThreadPool(4); // Max 4 directions
|
|
||||||
this.running = false;
|
|
||||||
this.trafficCoordinationLock = new ReentrantLock();
|
|
||||||
this.currentGreenDirection = null;
|
|
||||||
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
System.out.println("INTERSECTION PROCESS: " + intersectionId);
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Main entry point for running an intersection process
|
|
||||||
public static void main(String[] args) {
|
|
||||||
if (args.length < 1) {
|
|
||||||
System.err.println("Usage: java IntersectionProcess <intersectionId> [configFile]");
|
|
||||||
System.err.println("Example: java IntersectionProcess Cr1");
|
|
||||||
System.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
String intersectionId = args[0];
|
|
||||||
String configFile = args.length > 1 ? args[1] : "src/main/resources/simulation.properties";
|
|
||||||
|
|
||||||
try {
|
|
||||||
IntersectionProcess process = new IntersectionProcess(intersectionId, configFile);
|
|
||||||
process.initialize();
|
|
||||||
process.start();
|
|
||||||
|
|
||||||
// Add shutdown hook
|
|
||||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
|
||||||
System.out.println("\nShutdown signal received...");
|
|
||||||
process.shutdown();
|
|
||||||
}));
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("Failed to start intersection process: " + e.getMessage());
|
|
||||||
e.printStackTrace();
|
|
||||||
System.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void initialize() {
|
|
||||||
System.out.println("\n[" + intersectionId + "] Initializing intersection...");
|
|
||||||
|
|
||||||
createTrafficLights();
|
|
||||||
|
|
||||||
configureRouting();
|
|
||||||
|
|
||||||
connectToDashboard();
|
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Initialization complete.");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Establishes connection to the dashboard server for statistics reporting.
|
|
||||||
*/
|
|
||||||
private void connectToDashboard() {
|
|
||||||
try {
|
|
||||||
String dashboardHost = config.getDashboardHost();
|
|
||||||
int dashboardPort = config.getDashboardPort();
|
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Connecting to dashboard at " +
|
|
||||||
dashboardHost + ":" + dashboardPort + "...");
|
|
||||||
|
|
||||||
dashboardClient = new SocketClient(intersectionId, dashboardHost, dashboardPort);
|
|
||||||
dashboardClient.connect();
|
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Connected to dashboard.");
|
|
||||||
lastStatsUpdateTime = System.currentTimeMillis();
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("[" + intersectionId + "] Failed to connect to dashboard: " +
|
|
||||||
e.getMessage());
|
|
||||||
System.err.println("[" + intersectionId + "] Will continue without dashboard reporting.");
|
|
||||||
dashboardClient = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates traffic lights for this intersection based on its physical
|
|
||||||
* connections.
|
|
||||||
* Each intersection has different number and directions of traffic lights
|
|
||||||
* according to the network topology.
|
|
||||||
*/
|
|
||||||
private void createTrafficLights() {
|
|
||||||
System.out.println("\n[" + intersectionId + "] Creating traffic lights...");
|
|
||||||
|
|
||||||
String[] directions = new String[0];
|
|
||||||
switch (intersectionId) {
|
|
||||||
case "Cr1":
|
|
||||||
directions = new String[] { "East", "South" };
|
|
||||||
break;
|
|
||||||
case "Cr2":
|
|
||||||
directions = new String[] { "West", "East", "South" };
|
|
||||||
break;
|
|
||||||
case "Cr3":
|
|
||||||
directions = new String[] { "West", "South" };
|
|
||||||
break;
|
|
||||||
case "Cr4":
|
|
||||||
directions = new String[] { "East" };
|
|
||||||
break;
|
|
||||||
case "Cr5":
|
|
||||||
directions = new String[] { "East" };
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (String direction : directions) {
|
|
||||||
double greenTime = config.getTrafficLightGreenTime(intersectionId, direction);
|
|
||||||
double redTime = config.getTrafficLightRedTime(intersectionId, direction);
|
|
||||||
|
|
||||||
TrafficLight light = new TrafficLight(
|
|
||||||
intersectionId + "-" + direction,
|
|
||||||
direction,
|
|
||||||
greenTime,
|
|
||||||
redTime);
|
|
||||||
|
|
||||||
intersection.addTrafficLight(light);
|
|
||||||
System.out.println(" Created traffic light: " + direction +
|
|
||||||
" (Green: " + greenTime + "s, Red: " + redTime + "s)");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void configureRouting() {
|
|
||||||
System.out.println("\n[" + intersectionId + "] Configuring routing...");
|
|
||||||
|
|
||||||
switch (intersectionId) {
|
|
||||||
case "Cr1":
|
|
||||||
intersection.configureRoute("Cr2", "East");
|
|
||||||
intersection.configureRoute("Cr4", "South");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "Cr2":
|
|
||||||
intersection.configureRoute("Cr1", "West");
|
|
||||||
intersection.configureRoute("Cr3", "East");
|
|
||||||
intersection.configureRoute("Cr5", "South");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "Cr3":
|
|
||||||
intersection.configureRoute("Cr2", "West");
|
|
||||||
intersection.configureRoute("S", "South");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "Cr4":
|
|
||||||
intersection.configureRoute("Cr5", "East");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "Cr5":
|
|
||||||
intersection.configureRoute("S", "East");
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
System.err.println(" Error: unknown intersection ID: " + intersectionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println(" Routing configured.");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Requests permission for a traffic light to turn green.
|
|
||||||
* Blocks until permission is granted (no other light is green).
|
|
||||||
*
|
|
||||||
* @param direction The direction requesting green light
|
|
||||||
*/
|
|
||||||
public void requestGreenLight(String direction) {
|
|
||||||
trafficCoordinationLock.lock();
|
|
||||||
currentGreenDirection = direction;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Releases the green light permission, allowing another light to turn green.
|
|
||||||
*
|
|
||||||
* @param direction The direction releasing green light
|
|
||||||
*/
|
|
||||||
public void releaseGreenLight(String direction) {
|
|
||||||
if (direction.equals(currentGreenDirection)) {
|
|
||||||
currentGreenDirection = null;
|
|
||||||
trafficCoordinationLock.unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Starts all traffic light threads.
|
|
||||||
*/
|
|
||||||
private void startTrafficLights() {
|
|
||||||
System.out.println("\n[" + intersectionId + "] Starting traffic light threads...");
|
|
||||||
|
|
||||||
for (TrafficLight light : intersection.getTrafficLights()) {
|
|
||||||
|
|
||||||
TrafficLightThread lightTask = new TrafficLightThread(light, this, config);
|
|
||||||
|
|
||||||
trafficLightPool.submit(lightTask);
|
|
||||||
|
|
||||||
System.out.println(" Started thread for: " + light.getDirection());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sends a vehicle to its next destination via socket connection.
|
|
||||||
*
|
|
||||||
* @param vehicle The vehicle that has crossed this intersection.
|
|
||||||
*/
|
|
||||||
public void sendVehicleToNextDestination(Vehicle vehicle) {
|
|
||||||
String nextDestination = vehicle.getCurrentDestination();
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Get or create connection to next destination
|
|
||||||
SocketConnection connection = getOrCreateConnection(nextDestination);
|
|
||||||
|
|
||||||
// Create and send message using Message class
|
|
||||||
MessageProtocol message = new Message(
|
|
||||||
MessageType.VEHICLE_TRANSFER,
|
|
||||||
intersectionId,
|
|
||||||
nextDestination,
|
|
||||||
vehicle,
|
|
||||||
System.currentTimeMillis());
|
|
||||||
|
|
||||||
connection.sendMessage(message);
|
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Sent vehicle " + vehicle.getId() +
|
|
||||||
" to " + nextDestination);
|
|
||||||
|
|
||||||
// Record departure for statistics
|
|
||||||
recordVehicleDeparture();
|
|
||||||
|
|
||||||
// Note: vehicle route is advanced when it arrives at the next intersection
|
|
||||||
|
|
||||||
} catch (IOException | InterruptedException e) {
|
|
||||||
System.err.println("[" + intersectionId + "] Failed to send vehicle " +
|
|
||||||
vehicle.getId() + " to " + nextDestination + ": " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets an existing connection to a destination or creates a new one.
|
|
||||||
*
|
|
||||||
* @param destinationId The ID of the destination node.
|
|
||||||
* @return The SocketConnection to that destination.
|
|
||||||
* @throws IOException If connection cannot be established.
|
|
||||||
* @throws InterruptedException If connection attempt is interrupted.
|
|
||||||
*/
|
|
||||||
private synchronized SocketConnection getOrCreateConnection(String destinationId)
|
|
||||||
throws IOException, InterruptedException {
|
|
||||||
|
|
||||||
if (!outgoingConnections.containsKey(destinationId)) {
|
|
||||||
String host = getHostForDestination(destinationId);
|
|
||||||
int port = getPortForDestination(destinationId);
|
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Creating connection to " +
|
|
||||||
destinationId + " at " + host + ":" + port);
|
|
||||||
|
|
||||||
SocketConnection connection = new SocketConnection(host, port);
|
|
||||||
outgoingConnections.put(destinationId, connection);
|
|
||||||
}
|
|
||||||
|
|
||||||
return outgoingConnections.get(destinationId);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the host address for a destination node from configuration.
|
|
||||||
*
|
|
||||||
* @param destinationId The destination node ID.
|
|
||||||
* @return The host address.
|
|
||||||
*/
|
|
||||||
private String getHostForDestination(String destinationId) {
|
|
||||||
if (destinationId.equals("S")) {
|
|
||||||
return config.getExitHost();
|
|
||||||
} else {
|
|
||||||
return config.getIntersectionHost(destinationId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the port number for a destination node from configuration.
|
|
||||||
*
|
|
||||||
* @param destinationId The destination node ID.
|
|
||||||
* @return The port number.
|
|
||||||
*/
|
|
||||||
private int getPortForDestination(String destinationId) {
|
|
||||||
if (destinationId.equals("S")) {
|
|
||||||
return config.getExitPort();
|
|
||||||
} else {
|
|
||||||
return config.getIntersectionPort(destinationId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Starts the server socket and begins accepting incoming connections.
|
|
||||||
* This is the main listening loop of the process.
|
|
||||||
*
|
|
||||||
* @throws IOException If the server socket cannot be created.
|
|
||||||
*/
|
|
||||||
public void start() throws IOException {
|
|
||||||
int port = config.getIntersectionPort(intersectionId);
|
|
||||||
serverSocket = new ServerSocket(port);
|
|
||||||
running = true;
|
|
||||||
|
|
||||||
System.out.println("\n[" + intersectionId + "] Server started on port " + port);
|
|
||||||
|
|
||||||
// Start traffic light threads when running is true
|
|
||||||
startTrafficLights();
|
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Waiting for incoming connections...\n");
|
|
||||||
|
|
||||||
// Main accept loop
|
|
||||||
while (running) {
|
|
||||||
try {
|
|
||||||
Socket clientSocket = serverSocket.accept();
|
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] New connection accepted from " +
|
|
||||||
clientSocket.getInetAddress().getHostAddress());
|
|
||||||
|
|
||||||
// Check running flag again before handling
|
|
||||||
if (!running) {
|
|
||||||
clientSocket.close();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// **Set timeout before submitting to handler**
|
|
||||||
try {
|
|
||||||
clientSocket.setSoTimeout(1000);
|
|
||||||
} catch (java.net.SocketException e) {
|
|
||||||
System.err.println("[" + intersectionId + "] Failed to set timeout: " + e.getMessage());
|
|
||||||
clientSocket.close();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle each connection in a separate thread
|
|
||||||
connectionHandlerPool.submit(() -> handleIncomingConnection(clientSocket));
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
// Expected when serverSocket.close() is called during shutdown
|
|
||||||
if (!running) {
|
|
||||||
break; // Normal shutdown
|
|
||||||
}
|
|
||||||
System.err.println("[" + intersectionId + "] Error accepting connection: " +
|
|
||||||
e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Handles an incoming connection from another process.
|
|
||||||
* Continuously listens for vehicle transfer messages.
|
|
||||||
*
|
|
||||||
* @param clientSocket The accepted socket connection.
|
|
||||||
*/
|
|
||||||
private void handleIncomingConnection(Socket clientSocket) {
|
|
||||||
try {
|
|
||||||
clientSocket.setSoTimeout(1000); // 1 second timeout
|
|
||||||
|
|
||||||
} catch (java.net.SocketException e) {
|
|
||||||
System.err.println("[" + intersectionId + "] Failed to set socket timeout: " + e.getMessage());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try (SocketConnection connection = new SocketConnection(clientSocket)) {
|
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] New connection accepted from " +
|
|
||||||
clientSocket.getInetAddress().getHostAddress());
|
|
||||||
|
|
||||||
// Continuously receive messages while connection is active
|
|
||||||
while (running && connection.isConnected()) {
|
|
||||||
try {
|
|
||||||
MessageProtocol message = connection.receiveMessage();
|
|
||||||
|
|
||||||
// Handle simulation start time synchronization
|
|
||||||
if (message.getType() == MessageType.SIMULATION_START) {
|
|
||||||
simulationStartMillis = ((Number) message.getPayload()).longValue();
|
|
||||||
System.out.println("[" + intersectionId + "] Simulation start time synchronized");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Accept both VEHICLE_TRANSFER and VEHICLE_SPAWN (from coordinator)
|
|
||||||
if (message.getType() == MessageType.VEHICLE_TRANSFER ||
|
|
||||||
message.getType() == MessageType.VEHICLE_SPAWN) {
|
|
||||||
// Cast payload to Vehicle - handle Gson deserialization
|
|
||||||
Vehicle vehicle;
|
|
||||||
Object payload = message.getPayload();
|
|
||||||
if (payload instanceof Vehicle) {
|
|
||||||
vehicle = (Vehicle) payload;
|
|
||||||
} else if (payload instanceof java.util.Map) {
|
|
||||||
// Gson deserialized as LinkedHashMap - re-serialize and deserialize as Vehicle
|
|
||||||
com.google.gson.Gson gson = new com.google.gson.Gson();
|
|
||||||
String json = gson.toJson(payload);
|
|
||||||
vehicle = gson.fromJson(json, Vehicle.class);
|
|
||||||
} else {
|
|
||||||
System.err.println("[" + intersectionId + "] Unknown payload type: " + payload.getClass());
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Received vehicle: " +
|
|
||||||
vehicle.getId() + " from " + message.getSourceNode());
|
|
||||||
|
|
||||||
// Advance vehicle to next destination in its route
|
|
||||||
vehicle.advanceRoute();
|
|
||||||
|
|
||||||
// Add vehicle to appropriate queue
|
|
||||||
intersection.receiveVehicle(vehicle);
|
|
||||||
|
|
||||||
// Record arrival for statistics
|
|
||||||
recordVehicleArrival();
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (java.net.SocketTimeoutException e) {
|
|
||||||
// Timeout - check running flag and continue
|
|
||||||
if (!running) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
// Continue waiting for next message
|
|
||||||
} catch (ClassNotFoundException e) {
|
|
||||||
System.err.println("[" + intersectionId + "] Unknown message type received: " +
|
|
||||||
e.getMessage());
|
|
||||||
break; // Invalid message, close connection
|
|
||||||
} catch (IOException e) {
|
|
||||||
if (running) {
|
|
||||||
System.err.println("[" + intersectionId + "] Failed to deserialize message: " +
|
|
||||||
e.getMessage());
|
|
||||||
e.printStackTrace(); // For debugging - maybe change//remove later
|
|
||||||
}
|
|
||||||
break; // Connection error, close connection
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
if (running) {
|
|
||||||
System.err.println("[" + intersectionId + "] Connection error: " + e.getMessage());
|
|
||||||
}
|
|
||||||
// Expected during shutdown
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Stops the intersection process gracefully.
|
|
||||||
* Shuts down all threads and closes all connections.
|
|
||||||
*/
|
|
||||||
public void shutdown() {
|
|
||||||
// Check if already shutdown
|
|
||||||
if (!running) {
|
|
||||||
return; // Already shutdown, do nothing
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("\n[" + intersectionId + "] Shutting down...");
|
|
||||||
running = false;
|
|
||||||
|
|
||||||
// 1. Close ServerSocket first
|
|
||||||
if (serverSocket != null && !serverSocket.isClosed()) {
|
|
||||||
try {
|
|
||||||
serverSocket.close();
|
|
||||||
} catch (IOException e) {
|
|
||||||
// Expected
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Shutdown thread pools with force
|
|
||||||
if (trafficLightPool != null && !trafficLightPool.isShutdown()) {
|
|
||||||
trafficLightPool.shutdownNow();
|
|
||||||
}
|
|
||||||
if (connectionHandlerPool != null && !connectionHandlerPool.isShutdown()) {
|
|
||||||
connectionHandlerPool.shutdownNow();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Wait briefly for termination (don't block forever)
|
|
||||||
try {
|
|
||||||
if (trafficLightPool != null) {
|
|
||||||
trafficLightPool.awaitTermination(1, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
if (connectionHandlerPool != null) {
|
|
||||||
connectionHandlerPool.awaitTermination(1, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Close outgoing connections
|
|
||||||
synchronized (outgoingConnections) {
|
|
||||||
for (SocketConnection conn : outgoingConnections.values()) {
|
|
||||||
try {
|
|
||||||
conn.close();
|
|
||||||
} catch (Exception e) {
|
|
||||||
// Ignore
|
|
||||||
}
|
|
||||||
}
|
|
||||||
outgoingConnections.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 5. Close dashboard connection
|
|
||||||
if (dashboardClient != null) {
|
|
||||||
dashboardClient.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Shutdown complete.");
|
|
||||||
System.out.println("============================================================\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the Intersection object managed by this process.
|
|
||||||
* Useful for testing and monitoring.
|
|
||||||
*
|
|
||||||
* @return The Intersection object.
|
|
||||||
*/
|
|
||||||
public Intersection getIntersection() {
|
|
||||||
return intersection;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Records that a vehicle has arrived at this intersection.
|
|
||||||
*/
|
|
||||||
public void recordVehicleArrival() {
|
|
||||||
totalArrivals++;
|
|
||||||
checkAndSendStats();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Records that a vehicle has departed from this intersection.
|
|
||||||
*/
|
|
||||||
public void recordVehicleDeparture() {
|
|
||||||
totalDepartures++;
|
|
||||||
checkAndSendStats();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Checks if it's time to send statistics to the dashboard and sends them if needed.
|
|
||||||
*/
|
|
||||||
private void checkAndSendStats() {
|
|
||||||
long now = System.currentTimeMillis();
|
|
||||||
long elapsed = now - lastStatsUpdateTime;
|
|
||||||
|
|
||||||
// Send stats every 5 seconds
|
|
||||||
if (elapsed >= 5000) {
|
|
||||||
sendStatsToDashboard();
|
|
||||||
lastStatsUpdateTime = now;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sends current statistics to the dashboard server.
|
|
||||||
*/
|
|
||||||
private void sendStatsToDashboard() {
|
|
||||||
if (dashboardClient == null || !dashboardClient.isConnected()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Calculate current queue size
|
|
||||||
int currentQueueSize = intersection.getTrafficLights().stream()
|
|
||||||
.mapToInt(TrafficLight::getQueueSize)
|
|
||||||
.sum();
|
|
||||||
|
|
||||||
StatsUpdatePayload payload = new StatsUpdatePayload()
|
|
||||||
.setIntersectionArrivals(totalArrivals)
|
|
||||||
.setIntersectionDepartures(totalDepartures)
|
|
||||||
.setIntersectionQueueSize(currentQueueSize);
|
|
||||||
|
|
||||||
// Send StatsUpdatePayload directly as the message payload
|
|
||||||
sd.model.Message message = new sd.model.Message(
|
|
||||||
MessageType.STATS_UPDATE,
|
|
||||||
intersectionId,
|
|
||||||
"Dashboard",
|
|
||||||
payload
|
|
||||||
);
|
|
||||||
|
|
||||||
dashboardClient.send(message);
|
|
||||||
|
|
||||||
System.out.printf("[%s] Sent stats to dashboard (arrivals=%d, departures=%d, queue=%d)%n",
|
|
||||||
intersectionId, totalArrivals, totalDepartures, currentQueueSize);
|
|
||||||
|
|
||||||
} catch (SerializationException | IOException e) {
|
|
||||||
System.err.println("[" + intersectionId + "] Failed to send stats to dashboard: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Inner class for Vehicle Transfer Messages ---
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Implementation of MessageProtocol for vehicle transfers between processes.
|
|
||||||
*/
|
|
||||||
private static class VehicleTransferMessage implements MessageProtocol {
|
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
|
|
||||||
private final String sourceNode;
|
|
||||||
private final String destinationNode;
|
|
||||||
private final Vehicle payload;
|
|
||||||
|
|
||||||
public VehicleTransferMessage(String sourceNode, String destinationNode, Vehicle vehicle) {
|
|
||||||
this.sourceNode = sourceNode;
|
|
||||||
this.destinationNode = destinationNode;
|
|
||||||
this.payload = vehicle;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -227,32 +227,6 @@ public class SimulationConfig {
|
|||||||
return Double.parseDouble(properties.getProperty("vehicle.crossing.time.heavy", "4.0"));
|
return Double.parseDouble(properties.getProperty("vehicle.crossing.time.heavy", "4.0"));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the base travel time between intersections for light vehicles.
|
|
||||||
* @return The base travel time in seconds.
|
|
||||||
*/
|
|
||||||
public double getBaseTravelTime() {
|
|
||||||
return Double.parseDouble(properties.getProperty("vehicle.travel.time.base", "8.0"));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the travel time multiplier for bike vehicles.
|
|
||||||
* Bike travel time = base time × this multiplier.
|
|
||||||
* @return The multiplier for bike travel time.
|
|
||||||
*/
|
|
||||||
public double getBikeTravelTimeMultiplier() {
|
|
||||||
return Double.parseDouble(properties.getProperty("vehicle.travel.time.bike.multiplier", "0.5"));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the travel time multiplier for heavy vehicles.
|
|
||||||
* Heavy vehicle travel time = base time × this multiplier.
|
|
||||||
* @return The multiplier for heavy vehicle travel time.
|
|
||||||
*/
|
|
||||||
public double getHeavyTravelTimeMultiplier() {
|
|
||||||
return Double.parseDouble(properties.getProperty("vehicle.travel.time.heavy.multiplier", "2.0"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Statistics ---
|
// --- Statistics ---
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,288 +0,0 @@
|
|||||||
package sd.coordinator;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import sd.config.SimulationConfig;
|
|
||||||
import sd.dashboard.StatsUpdatePayload;
|
|
||||||
import sd.model.Message;
|
|
||||||
import sd.model.MessageType;
|
|
||||||
import sd.model.Vehicle;
|
|
||||||
import sd.serialization.SerializationException;
|
|
||||||
import sd.util.VehicleGenerator;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Coordinator process responsible for:
|
|
||||||
* 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.
|
|
||||||
*/
|
|
||||||
public class CoordinatorProcess {
|
|
||||||
|
|
||||||
private final SimulationConfig config;
|
|
||||||
private final VehicleGenerator vehicleGenerator;
|
|
||||||
private final Map<String, SocketClient> intersectionClients;
|
|
||||||
private SocketClient dashboardClient;
|
|
||||||
private double currentTime;
|
|
||||||
private int vehicleCounter;
|
|
||||||
private boolean running;
|
|
||||||
private double nextGenerationTime;
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
System.out.println("COORDINATOR PROCESS - DISTRIBUTED TRAFFIC SIMULATION");
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 1. Load configuration
|
|
||||||
String configFile = args.length > 0 ? args[0] : "src/main/resources/simulation.properties";
|
|
||||||
System.out.println("Loading configuration from: " + configFile);
|
|
||||||
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile);
|
|
||||||
CoordinatorProcess coordinator = new CoordinatorProcess(config);
|
|
||||||
|
|
||||||
// 2. Connect to intersection processes
|
|
||||||
System.out.println("\n" + "=".repeat(60));
|
|
||||||
coordinator.initialize();
|
|
||||||
|
|
||||||
// 3. Run the sim
|
|
||||||
System.out.println("\n" + "=".repeat(60));
|
|
||||||
coordinator.run();
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("Failed to load configuration: " + e.getMessage());
|
|
||||||
System.exit(1);
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.err.println("Coordinator error: " + e.getMessage());
|
|
||||||
System.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public CoordinatorProcess(SimulationConfig config) {
|
|
||||||
this.config = config;
|
|
||||||
this.vehicleGenerator = new VehicleGenerator(config);
|
|
||||||
this.intersectionClients = new HashMap<>();
|
|
||||||
this.currentTime = 0.0;
|
|
||||||
this.vehicleCounter = 0;
|
|
||||||
this.running = false;
|
|
||||||
this.nextGenerationTime = 0.0;
|
|
||||||
|
|
||||||
System.out.println("Coordinator initialized with configuration:");
|
|
||||||
System.out.println(" - Simulation duration: " + config.getSimulationDuration() + "s");
|
|
||||||
System.out.println(" - Arrival model: " + config.getArrivalModel());
|
|
||||||
System.out.println(" - Arrival rate: " + config.getArrivalRate() + " vehicles/s");
|
|
||||||
}
|
|
||||||
|
|
||||||
public void initialize() {
|
|
||||||
// Connect to dashboard first
|
|
||||||
connectToDashboard();
|
|
||||||
|
|
||||||
System.out.println("Connecting to intersection processes...");
|
|
||||||
|
|
||||||
String[] intersectionIds = {"Cr1", "Cr2", "Cr3", "Cr4", "Cr5"};
|
|
||||||
|
|
||||||
for (String intersectionId : intersectionIds) {
|
|
||||||
try {
|
|
||||||
String host = config.getIntersectionHost(intersectionId);
|
|
||||||
int port = config.getIntersectionPort(intersectionId);
|
|
||||||
|
|
||||||
SocketClient client = new SocketClient(intersectionId, host, port);
|
|
||||||
client.connect();
|
|
||||||
intersectionClients.put(intersectionId, client);
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("Failed to connect to " + intersectionId + ": " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("Successfully connected to " + intersectionClients.size() + " intersection(s)");
|
|
||||||
|
|
||||||
if (intersectionClients.isEmpty()) {
|
|
||||||
System.err.println("WARNING: No intersections connected. Simulation cannot proceed.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void run() {
|
|
||||||
double duration = config.getSimulationDuration();
|
|
||||||
running = true;
|
|
||||||
|
|
||||||
System.out.println("Starting vehicle generation simulation...");
|
|
||||||
System.out.println("Duration: " + duration + " seconds");
|
|
||||||
System.out.println();
|
|
||||||
|
|
||||||
// Send simulation start time to all processes for synchronization
|
|
||||||
sendSimulationStartTime();
|
|
||||||
|
|
||||||
nextGenerationTime = vehicleGenerator.getNextArrivalTime(currentTime);
|
|
||||||
final double TIME_STEP = 0.1;
|
|
||||||
|
|
||||||
while (running && currentTime < duration) {
|
|
||||||
if (currentTime >= nextGenerationTime) {
|
|
||||||
generateAndSendVehicle();
|
|
||||||
nextGenerationTime = vehicleGenerator.getNextArrivalTime(currentTime);
|
|
||||||
}
|
|
||||||
currentTime += TIME_STEP;
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println();
|
|
||||||
System.out.println("Simulation complete at t=" + String.format("%.2f", currentTime) + "s");
|
|
||||||
System.out.println("Total vehicles generated: " + vehicleCounter);
|
|
||||||
|
|
||||||
shutdown();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void generateAndSendVehicle() {
|
|
||||||
Vehicle vehicle = vehicleGenerator.generateVehicle("V" + (++vehicleCounter), currentTime);
|
|
||||||
|
|
||||||
System.out.printf("[t=%.2f] Vehicle %s generated (type=%s, route=%s)%n",
|
|
||||||
currentTime, vehicle.getId(), vehicle.getType(), vehicle.getRoute());
|
|
||||||
|
|
||||||
// Send generation count to dashboard
|
|
||||||
sendGenerationStatsToDashboard();
|
|
||||||
|
|
||||||
if (vehicle.getRoute().isEmpty()) {
|
|
||||||
System.err.println("ERROR: Vehicle " + vehicle.getId() + " has empty route!");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
String entryIntersection = vehicle.getRoute().get(0);
|
|
||||||
sendVehicleToIntersection(vehicle, entryIntersection);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendVehicleToIntersection(Vehicle vehicle, String intersectionId) {
|
|
||||||
SocketClient client = intersectionClients.get(intersectionId);
|
|
||||||
|
|
||||||
if (client == null || !client.isConnected()) {
|
|
||||||
System.err.println("ERROR: No connection to " + intersectionId + " for vehicle " + vehicle.getId());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
Message message = new Message(
|
|
||||||
MessageType.VEHICLE_SPAWN,
|
|
||||||
"COORDINATOR",
|
|
||||||
intersectionId,
|
|
||||||
vehicle
|
|
||||||
);
|
|
||||||
|
|
||||||
client.send(message);
|
|
||||||
System.out.printf("->Sent to %s%n", intersectionId);
|
|
||||||
|
|
||||||
} catch (SerializationException | IOException e) {
|
|
||||||
System.err.println("ERROR: Failed to send vehicle " + vehicle.getId() + " to " + intersectionId);
|
|
||||||
System.err.println("Reason: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void shutdown() {
|
|
||||||
System.out.println();
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
System.out.println("Shutting down coordinator...");
|
|
||||||
|
|
||||||
for (Map.Entry<String, SocketClient> entry : intersectionClients.entrySet()) {
|
|
||||||
String intersectionId = entry.getKey();
|
|
||||||
SocketClient client = entry.getValue();
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (client.isConnected()) {
|
|
||||||
Message personalizedShutdown = new Message(
|
|
||||||
MessageType.SHUTDOWN,
|
|
||||||
"COORDINATOR",
|
|
||||||
intersectionId,
|
|
||||||
"Simulation complete"
|
|
||||||
);
|
|
||||||
client.send(personalizedShutdown);
|
|
||||||
System.out.println("Sent shutdown message to " + intersectionId);
|
|
||||||
}
|
|
||||||
} catch (SerializationException | IOException e) {
|
|
||||||
System.err.println("Error sending shutdown to " + intersectionId + ": " + e.getMessage());
|
|
||||||
} finally {
|
|
||||||
client.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("Coordinator shutdown complete");
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
}
|
|
||||||
|
|
||||||
public void stop() {
|
|
||||||
System.out.println("\nStop signal received...");
|
|
||||||
running = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void connectToDashboard() {
|
|
||||||
try {
|
|
||||||
String host = config.getDashboardHost();
|
|
||||||
int port = config.getDashboardPort();
|
|
||||||
|
|
||||||
System.out.println("Connecting to dashboard at " + host + ":" + port);
|
|
||||||
dashboardClient = new SocketClient("Dashboard", host, port);
|
|
||||||
dashboardClient.connect();
|
|
||||||
System.out.println("Successfully connected to dashboard\n");
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("WARNING: Failed to connect to dashboard: " + e.getMessage());
|
|
||||||
System.err.println("Coordinator will continue without dashboard connection\n");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendGenerationStatsToDashboard() {
|
|
||||||
if (dashboardClient == null || !dashboardClient.isConnected()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Create stats payload with vehicle generation count
|
|
||||||
StatsUpdatePayload payload = new StatsUpdatePayload();
|
|
||||||
payload.setTotalVehiclesGenerated(vehicleCounter);
|
|
||||||
|
|
||||||
Message message = new Message(
|
|
||||||
MessageType.STATS_UPDATE,
|
|
||||||
"COORDINATOR",
|
|
||||||
"Dashboard",
|
|
||||||
payload
|
|
||||||
);
|
|
||||||
|
|
||||||
dashboardClient.send(message);
|
|
||||||
} catch (Exception e) { //This is fine - can add IOException if need be
|
|
||||||
// Don't crash if dashboard update fails
|
|
||||||
System.err.println("Failed to send stats to dashboard: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendSimulationStartTime() {
|
|
||||||
long startTimeMillis = System.currentTimeMillis();
|
|
||||||
|
|
||||||
// Send to all intersections
|
|
||||||
for (Map.Entry<String, SocketClient> entry : intersectionClients.entrySet()) {
|
|
||||||
try {
|
|
||||||
Message message = new Message(
|
|
||||||
MessageType.SIMULATION_START,
|
|
||||||
"COORDINATOR",
|
|
||||||
entry.getKey(),
|
|
||||||
startTimeMillis
|
|
||||||
);
|
|
||||||
entry.getValue().send(message);
|
|
||||||
} catch (Exception e) { // Same thing here
|
|
||||||
System.err.println("Failed to send start time to " + entry.getKey() + ": " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send to dashboard
|
|
||||||
if (dashboardClient != null && dashboardClient.isConnected()) {
|
|
||||||
try {
|
|
||||||
Message message = new Message(
|
|
||||||
MessageType.SIMULATION_START,
|
|
||||||
"COORDINATOR",
|
|
||||||
"Dashboard",
|
|
||||||
startTimeMillis
|
|
||||||
);
|
|
||||||
dashboardClient.send(message);
|
|
||||||
} catch (Exception e) { // And here
|
|
||||||
// Don't crash
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,124 +0,0 @@
|
|||||||
package sd.coordinator;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.OutputStream;
|
|
||||||
import java.net.Socket;
|
|
||||||
|
|
||||||
import sd.model.Message;
|
|
||||||
import sd.serialization.MessageSerializer;
|
|
||||||
import sd.serialization.SerializationException;
|
|
||||||
import sd.serialization.SerializerFactory;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Socket client for communication with a single intersection process.
|
|
||||||
*
|
|
||||||
* Handles a persistent TCP connection to one intersection,
|
|
||||||
* providing a simple way to send serialized messages.
|
|
||||||
*/
|
|
||||||
public class SocketClient {
|
|
||||||
|
|
||||||
private final String intersectionId;
|
|
||||||
private final String host;
|
|
||||||
private final int port;
|
|
||||||
private Socket socket;
|
|
||||||
private OutputStream outputStream;
|
|
||||||
private MessageSerializer serializer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a new SocketClient for a given intersection.
|
|
||||||
*
|
|
||||||
* @param intersectionId Intersection ID (ex. "Cr1")
|
|
||||||
* @param host Host address (ex. "localhost")
|
|
||||||
* @param port Port number
|
|
||||||
*/
|
|
||||||
public SocketClient(String intersectionId, String host, int port) {
|
|
||||||
this.intersectionId = intersectionId;
|
|
||||||
this.host = host;
|
|
||||||
this.port = port;
|
|
||||||
this.serializer = SerializerFactory.createDefault();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Connects to the intersection process via TCP.
|
|
||||||
*
|
|
||||||
* @throws IOException if the connection cannot be established
|
|
||||||
*/
|
|
||||||
|
|
||||||
public void connect() throws IOException {
|
|
||||||
try {
|
|
||||||
socket = new Socket(host, port);
|
|
||||||
outputStream = socket.getOutputStream();
|
|
||||||
System.out.println("Connected to " + intersectionId + " at " + host + ":" + port);
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("Failed to connect to " + intersectionId + " at " + host + ":" + port);
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sends a message to the connected intersection.
|
|
||||||
* The message is serialized and written over the socket.
|
|
||||||
*
|
|
||||||
* @param message The message to send
|
|
||||||
* @throws SerializationException if serialization fails
|
|
||||||
* @throws IOException if the socket write fails
|
|
||||||
*/
|
|
||||||
public void send(Message message) throws SerializationException, IOException {
|
|
||||||
if (socket == null || socket.isClosed()) {
|
|
||||||
throw new IOException("Socket is not connected to " + intersectionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
byte[] data = serializer.serialize(message);
|
|
||||||
|
|
||||||
// Prefix with message length (so receiver knows how much to read)
|
|
||||||
int length = data.length;
|
|
||||||
outputStream.write((length >> 24) & 0xFF);
|
|
||||||
outputStream.write((length >> 16) & 0xFF);
|
|
||||||
outputStream.write((length >> 8) & 0xFF);
|
|
||||||
outputStream.write(length & 0xFF);
|
|
||||||
|
|
||||||
outputStream.write(data);
|
|
||||||
outputStream.flush();
|
|
||||||
|
|
||||||
} catch (SerializationException | IOException e) {
|
|
||||||
System.err.println("Error sending message to " + intersectionId + ": " + e.getMessage());
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Closes the socket connection safely.
|
|
||||||
* Calling it multiple times won’t cause issues.
|
|
||||||
*/
|
|
||||||
public void close() {
|
|
||||||
try {
|
|
||||||
if (outputStream != null) {
|
|
||||||
outputStream.close();
|
|
||||||
}
|
|
||||||
if (socket != null && !socket.isClosed()) {
|
|
||||||
socket.close();
|
|
||||||
System.out.println("Closed connection to " + intersectionId);
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("Error closing connection to " + intersectionId + ": " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return true if connected and socket is open, false otherwise
|
|
||||||
*/
|
|
||||||
public boolean isConnected() {
|
|
||||||
return socket != null && socket.isConnected() && !socket.isClosed();
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getIntersectionId() {
|
|
||||||
return intersectionId;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return String.format("SocketClient[intersection=%s, host=%s, port=%d, connected=%s]",
|
|
||||||
intersectionId, host, port, isConnected());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,137 +0,0 @@
|
|||||||
package sd.dashboard;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.Socket;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import sd.model.MessageType;
|
|
||||||
import sd.protocol.MessageProtocol;
|
|
||||||
import sd.protocol.SocketConnection;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Processes statistics messages from a single client connection.
|
|
||||||
* Runs in a separate thread per client.
|
|
||||||
*/
|
|
||||||
public class DashboardClientHandler implements Runnable {
|
|
||||||
|
|
||||||
private final Socket clientSocket;
|
|
||||||
private final DashboardStatistics statistics;
|
|
||||||
|
|
||||||
public DashboardClientHandler(Socket clientSocket, DashboardStatistics statistics) {
|
|
||||||
this.clientSocket = clientSocket;
|
|
||||||
this.statistics = statistics;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
String clientInfo = clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort();
|
|
||||||
|
|
||||||
try (SocketConnection connection = new SocketConnection(clientSocket)) {
|
|
||||||
System.out.println("[Handler] Started handling client: " + clientInfo);
|
|
||||||
|
|
||||||
while (!Thread.currentThread().isInterrupted()) {
|
|
||||||
try {
|
|
||||||
MessageProtocol message = connection.receiveMessage();
|
|
||||||
|
|
||||||
if (message == null) {
|
|
||||||
System.out.println("[Handler] Client disconnected: " + clientInfo);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
processMessage(message);
|
|
||||||
|
|
||||||
} catch (ClassNotFoundException e) {
|
|
||||||
System.err.println("[Handler] Unknown message class from " + clientInfo + ": " + e.getMessage());
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.out.println("[Handler] Connection error with " + clientInfo + ": " + e.getMessage());
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("[Handler] Error initializing connection with " + clientInfo + ": " + e.getMessage());
|
|
||||||
} finally {
|
|
||||||
try {
|
|
||||||
if (!clientSocket.isClosed()) {
|
|
||||||
clientSocket.close();
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("[Handler] Error closing socket for " + clientInfo + ": " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void processMessage(MessageProtocol message) {
|
|
||||||
if (message.getType() != MessageType.STATS_UPDATE) {
|
|
||||||
System.out.println("[Handler] Ignoring non-statistics message type: " + message.getType());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
String senderId = message.getSourceNode();
|
|
||||||
Object payload = message.getPayload();
|
|
||||||
|
|
||||||
System.out.println("[Handler] Received STATS_UPDATE from: " + senderId);
|
|
||||||
|
|
||||||
// Handle both direct StatsUpdatePayload and Gson-deserialized Map
|
|
||||||
StatsUpdatePayload stats;
|
|
||||||
if (payload instanceof StatsUpdatePayload) {
|
|
||||||
stats = (StatsUpdatePayload) payload;
|
|
||||||
} else if (payload instanceof java.util.Map) {
|
|
||||||
// Gson deserialized as LinkedHashMap - re-serialize and deserialize properly
|
|
||||||
com.google.gson.Gson gson = new com.google.gson.Gson();
|
|
||||||
String json = gson.toJson(payload);
|
|
||||||
stats = gson.fromJson(json, StatsUpdatePayload.class);
|
|
||||||
} else {
|
|
||||||
System.err.println("[Handler] Unknown payload type: " +
|
|
||||||
(payload != null ? payload.getClass().getName() : "null"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
updateStatistics(senderId, stats);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void updateStatistics(String senderId, StatsUpdatePayload stats) {
|
|
||||||
if (stats.getTotalVehiclesGenerated() >= 0) {
|
|
||||||
statistics.updateVehiclesGenerated(stats.getTotalVehiclesGenerated());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (stats.getTotalVehiclesCompleted() >= 0) {
|
|
||||||
statistics.updateVehiclesCompleted(stats.getTotalVehiclesCompleted());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exit Node sends cumulative totals, so we SET rather than ADD
|
|
||||||
if (stats.getTotalSystemTime() >= 0) {
|
|
||||||
statistics.setTotalSystemTime(stats.getTotalSystemTime());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (stats.getTotalWaitingTime() >= 0) {
|
|
||||||
statistics.setTotalWaitingTime(stats.getTotalWaitingTime());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process vehicle type statistics (from Exit Node)
|
|
||||||
if (stats.getVehicleTypeCounts() != null && !stats.getVehicleTypeCounts().isEmpty()) {
|
|
||||||
Map<sd.model.VehicleType, Integer> counts = stats.getVehicleTypeCounts();
|
|
||||||
Map<sd.model.VehicleType, Long> waitTimes = stats.getVehicleTypeWaitTimes();
|
|
||||||
|
|
||||||
for (var entry : counts.entrySet()) {
|
|
||||||
sd.model.VehicleType type = entry.getKey();
|
|
||||||
int count = entry.getValue();
|
|
||||||
long waitTime = (waitTimes != null && waitTimes.containsKey(type))
|
|
||||||
? waitTimes.get(type) : 0L;
|
|
||||||
statistics.updateVehicleTypeStats(type, count, waitTime);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process intersection statistics (from Intersection processes)
|
|
||||||
if (senderId.startsWith("Cr") || senderId.startsWith("E")) {
|
|
||||||
statistics.updateIntersectionStats(
|
|
||||||
senderId,
|
|
||||||
stats.getIntersectionArrivals(),
|
|
||||||
stats.getIntersectionDepartures(),
|
|
||||||
stats.getIntersectionQueueSize()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("[Handler] Successfully updated statistics from: " + senderId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,165 +0,0 @@
|
|||||||
package sd.dashboard;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.ServerSocket;
|
|
||||||
import java.net.Socket;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
|
||||||
|
|
||||||
import sd.config.SimulationConfig;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Aggregates and displays real-time statistics from all simulation processes.
|
|
||||||
* Uses a thread pool to handle concurrent client connections.
|
|
||||||
*/
|
|
||||||
public class DashboardServer {
|
|
||||||
|
|
||||||
private final int port;
|
|
||||||
private final DashboardStatistics statistics;
|
|
||||||
private final ExecutorService clientHandlerPool;
|
|
||||||
private final AtomicBoolean running;
|
|
||||||
private ServerSocket serverSocket;
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
// Check if GUI mode is requested
|
|
||||||
boolean useGUI = false;
|
|
||||||
String configFile = "src/main/resources/simulation.properties";
|
|
||||||
|
|
||||||
for (int i = 0; i < args.length; i++) {
|
|
||||||
if (args[i].equals("--gui") || args[i].equals("-g")) {
|
|
||||||
useGUI = true;
|
|
||||||
} else {
|
|
||||||
configFile = args[i];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (useGUI) {
|
|
||||||
// Launch JavaFX UI
|
|
||||||
System.out.println("Launching Dashboard with JavaFX GUI...");
|
|
||||||
DashboardUI.main(args);
|
|
||||||
} else {
|
|
||||||
// Traditional terminal mode
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
System.out.println("DASHBOARD SERVER - DISTRIBUTED TRAFFIC SIMULATION");
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
|
|
||||||
try {
|
|
||||||
System.out.println("Loading configuration from: " + configFile);
|
|
||||||
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile);
|
|
||||||
DashboardServer server = new DashboardServer(config);
|
|
||||||
|
|
||||||
// Start the server
|
|
||||||
System.out.println("\n" + "=".repeat(60));
|
|
||||||
server.start();
|
|
||||||
|
|
||||||
// Keep running until interrupted
|
|
||||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
|
||||||
System.out.println("\n\nShutdown signal received...");
|
|
||||||
server.stop();
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Display statistics periodically
|
|
||||||
server.displayLoop();
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("Failed to start Dashboard Server: " + e.getMessage());
|
|
||||||
System.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public DashboardServer(SimulationConfig config) {
|
|
||||||
this.port = config.getDashboardPort();
|
|
||||||
this.statistics = new DashboardStatistics();
|
|
||||||
this.clientHandlerPool = Executors.newFixedThreadPool(10);
|
|
||||||
this.running = new AtomicBoolean(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void start() throws IOException {
|
|
||||||
if (running.get()) {
|
|
||||||
System.out.println("Dashboard Server is already running.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
serverSocket = new ServerSocket(port);
|
|
||||||
running.set(true);
|
|
||||||
|
|
||||||
System.out.println("Dashboard Server started on port " + port);
|
|
||||||
System.out.println("Waiting for statistics updates from simulation processes...");
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
|
|
||||||
Thread acceptThread = new Thread(this::acceptConnections, "DashboardServer-Accept");
|
|
||||||
acceptThread.setDaemon(false);
|
|
||||||
acceptThread.start();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void acceptConnections() {
|
|
||||||
while (running.get()) {
|
|
||||||
try {
|
|
||||||
Socket clientSocket = serverSocket.accept();
|
|
||||||
System.out.println("[Connection] New client connected: " +
|
|
||||||
clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort());
|
|
||||||
|
|
||||||
clientHandlerPool.execute(new DashboardClientHandler(clientSocket, statistics));
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
if (running.get()) {
|
|
||||||
System.err.println("[Error] Failed to accept client connection: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("BusyWait")
|
|
||||||
private void displayLoop() {
|
|
||||||
final long DISPLAY_INTERVAL_MS = 5000;
|
|
||||||
|
|
||||||
while (running.get()) {
|
|
||||||
try {
|
|
||||||
Thread.sleep(DISPLAY_INTERVAL_MS);
|
|
||||||
displayStatistics();
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void displayStatistics() {
|
|
||||||
System.out.println("\n" + "=".repeat(60));
|
|
||||||
System.out.println("REAL-TIME SIMULATION STATISTICS");
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
statistics.display();
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
}
|
|
||||||
|
|
||||||
public void stop() {
|
|
||||||
if (!running.get()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("\nStopping Dashboard Server...");
|
|
||||||
running.set(false);
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (serverSocket != null && !serverSocket.isClosed()) {
|
|
||||||
serverSocket.close();
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("Error closing server socket: " + e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
clientHandlerPool.shutdownNow();
|
|
||||||
System.out.println("Dashboard Server stopped.");
|
|
||||||
}
|
|
||||||
|
|
||||||
public DashboardStatistics getStatistics() {
|
|
||||||
return statistics;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isRunning() {
|
|
||||||
return running.get();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,224 +0,0 @@
|
|||||||
package sd.dashboard;
|
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
|
||||||
import java.util.concurrent.atomic.AtomicLong;
|
|
||||||
|
|
||||||
import sd.model.VehicleType;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Thread-safe storage for aggregated simulation statistics.
|
|
||||||
* Uses atomic types and concurrent collections for lock-free updates.
|
|
||||||
*/
|
|
||||||
public class DashboardStatistics {
|
|
||||||
|
|
||||||
private final AtomicInteger totalVehiclesGenerated;
|
|
||||||
private final AtomicInteger totalVehiclesCompleted;
|
|
||||||
private final AtomicLong totalSystemTime;
|
|
||||||
private final AtomicLong totalWaitingTime;
|
|
||||||
|
|
||||||
private final Map<String, IntersectionStats> intersectionStats;
|
|
||||||
private final Map<VehicleType, AtomicInteger> vehicleTypeCount;
|
|
||||||
private final Map<VehicleType, AtomicLong> vehicleTypeWaitTime;
|
|
||||||
|
|
||||||
private volatile long lastUpdateTime;
|
|
||||||
|
|
||||||
public DashboardStatistics() {
|
|
||||||
this.totalVehiclesGenerated = new AtomicInteger(0);
|
|
||||||
this.totalVehiclesCompleted = new AtomicInteger(0);
|
|
||||||
this.totalSystemTime = new AtomicLong(0);
|
|
||||||
this.totalWaitingTime = new AtomicLong(0);
|
|
||||||
|
|
||||||
this.intersectionStats = new ConcurrentHashMap<>();
|
|
||||||
this.vehicleTypeCount = new ConcurrentHashMap<>();
|
|
||||||
this.vehicleTypeWaitTime = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
for (VehicleType type : VehicleType.values()) {
|
|
||||||
vehicleTypeCount.put(type, new AtomicInteger(0));
|
|
||||||
vehicleTypeWaitTime.put(type, new AtomicLong(0));
|
|
||||||
}
|
|
||||||
|
|
||||||
this.lastUpdateTime = System.currentTimeMillis();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updateVehiclesGenerated(int count) {
|
|
||||||
totalVehiclesGenerated.set(count);
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void incrementVehiclesGenerated() {
|
|
||||||
totalVehiclesGenerated.incrementAndGet();
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updateVehiclesCompleted(int count) {
|
|
||||||
totalVehiclesCompleted.set(count);
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void incrementVehiclesCompleted() {
|
|
||||||
totalVehiclesCompleted.incrementAndGet();
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void addSystemTime(long timeMs) {
|
|
||||||
totalSystemTime.addAndGet(timeMs);
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTotalSystemTime(long timeMs) {
|
|
||||||
totalSystemTime.set(timeMs);
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void addWaitingTime(long timeMs) {
|
|
||||||
totalWaitingTime.addAndGet(timeMs);
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTotalWaitingTime(long timeMs) {
|
|
||||||
totalWaitingTime.set(timeMs);
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updateVehicleTypeStats(VehicleType type, int count, long waitTimeMs) {
|
|
||||||
vehicleTypeCount.get(type).set(count);
|
|
||||||
vehicleTypeWaitTime.get(type).set(waitTimeMs);
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void incrementVehicleType(VehicleType type) {
|
|
||||||
vehicleTypeCount.get(type).incrementAndGet();
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updateIntersectionStats(String intersectionId, int arrivals,
|
|
||||||
int departures, int currentQueueSize) {
|
|
||||||
intersectionStats.compute(intersectionId, (id, stats) -> {
|
|
||||||
if (stats == null) {
|
|
||||||
stats = new IntersectionStats(intersectionId);
|
|
||||||
}
|
|
||||||
stats.updateStats(arrivals, departures, currentQueueSize);
|
|
||||||
return stats;
|
|
||||||
});
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void updateTimestamp() {
|
|
||||||
lastUpdateTime = System.currentTimeMillis();
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTotalVehiclesGenerated() {
|
|
||||||
return totalVehiclesGenerated.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTotalVehiclesCompleted() {
|
|
||||||
return totalVehiclesCompleted.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public double getAverageSystemTime() {
|
|
||||||
int completed = totalVehiclesCompleted.get();
|
|
||||||
if (completed == 0) return 0.0;
|
|
||||||
return (double) totalSystemTime.get() / completed;
|
|
||||||
}
|
|
||||||
|
|
||||||
public double getAverageWaitingTime() {
|
|
||||||
int completed = totalVehiclesCompleted.get();
|
|
||||||
if (completed == 0) return 0.0;
|
|
||||||
return (double) totalWaitingTime.get() / completed;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getVehicleTypeCount(VehicleType type) {
|
|
||||||
return vehicleTypeCount.get(type).get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public double getAverageWaitingTimeByType(VehicleType type) {
|
|
||||||
int count = vehicleTypeCount.get(type).get();
|
|
||||||
if (count == 0) return 0.0;
|
|
||||||
return (double) vehicleTypeWaitTime.get(type).get() / count;
|
|
||||||
}
|
|
||||||
|
|
||||||
public IntersectionStats getIntersectionStats(String intersectionId) {
|
|
||||||
return intersectionStats.get(intersectionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, IntersectionStats> getAllIntersectionStats() {
|
|
||||||
return new HashMap<>(intersectionStats);
|
|
||||||
}
|
|
||||||
|
|
||||||
public long getLastUpdateTime() {
|
|
||||||
return lastUpdateTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void display() {
|
|
||||||
System.out.println("\n--- GLOBAL STATISTICS ---");
|
|
||||||
System.out.printf("Total Vehicles Generated: %d%n", getTotalVehiclesGenerated());
|
|
||||||
System.out.printf("Total Vehicles Completed: %d%n", getTotalVehiclesCompleted());
|
|
||||||
System.out.printf("Vehicles In Transit: %d%n",
|
|
||||||
getTotalVehiclesGenerated() - getTotalVehiclesCompleted());
|
|
||||||
System.out.printf("Average System Time: %.2f ms%n", getAverageSystemTime());
|
|
||||||
System.out.printf("Average Waiting Time: %.2f ms%n", getAverageWaitingTime());
|
|
||||||
|
|
||||||
System.out.println("\n--- VEHICLE TYPE STATISTICS ---");
|
|
||||||
for (VehicleType type : VehicleType.values()) {
|
|
||||||
int count = getVehicleTypeCount(type);
|
|
||||||
double avgWait = getAverageWaitingTimeByType(type);
|
|
||||||
System.out.printf("%s: %d vehicles, avg wait: %.2f ms%n",
|
|
||||||
type, count, avgWait);
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("\n--- INTERSECTION STATISTICS ---");
|
|
||||||
if (intersectionStats.isEmpty()) {
|
|
||||||
System.out.println("(No data received yet)");
|
|
||||||
} else {
|
|
||||||
for (IntersectionStats stats : intersectionStats.values()) {
|
|
||||||
stats.display();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.printf("%nLast Update: %tT%n", lastUpdateTime);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static class IntersectionStats {
|
|
||||||
private final String intersectionId;
|
|
||||||
private final AtomicInteger totalArrivals;
|
|
||||||
private final AtomicInteger totalDepartures;
|
|
||||||
private final AtomicInteger currentQueueSize;
|
|
||||||
|
|
||||||
public IntersectionStats(String intersectionId) {
|
|
||||||
this.intersectionId = intersectionId;
|
|
||||||
this.totalArrivals = new AtomicInteger(0);
|
|
||||||
this.totalDepartures = new AtomicInteger(0);
|
|
||||||
this.currentQueueSize = new AtomicInteger(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updateStats(int arrivals, int departures, int queueSize) {
|
|
||||||
this.totalArrivals.set(arrivals);
|
|
||||||
this.totalDepartures.set(departures);
|
|
||||||
this.currentQueueSize.set(queueSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getIntersectionId() {
|
|
||||||
return intersectionId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTotalArrivals() {
|
|
||||||
return totalArrivals.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTotalDepartures() {
|
|
||||||
return totalDepartures.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getCurrentQueueSize() {
|
|
||||||
return currentQueueSize.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void display() {
|
|
||||||
System.out.printf("%s: Arrivals=%d, Departures=%d, Queue=%d%n",
|
|
||||||
intersectionId, getTotalArrivals(), getTotalDepartures(), getCurrentQueueSize());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,378 +0,0 @@
|
|||||||
package sd.dashboard;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import javafx.application.Application;
|
|
||||||
import javafx.application.Platform;
|
|
||||||
import javafx.geometry.Insets;
|
|
||||||
import javafx.geometry.Pos;
|
|
||||||
import javafx.scene.Scene;
|
|
||||||
import javafx.scene.control.Alert;
|
|
||||||
import javafx.scene.control.Label;
|
|
||||||
import javafx.scene.control.TableColumn;
|
|
||||||
import javafx.scene.control.TableView;
|
|
||||||
import javafx.scene.control.TitledPane;
|
|
||||||
import javafx.scene.control.cell.PropertyValueFactory;
|
|
||||||
import javafx.scene.layout.BorderPane;
|
|
||||||
import javafx.scene.layout.GridPane;
|
|
||||||
import javafx.scene.layout.HBox;
|
|
||||||
import javafx.scene.layout.Priority;
|
|
||||||
import javafx.scene.layout.Region;
|
|
||||||
import javafx.scene.layout.VBox;
|
|
||||||
import javafx.scene.paint.Color;
|
|
||||||
import javafx.scene.shape.Circle;
|
|
||||||
import javafx.scene.text.Font;
|
|
||||||
import javafx.scene.text.FontWeight;
|
|
||||||
import javafx.stage.Stage;
|
|
||||||
import sd.config.SimulationConfig;
|
|
||||||
import sd.model.VehicleType;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* JavaFX-based Dashboard UI for displaying real-time simulation statistics.
|
|
||||||
* Provides a graphical interface with auto-updating statistics panels.
|
|
||||||
*/
|
|
||||||
public class DashboardUI extends Application {
|
|
||||||
|
|
||||||
private DashboardServer server;
|
|
||||||
private DashboardStatistics statistics;
|
|
||||||
|
|
||||||
// Global Statistics Labels
|
|
||||||
private Label lblVehiclesGenerated;
|
|
||||||
private Label lblVehiclesCompleted;
|
|
||||||
private Label lblVehiclesInTransit;
|
|
||||||
private Label lblAvgSystemTime;
|
|
||||||
private Label lblAvgWaitingTime;
|
|
||||||
private Label lblLastUpdate;
|
|
||||||
|
|
||||||
// Vehicle Type Table
|
|
||||||
private TableView<VehicleTypeRow> vehicleTypeTable;
|
|
||||||
|
|
||||||
// Intersection Table
|
|
||||||
private TableView<IntersectionRow> intersectionTable;
|
|
||||||
|
|
||||||
// Update scheduler
|
|
||||||
private ScheduledExecutorService updateScheduler;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void start(Stage primaryStage) {
|
|
||||||
try {
|
|
||||||
// Initialize server
|
|
||||||
String configFile = getParameters().getRaw().isEmpty()
|
|
||||||
? "src/main/resources/simulation.properties"
|
|
||||||
: getParameters().getRaw().get(0);
|
|
||||||
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile);
|
|
||||||
server = new DashboardServer(config);
|
|
||||||
statistics = server.getStatistics();
|
|
||||||
|
|
||||||
// Start the dashboard server
|
|
||||||
server.start();
|
|
||||||
|
|
||||||
// Build UI
|
|
||||||
BorderPane root = new BorderPane();
|
|
||||||
root.setStyle("-fx-background-color: #f5f5f5;");
|
|
||||||
|
|
||||||
// Header
|
|
||||||
VBox header = createHeader();
|
|
||||||
root.setTop(header);
|
|
||||||
|
|
||||||
// Main content
|
|
||||||
VBox mainContent = createMainContent();
|
|
||||||
root.setCenter(mainContent);
|
|
||||||
|
|
||||||
// Footer
|
|
||||||
HBox footer = createFooter();
|
|
||||||
root.setBottom(footer);
|
|
||||||
|
|
||||||
// Create scene
|
|
||||||
Scene scene = new Scene(root, 1200, 800);
|
|
||||||
primaryStage.setTitle("Traffic Simulation Dashboard - Real-time Statistics");
|
|
||||||
primaryStage.setScene(scene);
|
|
||||||
primaryStage.show();
|
|
||||||
|
|
||||||
// Start periodic updates
|
|
||||||
startPeriodicUpdates();
|
|
||||||
|
|
||||||
// Handle window close
|
|
||||||
primaryStage.setOnCloseRequest(event -> {
|
|
||||||
shutdown();
|
|
||||||
});
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
showErrorAlert("Failed to start Dashboard Server", e.getMessage());
|
|
||||||
Platform.exit();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private VBox createHeader() {
|
|
||||||
VBox header = new VBox(10);
|
|
||||||
header.setPadding(new Insets(20));
|
|
||||||
header.setStyle("-fx-background-color: linear-gradient(to right, #2c3e50, #3498db);");
|
|
||||||
|
|
||||||
Label title = new Label("DISTRIBUTED TRAFFIC SIMULATION DASHBOARD");
|
|
||||||
title.setFont(Font.font("Arial", FontWeight.BOLD, 28));
|
|
||||||
title.setTextFill(Color.WHITE);
|
|
||||||
|
|
||||||
Label subtitle = new Label("Real-time Statistics and Monitoring");
|
|
||||||
subtitle.setFont(Font.font("Arial", FontWeight.NORMAL, 16));
|
|
||||||
subtitle.setTextFill(Color.web("#ecf0f1"));
|
|
||||||
|
|
||||||
header.getChildren().addAll(title, subtitle);
|
|
||||||
header.setAlignment(Pos.CENTER);
|
|
||||||
|
|
||||||
return header;
|
|
||||||
}
|
|
||||||
|
|
||||||
private VBox createMainContent() {
|
|
||||||
VBox mainContent = new VBox(15);
|
|
||||||
mainContent.setPadding(new Insets(20));
|
|
||||||
|
|
||||||
// Global Statistics Panel
|
|
||||||
TitledPane globalStatsPane = createGlobalStatisticsPanel();
|
|
||||||
|
|
||||||
// Vehicle Type Statistics Panel
|
|
||||||
TitledPane vehicleTypePane = createVehicleTypePanel();
|
|
||||||
|
|
||||||
// Intersection Statistics Panel
|
|
||||||
TitledPane intersectionPane = createIntersectionPanel();
|
|
||||||
|
|
||||||
mainContent.getChildren().addAll(globalStatsPane, vehicleTypePane, intersectionPane);
|
|
||||||
|
|
||||||
return mainContent;
|
|
||||||
}
|
|
||||||
|
|
||||||
private TitledPane createGlobalStatisticsPanel() {
|
|
||||||
GridPane grid = new GridPane();
|
|
||||||
grid.setPadding(new Insets(15));
|
|
||||||
grid.setHgap(20);
|
|
||||||
grid.setVgap(15);
|
|
||||||
grid.setStyle("-fx-background-color: white; -fx-border-radius: 5;");
|
|
||||||
|
|
||||||
// Initialize labels
|
|
||||||
lblVehiclesGenerated = createStatLabel("0");
|
|
||||||
lblVehiclesCompleted = createStatLabel("0");
|
|
||||||
lblVehiclesInTransit = createStatLabel("0");
|
|
||||||
lblAvgSystemTime = createStatLabel("0.00 ms");
|
|
||||||
lblAvgWaitingTime = createStatLabel("0.00 ms");
|
|
||||||
|
|
||||||
// Add labels with descriptions
|
|
||||||
addStatRow(grid, 0, "Total Vehicles Generated:", lblVehiclesGenerated);
|
|
||||||
addStatRow(grid, 1, "Total Vehicles Completed:", lblVehiclesCompleted);
|
|
||||||
addStatRow(grid, 2, "Vehicles In Transit:", lblVehiclesInTransit);
|
|
||||||
addStatRow(grid, 3, "Average System Time:", lblAvgSystemTime);
|
|
||||||
addStatRow(grid, 4, "Average Waiting Time:", lblAvgWaitingTime);
|
|
||||||
|
|
||||||
TitledPane pane = new TitledPane("Global Statistics", grid);
|
|
||||||
pane.setCollapsible(false);
|
|
||||||
pane.setFont(Font.font("Arial", FontWeight.BOLD, 16));
|
|
||||||
|
|
||||||
return pane;
|
|
||||||
}
|
|
||||||
|
|
||||||
private TitledPane createVehicleTypePanel() {
|
|
||||||
vehicleTypeTable = new TableView<>();
|
|
||||||
vehicleTypeTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
|
||||||
vehicleTypeTable.setPrefHeight(200);
|
|
||||||
|
|
||||||
TableColumn<VehicleTypeRow, String> typeCol = new TableColumn<>("Vehicle Type");
|
|
||||||
typeCol.setCellValueFactory(new PropertyValueFactory<>("vehicleType"));
|
|
||||||
typeCol.setPrefWidth(200);
|
|
||||||
|
|
||||||
TableColumn<VehicleTypeRow, Integer> countCol = new TableColumn<>("Count");
|
|
||||||
countCol.setCellValueFactory(new PropertyValueFactory<>("count"));
|
|
||||||
countCol.setPrefWidth(150);
|
|
||||||
|
|
||||||
TableColumn<VehicleTypeRow, String> avgWaitCol = new TableColumn<>("Avg Wait Time");
|
|
||||||
avgWaitCol.setCellValueFactory(new PropertyValueFactory<>("avgWaitTime"));
|
|
||||||
avgWaitCol.setPrefWidth(150);
|
|
||||||
|
|
||||||
vehicleTypeTable.getColumns().addAll(typeCol, countCol, avgWaitCol);
|
|
||||||
|
|
||||||
TitledPane pane = new TitledPane("Vehicle Type Statistics", vehicleTypeTable);
|
|
||||||
pane.setCollapsible(false);
|
|
||||||
pane.setFont(Font.font("Arial", FontWeight.BOLD, 16));
|
|
||||||
|
|
||||||
return pane;
|
|
||||||
}
|
|
||||||
|
|
||||||
private TitledPane createIntersectionPanel() {
|
|
||||||
intersectionTable = new TableView<>();
|
|
||||||
intersectionTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
|
||||||
intersectionTable.setPrefHeight(250);
|
|
||||||
|
|
||||||
TableColumn<IntersectionRow, String> idCol = new TableColumn<>("Intersection ID");
|
|
||||||
idCol.setCellValueFactory(new PropertyValueFactory<>("intersectionId"));
|
|
||||||
idCol.setPrefWidth(200);
|
|
||||||
|
|
||||||
TableColumn<IntersectionRow, Integer> arrivalsCol = new TableColumn<>("Total Arrivals");
|
|
||||||
arrivalsCol.setCellValueFactory(new PropertyValueFactory<>("arrivals"));
|
|
||||||
arrivalsCol.setPrefWidth(150);
|
|
||||||
|
|
||||||
TableColumn<IntersectionRow, Integer> departuresCol = new TableColumn<>("Total Departures");
|
|
||||||
departuresCol.setCellValueFactory(new PropertyValueFactory<>("departures"));
|
|
||||||
departuresCol.setPrefWidth(150);
|
|
||||||
|
|
||||||
TableColumn<IntersectionRow, Integer> queueCol = new TableColumn<>("Current Queue");
|
|
||||||
queueCol.setCellValueFactory(new PropertyValueFactory<>("queueSize"));
|
|
||||||
queueCol.setPrefWidth(150);
|
|
||||||
|
|
||||||
intersectionTable.getColumns().addAll(idCol, arrivalsCol, departuresCol, queueCol);
|
|
||||||
|
|
||||||
TitledPane pane = new TitledPane("Intersection Statistics", intersectionTable);
|
|
||||||
pane.setCollapsible(false);
|
|
||||||
pane.setFont(Font.font("Arial", FontWeight.BOLD, 16));
|
|
||||||
|
|
||||||
return pane;
|
|
||||||
}
|
|
||||||
|
|
||||||
private HBox createFooter() {
|
|
||||||
HBox footer = new HBox(10);
|
|
||||||
footer.setPadding(new Insets(10, 20, 10, 20));
|
|
||||||
footer.setStyle("-fx-background-color: #34495e;");
|
|
||||||
footer.setAlignment(Pos.CENTER_LEFT);
|
|
||||||
|
|
||||||
Label statusLabel = new Label("Status:");
|
|
||||||
statusLabel.setTextFill(Color.WHITE);
|
|
||||||
statusLabel.setFont(Font.font("Arial", FontWeight.BOLD, 12));
|
|
||||||
|
|
||||||
Circle statusIndicator = new Circle(6);
|
|
||||||
statusIndicator.setFill(Color.LIME);
|
|
||||||
|
|
||||||
Label statusText = new Label("Connected and Receiving Data");
|
|
||||||
statusText.setTextFill(Color.WHITE);
|
|
||||||
statusText.setFont(Font.font("Arial", 12));
|
|
||||||
|
|
||||||
lblLastUpdate = new Label("Last Update: --:--:--");
|
|
||||||
lblLastUpdate.setTextFill(Color.web("#ecf0f1"));
|
|
||||||
lblLastUpdate.setFont(Font.font("Arial", 12));
|
|
||||||
|
|
||||||
Region spacer = new Region();
|
|
||||||
HBox.setHgrow(spacer, Priority.ALWAYS);
|
|
||||||
|
|
||||||
footer.getChildren().addAll(statusLabel, statusIndicator, statusText, spacer, lblLastUpdate);
|
|
||||||
|
|
||||||
return footer;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Label createStatLabel(String initialValue) {
|
|
||||||
Label label = new Label(initialValue);
|
|
||||||
label.setFont(Font.font("Arial", FontWeight.BOLD, 20));
|
|
||||||
label.setTextFill(Color.web("#2980b9"));
|
|
||||||
return label;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void addStatRow(GridPane grid, int row, String description, Label valueLabel) {
|
|
||||||
Label descLabel = new Label(description);
|
|
||||||
descLabel.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
|
|
||||||
descLabel.setTextFill(Color.web("#34495e"));
|
|
||||||
|
|
||||||
grid.add(descLabel, 0, row);
|
|
||||||
grid.add(valueLabel, 1, row);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void startPeriodicUpdates() {
|
|
||||||
updateScheduler = Executors.newSingleThreadScheduledExecutor();
|
|
||||||
updateScheduler.scheduleAtFixedRate(() -> {
|
|
||||||
Platform.runLater(this::updateUI);
|
|
||||||
}, 0, 5, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void updateUI() {
|
|
||||||
// Update global statistics
|
|
||||||
lblVehiclesGenerated.setText(String.valueOf(statistics.getTotalVehiclesGenerated()));
|
|
||||||
lblVehiclesCompleted.setText(String.valueOf(statistics.getTotalVehiclesCompleted()));
|
|
||||||
lblVehiclesInTransit.setText(String.valueOf(
|
|
||||||
statistics.getTotalVehiclesGenerated() - statistics.getTotalVehiclesCompleted()));
|
|
||||||
lblAvgSystemTime.setText(String.format("%.2f ms", statistics.getAverageSystemTime()));
|
|
||||||
lblAvgWaitingTime.setText(String.format("%.2f ms", statistics.getAverageWaitingTime()));
|
|
||||||
lblLastUpdate.setText(String.format("Last Update: %tT", statistics.getLastUpdateTime()));
|
|
||||||
|
|
||||||
// Update vehicle type table
|
|
||||||
vehicleTypeTable.getItems().clear();
|
|
||||||
for (VehicleType type : VehicleType.values()) {
|
|
||||||
int count = statistics.getVehicleTypeCount(type);
|
|
||||||
double avgWait = statistics.getAverageWaitingTimeByType(type);
|
|
||||||
vehicleTypeTable.getItems().add(new VehicleTypeRow(
|
|
||||||
type.toString(), count, String.format("%.2f ms", avgWait)));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update intersection table
|
|
||||||
intersectionTable.getItems().clear();
|
|
||||||
Map<String, DashboardStatistics.IntersectionStats> intersectionStats =
|
|
||||||
statistics.getAllIntersectionStats();
|
|
||||||
for (DashboardStatistics.IntersectionStats stats : intersectionStats.values()) {
|
|
||||||
intersectionTable.getItems().add(new IntersectionRow(
|
|
||||||
stats.getIntersectionId(),
|
|
||||||
stats.getTotalArrivals(),
|
|
||||||
stats.getTotalDepartures(),
|
|
||||||
stats.getCurrentQueueSize()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void shutdown() {
|
|
||||||
System.out.println("Shutting down Dashboard UI...");
|
|
||||||
|
|
||||||
if (updateScheduler != null && !updateScheduler.isShutdown()) {
|
|
||||||
updateScheduler.shutdownNow();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (server != null) {
|
|
||||||
server.stop();
|
|
||||||
}
|
|
||||||
|
|
||||||
Platform.exit();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void showErrorAlert(String title, String message) {
|
|
||||||
Alert alert = new Alert(Alert.AlertType.ERROR);
|
|
||||||
alert.setTitle(title);
|
|
||||||
alert.setHeaderText(null);
|
|
||||||
alert.setContentText(message);
|
|
||||||
alert.showAndWait();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
launch(args);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Inner classes for TableView data models
|
|
||||||
public static class VehicleTypeRow {
|
|
||||||
private final String vehicleType;
|
|
||||||
private final int count;
|
|
||||||
private final String avgWaitTime;
|
|
||||||
|
|
||||||
public VehicleTypeRow(String vehicleType, int count, String avgWaitTime) {
|
|
||||||
this.vehicleType = vehicleType;
|
|
||||||
this.count = count;
|
|
||||||
this.avgWaitTime = avgWaitTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getVehicleType() { return vehicleType; }
|
|
||||||
public int getCount() { return count; }
|
|
||||||
public String getAvgWaitTime() { return avgWaitTime; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public static class IntersectionRow {
|
|
||||||
private final String intersectionId;
|
|
||||||
private final int arrivals;
|
|
||||||
private final int departures;
|
|
||||||
private final int queueSize;
|
|
||||||
|
|
||||||
public IntersectionRow(String intersectionId, int arrivals, int departures, int queueSize) {
|
|
||||||
this.intersectionId = intersectionId;
|
|
||||||
this.arrivals = arrivals;
|
|
||||||
this.departures = departures;
|
|
||||||
this.queueSize = queueSize;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getIntersectionId() { return intersectionId; }
|
|
||||||
public int getArrivals() { return arrivals; }
|
|
||||||
public int getDepartures() { return departures; }
|
|
||||||
public int getQueueSize() { return queueSize; }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
package sd.dashboard;
|
|
||||||
|
|
||||||
import sd.model.MessageType;
|
|
||||||
import sd.protocol.MessageProtocol;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Message wrapper for sending statistics to the dashboard.
|
|
||||||
*/
|
|
||||||
public class StatsMessage implements MessageProtocol {
|
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
|
|
||||||
private final String sourceNode;
|
|
||||||
private final String destinationNode;
|
|
||||||
private final StatsUpdatePayload payload;
|
|
||||||
|
|
||||||
public StatsMessage(String sourceNode, StatsUpdatePayload payload) {
|
|
||||||
this.sourceNode = sourceNode;
|
|
||||||
this.destinationNode = "DashboardServer";
|
|
||||||
this.payload = payload;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public MessageType getType() {
|
|
||||||
return MessageType.STATS_UPDATE;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object getPayload() {
|
|
||||||
return payload;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getSourceNode() {
|
|
||||||
return sourceNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getDestinationNode() {
|
|
||||||
return destinationNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return String.format("StatsMessage[from=%s, to=%s, payload=%s]",
|
|
||||||
sourceNode, destinationNode, payload);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,121 +0,0 @@
|
|||||||
package sd.dashboard;
|
|
||||||
|
|
||||||
import java.io.Serializable;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import sd.model.VehicleType;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Data transfer object for statistics updates to the dashboard.
|
|
||||||
* Use -1 for fields not being updated in this message.
|
|
||||||
*/
|
|
||||||
public class StatsUpdatePayload implements Serializable {
|
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
|
|
||||||
private int totalVehiclesGenerated = -1;
|
|
||||||
private int totalVehiclesCompleted = -1;
|
|
||||||
private long totalSystemTime = -1;
|
|
||||||
private long totalWaitingTime = -1;
|
|
||||||
|
|
||||||
private int intersectionArrivals = 0;
|
|
||||||
private int intersectionDepartures = 0;
|
|
||||||
private int intersectionQueueSize = 0;
|
|
||||||
|
|
||||||
private Map<VehicleType, Integer> vehicleTypeCounts;
|
|
||||||
private Map<VehicleType, Long> vehicleTypeWaitTimes;
|
|
||||||
|
|
||||||
public StatsUpdatePayload() {
|
|
||||||
this.vehicleTypeCounts = new HashMap<>();
|
|
||||||
this.vehicleTypeWaitTimes = new HashMap<>();
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTotalVehiclesGenerated() {
|
|
||||||
return totalVehiclesGenerated;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTotalVehiclesCompleted() {
|
|
||||||
return totalVehiclesCompleted;
|
|
||||||
}
|
|
||||||
|
|
||||||
public long getTotalSystemTime() {
|
|
||||||
return totalSystemTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
public long getTotalWaitingTime() {
|
|
||||||
return totalWaitingTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getIntersectionArrivals() {
|
|
||||||
return intersectionArrivals;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getIntersectionDepartures() {
|
|
||||||
return intersectionDepartures;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getIntersectionQueueSize() {
|
|
||||||
return intersectionQueueSize;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<VehicleType, Integer> getVehicleTypeCounts() {
|
|
||||||
return vehicleTypeCounts;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<VehicleType, Long> getVehicleTypeWaitTimes() {
|
|
||||||
return vehicleTypeWaitTimes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setTotalVehiclesGenerated(int totalVehiclesGenerated) {
|
|
||||||
this.totalVehiclesGenerated = totalVehiclesGenerated;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setTotalVehiclesCompleted(int totalVehiclesCompleted) {
|
|
||||||
this.totalVehiclesCompleted = totalVehiclesCompleted;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setTotalSystemTime(long totalSystemTime) {
|
|
||||||
this.totalSystemTime = totalSystemTime;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setTotalWaitingTime(long totalWaitingTime) {
|
|
||||||
this.totalWaitingTime = totalWaitingTime;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setIntersectionArrivals(int intersectionArrivals) {
|
|
||||||
this.intersectionArrivals = intersectionArrivals;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setIntersectionDepartures(int intersectionDepartures) {
|
|
||||||
this.intersectionDepartures = intersectionDepartures;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setIntersectionQueueSize(int intersectionQueueSize) {
|
|
||||||
this.intersectionQueueSize = intersectionQueueSize;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setVehicleTypeCounts(Map<VehicleType, Integer> vehicleTypeCounts) {
|
|
||||||
this.vehicleTypeCounts = vehicleTypeCounts;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setVehicleTypeWaitTimes(Map<VehicleType, Long> vehicleTypeWaitTimes) {
|
|
||||||
this.vehicleTypeWaitTimes = vehicleTypeWaitTimes;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return String.format("StatsUpdatePayload[generated=%d, completed=%d, arrivals=%d, departures=%d, queueSize=%d]",
|
|
||||||
totalVehiclesGenerated, totalVehiclesCompleted, intersectionArrivals,
|
|
||||||
intersectionDepartures, intersectionQueueSize);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -41,14 +41,12 @@ public class SimulationEngine {
|
|||||||
private final PriorityQueue<Event> eventQueue;
|
private final PriorityQueue<Event> eventQueue;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A map storing all intersections in the simulation, keyed by their ID (e.g.,
|
* A map storing all intersections in the simulation, keyed by their ID (e.g., "Cr1").
|
||||||
* "Cr1").
|
|
||||||
*/
|
*/
|
||||||
private final Map<String, Intersection> intersections;
|
private final Map<String, Intersection> intersections;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Responsible for creating new vehicles according to the configured arrival
|
* Responsible for creating new vehicles according to the configured arrival model.
|
||||||
* model.
|
|
||||||
*/
|
*/
|
||||||
private final VehicleGenerator vehicleGenerator;
|
private final VehicleGenerator vehicleGenerator;
|
||||||
|
|
||||||
@@ -72,7 +70,7 @@ public class SimulationEngine {
|
|||||||
* Constructs a new SimulationEngine.
|
* Constructs a new SimulationEngine.
|
||||||
*
|
*
|
||||||
* @param config The {@link SimulationConfig} object containing all
|
* @param config The {@link SimulationConfig} object containing all
|
||||||
* simulation parameters.
|
* simulation parameters.
|
||||||
*/
|
*/
|
||||||
public SimulationEngine(SimulationConfig config) {
|
public SimulationEngine(SimulationConfig config) {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
@@ -84,26 +82,6 @@ public class SimulationEngine {
|
|||||||
this.vehicleCounter = 0;
|
this.vehicleCounter = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Calculates the travel time between intersections based on vehicle type.
|
|
||||||
*
|
|
||||||
* @param vehicleType The type of the vehicle.
|
|
||||||
* @return The travel time in seconds.
|
|
||||||
*/
|
|
||||||
private double calculateTravelTime(VehicleType vehicleType) {
|
|
||||||
double baseTime = config.getBaseTravelTime();
|
|
||||||
|
|
||||||
switch (vehicleType) {
|
|
||||||
case BIKE:
|
|
||||||
return baseTime * config.getBikeTravelTimeMultiplier();
|
|
||||||
case HEAVY:
|
|
||||||
return baseTime * config.getHeavyTravelTimeMultiplier();
|
|
||||||
case LIGHT:
|
|
||||||
default:
|
|
||||||
return baseTime;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes the simulation. This involves:
|
* Initializes the simulation. This involves:
|
||||||
* 1. Creating all {@link Intersection} and {@link TrafficLight} objects.
|
* 1. Creating all {@link Intersection} and {@link TrafficLight} objects.
|
||||||
@@ -130,9 +108,9 @@ public class SimulationEngine {
|
|||||||
* and adds their corresponding traffic lights.
|
* and adds their corresponding traffic lights.
|
||||||
*/
|
*/
|
||||||
private void setupIntersections() {
|
private void setupIntersections() {
|
||||||
String[] intersectionIds = { "Cr1", "Cr2", "Cr3", "Cr4", "Cr5" };
|
String[] intersectionIds = {"Cr1", "Cr2", "Cr3", "Cr4", "Cr5"};
|
||||||
// Note: "North" is commented out, so it won't be created.
|
// Note: "North" is commented out, so it won't be created.
|
||||||
String[] directions = { /* "North", */ "South", "East", "West" };
|
String[] directions = {/*"North",*/ "South", "East", "West"};
|
||||||
|
|
||||||
for (String id : intersectionIds) {
|
for (String id : intersectionIds) {
|
||||||
Intersection intersection = new Intersection(id);
|
Intersection intersection = new Intersection(id);
|
||||||
@@ -143,10 +121,11 @@ public class SimulationEngine {
|
|||||||
double redTime = config.getTrafficLightRedTime(id, direction);
|
double redTime = config.getTrafficLightRedTime(id, direction);
|
||||||
|
|
||||||
TrafficLight light = new TrafficLight(
|
TrafficLight light = new TrafficLight(
|
||||||
id + "-" + direction,
|
id + "-" + direction,
|
||||||
direction,
|
direction,
|
||||||
greenTime,
|
greenTime,
|
||||||
redTime);
|
redTime
|
||||||
|
);
|
||||||
|
|
||||||
intersection.addTrafficLight(light);
|
intersection.addTrafficLight(light);
|
||||||
}
|
}
|
||||||
@@ -158,8 +137,7 @@ public class SimulationEngine {
|
|||||||
/**
|
/**
|
||||||
* Configures how vehicles should be routed between intersections.
|
* Configures how vehicles should be routed between intersections.
|
||||||
* This hardcoded logic defines the "map" of the city.
|
* This hardcoded logic defines the "map" of the city.
|
||||||
* * For example, `intersections.get("Cr1").configureRoute("Cr2", "East");`
|
* * For example, `intersections.get("Cr1").configureRoute("Cr2", "East");` means
|
||||||
* means
|
|
||||||
* "at intersection Cr1, any vehicle whose *next* destination is Cr2
|
* "at intersection Cr1, any vehicle whose *next* destination is Cr2
|
||||||
* should be sent to the 'East' traffic light queue."
|
* should be sent to the 'East' traffic light queue."
|
||||||
*/
|
*/
|
||||||
@@ -178,12 +156,12 @@ public class SimulationEngine {
|
|||||||
intersections.get("Cr3").configureRoute("S", "South"); // "S" is the exit
|
intersections.get("Cr3").configureRoute("S", "South"); // "S" is the exit
|
||||||
|
|
||||||
// Cr4 routing
|
// Cr4 routing
|
||||||
// intersections.get("Cr4").configureRoute("Cr1", "North");
|
//intersections.get("Cr4").configureRoute("Cr1", "North");
|
||||||
intersections.get("Cr4").configureRoute("Cr5", "East");
|
intersections.get("Cr4").configureRoute("Cr5", "East");
|
||||||
|
|
||||||
// Cr5 routing
|
// Cr5 routing
|
||||||
// intersections.get("Cr5").configureRoute("Cr2", "North");
|
//intersections.get("Cr5").configureRoute("Cr2", "North");
|
||||||
// intersections.get("Cr5").configureRoute("Cr4", "West");
|
//intersections.get("Cr5").configureRoute("Cr4", "West");
|
||||||
intersections.get("Cr5").configureRoute("S", "East"); // "S" is the exit
|
intersections.get("Cr5").configureRoute("S", "East"); // "S" is the exit
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,10 +186,9 @@ public class SimulationEngine {
|
|||||||
* Creates and schedules a new {@link EventType#TRAFFIC_LIGHT_CHANGE} event.
|
* Creates and schedules a new {@link EventType#TRAFFIC_LIGHT_CHANGE} event.
|
||||||
* The event is scheduled to occur at {@code currentTime + delay}.
|
* The event is scheduled to occur at {@code currentTime + delay}.
|
||||||
*
|
*
|
||||||
* @param light The {@link TrafficLight} that will change state.
|
* @param light The {@link TrafficLight} that will change state.
|
||||||
* @param intersectionId The ID of the intersection where the light is located.
|
* @param intersectionId The ID of the intersection where the light is located.
|
||||||
* @param delay The time (in seconds) from {@code currentTime} when the
|
* @param delay The time (in seconds) from {@code currentTime} when the change should occur.
|
||||||
* change should occur.
|
|
||||||
*/
|
*/
|
||||||
private void scheduleTrafficLightChange(TrafficLight light, String intersectionId, double delay) {
|
private void scheduleTrafficLightChange(TrafficLight light, String intersectionId, double delay) {
|
||||||
double changeTime = currentTime + delay;
|
double changeTime = currentTime + delay;
|
||||||
@@ -223,8 +200,7 @@ public class SimulationEngine {
|
|||||||
* Schedules the next {@link EventType#VEHICLE_GENERATION} event.
|
* Schedules the next {@link EventType#VEHICLE_GENERATION} event.
|
||||||
* The time of the next arrival is determined by the {@link VehicleGenerator}.
|
* The time of the next arrival is determined by the {@link VehicleGenerator}.
|
||||||
*
|
*
|
||||||
* @param baseTime The time from which to calculate the next arrival (usually
|
* @param baseTime The time from which to calculate the next arrival (usually {@code currentTime}).
|
||||||
* {@code currentTime}).
|
|
||||||
*/
|
*/
|
||||||
private void scheduleNextVehicleGeneration(double baseTime) {
|
private void scheduleNextVehicleGeneration(double baseTime) {
|
||||||
// Get the absolute time for the next arrival.
|
// Get the absolute time for the next arrival.
|
||||||
@@ -282,8 +258,7 @@ public class SimulationEngine {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Main event processing logic.
|
* Main event processing logic.
|
||||||
* Delegates the event to the appropriate handler method based on its
|
* Delegates the event to the appropriate handler method based on its {@link EventType}.
|
||||||
* {@link EventType}.
|
|
||||||
*
|
*
|
||||||
* @param event The {@link Event} to be processed.
|
* @param event The {@link Event} to be processed.
|
||||||
*/
|
*/
|
||||||
@@ -313,14 +288,13 @@ public class SimulationEngine {
|
|||||||
* at its first destination intersection.
|
* at its first destination intersection.
|
||||||
* 4. Schedules the *next* {@link EventType#VEHICLE_GENERATION} event.
|
* 4. Schedules the *next* {@link EventType#VEHICLE_GENERATION} event.
|
||||||
* (Note: This line is commented out in the original, which might be a bug,
|
* (Note: This line is commented out in the original, which might be a bug,
|
||||||
* as it implies only one vehicle is ever generated. It should likely be
|
* as it implies only one vehicle is ever generated. It should likely be active.)
|
||||||
* active.)
|
|
||||||
*/
|
*/
|
||||||
private void handleVehicleGeneration() {
|
private void handleVehicleGeneration() {
|
||||||
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());
|
||||||
|
|
||||||
// Register with statistics collector
|
// Register with statistics collector
|
||||||
statisticsCollector.recordVehicleGeneration(vehicle, currentTime);
|
statisticsCollector.recordVehicleGeneration(vehicle, currentTime);
|
||||||
@@ -328,8 +302,8 @@ public class SimulationEngine {
|
|||||||
// Schedule arrival at first intersection
|
// Schedule arrival at first intersection
|
||||||
String firstIntersection = vehicle.getCurrentDestination();
|
String firstIntersection = vehicle.getCurrentDestination();
|
||||||
if (firstIntersection != null && !firstIntersection.equals("S")) {
|
if (firstIntersection != null && !firstIntersection.equals("S")) {
|
||||||
double travelTime = calculateTravelTime(vehicle.getType());
|
// Assume minimal travel time to first intersection (e.g., 1-3 seconds)
|
||||||
double arrivalTime = currentTime + travelTime;
|
double arrivalTime = currentTime + 1.0 + Math.random() * 2.0;
|
||||||
Event arrivalEvent = new Event(arrivalTime, EventType.VEHICLE_ARRIVAL, vehicle, firstIntersection);
|
Event arrivalEvent = new Event(arrivalTime, EventType.VEHICLE_ARRIVAL, vehicle, firstIntersection);
|
||||||
eventQueue.offer(arrivalEvent);
|
eventQueue.offer(arrivalEvent);
|
||||||
}
|
}
|
||||||
@@ -350,8 +324,7 @@ public class SimulationEngine {
|
|||||||
* current intersection using {@link Intersection#receiveVehicle(Vehicle)}.
|
* current intersection using {@link Intersection#receiveVehicle(Vehicle)}.
|
||||||
* 5. Attempts to process the vehicle immediately if its light is green.
|
* 5. Attempts to process the vehicle immediately if its light is green.
|
||||||
*
|
*
|
||||||
* @param event The arrival event, containing the {@link Vehicle} and
|
* @param event The arrival event, containing the {@link Vehicle} and intersection ID.
|
||||||
* intersection ID.
|
|
||||||
*/
|
*/
|
||||||
private void handleVehicleArrival(Event event) {
|
private void handleVehicleArrival(Event event) {
|
||||||
Vehicle vehicle = (Vehicle) event.getData();
|
Vehicle vehicle = (Vehicle) event.getData();
|
||||||
@@ -364,7 +337,7 @@ public class SimulationEngine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
System.out.printf("[t=%.2f] Vehicle %s arrived at %s%n",
|
System.out.printf("[t=%.2f] Vehicle %s arrived at %s%n",
|
||||||
currentTime, vehicle.getId(), intersectionId);
|
currentTime, vehicle.getId(), intersectionId);
|
||||||
|
|
||||||
// Record arrival time (used to calculate waiting time later)
|
// Record arrival time (used to calculate waiting time later)
|
||||||
statisticsCollector.recordVehicleArrival(vehicle, intersectionId, currentTime);
|
statisticsCollector.recordVehicleArrival(vehicle, intersectionId, currentTime);
|
||||||
@@ -386,8 +359,7 @@ public class SimulationEngine {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add vehicle to the appropriate traffic light queue based on its next
|
// Add vehicle to the appropriate traffic light queue based on its next destination
|
||||||
// destination
|
|
||||||
intersection.receiveVehicle(vehicle);
|
intersection.receiveVehicle(vehicle);
|
||||||
|
|
||||||
// Try to process the vehicle immediately if its light is already green
|
// Try to process the vehicle immediately if its light is already green
|
||||||
@@ -398,18 +370,18 @@ public class SimulationEngine {
|
|||||||
* Checks if a newly arrived vehicle (or a vehicle in a queue
|
* Checks if a newly arrived vehicle (or a vehicle in a queue
|
||||||
* that just turned green) can start crossing.
|
* that just turned green) can start crossing.
|
||||||
*
|
*
|
||||||
* @param vehicle The vehicle to process.
|
* @param vehicle The vehicle to process.
|
||||||
* @param intersection The intersection where the vehicle is.
|
* @param intersection The intersection where the vehicle is.
|
||||||
*/
|
*/
|
||||||
private void tryProcessVehicle(Vehicle vehicle, Intersection intersection) { // FIXME
|
private void tryProcessVehicle(Vehicle vehicle, Intersection intersection) { //FIXME
|
||||||
// Find the direction (and light) this vehicle is queued at
|
// Find the direction (and light) this vehicle is queued at
|
||||||
// This logic is a bit flawed: it just finds the *first* non-empty queue
|
// This logic is a bit flawed: it just finds the *first* non-empty queue
|
||||||
// A better approach would be to get the light from the vehicle's route
|
// A better approach would be to get the light from the vehicle's route
|
||||||
String direction = intersection.getTrafficLights().stream()
|
String direction = intersection.getTrafficLights().stream()
|
||||||
.filter(tl -> tl.getQueueSize() > 0)
|
.filter(tl -> tl.getQueueSize() > 0)
|
||||||
.map(TrafficLight::getDirection)
|
.map(TrafficLight::getDirection)
|
||||||
.findFirst()
|
.findFirst()
|
||||||
.orElse(null);
|
.orElse(null);
|
||||||
|
|
||||||
if (direction != null) {
|
if (direction != null) {
|
||||||
TrafficLight light = intersection.getTrafficLight(direction);
|
TrafficLight light = intersection.getTrafficLight(direction);
|
||||||
@@ -431,7 +403,7 @@ public class SimulationEngine {
|
|||||||
* 1. Calculates and records the vehicle's waiting time.
|
* 1. Calculates and records the vehicle's waiting time.
|
||||||
* 2. Schedules an immediate {@link EventType#CROSSING_START} event.
|
* 2. Schedules an immediate {@link EventType#CROSSING_START} event.
|
||||||
*
|
*
|
||||||
* @param vehicle The {@link Vehicle} that is crossing.
|
* @param vehicle The {@link Vehicle} that is crossing.
|
||||||
* @param intersection The {@link Intersection} it is crossing.
|
* @param intersection The {@link Intersection} it is crossing.
|
||||||
*/
|
*/
|
||||||
private void scheduleCrossing(Vehicle vehicle, Intersection intersection) {
|
private void scheduleCrossing(Vehicle vehicle, Intersection intersection) {
|
||||||
@@ -459,7 +431,7 @@ public class SimulationEngine {
|
|||||||
double crossingTime = getCrossingTime(vehicle.getType());
|
double crossingTime = getCrossingTime(vehicle.getType());
|
||||||
|
|
||||||
System.out.printf("[t=%.2f] Vehicle %s started crossing at %s (duration=%.2fs)%n",
|
System.out.printf("[t=%.2f] Vehicle %s started crossing at %s (duration=%.2fs)%n",
|
||||||
currentTime, vehicle.getId(), intersectionId, crossingTime);
|
currentTime, vehicle.getId(), intersectionId, crossingTime);
|
||||||
|
|
||||||
// Schedule the *end* of the crossing
|
// Schedule the *end* of the crossing
|
||||||
double endTime = currentTime + crossingTime;
|
double endTime = currentTime + crossingTime;
|
||||||
@@ -471,8 +443,7 @@ public class SimulationEngine {
|
|||||||
* Handles {@link EventType#CROSSING_END}.
|
* Handles {@link EventType#CROSSING_END}.
|
||||||
* 1. Updates intersection and vehicle statistics.
|
* 1. Updates intersection and vehicle statistics.
|
||||||
* 2. Checks the vehicle's *next* destination.
|
* 2. Checks the vehicle's *next* destination.
|
||||||
* 3. If the next destination is the exit ("S"), call
|
* 3. If the next destination is the exit ("S"), call {@link #handleVehicleExit(Vehicle)}.
|
||||||
* {@link #handleVehicleExit(Vehicle)}.
|
|
||||||
* 4. Otherwise, schedule a {@link EventType#VEHICLE_ARRIVAL} event at the
|
* 4. Otherwise, schedule a {@link EventType#VEHICLE_ARRIVAL} event at the
|
||||||
* *next* intersection, after some travel time.
|
* *next* intersection, after some travel time.
|
||||||
*
|
*
|
||||||
@@ -492,15 +463,14 @@ public class SimulationEngine {
|
|||||||
vehicle.addCrossingTime(crossingTime);
|
vehicle.addCrossingTime(crossingTime);
|
||||||
|
|
||||||
System.out.printf("[t=%.2f] Vehicle %s finished crossing at %s%n",
|
System.out.printf("[t=%.2f] Vehicle %s finished crossing at %s%n",
|
||||||
currentTime, vehicle.getId(), intersectionId);
|
currentTime, vehicle.getId(), intersectionId);
|
||||||
|
|
||||||
// Decide what to do next
|
// Decide what to do next
|
||||||
String nextDest = vehicle.getCurrentDestination();
|
String nextDest = vehicle.getCurrentDestination();
|
||||||
if (nextDest != null && !nextDest.equals("S")) {
|
if (nextDest != null && !nextDest.equals("S")) {
|
||||||
// Route to the *next* intersection
|
// Route to the *next* intersection
|
||||||
// Travel time varies by vehicle type: tmoto = 0.5 × tcarro, tcaminhão = 4 ×
|
// Assume 5-10 seconds travel time between intersections
|
||||||
// tmoto
|
double travelTime = 5.0 + Math.random() * 5.0;
|
||||||
double travelTime = calculateTravelTime(vehicle.getType());
|
|
||||||
double arrivalTime = currentTime + travelTime;
|
double arrivalTime = currentTime + travelTime;
|
||||||
Event arrivalEvent = new Event(arrivalTime, EventType.VEHICLE_ARRIVAL, vehicle, nextDest);
|
Event arrivalEvent = new Event(arrivalTime, EventType.VEHICLE_ARRIVAL, vehicle, nextDest);
|
||||||
eventQueue.offer(arrivalEvent);
|
eventQueue.offer(arrivalEvent);
|
||||||
@@ -518,9 +488,9 @@ public class SimulationEngine {
|
|||||||
*/
|
*/
|
||||||
private void handleVehicleExit(Vehicle vehicle) {
|
private void handleVehicleExit(Vehicle vehicle) {
|
||||||
System.out.printf("[t=%.2f] Vehicle %s exited the system (wait=%.2fs, travel=%.2fs)%n",
|
System.out.printf("[t=%.2f] Vehicle %s exited the system (wait=%.2fs, travel=%.2fs)%n",
|
||||||
currentTime, vehicle.getId(),
|
currentTime, vehicle.getId(),
|
||||||
vehicle.getTotalWaitingTime(),
|
vehicle.getTotalWaitingTime(),
|
||||||
vehicle.getTotalTravelTime(currentTime));
|
vehicle.getTotalTravelTime(currentTime));
|
||||||
|
|
||||||
// Record the exit for final statistics calculation
|
// Record the exit for final statistics calculation
|
||||||
statisticsCollector.recordVehicleExit(vehicle, currentTime);
|
statisticsCollector.recordVehicleExit(vehicle, currentTime);
|
||||||
@@ -529,8 +499,7 @@ public class SimulationEngine {
|
|||||||
/**
|
/**
|
||||||
* Handles {@link EventType#TRAFFIC_LIGHT_CHANGE}.
|
* Handles {@link EventType#TRAFFIC_LIGHT_CHANGE}.
|
||||||
* 1. Toggles the light's state (RED to GREEN or GREEN to RED).
|
* 1. Toggles the light's state (RED to GREEN or GREEN to RED).
|
||||||
* 2. If the light just turned GREEN, call
|
* 2. If the light just turned GREEN, call {@link #processGreenLight(TrafficLight, Intersection)}
|
||||||
* {@link #processGreenLight(TrafficLight, Intersection)}
|
|
||||||
* to process any waiting vehicles.
|
* to process any waiting vehicles.
|
||||||
* 3. Schedules the *next* state change for this light based on its
|
* 3. Schedules the *next* state change for this light based on its
|
||||||
* green/red time duration.
|
* green/red time duration.
|
||||||
@@ -543,13 +512,13 @@ public class SimulationEngine {
|
|||||||
|
|
||||||
// Toggle state
|
// Toggle state
|
||||||
TrafficLightState newState = (light.getState() == TrafficLightState.RED)
|
TrafficLightState newState = (light.getState() == TrafficLightState.RED)
|
||||||
? TrafficLightState.GREEN
|
? TrafficLightState.GREEN
|
||||||
: TrafficLightState.RED;
|
: TrafficLightState.RED;
|
||||||
|
|
||||||
light.changeState(newState);
|
light.changeState(newState);
|
||||||
|
|
||||||
System.out.printf("[t=%.2f] Traffic light %s changed to %s%n",
|
System.out.printf("[t=%.2f] Traffic light %s changed to %s%n",
|
||||||
currentTime, light.getId(), newState);
|
currentTime, light.getId(), newState);
|
||||||
|
|
||||||
// If changed to GREEN, process waiting vehicles
|
// If changed to GREEN, process waiting vehicles
|
||||||
if (newState == TrafficLightState.GREEN) {
|
if (newState == TrafficLightState.GREEN) {
|
||||||
@@ -561,8 +530,8 @@ public class SimulationEngine {
|
|||||||
|
|
||||||
// Schedule the *next* state change for this same light
|
// Schedule the *next* state change for this same light
|
||||||
double nextChangeDelay = (newState == TrafficLightState.GREEN)
|
double nextChangeDelay = (newState == TrafficLightState.GREEN)
|
||||||
? light.getGreenTime()
|
? light.getGreenTime()
|
||||||
: light.getRedTime();
|
: light.getRedTime();
|
||||||
|
|
||||||
scheduleTrafficLightChange(light, intersectionId, nextChangeDelay);
|
scheduleTrafficLightChange(light, intersectionId, nextChangeDelay);
|
||||||
}
|
}
|
||||||
@@ -577,7 +546,7 @@ public class SimulationEngine {
|
|||||||
* processes the entire queue "instantaneously" at the moment
|
* processes the entire queue "instantaneously" at the moment
|
||||||
* the light turns green.
|
* the light turns green.
|
||||||
*
|
*
|
||||||
* @param light The {@link TrafficLight} that just turned green.
|
* @param light The {@link TrafficLight} that just turned green.
|
||||||
* @param intersection The {@link Intersection} where the light is.
|
* @param intersection The {@link Intersection} where the light is.
|
||||||
*/
|
*/
|
||||||
private void processGreenLight(TrafficLight light, Intersection intersection) {
|
private void processGreenLight(TrafficLight light, Intersection intersection) {
|
||||||
@@ -603,8 +572,7 @@ public class SimulationEngine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Utility method to get the configured crossing time for a given
|
* Utility method to get the configured crossing time for a given {@link VehicleType}.
|
||||||
* {@link VehicleType}.
|
|
||||||
*
|
*
|
||||||
* @param type The type of vehicle.
|
* @param type The type of vehicle.
|
||||||
* @return The crossing time in seconds.
|
* @return The crossing time in seconds.
|
||||||
@@ -635,7 +603,6 @@ public class SimulationEngine {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the current simulation time.
|
* Gets the current simulation time.
|
||||||
*
|
|
||||||
* @return The time in virtual seconds.
|
* @return The time in virtual seconds.
|
||||||
*/
|
*/
|
||||||
public double getCurrentTime() {
|
public double getCurrentTime() {
|
||||||
@@ -645,7 +612,6 @@ public class SimulationEngine {
|
|||||||
/**
|
/**
|
||||||
* Gets a map of all intersections in the simulation.
|
* Gets a map of all intersections in the simulation.
|
||||||
* Returns a copy to prevent external modification.
|
* Returns a copy to prevent external modification.
|
||||||
*
|
|
||||||
* @return A {@link Map} of intersection IDs to {@link Intersection} objects.
|
* @return A {@link Map} of intersection IDs to {@link Intersection} objects.
|
||||||
*/
|
*/
|
||||||
public Map<String, Intersection> getIntersections() {
|
public Map<String, Intersection> getIntersections() {
|
||||||
@@ -654,7 +620,6 @@ public class SimulationEngine {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the statistics collector instance.
|
* Gets the statistics collector instance.
|
||||||
*
|
|
||||||
* @return The {@link StatisticsCollector}.
|
* @return The {@link StatisticsCollector}.
|
||||||
*/
|
*/
|
||||||
public StatisticsCollector getStatisticsCollector() {
|
public StatisticsCollector getStatisticsCollector() {
|
||||||
|
|||||||
@@ -1,115 +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");
|
|
||||||
|
|
||||||
processGreenLightQueue();
|
|
||||||
|
|
||||||
if (!running || Thread.currentThread().isInterrupted()) break;
|
|
||||||
|
|
||||||
// Wait for green duration
|
|
||||||
Thread.sleep((long) (light.getGreenTime() * 1000));
|
|
||||||
|
|
||||||
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() throws InterruptedException {
|
|
||||||
while (running && !Thread.currentThread().isInterrupted()
|
|
||||||
&& light.getState() == TrafficLightState.GREEN
|
|
||||||
&& light.getQueueSize() > 0) {
|
|
||||||
|
|
||||||
Vehicle vehicle = light.removeVehicle();
|
|
||||||
|
|
||||||
if (vehicle != null) {
|
|
||||||
double crossingTime = getCrossingTimeForVehicle(vehicle);
|
|
||||||
|
|
||||||
Thread.sleep((long) (crossingTime * 1000));
|
|
||||||
|
|
||||||
vehicle.addCrossingTime(crossingTime);
|
|
||||||
process.getIntersection().incrementVehiclesSent();
|
|
||||||
process.sendVehicleToNextDestination(vehicle);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -104,28 +104,16 @@ public class Intersection {
|
|||||||
* Accepts an incoming vehicle and places it in the correct queue.
|
* Accepts an incoming vehicle and places it in the correct queue.
|
||||||
* * This method:
|
* * This method:
|
||||||
* 1. Increments the {@link #totalVehiclesReceived} counter.
|
* 1. Increments the {@link #totalVehiclesReceived} counter.
|
||||||
* 2. Advances the vehicle's route (since it just arrived here)
|
* 2. Gets the vehicle's *next* destination (from {@link Vehicle#getCurrentDestination()}).
|
||||||
* 3. Gets the vehicle's *next* destination (from {@link Vehicle#getCurrentDestination()}).
|
* 3. Uses the {@link #routing} map to find the correct *direction* for that destination.
|
||||||
* 4. Uses the {@link #routing} map to find the correct *direction* for that destination.
|
* 4. Adds the vehicle to the queue of the {@link TrafficLight} for that direction.
|
||||||
* 5. Adds the vehicle to the queue of the {@link TrafficLight} for that direction.
|
|
||||||
*
|
*
|
||||||
* @param vehicle The {@link Vehicle} arriving at the intersection.
|
* @param vehicle The {@link Vehicle} arriving at the intersection.
|
||||||
*/
|
*/
|
||||||
public void receiveVehicle(Vehicle vehicle) {
|
public void receiveVehicle(Vehicle vehicle) {
|
||||||
totalVehiclesReceived++;
|
totalVehiclesReceived++;
|
||||||
|
|
||||||
// Note: Route advancement is handled by SimulationEngine.handleVehicleArrival()
|
|
||||||
// before calling this method, so we don't advance here.
|
|
||||||
|
|
||||||
String nextDestination = vehicle.getCurrentDestination();
|
String nextDestination = vehicle.getCurrentDestination();
|
||||||
|
|
||||||
// Check if vehicle reached final destination
|
|
||||||
if (nextDestination == null) {
|
|
||||||
System.out.printf("[%s] Vehicle %s reached final destination%n",
|
|
||||||
this.id, vehicle.getId());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
String direction = routing.get(nextDestination);
|
String direction = routing.get(nextDestination);
|
||||||
|
|
||||||
if (direction != null && trafficLights.containsKey(direction)) {
|
if (direction != null && trafficLights.containsKey(direction)) {
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
package sd.model;
|
package sd.model;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import sd.protocol.MessageProtocol;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents a message exchanged between processes in the distributed simulation.
|
* Represents a message exchanged between processes in the distributed simulation.
|
||||||
* Each message has a unique ID, a type, a sender, a destination, and a payload.
|
* Each message has a unique ID, a type, a sender, a destination, and a payload.
|
||||||
* This class implements {@link MessageProtocol} which extends Serializable for network transmission.
|
* This class implements {@link Serializable} to allow transmission over the network.
|
||||||
*/
|
*/
|
||||||
public class Message implements MessageProtocol {
|
public class Message implements Serializable {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
@@ -133,17 +132,6 @@ public class Message implements MessageProtocol {
|
|||||||
return (T) payload;
|
return (T) payload;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Impl MessageProtocol interface
|
|
||||||
@Override
|
|
||||||
public String getSourceNode() {
|
|
||||||
return senderId;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getDestinationNode() {
|
|
||||||
return destinationId;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return String.format("Message[id=%s, type=%s, from=%s, to=%s, timestamp=%d]",
|
return String.format("Message[id=%s, type=%s, from=%s, to=%s, timestamp=%d]",
|
||||||
|
|||||||
@@ -19,12 +19,6 @@ public enum MessageType {
|
|||||||
*/
|
*/
|
||||||
STATS_UPDATE,
|
STATS_UPDATE,
|
||||||
|
|
||||||
/**
|
|
||||||
* Message to synchronize simulation start time across all processes.
|
|
||||||
* Payload: Start timestamp (long milliseconds)
|
|
||||||
*/
|
|
||||||
SIMULATION_START,
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Message to synchronize traffic light states between processes.
|
* Message to synchronize traffic light states between processes.
|
||||||
* Payload: TrafficLight state and timing information
|
* Payload: TrafficLight state and timing information
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
package sd.model;
|
package sd.model;
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Queue;
|
import java.util.Queue;
|
||||||
import java.util.concurrent.locks.Condition;
|
import java.util.concurrent.locks.Condition;
|
||||||
import java.util.concurrent.locks.Lock;
|
import java.util.concurrent.locks.Lock;
|
||||||
@@ -96,12 +94,6 @@ public class TrafficLight {
|
|||||||
*/
|
*/
|
||||||
private int totalVehiclesProcessed;
|
private int totalVehiclesProcessed;
|
||||||
|
|
||||||
/**
|
|
||||||
* Track when vehicles arrive at this light for wait time calculation.
|
|
||||||
* Maps vehicle ID to arrival timestamp (milliseconds).
|
|
||||||
*/
|
|
||||||
private final Map<String, Long> vehicleArrivalTimes;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new TrafficLight.
|
* Constructs a new TrafficLight.
|
||||||
*
|
*
|
||||||
@@ -123,7 +115,6 @@ public class TrafficLight {
|
|||||||
|
|
||||||
this.greenTime = greenTime;
|
this.greenTime = greenTime;
|
||||||
this.redTime = redTime;
|
this.redTime = redTime;
|
||||||
this.vehicleArrivalTimes = new HashMap<>();
|
|
||||||
this.totalVehiclesProcessed = 0;
|
this.totalVehiclesProcessed = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,7 +128,6 @@ public class TrafficLight {
|
|||||||
lock.lock(); // Acquire the lock
|
lock.lock(); // Acquire the lock
|
||||||
try {
|
try {
|
||||||
queue.offer(vehicle); // Add vehicle to queue
|
queue.offer(vehicle); // Add vehicle to queue
|
||||||
vehicleArrivalTimes.put(vehicle.getId(), System.currentTimeMillis());
|
|
||||||
vehicleAdded.signalAll(); // Signal (for concurrent models)
|
vehicleAdded.signalAll(); // Signal (for concurrent models)
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock(); // Always release the lock
|
lock.unlock(); // Always release the lock
|
||||||
@@ -162,13 +152,6 @@ public class TrafficLight {
|
|||||||
Vehicle vehicle = queue.poll(); // Remove vehicle from queue
|
Vehicle vehicle = queue.poll(); // Remove vehicle from queue
|
||||||
if (vehicle != null) {
|
if (vehicle != null) {
|
||||||
totalVehiclesProcessed++;
|
totalVehiclesProcessed++;
|
||||||
|
|
||||||
// Calculate wait time (time spent in queue)
|
|
||||||
Long arrivalTime = vehicleArrivalTimes.remove(vehicle.getId());
|
|
||||||
if (arrivalTime != null) {
|
|
||||||
double waitTimeSeconds = (System.currentTimeMillis() - arrivalTime) / 1000.0;
|
|
||||||
vehicle.addWaitingTime(waitTimeSeconds);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return vehicle;
|
return vehicle;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,41 +0,0 @@
|
|||||||
package sd.protocol;
|
|
||||||
|
|
||||||
import java.io.Serializable;
|
|
||||||
import sd.model.MessageType; // Assuming MessageType is in sd.model or sd.protocol
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Interface defining the contract for all messages exchanged in the simulator.
|
|
||||||
* Ensures that any message can be identified and routed.
|
|
||||||
* * This interface extends Serializable to allow objects that implement it
|
|
||||||
* to be sent over Sockets (ObjectOutputStream).
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public interface MessageProtocol extends Serializable {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the type of the message, indicating its purpose.
|
|
||||||
* @return The MessageType (e.g., VEHICLE_TRANSFER, STATS_UPDATE).
|
|
||||||
*/
|
|
||||||
MessageType getType();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the data object (payload) that this message carries.
|
|
||||||
* The type of object will depend on the MessageType.
|
|
||||||
* * - If getType() == VEHICLE_TRANSFER, the payload will be a {@link sd.model.Vehicle} object.
|
|
||||||
* - If getType() == STATS_UPDATE, the payload will be a statistics object.
|
|
||||||
* * @return The data object (payload), which must also be Serializable.
|
|
||||||
*/
|
|
||||||
Object getPayload();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the ID of the node (Process) that sent this message.
|
|
||||||
* @return String (e.g., "Cr1", "Cr5", "S").
|
|
||||||
*/
|
|
||||||
String getSourceNode();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the ID of the destination node (Process) for this message.
|
|
||||||
* @return String (e.g., "Cr2", "DashboardServer").
|
|
||||||
*/
|
|
||||||
String getDestinationNode();
|
|
||||||
}
|
|
||||||
@@ -1,199 +0,0 @@
|
|||||||
package sd.protocol;
|
|
||||||
|
|
||||||
import java.io.Closeable;
|
|
||||||
import java.io.DataInputStream;
|
|
||||||
import java.io.DataOutputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.io.OutputStream;
|
|
||||||
import java.net.ConnectException;
|
|
||||||
import java.net.Socket;
|
|
||||||
import java.net.SocketTimeoutException;
|
|
||||||
import java.net.UnknownHostException;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import sd.serialization.MessageSerializer;
|
|
||||||
import sd.serialization.SerializationException;
|
|
||||||
import sd.serialization.SerializerFactory;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Wrapper class that simplifies communication via Sockets.
|
|
||||||
* Includes connection retry logic for robustness.
|
|
||||||
*/
|
|
||||||
public class SocketConnection implements Closeable {
|
|
||||||
|
|
||||||
private final Socket socket;
|
|
||||||
private final OutputStream outputStream;
|
|
||||||
private final InputStream inputStream;
|
|
||||||
private final MessageSerializer serializer;
|
|
||||||
|
|
||||||
// --- Configuration for Retry Logic ---
|
|
||||||
/** Maximum number of connection attempts. */
|
|
||||||
private static final int MAX_RETRIES = 5;
|
|
||||||
/** Delay between retry attempts in milliseconds. */
|
|
||||||
private static final long RETRY_DELAY_MS = 1000;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructor for the "Client" (who initiates the connection).
|
|
||||||
* Tries to connect to a process that is already listening (Server).
|
|
||||||
* Includes retry logic in case of initial connection failure.
|
|
||||||
*
|
|
||||||
* @param host The host address (e.g., "localhost" from your simulation.properties)
|
|
||||||
* @param port The port (e.g., 8001 from your simulation.properties)
|
|
||||||
* @throws IOException If connection fails after all retries.
|
|
||||||
* @throws UnknownHostException If the host is not found (this error usually doesn't need retry).
|
|
||||||
* @throws InterruptedException If the thread is interrupted while waiting between retries.
|
|
||||||
*/
|
|
||||||
public SocketConnection(String host, int port) throws IOException, UnknownHostException, InterruptedException {
|
|
||||||
Socket tempSocket = null;
|
|
||||||
IOException lastException = null;
|
|
||||||
|
|
||||||
System.out.printf("[SocketConnection] Attempting to connect to %s:%d...%n", host, port);
|
|
||||||
|
|
||||||
// --- Retry Loop ---
|
|
||||||
for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
|
||||||
try {
|
|
||||||
// Try to establish the connection
|
|
||||||
tempSocket = new Socket(host, port);
|
|
||||||
|
|
||||||
// If successful, break out of the retry loop
|
|
||||||
System.out.printf("[SocketConnection] Connected successfully on attempt %d.%n", attempt);
|
|
||||||
lastException = null; // Clear last error on success
|
|
||||||
break;
|
|
||||||
|
|
||||||
} catch (ConnectException | SocketTimeoutException e) {
|
|
||||||
// These are common errors indicating the server might not be ready.
|
|
||||||
lastException = e;
|
|
||||||
System.out.printf("[SocketConnection] Attempt %d/%d failed: %s. Retrying in %d ms...%n",
|
|
||||||
attempt, MAX_RETRIES, e.getMessage(), RETRY_DELAY_MS);
|
|
||||||
|
|
||||||
if (attempt < MAX_RETRIES) {
|
|
||||||
// Wait before the next attempt
|
|
||||||
TimeUnit.MILLISECONDS.sleep(RETRY_DELAY_MS);
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
// Other IOExceptions might be more permanent, but we retry anyway.
|
|
||||||
lastException = e;
|
|
||||||
System.out.printf("[SocketConnection] Attempt %d/%d failed with IOException: %s. Retrying in %d ms...%n",
|
|
||||||
attempt, MAX_RETRIES, e.getMessage(), RETRY_DELAY_MS);
|
|
||||||
if (attempt < MAX_RETRIES) {
|
|
||||||
TimeUnit.MILLISECONDS.sleep(RETRY_DELAY_MS);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} // --- End of Retry Loop ---
|
|
||||||
|
|
||||||
// If after all retries tempSocket is still null, it means connection failed permanently.
|
|
||||||
if (tempSocket == null) {
|
|
||||||
System.err.printf("[SocketConnection] Failed to connect to %s:%d after %d attempts.%n", host, port, MAX_RETRIES);
|
|
||||||
if (lastException != null) {
|
|
||||||
throw lastException; // Throw the last exception encountered
|
|
||||||
} else {
|
|
||||||
// Should not happen if loop ran, but as a fallback
|
|
||||||
throw new IOException("Failed to connect after " + MAX_RETRIES + " attempts, reason unknown.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If connection was successful, assign to final variable and create streams
|
|
||||||
this.socket = tempSocket;
|
|
||||||
|
|
||||||
this.outputStream = socket.getOutputStream();
|
|
||||||
this.inputStream = socket.getInputStream();
|
|
||||||
this.serializer = SerializerFactory.createDefault();
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructor for the "Server" (who accepts the connection).
|
|
||||||
* Receives a Socket that has already been accepted by a ServerSocket.
|
|
||||||
* No retry logic needed here as the connection is already established.
|
|
||||||
*
|
|
||||||
* @param acceptedSocket The Socket returned by serverSocket.accept().
|
|
||||||
* @throws IOException If stream creation fails.
|
|
||||||
*/
|
|
||||||
public SocketConnection(Socket acceptedSocket) throws IOException {
|
|
||||||
this.socket = acceptedSocket;
|
|
||||||
this.outputStream = socket.getOutputStream();
|
|
||||||
this.inputStream = socket.getInputStream();
|
|
||||||
this.serializer = SerializerFactory.createDefault();
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sends (serializes) a MessageProtocol object over the socket.
|
|
||||||
*
|
|
||||||
* @param message The "envelope" (which contains the Vehicle) to be sent.
|
|
||||||
* @throws IOException If writing to the stream fails or socket is not connected.
|
|
||||||
*/
|
|
||||||
public void sendMessage(MessageProtocol message) throws IOException {
|
|
||||||
if (socket == null || !socket.isConnected()) {
|
|
||||||
throw new IOException("Socket is not connected");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Serializa para bytes JSON
|
|
||||||
byte[] data = serializer.serialize(message);
|
|
||||||
|
|
||||||
// Write 4-byte length prefix
|
|
||||||
DataOutputStream dataOut = new DataOutputStream(outputStream);
|
|
||||||
dataOut.writeInt(data.length);
|
|
||||||
dataOut.write(data);
|
|
||||||
dataOut.flush();
|
|
||||||
|
|
||||||
} catch (SerializationException e) {
|
|
||||||
throw new IOException("Failed to serialize message", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tries to read (deserialize) a MessageProtocol object from the socket.
|
|
||||||
*
|
|
||||||
* @return The "envelope" (MessageProtocol) that was received.
|
|
||||||
* @throws IOException If the connection is lost, the stream is corrupted, or socket is not connected.
|
|
||||||
* @throws ClassNotFoundException If the received object is unknown.
|
|
||||||
*/
|
|
||||||
public MessageProtocol receiveMessage() throws IOException, ClassNotFoundException {
|
|
||||||
if (socket == null || !socket.isConnected()) {
|
|
||||||
throw new IOException("Socket is not connected");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Lê um prefixo de 4 bytes - indicador de tamanho
|
|
||||||
DataInputStream dataIn = new DataInputStream(inputStream);
|
|
||||||
int length = dataIn.readInt();
|
|
||||||
|
|
||||||
if (length <= 0 || length > 10_000_000) { // Sanity check (10MB max)
|
|
||||||
throw new IOException("Invalid message length: " + length);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ler dados da mensagem
|
|
||||||
byte[] data = new byte[length];
|
|
||||||
dataIn.readFully(data);
|
|
||||||
|
|
||||||
// Deserialize do JSON - use concrete Message class, not interface
|
|
||||||
return serializer.deserialize(data, sd.model.Message.class);
|
|
||||||
|
|
||||||
} catch (SerializationException e) {
|
|
||||||
throw new IOException("Failed to deserialize message", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Closes the socket and all streams (Input and Output).
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void close() throws IOException {
|
|
||||||
if (inputStream != null) inputStream.close();
|
|
||||||
if (outputStream != null) outputStream.close();
|
|
||||||
if (socket != null) socket.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return true if the socket is still connected and not closed.
|
|
||||||
*/
|
|
||||||
public boolean isConnected() {
|
|
||||||
return socket != null && socket.isConnected() && !socket.isClosed();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -46,54 +46,54 @@ simulation.arrival.fixed.interval=2.0
|
|||||||
# === TRAFFIC LIGHT TIMINGS ===
|
# === TRAFFIC LIGHT TIMINGS ===
|
||||||
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
|
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
|
||||||
|
|
||||||
# Intersection 1 (Entry point - balanced)
|
# Intersection 1
|
||||||
trafficlight.Cr1.North.green=20.0
|
trafficlight.Cr1.North.green=30.0
|
||||||
trafficlight.Cr1.North.red=40.0
|
trafficlight.Cr1.North.red=30.0
|
||||||
trafficlight.Cr1.South.green=20.0
|
trafficlight.Cr1.South.green=30.0
|
||||||
trafficlight.Cr1.South.red=40.0
|
trafficlight.Cr1.South.red=30.0
|
||||||
trafficlight.Cr1.East.green=20.0
|
trafficlight.Cr1.East.green=30.0
|
||||||
trafficlight.Cr1.East.red=40.0
|
trafficlight.Cr1.East.red=30.0
|
||||||
trafficlight.Cr1.West.green=20.0
|
trafficlight.Cr1.West.green=30.0
|
||||||
trafficlight.Cr1.West.red=40.0
|
trafficlight.Cr1.West.red=30.0
|
||||||
|
|
||||||
# Intersection 2 (Main hub - shorter cycles, favor East-West)
|
# Intersection 2
|
||||||
trafficlight.Cr2.North.green=12.0
|
trafficlight.Cr2.North.green=25.0
|
||||||
trafficlight.Cr2.North.red=36.0
|
trafficlight.Cr2.North.red=35.0
|
||||||
trafficlight.Cr2.South.green=12.0
|
trafficlight.Cr2.South.green=25.0
|
||||||
trafficlight.Cr2.South.red=36.0
|
trafficlight.Cr2.South.red=35.0
|
||||||
trafficlight.Cr2.East.green=18.0
|
trafficlight.Cr2.East.green=35.0
|
||||||
trafficlight.Cr2.East.red=30.0
|
trafficlight.Cr2.East.red=25.0
|
||||||
trafficlight.Cr2.West.green=18.0
|
trafficlight.Cr2.West.green=35.0
|
||||||
trafficlight.Cr2.West.red=30.0
|
trafficlight.Cr2.West.red=25.0
|
||||||
|
|
||||||
# Intersection 3 (Path to exit - favor East)
|
# Intersection 3
|
||||||
trafficlight.Cr3.North.green=15.0
|
trafficlight.Cr3.North.green=30.0
|
||||||
trafficlight.Cr3.North.red=30.0
|
trafficlight.Cr3.North.red=30.0
|
||||||
trafficlight.Cr3.South.green=15.0
|
trafficlight.Cr3.South.green=30.0
|
||||||
trafficlight.Cr3.South.red=30.0
|
trafficlight.Cr3.South.red=30.0
|
||||||
trafficlight.Cr3.East.green=20.0
|
trafficlight.Cr3.East.green=30.0
|
||||||
trafficlight.Cr3.East.red=25.0
|
trafficlight.Cr3.East.red=30.0
|
||||||
trafficlight.Cr3.West.green=15.0
|
trafficlight.Cr3.West.green=30.0
|
||||||
trafficlight.Cr3.West.red=30.0
|
trafficlight.Cr3.West.red=30.0
|
||||||
|
|
||||||
# Intersection 4 (Favor East toward Cr5)
|
# Intersection 4
|
||||||
trafficlight.Cr4.North.green=15.0
|
trafficlight.Cr4.North.green=30.0
|
||||||
trafficlight.Cr4.North.red=30.0
|
trafficlight.Cr4.North.red=30.0
|
||||||
trafficlight.Cr4.South.green=15.0
|
trafficlight.Cr4.South.green=30.0
|
||||||
trafficlight.Cr4.South.red=30.0
|
trafficlight.Cr4.South.red=30.0
|
||||||
trafficlight.Cr4.East.green=20.0
|
trafficlight.Cr4.East.green=30.0
|
||||||
trafficlight.Cr4.East.red=25.0
|
trafficlight.Cr4.East.red=30.0
|
||||||
trafficlight.Cr4.West.green=15.0
|
trafficlight.Cr4.West.green=30.0
|
||||||
trafficlight.Cr4.West.red=30.0
|
trafficlight.Cr4.West.red=30.0
|
||||||
|
|
||||||
# Intersection 5 (Near exit - favor East)
|
# Intersection 5
|
||||||
trafficlight.Cr5.North.green=15.0
|
trafficlight.Cr5.North.green=30.0
|
||||||
trafficlight.Cr5.North.red=30.0
|
trafficlight.Cr5.North.red=30.0
|
||||||
trafficlight.Cr5.South.green=15.0
|
trafficlight.Cr5.South.green=30.0
|
||||||
trafficlight.Cr5.South.red=30.0
|
trafficlight.Cr5.South.red=30.0
|
||||||
trafficlight.Cr5.East.green=22.0
|
trafficlight.Cr5.East.green=30.0
|
||||||
trafficlight.Cr5.East.red=23.0
|
trafficlight.Cr5.East.red=30.0
|
||||||
trafficlight.Cr5.West.green=15.0
|
trafficlight.Cr5.West.green=30.0
|
||||||
trafficlight.Cr5.West.red=30.0
|
trafficlight.Cr5.West.red=30.0
|
||||||
|
|
||||||
# === VEHICLE CONFIGURATION ===
|
# === VEHICLE CONFIGURATION ===
|
||||||
@@ -103,19 +103,11 @@ vehicle.probability.light=0.6
|
|||||||
vehicle.probability.heavy=0.2
|
vehicle.probability.heavy=0.2
|
||||||
|
|
||||||
# Average crossing times (in seconds)
|
# Average crossing times (in seconds)
|
||||||
vehicle.crossing.time.bike=1.0
|
vehicle.crossing.time.bike=1.5
|
||||||
vehicle.crossing.time.light=2.0
|
vehicle.crossing.time.light=2.0
|
||||||
vehicle.crossing.time.heavy=4.0
|
vehicle.crossing.time.heavy=4.0
|
||||||
|
|
||||||
# Travel times between intersections (in seconds)
|
|
||||||
# Base time for light vehicles (cars)
|
|
||||||
vehicle.travel.time.base=8.0
|
|
||||||
# Bike travel time = 0.5 × car travel time
|
|
||||||
vehicle.travel.time.bike.multiplier=0.5
|
|
||||||
# Heavy vehicle travel time = 4 × bike travel time
|
|
||||||
vehicle.travel.time.heavy.multiplier=2.0
|
|
||||||
|
|
||||||
# === STATISTICS ===
|
# === STATISTICS ===
|
||||||
|
|
||||||
# Interval between dashboard updates (seconds)
|
# Interval between dashboard updates (seconds)
|
||||||
statistics.update.interval=1.0
|
statistics.update.interval=10.0
|
||||||
|
|||||||
@@ -1,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,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,206 +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 15 seconds (enough time for all lights to cycle)
|
|
||||||
long endTime = System.currentTimeMillis() + 15000;
|
|
||||||
|
|
||||||
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,60 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
# Distributed Traffic Simulation Startup Script
|
|
||||||
|
|
||||||
# kill java
|
|
||||||
echo "-> Cleaning up existing processes..."
|
|
||||||
pkill -9 java 2>/dev/null
|
|
||||||
sleep 2
|
|
||||||
|
|
||||||
# build
|
|
||||||
echo "-> Building project..."
|
|
||||||
cd "$(dirname "$0")"
|
|
||||||
mvn package -DskipTests -q
|
|
||||||
if [ $? -ne 0 ]; then
|
|
||||||
echo "XXX Build failed! XXX"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "-> Build complete"
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# start gui
|
|
||||||
echo "-> Starting JavaFX Dashboard..."
|
|
||||||
mvn javafx:run &
|
|
||||||
DASHBOARD_PID=$!
|
|
||||||
sleep 3
|
|
||||||
|
|
||||||
# acho que é assim idk
|
|
||||||
echo "-> Starting 5 Intersection processes..."
|
|
||||||
for id in Cr1 Cr2 Cr3 Cr4 Cr5; do
|
|
||||||
java -cp target/classes:target/main-1.0-SNAPSHOT.jar sd.IntersectionProcess $id > /tmp/$(echo $id | tr '[:upper:]' '[:lower:]').log 2>&1 &
|
|
||||||
echo "[SUCCESS] Started $id"
|
|
||||||
done
|
|
||||||
sleep 2
|
|
||||||
|
|
||||||
# exit
|
|
||||||
echo "-> Starting Exit Node..."
|
|
||||||
java -cp target/classes:target/main-1.0-SNAPSHOT.jar sd.ExitNodeProcess > /tmp/exit.log 2>&1 &
|
|
||||||
sleep 1
|
|
||||||
|
|
||||||
# coordinator
|
|
||||||
echo "-> Starting Coordinator..."
|
|
||||||
java -cp target/classes:target/main-1.0-SNAPSHOT.jar sd.coordinator.CoordinatorProcess > /tmp/coordinator.log 2>&1 &
|
|
||||||
sleep 1
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo "-> All processes started!"
|
|
||||||
echo ""
|
|
||||||
echo "-> System Status:"
|
|
||||||
ps aux | grep "java.*sd\." | grep -v grep | wc -l | xargs -I {} echo " {} Java processes running"
|
|
||||||
echo ""
|
|
||||||
echo " IMPORTANT: Keep the JavaFX Dashboard window OPEN for 60+ seconds"
|
|
||||||
echo " to see live updates! The simulation runs for 60 seconds."
|
|
||||||
echo ""
|
|
||||||
echo "-> Logs available at:"
|
|
||||||
echo " Dashboard: Check JavaFX window (live updates)"
|
|
||||||
echo " Intersections: /tmp/cr*.log"
|
|
||||||
echo " Exit Node: /tmp/exit.log"
|
|
||||||
echo " Coordinator: /tmp/coordinator.log"
|
|
||||||
echo ""
|
|
||||||
echo "-> To stop all processes: pkill -9 java"
|
|
||||||
echo ""
|
|
||||||
Reference in New Issue
Block a user