Spaces:
Sleeping
Sleeping
File size: 18,488 Bytes
246b364 e02c2ff a1f84cc 246b364 e02c2ff 246b364 e02c2ff 246b364 e02c2ff a1f84cc e02c2ff 246b364 a1f84cc 246b364 e02c2ff 246b364 a1f84cc 246b364 e02c2ff a1f84cc e02c2ff 246b364 e02c2ff 246b364 d8efc65 a1f84cc d8efc65 246b364 a1f84cc 246b364 d8efc65 246b364 a1f84cc 246b364 d8efc65 246b364 d8efc65 a1f84cc 246b364 a1f84cc 246b364 e02c2ff 246b364 d8efc65 246b364 d8efc65 e02c2ff 246b364 e02c2ff d8efc65 a1f84cc d8efc65 a1f84cc d8efc65 246b364 e02c2ff | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 | import os
import json
import urllib.request
from fastapi import FastAPI, HTTPException, status
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from typing import Optional
app = FastAPI(title="GSM-R & FiS Web Simulation")
WEBHOOK_URL = os.getenv("DISCORD_WEBHOOK_URL")
SYSTEM_PIN = os.getenv("GSM_R_PIN", "1234")
# GitHub URL für die Fahrplandaten (hier anpassen oder deine Raw-URL einfügen)
GITHUB_FAHRPLAN_URL = os.getenv("GITHUB_FAHRPLAN_URL", "https://raw.githubusercontent.com/DeinGitHubUser/DeinRepo/main/fahrplaene.json")
class GSMRState(BaseModel):
zugnummer: str
rolle: str
event: str # "BOOT", "LOGIN", "NOTRUF", "FDL_ANRUF", "TRENNEN", "FAHRPLAN_LADEN"
pin: str
fdl_kennung: Optional[str] = "Zentraler Fdl"
betriebsstelle: Optional[str] = ""
def send_to_discord(content: str, embed: dict = None):
if not WEBHOOK_URL:
print("🚨 Discord Webhook URL nicht konfiguriert!")
return False
payload = {"content": content}
if embed:
payload["embeds"] = [embed]
try:
response = urllib.request.urlopen(
urllib.request.Request(
WEBHOOK_URL,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json", "User-Agent": "GSM-R-Simulation"}
)
)
return response.status == 204
except Exception as e:
print(f"Fehler bei Discord-Übertragung: {e}")
return False
def lade_fahrplan_von_github(zugnummer):
zugnummer = str(zugnummer).strip()
try:
req = urllib.request.Request(GITHUB_FAHRPLAN_URL, headers={'User-Agent': 'Mozilla/5.0'})
with urllib.request.urlopen(req) as response:
data = json.loads(response.read().decode())
return data.get(zugnummer, None)
except Exception as e:
# Fallback-Daten, falls GitHub nicht erreichbar ist
fallback_daten = {
"26815": {
"linie": "RE 1 (NRW-Express)",
"fahrplan": [
{"bs": "KKS", "name": "Köln Hbf", "an": "--:--", "ab": "14:15"},
{"bs": "KKO", "name": "Köln Messe/Deutz", "an": "14:17", "ab": "14:19"},
{"bs": "DDU", "name": "Düsseldorf Hbf", "an": "14:48", "ab": "14:50"},
{"bs": "DU", "name": "Duisburg Hbf", "an": "15:03", "ab": "15:05"},
{"bs": "E", "name": "Essen Hbf", "an": "15:17", "ab": "15:19"}
]
}
}
return fallback_daten.get(zugnummer, {"fehler": f"Zug {zugnummer} nicht gefunden (Fehler: {str(e)})"})
# Route für die Weboberfläche (liefert das integrierte HTML aus)
@app.get("/", response_class=HTMLResponse)
def get_gui():
return HTML_CONTENT
# API-Endpunkt für Fahrpläne aus GitHub
@app.get("/gsmr/fahrplan/{zugnummer}")
def get_fahrplan(zugnummer: str):
plan = lade_fahrplan_von_github(zugnummer)
if not plan or "fehler" in plan:
raise HTTPException(status_code=404, detail=plan.get("fehler", "Fahrplan nicht gefunden."))
return plan
# API-Endpunkt für die GSM-R Events & Discord Webhooks
@app.post("/gsmr/event")
def handle_gsmr_event(data: GSMRState):
if data.pin != SYSTEM_PIN:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Ungültige GSM-R System-PIN!"
)
role_prefix = "01" if "Tf" in data.rolle or "Triebfahrzeug" in data.rolle else "02"
fka = f"{role_prefix}{data.zugnummer}"
if data.event == "LOGIN":
embed = {
"title": "📡 Im GSM-R Netz registriert",
"color": 3066993,
"fields": [
{"name": "Zugnummer", "value": data.zugnummer, "inline": True},
{"name": "Funktionale Adresse (FKA)", "value": fka, "inline": True},
{"name": "Rolle", "value": data.rolle, "inline": True}
]
}
send_to_discord(content=f"🟢 Zug **{data.zugnummer}** hat sich im Netz angemeldet.", embed=embed)
elif data.event == "NOTRUF":
embed = {
"title": "🚨🚨 RAILWAY EMERGENCY CALL (REC) 🚨🚨",
"color": 15158332,
"description": "**ACHTUNG:** Ein Zugfunk-Notruf wurde abgesetzt!",
"fields": [
{"name": "Absender (FKA)", "value": fka, "inline": True},
{"name": "Kanal", "value": "Gruppe 200 (Strecke)", "inline": True}
]
}
send_to_discord(content="@here ⚠️ **ZUGFUNK-NOTRUF AUSGELÖST!** ⚠️", embed=embed)
elif data.event == "FDL_ANRUF":
# Automatische Generierung der FDL-Nummer nach Schema FDL-[BETRIEBSSTELLENABKÜRZUNG]
bs = data.betriebsstelle if data.betriebsstelle else "Zentral"
fdl_rufnummer = f"FDL-{bs}"
embed = {
"title": "📞 Gesprächsaufbau zu Stellwerk",
"color": 3447003,
"fields": [
{"name": "Von Zug (FKA)", "value": fka, "inline": True},
{"name": "Angewählte Betriebsstelle", "value": bs, "inline": True},
{"name": "GSM-R FDL-Nummer", "value": fdl_rufnummer, "inline": True}
]
}
send_to_discord(content=f"📞 Eingehender Ruf bei **{fdl_rufnummer}** (von Zug {data.zugnummer})", embed=embed)
elif data.event == "TRENNEN":
embed = {
"title": "📴 Abmeldung / Verbindung beendet",
"color": 15105570,
"description": f"Zug {data.zugnummer} hat sich abgemeldet."
}
send_to_discord(content=f"⚪ Zug {data.zugnummer} abgemeldet.", embed=embed)
return {"status": "Event verarbeitet", "fka": fka}
# Das vollständige Frontend als integrierter HTML-String
HTML_CONTENT = """<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Zug-Führerstand: GSM-R & GitHub Fahrplan</title>
<style>
body {
background-color: #1a1a1a;
color: #ffffff;
font-family: 'Arial', sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
padding: 20px;
box-sizing: border-box;
}
.cab-setup {
display: flex;
gap: 30px;
background-color: #222222;
padding: 30px;
border-radius: 16px;
box-shadow: 0 15px 35px rgba(0,0,0,0.8);
border: 2px solid #333;
}
.panel {
background-color: #333333;
border: 6px solid #444444;
border-radius: 12px;
padding: 20px;
width: 400px;
box-shadow: inset 0 0 10px rgba(0,0,0,0.5);
}
h3 {
margin-top: 0;
text-align: center;
text-transform: uppercase;
font-size: 14px;
letter-spacing: 1px;
color: #aaa;
border-bottom: 1px solid #444;
padding-bottom: 8px;
}
.display {
background-color: #7fa375;
color: #051405;
font-family: 'Courier New', monospace;
font-weight: bold;
padding: 15px;
border-radius: 6px;
height: 130px;
margin-bottom: 20px;
border: 3px solid #222;
box-shadow: inset 0 0 10px rgba(0,0,0,0.5);
font-size: 13px;
white-space: pre-wrap;
overflow-y: auto;
}
.db-fis-display {
background-color: #000000;
color: #ff3c00;
font-family: 'Courier New', monospace;
text-transform: uppercase;
font-weight: bold;
padding: 10px;
border: 4px solid #111;
border-radius: 4px;
height: 45px;
display: flex;
align-items: center;
justify-content: space-between;
box-shadow: 0 0 15px rgba(255, 60, 0, 0.4);
margin-bottom: 15px;
font-size: 15px;
letter-spacing: 1px;
}
.row { display: flex; gap: 10px; margin-bottom: 10px; }
.btn {
flex: 1;
padding: 12px;
background-color: #555555;
color: white;
border: 2px solid #222;
border-radius: 6px;
cursor: pointer;
font-weight: bold;
text-align: center;
user-select: none;
}
.btn:active { background-color: #444; }
.btn-notruf { background-color: #b30000; color: white; border-color: #660000; }
.btn-notruf:active { background-color: #8b0000; }
.btn-pfeil { background-color: #3b6285; border-color: #1f374d; font-size: 16px; }
input, select {
width: 100%;
padding: 8px;
margin-bottom: 10px;
background-color: #111;
color: #fff;
border: 1px solid #555;
border-radius: 4px;
box-sizing: border-box;
}
.form-group { margin-bottom: 12px; }
.hidden { display: none; }
</style>
</head>
<body>
<div class="cab-setup">
<!-- GSM-R Panel -->
<div class="panel">
<h3>📟 Zugfunk (GSM-R MESA 23)</h3>
<div id="display" class="display">🔒 GERÄT GESPERRT Bitte System-PIN eingeben, um Führerstand freizuschalten.</div>
<div id="pin-section">
<div class="form-group">
<label>System-PIN:</label>
<input type="password" id="input-pin" placeholder="****" maxlength="8">
</div>
<div class="btn" onclick="verifyPin()">🔓 Systeme hochfahren</div>
</div>
<div id="register-section" class="hidden">
<div class="form-group">
<label>Zugnummer (aus GitHub):</label>
<input type="text" id="input-zugnr" placeholder="z.B. 26815">
</div>
<div class="form-group">
<label>Rolle:</label>
<select id="input-rolle">
<option>Triebfahrzeugführer (Tf)</option>
<option>Rangierleiter</option>
</select>
</div>
<div class="btn" onclick="registerTrain()">📡 Zug anmelden & Fahrplan laden</div>
</div>
<div id="control-section" class="hidden">
<div class="form-group">
<label>Aktueller Standort (Betriebsstelle):</label>
<select id="input-betriebsstelle">
<option value="">-- Zuerst Fahrplan laden --</option>
</select>
</div>
<div class="row">
<div class="btn" onclick="triggerCall('FDL_ANRUF')">📞 FDL anrufen</div>
<div class="btn" onclick="triggerCall('TRENNEN')">❌ Trennen</div>
</div>
<div class="row">
<div class="btn" style="background-color:#d4a373; color:#222;" onclick="changeZugnummer()">🔄 Zug wechseln</div>
<div class="btn btn-notruf" onclick="triggerCall('NOTRUF')">🚨 NOTRUF</div>
</div>
</div>
</div>
<!-- FiS & Buchfahrplan Panel -->
<div class="panel">
<h3>📺 Fahrgastraum-Anzeige (ZID)</h3>
<div class="db-fis-display">
<span id="zid-line">---</span>
<span id="zid-station">ZID INAKTIV</span>
</div>
<h3>📑 Buchfahrplan / Ebula</h3>
<div id="fis-display" class="display" style="background-color: #2c3e50; color: #ecf0f1; height: 120px;">🔒 Ebula gesperrt.<br>Wartet auf Zuganmeldung...</div>
<div id="fis-active-section" class="hidden">
<div class="row">
<div class="btn btn-pfeil" onclick="prevStation()">◀ Vorheriger Halt</div>
<div class="btn btn-pfeil" onclick="nextStation()">Nächster Halt ▶</div>
</div>
</div>
</div>
</div>
<script>
let currentPin = "";
let currentZug = "";
let currentRolle = "";
let activeFahrplan = null;
let stationIndex = 0;
const display = document.getElementById("display");
const fisDisplay = document.getElementById("fis-display");
const zidLine = document.getElementById("zid-line");
const zidStation = document.getElementById("zid-station");
function verifyPin() {
const pin = document.getElementById("input-pin").value;
if (!pin) return alert("Bitte PIN eingeben!");
currentPin = pin;
display.innerHTML = "📡 DB Netz GSM-R\n📶 [|||||]\n\nGerät bereit.\nBitte Zugnummer eingeben.";
document.getElementById("pin-section").classList.add("hidden");
document.getElementById("register-section").classList.remove("hidden");
fisDisplay.innerHTML = "Ebula V2.4\nWartet auf Zugnummern-Abruf von GitHub...";
}
async function registerTrain() {
const zugnr = document.getElementById("input-zugnr").value.trim();
const rolle = document.getElementById("input-rolle").value;
if (!zugnr) return alert("Bitte eine Zugnummer eingeben!");
// Fahrplan von FastAPI Backend (GitHub) laden
try {
const res = await fetch(`/gsmr/fahrplan/${zugnr}`);
if (!res.ok) throw new Error("Zugnummer nicht in GitHub gefunden.");
activeFahrplan = await res.json();
} catch (err) {
alert("Fehler: " + err.message);
return;
}
currentZug = zugnr;
currentRolle = rolle;
stationIndex = 0;
const success = await sendEvent("LOGIN");
if (success) {
updateDisplayStatus("Netz eingeloggt");
document.getElementById("register-section").classList.add("hidden");
document.getElementById("control-section").classList.remove("hidden");
document.getElementById("fis-active-section").classList.remove("hidden");
populateBetriebsstellenDropdown();
updateEbulaAndZid();
} else {
alert("Fehler bei Registrierung (Falsche PIN?).");
}
}
function populateBetriebsstellenDropdown() {
const select = document.getElementById("input-betriebsstelle");
select.innerHTML = "";
activeFahrplan.fahrplan.forEach(halt => {
let opt = document.createElement("option");
opt.value = halt.bs;
opt.textContent = `${halt.bs} - ${halt.name}`;
select.appendChild(opt);
});
}
function changeZugnummer() {
sendEvent("TRENNEN");
currentZug = "";
activeFahrplan = null;
display.innerHTML = "📡 DB Netz GSM-R\n\nBitte neue Zugnummer eingeben.";
document.getElementById("control-section").classList.add("hidden");
document.getElementById("fis-active-section").classList.add("hidden");
document.getElementById("register-section").classList.remove("hidden");
fisDisplay.innerHTML = "Ebula zurückgesetzt.";
zidLine.innerHTML = "---";
zidStation.innerHTML = "ZID INAKTIV";
}
fn updateDisplayStatus(statusText) {
// Syntax-Korrektur für Funktion
}
function updateDisplayStatus(statusText) {
const prefix = currentRolle.includes("Tf") ? "01" : "02";
display.innerHTML = `📡 DB Netz GSM-R | 📶 [|||||]\n---------------------------\nZugnummer: ${currentZug}\nFKA: ${prefix}${currentZug}\nStatus: ${statusText}`;
}
function updateEbulaAndZid() {
if (!activeFahrplan || !activeFahrplan.fahrplan.length) return;
const current = activeFahrplan.fahrplan[stationIndex];
const next = activeFahrplan.fahrplan[stationIndex + 1] ? activeFahrplan.fahrplan[stationIndex + 1].name : "Endstation";
// Dropdown synchronisieren
document.getElementById("input-betriebsstelle").value = current.bs;
fisDisplay.innerHTML = `Linie: ${activeFahrplan.linie}\\nAktuell: ${current.name} (${current.bs})\\nAn: ${current.an} | Ab: ${current.ab}\\nNächster Halt: ${next}`;
zidLine.innerHTML = activeFahrplan.linie;
const isEnd = stationIndex === activeFahrplan.fahrplan.length - 1;
zidStation.innerHTML = isEnd ? `Ziel: ${current.name}` : `Nächster Halt: ${current.name}`;
}
function nextStation() {
if (!activeFahrplan) return;
if (stationIndex < activeFahrplan.fahrplan.length - 1) {
stationIndex++;
updateEbulaAndZid();
}
}
function prevStation() {
if (!activeFahrplan) return;
if (stationIndex > 0) {
stationIndex--;
updateEbulaAndZid();
}
}
async function triggerCall(eventType) {
const selectedBs = document.getElementById("input-betriebsstelle").value;
const fdlKennung = `FDL-${selectedBs}`;
if (eventType === "NOTRUF") {
display.innerHTML = `🚨🚨 NOTRUF AKTIV 🚨🚨\\n---------------------------\nSende Notrufsignal an Gruppe 200...`;
} else if (eventType === "FDL_ANRUF") {
display.innerHTML = `📞 Verbindung aufbauen...\\n---------------------------\nRufnummer: ${fdlKennung}\\nSprachkanal offen.`;
} else if (eventType === "TRENNEN") {
updateDisplayStatus("Verbindung getrennt");
}
await sendEvent(eventType, selectedBs);
}
async function sendEvent(eventType, betriebsStelle = "") {
try {
const response = await fetch("/gsmr/event", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
zugnummer: currentZug || "00000",
rolle: currentRolle || "Triebfahrzeugführer (Tf)",
event: eventType,
pin: currentPin,
betriebsstelle: betriebsStelle
})
});
return response.ok;
} catch (error) {
console.error(error);
return false;
}
}
</script>
</body>
</html>
"""
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860) |