ATC: role wg częstotliwości, handoff, częstotliwości lotnisk z apt.dat

- poprawne czytanie częstotliwości (fallback cockpit2/radios/actuators)
- reset rozmowy przy zmianie służby ATC (Ground/Tower/...)
- zbieranie częstotliwości lotniska z apt.dat (Global Airports)
- handoff ATC z podaniem realnej częstotliwości następnej służby
- faza lotu (na ziemi / w powietrzu) z AGL
- wyświetlanie częstotliwości w oknie głównym (odświeżanie ręczne)
- fix menu Konfiguracja (refCon zamiast indeksu)
This commit is contained in:
pali112 committed 2026-10-21 16:33:34 +02:00
1 parent 2b3269c683
commit 16b1d7795a
2 files changed
+290 -17

No files matched your search

+289 -16
View File
@@ -52,6 +52,12 @@ DEFAULT_CONFIG = {
"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."
@@ -91,9 +97,9 @@ CONTEXT_DATAREFS = [
("sim/flightmodel/position/groundspeed", "GS", 1.943844, "kt"),
("sim/flightmodel/position/mag_psi", "HDG (mag)", 1.0, "deg"),
("sim/cockpit/radios/transponder_code", "Squawk", 1.0, ""),
("sim/cockpit/radios/com1_freq_hz", "COM1", 0.001, "MHz"),
("sim/cockpit/radios/com2_freq_hz", "COM2", 0.001, "MHz"),
("sim/cockpit/radios/nav1_freq_hz", "NAV1", 0.001, "MHz"),
("sim/cockpit/radios/com1_freq_hz", "COM1", 0.01, "MHz"),
("sim/cockpit/radios/com2_freq_hz", "COM2", 0.01, "MHz"),
("sim/cockpit/radios/nav1_freq_hz", "NAV1", 0.01, "MHz"),
]
TAILNUM_DATAREF = "sim/aircraft/view/acf_tailnum"
@@ -102,6 +108,15 @@ TUNED1_DATAREF = "sim/atc/com1_tuned_facility"
TUNED2_DATAREF = "sim/atc/com2_tuned_facility"
ELEVATION_DATAREF = "sim/flightmodel/position/elevation"
# Nowoczesne datarefy radiowe (cockpit2/radios/actuators). Samoloty z wlasnym
# systemem radiowym (Garmin / REP / Toliss / Zibo) czesto zapisuja czestotliwosc
# TU, a legacy sim/cockpit/radios/*_freq_hz zostaje 0. Uzywamy jako fallback.
RADIO_MODERN_DATAREFS = {
"sim/cockpit/radios/com1_freq_hz": "sim/cockpit2/radios/actuators/com1_frequency_hz",
"sim/cockpit/radios/com2_freq_hz": "sim/cockpit2/radios/actuators/com2_frequency_hz",
"sim/cockpit/radios/nav1_freq_hz": "sim/cockpit2/radios/actuators/nav1_frequency_hz",
}
# Mapa typu sluzby ATC (sim/atc/*_tuned_facility)
FACILITY_NAMES = {
0: "None",
@@ -124,6 +139,31 @@ TCAS_ICAO_TYPE_DATAREF = "sim/cockpit2/tcas/targets/icao_type"
# Ile slotow TCAS sprawdzac (X-Plane ma tablice float[64])
NUM_TCAS_SLOTS = 64
# Typy sluzb ATC w plikach scenery apt.dat (kolumna 1, wiersze 1050-1056)
# 1050=ATIS/AWOS/ASOS, 1051=UNICOM/CTAF, 1052=Delivery/Clearance,
# 1053=Ground, 1054=Tower, 1055=Approach, 1056=Departure
APT_FREQ_CODES = {
"1050": "ATIS",
"1051": "UNICOM/CTAF",
"1052": "Delivery/Clearance",
"1053": "Ground",
"1054": "Tower",
"1055": "Approach",
"1056": "Departure",
}
# Sluzby ATC, ktore powinny przy przelaczeniu podac nastepna czestotliwosc.
# Kolejnosc zyciowa: Delivery -> Ground -> Tower -> Departure -> Center -> Approach.
NEXT_FACILITY_HINT = {
"Delivery/Clearance": "Ground",
"Ground": "Tower",
"Tower": "Departure/Tracon",
"Tracon/Approach-Departure": "Center",
"Center": "Approach/Tracon",
}
ELEVATION_AGL_DATAREF = "sim/flightmodel/position/y_agl"
class XSayATC:
def __init__(self):
@@ -132,6 +172,7 @@ class XSayATC:
self._resolved_datarefs = False
self._tailnum_ref = None
self._vr_ref = None
self._modern_radio_refs = {}
# Stan rozmowy
self.messages = [] # lista slownikow {"role": "user"/"assistant"/"system", "text": str}
@@ -152,6 +193,10 @@ class XSayATC:
self._menu_open_idx = None
self._menu_cfg_idx = None
# Cache wyswietlania czestotliwosci w oknie glownym
self._freq_display_cache = None # (icao, [linie]) lub None
self._freq_display_ts = 0.0
# VR
self._last_vr = None
@@ -160,6 +205,17 @@ class XSayATC:
self._record_proc = None
self._ptt_toggled = False # dla trybu "toggle"
# Sluzba ATC, na ktora bylismy ostatnio nastrojeni (do resetu rozmowy)
self._last_facility = None
# Czestotliwosci lotnisk z apt.dat (leniwie wczytywane w tle)
self._apt_freqs = {} # ICAO -> {kategoria: [freq_khz, ...]}
self._apt_loading = False
self._apt_loaded = False
self._elevation_agl_ref = None
# Cache najblizszego lotniska (czasowy, zeby nie iterowac navaidow co klatke)
self._nearest_icao_cache = None # (icao, timestamp)
# ---------------------------- Config ----------------------------
def _load_config(self):
cfg = dict(DEFAULT_CONFIG)
@@ -190,6 +246,7 @@ class XSayATC:
self._tuned1_ref = xp.findDataRef(TUNED1_DATAREF)
self._tuned2_ref = xp.findDataRef(TUNED2_DATAREF)
self._elevation_ref = xp.findDataRef(ELEVATION_DATAREF)
self._elevation_agl_ref = xp.findDataRef(ELEVATION_AGL_DATAREF)
# Datarefy TCAS (ruch z LiveTraffic / AI / multiplayer)
self._tcas_bearing_ref = xp.findDataRef(TCAS_BEARING_DATAREF)
self._tcas_distance_ref = xp.findDataRef(TCAS_DISTANCE_DATAREF)
@@ -197,6 +254,11 @@ class XSayATC:
self._tcas_num_ref = xp.findDataRef(TCAS_NUM_ACF_DATAREF)
self._tcas_flightid_ref = xp.findDataRef(TCAS_FLIGHT_ID_DATAREF)
self._tcas_icao_ref = xp.findDataRef(TCAS_ICAO_TYPE_DATAREF)
# Nowoczesne datarefy radiowe jako fallback
self._modern_radio_refs = {
name: xp.findDataRef(modern)
for name, modern in RADIO_MODERN_DATAREFS.items()
}
self._resolved_datarefs = True
def _get_dataref(self, name, is_float=True):
@@ -210,6 +272,27 @@ class XSayATC:
except Exception:
return None
def _get_radio_hz(self, name):
"""Czyta czestotliwosc radia (int, 10 kHz). Najpierw legacy
sim/cockpit/radios/*_freq_hz, a jesli 0 -> nowoczesny cockpit2."""
legacy = self.datarefs.get(name)
legacy_v = 0
try:
if legacy is not None:
legacy_v = xp.getDatai(legacy)
except Exception:
legacy_v = 0
modern_ref = self._modern_radio_refs.get(name)
modern_v = 0
if modern_ref is not None:
try:
modern_v = xp.getDatai(modern_ref)
except Exception:
modern_v = 0
if not legacy_v and not modern_v:
xp.log(f"[XSayATC] radio {name}: legacy i modern = 0 (radio wylaczone?)")
return legacy_v or modern_v
def _read_string(self, dref):
try:
return xp.getDatas(dref)
@@ -221,19 +304,32 @@ class XSayATC:
"""Zbiera kontekst lotu. WYWOLYWAC TYLKO na glownym watku."""
ctx = {}
lines = []
INT_RADIO_DATAREFS = (
"sim/cockpit/radios/transponder_code",
"sim/cockpit/radios/com1_freq_hz",
"sim/cockpit/radios/com2_freq_hz",
"sim/cockpit/radios/nav1_freq_hz",
)
RADIO_FREQ_DATAREFS = (
"sim/cockpit/radios/com1_freq_hz",
"sim/cockpit/radios/com2_freq_hz",
"sim/cockpit/radios/nav1_freq_hz",
)
for name, label, mult, unit in CONTEXT_DATAREFS:
v = self._get_dataref(name, is_float=(name != "sim/cockpit/radios/transponder_code"))
if name in RADIO_FREQ_DATAREFS:
# Czestotliwosc radia czytana z fallbackiem na cockpit2
v = self._get_radio_hz(name)
val = int(v) * mult
ctx[label] = val
lines.append(f"{label}: {val:.3f} {unit}".strip())
continue
v = self._get_dataref(name, is_float=(name not in INT_RADIO_DATAREFS))
if v is None:
continue
if name == "sim/cockpit/radios/transponder_code":
ctx[label] = int(v)
lines.append(f"{label}: {int(v)}")
elif name in ("sim/cockpit/radios/com1_freq_hz",
"sim/cockpit/radios/com2_freq_hz",
"sim/cockpit/radios/nav1_freq_hz"):
val = v * mult
ctx[label] = val
lines.append(f"{label}: {val:.3f} {unit}".strip())
else:
val = v * mult
ctx[label] = val
@@ -265,6 +361,32 @@ class XSayATC:
ctx["TunedFacility"] = "None"
lines.append("Tuned facility: None (no active ATC service on COM1/COM2)")
# Faza lotu (na ziemi / w powietrzu) z AGL
agl_m = self._get_agl()
on_ground = (agl_m is not None and agl_m < 1.0)
ctx["Phase"] = "ground" if on_ground else "airborne"
lines.append("Phase: " + ("on ground (taxi/ramp)" if on_ground else "airborne"))
# Czestotliwosci najblizszego lotniska (do podpowiedzi nastepnej czestotliwosci)
icao = self._nearest_airport_icao()
if icao:
ctx["NearestAirport"] = icao
lines.append(f"Nearest airport: {icao}")
freq_lines = self._format_airport_freqs(icao)
if freq_lines:
lines.append("Airport frequencies:")
lines.extend(freq_lines)
ctx["AirportFreqs"] = freq_lines
else:
lines.append("Airport frequencies: (not available)")
# Podpowiedz nastepna sluzbe, na ktora pilot ma sie przelaczyc
if tuned:
nxt = self._next_facility_hint(tuned[0])
if nxt:
ctx["NextFacility"] = nxt
lines.append(f"Next expected facility (per standard flow): {nxt}")
# Ruch lotniczy w poblizu
traffic_lines = self._collect_traffic()
ctx["Traffic"] = traffic_lines
@@ -292,14 +414,32 @@ class XSayATC:
except Exception:
return None
def _get_agl(self):
"""Zwraca wysokosc AGL w metrach (lub None)."""
if self._elevation_agl_ref is None:
return None
try:
return xp.getDataf(self._elevation_agl_ref)
except Exception:
return None
def _procedures_dir(self):
"""Zwraca sciezke katalogu procedur."""
if self.config.get("procedures_dir"):
return self.config["procedures_dir"]
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "procedures")
def _nearest_airport_icao(self):
"""Zwraca ICAO najblizszego lotniska (z natywnej bazy navaidow)."""
def _nearest_airport_icao(self, force=False):
"""Zwraca ICAO najblizszego lotniska (z natywnej bazy navaidow).
Skan calej bazy navaidow jest ciezki, wiec normalnie wynik jest
cache'owany (10 s). force=True wymusza ponowny skan."""
import time as _time
now = _time.time()
if not force and self._nearest_icao_cache is not None:
c_icao, c_ts = self._nearest_icao_cache
if now - c_ts < 10.0:
return c_icao
lat = self._get_dataref("sim/flightmodel/position/latitude", is_float=True)
lon = self._get_dataref("sim/flightmodel/position/longitude", is_float=True)
if lat is None or lon is None:
@@ -319,6 +459,7 @@ class XSayATC:
best_dist = dist
best_id = getattr(info, "navAidID", None)
nav = xp.getNextNavAid(nav)
self._nearest_icao_cache = (best_id, now)
return best_id
except Exception as e:
xp.log(f"[XSayATC] Blad szukania lotniska: {e}")
@@ -355,6 +496,120 @@ class XSayATC:
parts.append(f"[Procedures for {icao.upper()}]\n" + t)
return "\n\n".join(parts)
# ---------------------------- Czestotliwosci lotnisk (apt.dat) ----------------------------
def _airport_freq_path(self):
"""Zwraca sciezke do apt.dat Global Airports (najwieksza baza lotnisk)."""
try:
xp_dir = xp.getSystemPath()
except Exception:
xp_dir = None
if xp_dir:
p = os.path.join(xp_dir, "Global Scenery", "Global Airports", "Earth nav data", "apt.dat")
if os.path.exists(p):
return p
# Fallback: zgadnij wzgledem tego pliku (Resources/plugins/PythonPlugins)
here = os.path.dirname(os.path.abspath(__file__))
p = os.path.normpath(os.path.join(here, "..", "..", "..", "Global Scenery",
"Global Airports", "Earth nav data", "apt.dat"))
if os.path.exists(p):
return p
return None
def _ensure_apt_freqs(self):
"""Wczytuje czestotliwosci z apt.dat w tle (raz, leniwie)."""
if self._apt_loaded or self._apt_loading:
return
path = self._airport_freq_path()
if not path:
self._apt_loaded = True
xp.log("[XSayATC] Nie znaleziono apt.dat (Global Airports)")
return
self._apt_loading = True
threading.Thread(target=self._parse_apt_freqs, args=(path,), daemon=True).start()
def _parse_apt_freqs(self, path):
"""Watek roboczy: parsuje apt.dat i zapisuje self._apt_freqs."""
freqs = {}
try:
cur_icao = None
with open(path, "r", encoding="utf-8", errors="ignore") as f:
for line in f:
parts = line.split()
if not parts:
continue
code = parts[0]
# Wiersz naglowka lotniska: 1|16|17 ... ICAO Nazwa
if code in ("1", "16", "17") and len(parts) >= 5:
cur_icao = parts[4]
freqs.setdefault(cur_icao, {})
continue
# Wiersz czestotliwosci: 1050-1056 FREQ NAZWA
if code in APT_FREQ_CODES and len(parts) >= 2:
cat = APT_FREQ_CODES[code]
try:
freq_khz = int(parts[1])
except ValueError:
continue
if cur_icao:
freqs.setdefault(cur_icao, {}).setdefault(cat, []).append(freq_khz)
self._apt_freqs = freqs
except Exception as e:
xp.log(f"[XSayATC] Blad parsowania apt.dat: {e}")
self._apt_freqs = {}
finally:
self._apt_loaded = True
self._apt_loading = False
def _airport_freqs(self, icao):
"""Zwraca slownik {kategoria: [freq_khz, ...]} dla lotniska (albo {})."""
self._ensure_apt_freqs()
if not icao:
return {}
return self._apt_freqs.get(icao.upper(), self._apt_freqs.get(icao, {}))
def _format_airport_freqs(self, icao):
"""Zwraca liste linii tekstowych z czestotliwosciami lotniska."""
freqs = self._airport_freqs(icao)
if not freqs:
return []
lines = []
order = ["ATIS", "Delivery/Clearance", "Ground", "Tower", "Departure", "Approach", "UNICOM/CTAF"]
for cat in order:
vals = freqs.get(cat)
if not vals:
continue
for f in vals:
lines.append(f" {cat}: {f / 1000.0:.3f} MHz")
# Ewentualne kategorie spoza listy (np. inne nazwy)
for cat, vals in freqs.items():
if cat in order:
continue
for f in vals:
lines.append(f" {cat}: {f / 1000.0:.3f} MHz")
return lines
def _next_facility_hint(self, name):
"""Zwraca nastepna sluzbe ATC wg zyciowej kolejnosc, jesli znana."""
if not name:
return None
return NEXT_FACILITY_HINT.get(name)
def _freq_display_lines(self):
"""Zwraca (icao, [linie]) czestotliwosci z cache. NIE liczy nic — tylko
zwraca to, co bylo ostatnio policzone (przez _refresh_freq_display)."""
if self._freq_display_cache is None:
return (None, [])
return self._freq_display_cache
def _refresh_freq_display(self):
"""Recznie (przycisk) przelicza najblizsze lotnisko i jego czestotliwosci."""
import time as _time
icao = self._nearest_airport_icao(force=True)
lines = self._format_airport_freqs(icao) if icao else []
self._freq_display_cache = (icao, lines)
self._freq_display_ts = _time.time()
return self._freq_display_cache
def _read_float_array(self, ref, count):
"""Czyta tablice float z datarefu. Zwraca liste lub []."""
if ref is None:
@@ -605,6 +860,7 @@ class XSayATC:
# Zbierz kontekst lotu NA GLOWNYM WATKU
flight_ctx_text = None
_ctx = None
if self.config.get("include_flight_context", True):
try:
_ctx, flight_ctx_text = self._collect_context()
@@ -612,6 +868,14 @@ class XSayATC:
xp.log(f"[XSayATC] Blad zbierania kontekstu: {e}")
flight_ctx_text = None
# Reset rozmowy przy zmianie sluzby ATC (Ground->Tower itp.),
# zeby model nie mieszal frazeologii poprzednich rol.
facility = _ctx.get("TunedFacility") if _ctx else None
if facility is not None and facility != self._last_facility:
self.messages = []
self.status = f"Przelaczono na: {facility}"
self._last_facility = facility
# Zbierz procedury ATC NA GLOWNYM WATKU (czytanie plikow/navaidow)
procedures_text = ""
try:
@@ -823,8 +1087,17 @@ class XSayATC:
imgui.text(self.status)
imgui.separator()
if imgui.button("Konfiguracja"):
self._open_config_window()
# Czestotliwosci najblizszego lotniska (odswiezane recznie przyciskiem)
if imgui.button("Odswiez czestotliwosci"):
self._refresh_freq_display()
icao, freq_lines = self._freq_display_lines()
if icao:
imgui.text(f"Czestotliwosci - {icao}:")
else:
imgui.text_colored("Czestotliwosci: (kliknij Odswiez)", 0.7, 0.7, 0.7, 1.0)
if freq_lines:
for ln in freq_lines:
imgui.text(ln)
def _draw_config(self, windowID, refCon):
imgui.text("Konfiguracja XSayATC")
@@ -903,7 +1176,7 @@ class XSayATC:
self._menu = xp.createMenu("XSayATC", None, 0, self._menu_handler, None)
self._menu_open_idx = xp.appendMenuItemWithCommand(
self._menu, "Pokaz/ukryj okno", self._cmd_toggle)
self._menu_cfg_idx = xp.appendMenuItem(self._menu, "Konfiguracja", None)
self._menu_cfg_idx = xp.appendMenuItem(self._menu, "Konfiguracja", "xsayatc_config")
# Okno glowne (ukryte domyslnie — pokaz klawiszem/menu "Pokaz/ukryj okno")
self._imgui_window = ImguiWindow(
@@ -994,7 +1267,7 @@ class XSayATC:
return 1
def _menu_handler(self, menuRef, itemRef):
if itemRef == self._menu_cfg_idx:
if itemRef == "xsayatc_config":
self._toggle_config_window()
def _toggle_main_window(self):
+1 -1
View File
@@ -3,7 +3,7 @@
"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. 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. 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