From 00a771c7e09b2cdb150ecacd2e3b853c59210fde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Paluch?= Date: Wed, 21 Oct 2026 17:06:14 +0200 Subject: [PATCH] Proaktywny ATC: sam inicjuje kontakt (ruch, faza lotu, nowe lotnisko) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- PythonPlugins/PI_XSayATC.py | 135 ++++++++++++++++++++++++++++-- PythonPlugins/config.example.json | 6 +- 2 files changed, 130 insertions(+), 11 deletions(-) diff --git a/PythonPlugins/PI_XSayATC.py b/PythonPlugins/PI_XSayATC.py index b89dbdc..d14c64a 100644 --- a/PythonPlugins/PI_XSayATC.py +++ b/PythonPlugins/PI_XSayATC.py @@ -90,6 +90,12 @@ DEFAULT_CONFIG = { # _global.txt = zawsze dolaczane; .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( diff --git a/PythonPlugins/config.example.json b/PythonPlugins/config.example.json index c047414..6bd304c 100644 --- a/PythonPlugins/config.example.json +++ b/PythonPlugins/config.example.json @@ -3,8 +3,10 @@ "model": "", "temperature": 0.7, "max_tokens": 512, - "system_prompt": "You are a concise, professional air traffic controller in X-Plane 12. Give short, clear, realistic ATC instructions. Use standard phraseology. You have access to the pilot's current flight context (position, altitude, speed, heading, transponder, radio frequencies, nearest airport, weather) and to nearby traffic. IMPORTANT: adopt the role of the facility the pilot is currently tuned to (the 'Tuned facility' field): Delivery/Clearance gives IFR/VFR clearances and squawk codes; Ground issues taxi instructions; Tower controls takeoff, landing and the active runway; Tracon/Approach handles arrivals, departures and vectors; Center handles enroute. If 'Tuned facility' is 'None', act as a generic ATC using the active COM frequency. HANDOFF RULE (very important): when you finish with the pilot, you MUST hand them off to the next facility exactly like real ATC, using standard phraseology such as 'contact Ground on 121.900', 'contact Tower on 118.300', or 'frequency change approved'. Use the 'Airport frequencies' list to give the correct frequency for the 'Next expected facility'. If the next facility has several frequencies, pick the most plausible one and state it clearly. Use the nearby traffic list when issuing traffic advisories (e.g. bearing in clock positions and distance). Respond with ATC instructions only, no extra commentary.", + "system_prompt": "You are a concise, professional air traffic controller in X-Plane 12. Give short, clear, realistic ATC instructions. Use standard phraseology. You have access to the pilot's current flight context (position, altitude, speed, heading, transponder, radio frequencies, nearest airport, weather) and to nearby traffic. IMPORTANT: adopt the role of the facility the pilot is currently tuned to (the 'Tuned facility' field): Delivery/Clearance gives IFR/VFR clearances and squawk codes; Ground issues taxi instructions; Tower controls takeoff, landing and the active runway; Tracon/Approach handles arrivals, departures and vectors; Center handles enroute. If 'Tuned facility' is 'None', act as a generic ATC using the active COM frequency. HANDOFF RULE (very important): when you finish with the pilot, you MUST hand them off to the next facility exactly like real ATC, using standard phraseology such as 'contact Ground on 121.900', 'contact Tower on 118.300', or 'frequency change approved'. Use the 'Airport frequencies' list to give the correct frequency for the 'Next expected facility'. If the next facility has several frequencies, pick the most plausible one and state it clearly. DIRECTION: use the 'Flight phase' field. On DEPARTURE the flow is Delivery->Ground->Tower->Departure->Center (so Tower hands off to Departure). On ARRIVAL the flow is Center->Approach->Tower->Ground (so Tower hands off to Ground). Never hand off to yourself (e.g. Tower must NOT say 'contact Tower'). Use the nearby traffic list when issuing traffic advisories (e.g. bearing in clock positions and distance). Respond with ATC instructions only, no extra commentary.", "include_flight_context": true, "no_think": true, - "window_always_on_top": true + "window_always_on_top": true, + "proactive_enabled": true, + "proactive_cooldown": 30 }