Proaktywny ATC: sam inicjuje kontakt (ruch, faza lotu, nowe lotnisko)

- monitor w flight loop (co 1s) sprawdza wyzwalacze
- wyzwalacze: zmiana fazy (start/lądowanie), bliski ruch <5nm, nowe lotnisko w przylocie
- cooldown konfigurowalny (domyślnie 30s) zapobiega spamowaniu
- ATC inicjuje wiadomość w aktualnej roli (bez wiadomości pilota)
- checkbox + slider w oknie konfiguracji
This commit is contained in:
pali112 committed 2026-10-21 17:06:14 +02:00
1 parent 3c32bd97da
commit 00a771c7e0
2 files changed
+130 -11

No files matched your search

+126 -9
View File
@@ -90,6 +90,12 @@ DEFAULT_CONFIG = {
# _global.txt = zawsze dolaczane; <ICAO>.txt = per-lotnisko.
"procedures_dir": "",
"use_procedures": True,
# --- Proaktywny ATC ---
# Gdy wlaczone, ATC sam inicjuje kontakt (np. traffic advisory, zmiana fazy
# lotu), zamiast tylko odpowiadac na Twoje wiadomosci.
"proactive_enabled": True,
# Minimalny odstęp (sekundy) miedzy dwoma proaktywnymi komunikatami.
"proactive_cooldown": 30,
}
# Dataref -> (nazwa kontekstu, mnoznik, jednostka)
@@ -226,6 +232,11 @@ class XSayATC:
# Determinuje handoff Tower/Ground/Approach/Departure.
self.flight_phase = "departure" # "departure" | "arrival"
# Proaktywny ATC (sam inicjuje kontakt)
self._proactive_last_ts = 0.0 # timestamp ostatniego proaktywnego komunikatu
self._proactive_last_phase = None # ostatnia znana faza (ground/airborne)
self._proactive_announced_airports = set() # lotniska, na ktorych juz powitalismy/przegadalismy
# Czestotliwosci lotnisk z apt.dat (leniwie wczytywane w tle)
self._apt_freqs = {} # ICAO -> {kategoria: [freq_khz, ...]}
self._apt_loading = False
@@ -791,9 +802,10 @@ class XSayATC:
xp.log(f"[XSayATC] Nie mozna pobrac modelu: {e}")
return None
def _build_messages(self, user_text, flight_ctx_text, procedures_text):
def _build_messages(self, user_text, flight_ctx_text, procedures_text, proactive_reason=None):
"""Buduje liste messages. flight_ctx_text i procedures_text musza byc
przekazane (bez odczytu datarefow / plikow na watku roboczym)."""
przekazane (bez odczytu datarefow / plikow na watku roboczym).
proactive_reason != None -> ATC ma sie odezwac sam (bez wiadomosci pilota)."""
msgs = []
sp = self.config.get("system_prompt", "")
if self.config.get("no_think", True) and sp and "/no_think" not in sp:
@@ -809,7 +821,14 @@ class XSayATC:
for m in self.messages[-12:]:
msgs.append({"role": m["role"], "content": m["text"]})
msgs.append({"role": "user", "content": user_text})
if proactive_reason:
# ATC inicjuje kontakt — nie ma wiadomosci pilota, jest wyzwalacz.
msgs.append({"role": "system", "content":
"ATC PROACTIVE trigger: " + proactive_reason +
". You must now initiate contact with the pilot in your "
"current facility role, using standard phraseology."})
else:
msgs.append({"role": "user", "content": user_text})
return msgs
def _request(self, messages):
@@ -824,17 +843,21 @@ class XSayATC:
}
return requests.post(url, json=payload, stream=True, timeout=(10, 120))
def _run_stream(self, user_text, flight_ctx_text, procedures_text):
def _run_stream(self, user_text, flight_ctx_text, procedures_text, proactive_reason=None):
"""Watek roboczy: TYLKO siec i aktualizacja self.messages. Bez xp.getData*."""
self.streaming = True
self.status = "ATC mysli..."
# Historia do UI
self.messages.append({"role": "user", "text": user_text})
self.messages.append({"role": "assistant", "text": ""})
if proactive_reason:
# Brak wiadomosci pilota — ATC mowi sam. Zapisujemy tylko odpowiedz.
self.messages.append({"role": "assistant", "text": ""})
else:
self.messages.append({"role": "user", "text": user_text})
self.messages.append({"role": "assistant", "text": ""})
try:
messages = self._build_messages(user_text, flight_ctx_text, procedures_text)
messages = self._build_messages(user_text, flight_ctx_text, procedures_text, proactive_reason)
resp = self._request(messages)
resp.raise_for_status()
@@ -882,6 +905,13 @@ class XSayATC:
text = (text or "").strip()
if not text or self.streaming:
return
self._dispatch(text, None)
def _dispatch(self, user_text, proactive_reason):
"""Wspolna sciezka wysylania (tekst pilota lub wyzwalacz proaktywny).
Zbiera kontekst i procedury na glownym watku, potem startuje watek."""
if self.streaming:
return
# Zbierz kontekst lotu NA GLOWNYM WATKU
flight_ctx_text = None
@@ -911,7 +941,9 @@ class XSayATC:
self._stop_event.clear()
self._worker = threading.Thread(
target=self._run_stream, args=(text, flight_ctx_text, procedures_text), daemon=True)
target=self._run_stream,
args=(user_text, flight_ctx_text, procedures_text, proactive_reason),
daemon=True)
self._worker.start()
def stop(self):
@@ -1045,13 +1077,91 @@ class XSayATC:
except Exception as e:
xp.log(f"[XSayATC] Blad TTS: {e}")
# ---------------------------- Proaktywny ATC ----------------------------
def _proactive_check(self):
"""Sprawdza warunki i ewentualnie kaze ATC samodzielnie sie odezwac.
Wywolywane na glownym watku (z flight loop), co ~1 s. Samo wyslanie
do LLM idzie do watku roboczego przez _dispatch()."""
if not self.config.get("proactive_enabled", True):
return
if self.streaming:
return
import time as _time
now = _time.time()
cooldown = self.config.get("proactive_cooldown", 30)
if now - self._proactive_last_ts < cooldown:
return
reason = self._detect_proactive_reason()
if not reason:
return
# Zaznacz czas, zeby nie spamowac, i wyslij.
self._proactive_last_ts = now
self._dispatch("", reason)
def _detect_proactive_reason(self):
"""Wykrywa prosty wyzwalacz proaktywny. Zwraca opis powodu lub None."""
# 1) Zmiana fazy: ziemia -> powietrze (start) lub powietrze -> ziemia (ladowanie)
agl_m = self._get_agl()
if agl_m is not None:
phase = "ground" if agl_m < 1.0 else "airborne"
if self._proactive_last_phase is not None and phase != self._proactive_last_phase:
if phase == "airborne":
return "aircraft just became airborne (takeoff)"
else:
return "aircraft just touched down (landing)"
self._proactive_last_phase = phase
# 2) Nowe lotnisko w poblizu (podejscie/zbliżenie) — witamy raz.
icao = self._nearest_airport_icao()
if icao and icao not in self._proactive_announced_airports:
# Tylko gdy jestesmy w powietrzu (przylot) — nie przy starcie na ziemi.
if agl_m is not None and agl_m >= 1.0:
self._proactive_announced_airports.add(icao)
return f"pilot is approaching airport {icao}"
# 3) Bliski ruch (traffic advisory) — tylko jesli cos jest < 5 nm.
close = self._close_traffic(5.0)
if close:
return "nearby traffic within 5 nm (issue traffic advisory)"
return None
def _close_traffic(self, max_nm):
"""Zwraca liste bliskiego ruchu (dist_nm < max_nm). TYLKO glowny watek."""
bearing = self._read_float_array(self._tcas_bearing_ref, NUM_TCAS_SLOTS)
distance = self._read_float_array(self._tcas_distance_ref, NUM_TCAS_SLOTS)
if not distance:
return []
out = []
for i in range(NUM_TCAS_SLOTS):
if i >= len(distance):
break
dist_m = distance[i]
if not dist_m or dist_m <= 0:
continue
dist_nm = dist_m / 1852.0
if dist_nm < max_nm:
brg_rel = (bearing[i] % 360.0) if i < len(bearing) else 0.0
clock = int(round((brg_rel / 30.0) % 12)) or 12
out.append(f"{dist_nm:.1f} nm at {clock}:00")
return out
# ---------------------------- VR ----------------------------
def _vr_flight_loop(self, lastCall, elapsed, counter, refCon):
"""Co 1s sprawdza stan VR i ustawia tryb pozycjonowania okien (glowny watek)."""
"""Co 1s sprawdza stan VR i wywoluje monitor proaktywny (glowny watek)."""
vr = self._get_vr_enabled()
if vr != self._last_vr:
self._last_vr = vr
self._apply_vr_mode(vr)
# Proaktywny ATC (bezpiecznie w try/except, zeby nie wywalic pętli)
try:
self._proactive_check()
except Exception as e:
xp.log(f"[XSayATC] Blad monitora proaktywnego: {e}")
return 1.0
def _get_vr_enabled(self):
@@ -1177,6 +1287,13 @@ class XSayATC:
_, self.config["procedures_dir"] = imgui.input_text(
"Katalog procedur", self.config["procedures_dir"], 512)
imgui.separator()
imgui.text("Proaktywny ATC:")
_, self.config["proactive_enabled"] = imgui.checkbox(
"ATC sam inicjuje kontakt (ruch, faza lotu)", self.config["proactive_enabled"])
_, self.config["proactive_cooldown"] = imgui.slider_int(
"Odstep (s)", self.config["proactive_cooldown"], 5, 300)
imgui.separator()
imgui.text("System prompt (instrukcje ATC):")
_, self.config["system_prompt"] = imgui.input_text_multiline(