Spaces:
Sleeping
Sleeping
Download app.py from RSBofficial/RSB_GSM-R: direct link, hf CLI and curl.
- Browser
- Download file 18.5 kB
-
https://huggingface.co/spaces/RSBofficial/RSB_GSM-R/resolve/main/app.py
- Command line
-
hf download hf://spaces/RSBofficial/RSB_GSM-R/app.py
-
curl -L -o app.py https://huggingface.co/spaces/RSBofficial/RSB_GSM-R/resolve/main/app.py
18.5 kB
| 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) | |
| def get_gui(): | |
| return HTML_CONTENT | |
| # API-Endpunkt für Fahrpläne aus GitHub | |
| 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 | |
| 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) |