From 1705960c6eba3eaf0459b0896d019f48e5e540e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Paluch?= Date: Tue, 17 Nov 2026 11:38:32 +0100 Subject: [PATCH] XCoPilot - lokalny AI co-pilot dla X-Plane 12 (llama.cpp + sterowanie datarefami) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - PI_XCoPilot.py: co-pilot odpowiadajacy strukturalnym JSON-em z akcjami, ktore wtyczka wykonuje na datarefach/komendach X-Plane. - controls.json: mapowanie akcji -> datarefy (default + per-samolot), z kompletnym profilem Zibo 737-800X (laminar/B738/*) i przykładem ToLiss. - Okno widoczne w VR, głos (whisper STT + piper TTS), PTT. - config.example.json: przykładowa konfiguracja LLM/głosu. --- .gitignore | 7 + PythonPlugins/PI_XCoPilot.py | 1134 +++++++++++++++++++++++++++++ PythonPlugins/config.example.json | 20 + PythonPlugins/controls.json | 106 +++ README.md | 175 +++++ 5 files changed, 1442 insertions(+) create mode 100644 .gitignore create mode 100644 PythonPlugins/PI_XCoPilot.py create mode 100644 PythonPlugins/config.example.json create mode 100644 PythonPlugins/controls.json create mode 100644 README.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a8b8378 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +# Python +__pycache__/ +*.pyc +*.pyo + +# Lokalna konfiguracja (sciezki, adresy) — w repo tylko config.example.json +config.json diff --git a/PythonPlugins/PI_XCoPilot.py b/PythonPlugins/PI_XCoPilot.py new file mode 100644 index 0000000..fa76022 --- /dev/null +++ b/PythonPlugins/PI_XCoPilot.py @@ -0,0 +1,1134 @@ +# -*- coding: utf-8 -*- +""" +XCoPilot - lokalny co-pilot (drugi pilot / AI) dla X-Plane 12 (llama.cpp) + +Podlacza sie do lokalnego serwera llama.cpp (OpenAI-compat /v1/chat/completions), +czyta kontekst lotu z datarefow, a co-pilot ODPOWIADA STRUKTURALNYM JSON-em z +lista akcji, ktore wtyczka wykonuje NA DATAREFACH / KOMENDACH X-Plane. + +W odroznieniu od XSayATC (ATC tylko gada), co-pilot realnie STERUJE samolotem: +podnosi/chowa podwozie, klapy, ustawia autopilota, transponder itd. + +Kluczowa idea: plik controls.json mapuje NAZWY AKCJI ("gear_up", "set_heading") +na konkretne datarefy/komendy dla danego samolotu (per-Aircraft match po nazwie +ACF). AI widzi liste dostepnych akcji i wydaje polecenia uzywajac tylko tych +nazw - dzieki czemu nie zgaduje nazw datarefow i dziala dla kazdego samolotu. + +Wymaga: XPPython3 (Python 3.12 + imgui + requests). + +Konfiguracja: config.json (ustawienia LLM / glos) + controls.json (mapowanie +akcji na datarefy) obok tego pliku. + +WAZNE (bezpieczenstwo watkow): +- Odczyty ORAZ zapisy datarefow (xp.getData*, xp.setData*, xp.command*) MUSZA + dzialac na glownym watku X-Plane. +- Watek roboczy robi WYLACZNIE siec (requests) i parsowanie JSON-a. Wynik + (lista akcji + tekst) trafia do kolejki, a glowna petla (flight loop) je + wykonuje bezpiecznie. +""" + +import json +import os +import threading +import subprocess +import time + +from XPPython3 import xp +from XPPython3.xp_imgui import Window as ImguiWindow + +import imgui +import requests + + +# -------------------------------------------------------------------------- +# Konfiguracja i domyslne wartosci +# -------------------------------------------------------------------------- + +CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json") +CONTROLS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "controls.json") + +DEFAULT_CONFIG = { + "base_url": "http://localhost:8081", # adres serwera llama.cpp + "model": "", # puste = pobierze pierwszy z /v1/models + "temperature": 0.3, # nizsza = bardziej deterministyczne akcje + "max_tokens": 512, + "system_prompt": ( + "You are a calm, concise co-pilot (second pilot) in X-Plane 12. " + "You can actually FLY the aircraft by issuing structured actions that the " + "simulator executes on datarefs and commands. " + "You have the pilot's current flight context (position, altitude, speed, " + "heading, autopilot, gear, flaps, transponder, etc.) and a list of AVAILABLE " + "CONTROLS (named actions you may use) with their meaning. " + "Respond in the pilot's language (Polish by default, unless the pilot writes " + "otherwise). " + "IMPORTANT OUTPUT FORMAT - always answer with ONE JSON object and nothing " + "else (no markdown, no prose around it):\n" + "{\n" + " \"say\": \"short spoken confirmation of what you will do\",\n" + " \"actions\": [\n" + " {\"control\": \"gear_up\"},\n" + " {\"control\": \"set_heading\", \"value\": 270}\n" + " ]\n" + "}\n" + "- \"say\" is REQUIRED (one short sentence).\n" + "- \"actions\" is a list; each item uses a control NAME from the AVAILABLE " + "CONTROLS list. Add \"value\" only for controls that need a parameter.\n" + "- Never invent control names or dataref paths. Use only names from the list.\n" + "- If no action is needed (just a question or answer), set \"actions\": [].\n" + "- If you cannot safely do what the pilot asks, say so and set actions to [].\n" + "Act as a competent, safety-conscious first officer. Confirm actions briefly " + "and speak naturally." + ), + "include_flight_context": True, + "no_think": True, # dodaje /no_think do promptu (modele Qwen3 z reasoningiem) + "window_always_on_top": True, + # --- Mapowanie akcji -> datarefy --- + "controls_file": "", # puste = controls.json obok wtyczki + # Pozwol AI uzywac surowych datarefow/komend bezposrednio w JSON + # ({"dref": "sim/...", "value": v} / {"command": "sim/..."}). Ryzykowne - + # AI moze wymyslic bledna sciezke. Zalecane: False (tylko nazwane akcje). + "allow_raw_actions": False, + # --- Glos (whisper / piper) --- + "voice_enabled": True, + "voice_ptt_mode": "hold", # "hold" | "toggle" + "whisper_cli": "/usr/bin/whisper-cli", + "whisper_model": "/home/pali112/models/ggml-small.bin", + "whisper_language": "auto", + "record_cmd": ["pw-record", "--format=s16", "--rate=16000", "--channels=1"], + "piper": "/opt/piper-tts/piper", + "piper_model": "/home/pali112/.local/share/piper-voices/en_US-lessac-medium.onnx", + "play_cmd": ["pw-play"], + "tts_enabled": True, +} + +# Dataref -> (nazwa kontekstu, mnoznik, jednostka, czy_int) +CONTEXT_DATAREFS = [ + ("sim/flightmodel/position/latitude", "Latitude", 1.0, "deg", False), + ("sim/flightmodel/position/longitude", "Longitude", 1.0, "deg", False), + ("sim/flightmodel/misc/h_ind", "Alt (baro)", 1.0, "ft", False), + ("sim/flightmodel/position/elevation", "Alt (MSL)", 1.0, "ft", False), + ("sim/flightmodel/position/y_agl", "AGL", 3.28084, "ft", False), + ("sim/flightmodel/position/indicated_airspeed", "IAS", 1.0, "kt", False), + ("sim/flightmodel/position/groundspeed", "GS", 1.943844, "kt", False), + ("sim/flightmodel/position/vh_ind_fpm", "VS", 1.0, "fpm", False), + ("sim/flightmodel/position/mag_psi", "HDG (mag)", 1.0, "deg", False), + ("sim/flightmodel/position/true_psi", "HDG (true)", 1.0, "deg", False), + ("sim/flightmodel/position/true_theta", "Pitch", 1.0, "deg", False), + ("sim/flightmodel/position/phi", "Roll", 1.0, "deg", False), + ("sim/cockpit/radios/transponder_code", "Squawk", 1.0, "", True), + ("sim/cockpit/radios/com1_freq_hz", "COM1", 0.01, "MHz", True), + ("sim/cockpit/radios/com2_freq_hz", "COM2", 0.01, "MHz", True), + # Autopilot / auto-throttle + ("sim/cockpit2/autopilot/autopilot_on", "AP on", 1.0, "", True), + ("sim/cockpit2/autopilot/autothrottle_on", "ATHR on", 1.0, "", True), + ("sim/cockpit2/autopilot/heading_dial_deg_mag_pilot", "AP HDG", 1.0, "deg", False), + ("sim/cockpit2/autopilot/altitude_dial_ft", "AP ALT", 1.0, "ft", False), + ("sim/cockpit2/autopilot/airspeed_dial_kts_mach", "AP SPD", 1.0, "kt", False), +] + +TAILNUM_DATAREF = "sim/aircraft/view/acf_tailnum" +ACF_PATH_DATAREF = "sim/aircraft/view/acf_path" +ACF_ICAO_DATAREF = "sim/aircraft/view/acf_ICAO" +VR_ENABLED_DATAREF = "sim/graphics/VR/enabled" + +# Typy datarefow XPLM (bitfield) +XPLM_TYPE_INT = 1 +XPLM_TYPE_FLOAT = 2 +XPLM_TYPE_DOUBLE = 4 +XPLM_TYPE_FLOAT_ARRAY = 8 +XPLM_TYPE_INT_ARRAY = 16 +XPLM_TYPE_DATA = 32 + + +class XCoPilot: + def __init__(self): + self.config = self._load_config() + self.controls = {"controls": {}, "state": {}} # aktualne mapowanie (po matchu) + self._controls_raw = {} # surowy controls.json + self._controls_mtime = 0.0 + + self.datarefs = {} # name -> dataref object (CONTEXT_DATAREFS) + self._resolved_datarefs = False + self._tailnum_ref = None + self._acf_path_ref = None + self._acf_icao_ref = None + self._vr_ref = None + + self._cmd_cache = {} # command name -> command ref + + # Stan rozmowy + self.messages = [] # {"role": ..., "text": ...} + self.activity = [] # log wykonanych akcji (do okna) + self.pending_text = "" + self.status = "Gotowy." + self.streaming = False + + self._model_cache = None + self._stop_event = threading.Event() + self._worker = None + + # Kolejka akcji (wypelnia watek roboczy, oproznia glowny watek) + self._pending_actions = [] # lista dictow {"control"/"dref"/"command", "value", ...} + self._pending_say = None # tekst do TTS (z "say") + + # Okna ImGui + self._imgui_window = None + self._config_window = None + + # Menu + self._menu = None + self._menu_cfg_idx = None + + # VR + self._last_vr = None + + # Glos (STT / TTS) + self._recording = False + self._record_proc = None + self._ptt_toggled = False + self._pending_send = None # tekst ze STT do wyslania na glownym watku + self._speak_lock = threading.Lock() + + # Cache aktualnego samolotu (acf path / icao) + self._acf_cache = None # (path, icao, ts) + + # ---------------------------- Config ---------------------------- + def _load_config(self): + cfg = dict(DEFAULT_CONFIG) + try: + with open(CONFIG_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + if isinstance(data, dict): + cfg.update(data) + except Exception: + pass + return cfg + + def _save_config(self): + try: + with open(CONFIG_FILE, "w", encoding="utf-8") as f: + json.dump(self.config, f, ensure_ascii=False, indent=2) + except Exception as e: + xp.log(f"[XCoPilot] Blad zapisu config.json: {e}") + + def _controls_path(self): + p = self.config.get("controls_file", "") + return p or CONTROLS_FILE + + # ---------------------------- Mapowanie akcji (controls.json) ---------------------------- + def _load_controls(self, force=False): + """Wczytuje controls.json i wybiera mapowanie dla aktualnego samolotu.""" + path = self._controls_path() + try: + mtime = os.path.getmtime(path) + except Exception: + mtime = 0.0 + if not force and self._controls_raw and mtime == self._controls_mtime: + self._select_controls() + return + try: + with open(path, "r", encoding="utf-8") as f: + raw = json.load(f) + except Exception as e: + xp.log(f"[XCoPilot] Blad wczytywania controls.json ({path}): {e}") + raw = {} + self._controls_raw = raw if isinstance(raw, dict) else {} + self._controls_mtime = mtime + self._select_controls() + + def _select_controls(self): + """Wyznacza aktywne mapowanie: default + (opcjonalny) override per-aircraft.""" + default = self._controls_raw.get("default", {}) or {} + base_controls = dict(default.get("controls", {}) or {}) + base_state = dict(default.get("state", {}) or {}) + + path, icao = self._current_acf() + chosen = None + for ac in self._controls_raw.get("aircraft", []) or []: + if not isinstance(ac, dict): + continue + match = (ac.get("match") or "").lower() + if not match: + continue + haystack = ((path or "") + " " + (icao or "")).lower() + if match in haystack: + chosen = ac + break + + if chosen: + # override: nadpisuje/rozszerza default (per-klucz) + for k, v in (chosen.get("controls", {}) or {}).items(): + base_controls[k] = v + for k, v in (chosen.get("state", {}) or {}).items(): + base_state[k] = v + + self.controls = {"controls": base_controls, "state": base_state} + self._matched_acf = chosen.get("match", "default") if chosen else "default" + + def _current_acf(self, force=False): + """Zwraca (path, icao) aktualnego samolotu (cache 5 s).""" + now = time.time() + if not force and self._acf_cache is not None: + p, i, ts = self._acf_cache + if now - ts < 5.0: + return p, i + path = self._read_string(self._acf_path_ref) or "" + icao = self._read_string(self._acf_icao_ref) or "" + self._acf_cache = (path, icao, now) + return path, icao + + # ---------------------------- Datarefs ---------------------------- + def _ensure_datarefs(self): + if self._resolved_datarefs: + return + for name, _l, _m, _u, _i in CONTEXT_DATAREFS: + self.datarefs[name] = xp.findDataRef(name) + self._tailnum_ref = xp.findDataRef(TAILNUM_DATAREF) + self._acf_path_ref = xp.findDataRef(ACF_PATH_DATAREF) + self._acf_icao_ref = xp.findDataRef(ACF_ICAO_DATAREF) + self._vr_ref = xp.findDataRef(VR_ENABLED_DATAREF) + self._resolved_datarefs = True + + def _get_dataref(self, name, is_float=True): + d = self.datarefs.get(name) + if d is None: + return None + try: + if is_float: + return xp.getDataf(d) + return xp.getDatai(d) + except Exception: + return None + + def _read_string(self, dref): + if dref is None: + return None + try: + return xp.getDatas(dref) + except Exception: + return None + + def _ref_type_bits(self, ref): + try: + return int(xp.getDataRefTypes(ref)) + except Exception: + return 0 + + def _find_dref(self, path): + try: + return xp.findDataRef(path) + except Exception: + return None + + def _find_cmd(self, path): + if path in self._cmd_cache: + return self._cmd_cache[path] + try: + ref = xp.findCommand(path) + except Exception: + ref = None + self._cmd_cache[path] = ref + return ref + + # ---------------------------- Kontekst lotu (TYLKO glowny watek) ---------------------------- + def _collect_context(self): + """Zbiera kontekst lotu + liste dostepnych akcji. TYLKO glowny watek.""" + ctx = {} + lines = [] + + tail = self._read_string(self._tailnum_ref) + if tail and tail.strip(): + ctx["Callsign"] = tail.strip() + lines.append("Callsign: " + tail.strip()) + + path, icao = self._current_acf() + if path: + ctx["Aircraft"] = os.path.basename(path) + lines.append("Aircraft: " + os.path.basename(path)) + + for name, label, mult, unit, is_int in CONTEXT_DATAREFS: + v = self._get_dataref(name, is_float=not is_int) + if v is None: + continue + if is_int: + val = int(v) + ctx[label] = val + lines.append(f"{label}: {val}") + else: + val = v * mult + ctx[label] = val + unit_s = (" " + unit) if unit else "" + lines.append(f"{label}: {val:.1f}{unit_s}") + + # Stan z mapowania (state: nazwa -> dataref) + state_lines = self._collect_state() + if state_lines: + lines.append("Control state:") + lines.extend(state_lines) + ctx["ControlState"] = state_lines + + # Lista dostepnych akcji (z opisami) — kluczowa dla AI + avail = self._available_controls_desc() + if avail: + lines.append("AVAILABLE CONTROLS (use these exact names):") + lines.extend(avail) + ctx["AvailableControls"] = avail + + return ctx, "\n".join(lines) + + def _collect_state(self): + """Czyta datarefy stanu z mapowania 'state'. Zwraca liste linii.""" + out = [] + for name, dref_path in self.controls.get("state", {}).items(): + if not dref_path: + continue + ref = self._find_dref(dref_path) + if ref is None: + continue + bits = self._ref_type_bits(ref) + try: + if bits & XPLM_TYPE_DATA: + v = xp.getDatas(ref) + out.append(f" {name}: {v}") + elif bits & (XPLM_TYPE_INT | XPLM_TYPE_INT_ARRAY): + out.append(f" {name}: {int(xp.getDatai(ref))}") + else: + out.append(f" {name}: {float(xp.getDataf(ref)):.3f}") + except Exception as e: + xp.log(f"[XCoPilot] Blad odczytu stanu {name} ({dref_path}): {e}") + return out + + def _available_controls_desc(self): + """Zwraca liste linii opisujacych dostepne akcje (nazwa + opis + czy wymaga value).""" + out = [] + for name, ctrl in self.controls.get("controls", {}).items(): + if not isinstance(ctrl, dict): + continue + desc = ctrl.get("desc", "") + needs_value = self._control_needs_value(ctrl) + suffix = " (requires value)" if needs_value else "" + out.append(f" {name}{suffix}: {desc}") + return out + + def _control_needs_value(self, ctrl): + for op in ctrl.get("ops", []) or []: + v = op.get("value") + if isinstance(v, str) and "{value}" in v: + return True + return False + + # ---------------------------- Wykonywanie akcji (TYLKO glowny watek) ---------------------------- + def _execute_action(self, action): + """Wykonuje pojedyncza akcje z JSON-a. Zwraca opis (string) lub None. + + Obslugiwane formy: + {"control": "nazwa", "value": v} -> mapowanie controls.json + {"dref": "sim/...", "value": v} -> surowy zapis (gdy allow_raw_actions) + {"command": "sim/..."} -> surowa komenda (gdy allow_raw_actions) + """ + if "control" in action: + return self._execute_named(action.get("control"), action.get("value")) + if action.get("dref") and self.config.get("allow_raw_actions", False): + return self._execute_set_dref(action["dref"], action.get("value")) + if action.get("command") and self.config.get("allow_raw_actions", False): + ref = self._find_cmd(action["command"]) + if ref is None: + return f"command not found: {action['command']}" + try: + xp.commandOnce(ref) + except Exception as e: + return f"command error: {e}" + return f"cmd {action['command']}" + return None + + def _execute_named(self, name, value): + ctrl = self.controls.get("controls", {}).get(name) + if not isinstance(ctrl, dict): + return f"unknown control: {name}" + ops = ctrl.get("ops", []) or [] + results = [] + for op in ops: + if not isinstance(op, dict): + continue + if op.get("cmd"): + ref = self._find_cmd(op["cmd"]) + if ref is None: + results.append(f"{op['cmd']} (not found)") + continue + try: + xp.commandOnce(ref) + results.append(op["cmd"]) + except Exception as e: + results.append(f"{op['cmd']} err:{e}") + elif op.get("set"): + v = self._resolve_op_value(op["value"], value) + r = self._execute_set_dref(op["set"], v) + results.append(r or op["set"]) + elif op.get("toggle"): + r = self._execute_toggle_dref(op["toggle"]) + results.append(r or op["toggle"]) + return "; ".join(results) if results else f"{name} (no ops)" + + def _resolve_op_value(self, op_value, action_value): + """Op value moze byc literalem albo szablonem '{value}'.""" + if isinstance(op_value, str) and "{value}" in op_value: + return action_value + return op_value + + def _execute_set_dref(self, dref_path, value): + ref = self._find_dref(dref_path) + if ref is None: + return f"dref not found: {dref_path}" + bits = self._ref_type_bits(ref) + try: + if bits & XPLM_TYPE_DATA: + xp.setDatas(ref, str(value)) + return f"{dref_path}={value}" + if bits & (XPLM_TYPE_INT | XPLM_TYPE_INT_ARRAY): + iv = int(round(float(value))) + xp.setDatai(ref, iv) + return f"{dref_path}={iv}" + fv = float(value) + xp.setDataf(ref, fv) + return f"{dref_path}={fv}" + except Exception as e: + return f"{dref_path} err:{e}" + + def _execute_toggle_dref(self, dref_path): + ref = self._find_dref(dref_path) + if ref is None: + return f"dref not found: {dref_path}" + bits = self._ref_type_bits(ref) + try: + if bits & (XPLM_TYPE_INT | XPLM_TYPE_INT_ARRAY): + cur = int(xp.getDatai(ref)) + nv = 0 if cur else 1 + xp.setDatai(ref, nv) + return f"{dref_path}->{nv}" + cur = float(xp.getDataf(ref)) + nv = 0.0 if cur >= 0.5 else 1.0 + xp.setDataf(ref, nv) + return f"{dref_path}->{nv}" + except Exception as e: + return f"{dref_path} err:{e}" + + # ---------------------------- Komunikacja z LLM ---------------------------- + def _resolve_model(self): + if self._model_cache: + return self._model_cache + if self.config.get("model"): + self._model_cache = self.config["model"] + return self._model_cache + try: + r = requests.get(self.config["base_url"].rstrip("/") + "/v1/models", timeout=5) + r.raise_for_status() + models = (r.json().get("data") or []) + if models: + self._model_cache = models[0].get("id") + return self._model_cache + except Exception as e: + xp.log(f"[XCoPilot] Nie mozna pobrac modelu: {e}") + return None + + def _build_messages(self, user_text, flight_ctx_text): + msgs = [] + sp = self.config.get("system_prompt", "") + if self.config.get("no_think", True) and sp and "/no_think" not in sp: + sp = sp + "\n/no_think" + msgs.append({"role": "system", "content": sp}) + + if self.config.get("include_flight_context", True) and flight_ctx_text: + msgs.append({"role": "system", "content": + "Pilot's current flight context:\n" + flight_ctx_text}) + + for m in self.messages[-12:]: + msgs.append({"role": m["role"], "content": m["text"]}) + + msgs.append({"role": "user", "content": user_text}) + return msgs + + def _request(self, messages): + url = self.config["base_url"].rstrip("/") + "/v1/chat/completions" + model = self._resolve_model() or self.config.get("model") or "model" + payload = { + "model": model, + "messages": messages, + "temperature": self.config.get("temperature", 0.3), + "max_tokens": self.config.get("max_tokens", 512), + "stream": True, + } + return requests.post(url, json=payload, stream=True, timeout=(10, 120)) + + def _run_stream(self, user_text, flight_ctx_text): + """Watek roboczy: TYLKO siec + parsowanie. Bez xp.getData*/setData*.""" + self.streaming = True + self.status = "Co-pilot mysli..." + + self.messages.append({"role": "user", "text": user_text}) + self.messages.append({"role": "assistant", "text": ""}) + + try: + messages = self._build_messages(user_text, flight_ctx_text) + resp = self._request(messages) + resp.raise_for_status() + + buf = "" + for raw in resp.iter_lines(decode_unicode=True): + if self._stop_event.is_set(): + break + if not raw or not raw.startswith("data:"): + continue + data = raw[len("data:"):].strip() + if data == "[DONE]": + break + try: + chunk = json.loads(data) + except Exception: + continue + choices = chunk.get("choices") or [] + if not choices: + continue + delta = choices[0].get("delta") or {} + content = delta.get("content") + if content: + buf += content + self.messages[-1]["text"] = buf + + final = self.messages[-1]["text"].strip() + if not final: + final = "(brak odpowiedzi)" + self.messages[-1]["text"] = final + # Sparsuj JSON, przygotuj akcje i tekst do powiedzenia. + say, actions = self._parse_response(final) + self._pending_actions = actions + self._pending_say = say + self.status = "Gotowy." + except Exception as e: + xp.log(f"[XCoPilot] Blad zapytania: {e}") + self.status = f"Blad: {e}" + if self.messages and self.messages[-1]["role"] == "assistant": + if not self.messages[-1]["text"]: + self.messages[-1]["text"] = f"(blad: {e})" + finally: + self.streaming = False + + def _parse_response(self, text): + """Wyciaga z odpowiedzi (tekst + JSON) pare (say, actions).""" + # Tolerancyjne wyciagniecie pierwszego obiektu JSON + obj = self._extract_json(text) + if obj is None: + # Nie udalo sie sparsowac — traktuj calosc jako zwykla wypowiedz, + # bez akcji. + return text, [] + say = obj.get("say") if isinstance(obj, dict) else None + actions = obj.get("actions") if isinstance(obj, dict) else None + if not isinstance(actions, list): + actions = [] + # Jesli brak "say", zbuduj krotki opis z akcji (fallback do TTS/okna). + if not say: + say = self._describe_actions(actions) or "OK." + return say, actions + + def _extract_json(self, text): + """Zwraca pierwszy obiekt JSON w tekscie (albo None). Obsluguje code fence.""" + # Zdejmij ewentualny code fence ```json ... ``` + t = text.strip() + if t.startswith("```"): + lines = t.split("\n") + if lines and lines[0].startswith("```"): + lines = lines[1:] + if lines and lines[-1].strip() == "```": + lines = lines[:-1] + t = "\n".join(lines).strip() + # Proba bezposredniego parsowania calosci + try: + return json.loads(t) + except Exception: + pass + # Znajdz pierwszy '{' i pasujacy '}' (balans nawiasow) + start = t.find("{") + if start < 0: + return None + depth = 0 + in_str = False + esc = False + for i in range(start, len(t)): + c = t[i] + if in_str: + if esc: + esc = False + elif c == "\\": + esc = True + elif c == '"': + in_str = False + continue + if c == '"': + in_str = True + elif c == "{": + depth += 1 + elif c == "}": + depth -= 1 + if depth == 0: + try: + return json.loads(t[start:i + 1]) + except Exception: + return None + return None + + def _describe_actions(self, actions): + if not actions: + return "" + parts = [] + for a in actions: + if isinstance(a, dict): + name = a.get("control") or a.get("dref") or a.get("command") or "?" + if a.get("value") is not None: + parts.append(f"{name}={a['value']}") + else: + parts.append(str(name)) + else: + parts.append(str(a)) + return "Wykonuje: " + ", ".join(parts) + + def send(self, text): + """Wywolywane na glownym watku (przycisk / PTT).""" + text = (text or "").strip() + if not text or self.streaming: + return + self._dispatch(text) + + def _dispatch(self, user_text): + if self.streaming: + return + self.streaming = True + + # Odswiez mapowanie (mozesz edytowac controls.json w locie). + self._load_controls() + + flight_ctx_text = None + if self.config.get("include_flight_context", True): + try: + _ctx, flight_ctx_text = self._collect_context() + except Exception as e: + xp.log(f"[XCoPilot] Blad zbierania kontekstu: {e}") + flight_ctx_text = None + + self._stop_event.clear() + self._worker = threading.Thread( + target=self._run_stream, args=(user_text, flight_ctx_text), daemon=True) + self._worker.start() + + def stop(self): + self._stop_event.set() + + # ---------------------------- Wykonywanie akcji na glownym watku ---------------------------- + def _process_pending_actions(self): + """Oproznia kolejke akcji (wywolywane z flight loop na glownym watku).""" + if not self._pending_actions: + return + actions = self._pending_actions + self._pending_actions = [] + for a in actions: + try: + desc = self._execute_action(a) + except Exception as e: + desc = f"blad akcji: {e}" + if desc: + self.activity.append(desc) + xp.log(f"[XCoPilot] akcja: {desc}") + # ogranicz log do ostatnich 200 wpisow + if len(self.activity) > 200: + self.activity = self.activity[-200:] + + def _process_pending_say(self): + """Czyta tekst do powiedzenia (TTS). Wywolywane na glownym watku.""" + if self._pending_say is None: + return + say = self._pending_say + self._pending_say = None + if say and self.config.get("tts_enabled", True): + threading.Thread(target=self._speak, args=(say,), daemon=True).start() + + # ---------------------------- Glos (STT / TTS) ---------------------------- + def _voice_enabled(self): + return bool(self.config.get("voice_enabled", True)) + + def _start_recording(self): + if self._recording: + return + import tempfile + self._record_file = tempfile.mktemp(suffix=".wav", prefix="xcopilot_") + cmd = list(self.config.get("record_cmd", ["pw-record", "--format=s16", "--rate=16000", "--channels=1"])) + cmd.append(self._record_file) + try: + self._record_proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self._recording = True + self.status = "Nagrywanie... (pusc PTT aby wyslac)" + except Exception as e: + xp.log(f"[XCoPilot] Blad nagrywania: {e}") + self._record_proc = None + + def _stop_recording_and_send(self): + if not self._recording: + return + self._recording = False + if self._record_proc is not None: + try: + self._record_proc.send_signal(2) # SIGINT -> domkniecie WAV + try: + self._record_proc.wait(timeout=3) + except Exception: + self._record_proc.kill() + self._record_proc.wait(timeout=2) + except Exception: + pass + self._record_proc = None + + wav = getattr(self, "_record_file", None) + if not wav or not os.path.exists(wav): + self.status = "Blad: brak nagrania" + return + self.status = "Transkrybuje (whisper)..." + threading.Thread(target=self._transcribe_and_send, args=(wav,), daemon=True).start() + + def _transcribe_and_send(self, wav): + text = self._transcribe(wav) + try: + os.remove(wav) + except Exception: + pass + if text: + self._pending_send = text + else: + self.status = "Nie rozpoznano mowy." + + def _transcribe(self, wav_path): + import tempfile + out_file = tempfile.mktemp(suffix="", prefix="xcopilot_stt_") + cli = self.config.get("whisper_cli", "/usr/bin/whisper-cli") + model = self.config.get("whisper_model", "") + lang = self.config.get("whisper_language", "auto") + cmd = [cli, "-m", model, "-l", lang, "-otxt", "-of", out_file, "-f", wav_path, "-np"] + try: + subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=60) + txt_file = out_file + ".txt" + if os.path.exists(txt_file): + with open(txt_file, "r", encoding="utf-8") as f: + text = f.read().strip() + try: + os.remove(txt_file) + except Exception: + pass + return text + return "" + except Exception as e: + xp.log(f"[XCoPilot] Blad whisper: {e}") + return "" + + def _clean_env(self): + env = dict(os.environ) + env.pop("LD_PRELOAD", None) + env.pop("LD_LIBRARY_PATH", "") + env["LD_LIBRARY_PATH"] = "/opt/piper-tts" + return env + + def _speak(self, text): + if not self.config.get("tts_enabled", True): + return + text = (text or "").strip() + if not text: + return + if not self._speak_lock.acquire(blocking=False): + return + try: + self._speak_locked(text) + finally: + self._speak_lock.release() + + def _speak_locked(self, text): + piper = self.config.get("piper", "/opt/piper-tts/piper") + model = self.config.get("piper_model", "") + import tempfile + wav = tempfile.mktemp(suffix=".wav", prefix="xcopilot_tts_") + env = self._clean_env() + try: + p = subprocess.Popen( + [piper, "-m", model, "-f", wav], + stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + env=env) + p.communicate(input=text.encode("utf-8"), timeout=60) + if os.path.exists(wav) and os.path.getsize(wav) > 0: + play_cmd = list(self.config.get("play_cmd", ["pw-play"])) + subprocess.run(play_cmd + [wav], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, timeout=60, env=env) + try: + os.remove(wav) + except Exception: + pass + except Exception as e: + xp.log(f"[XCoPilot] Blad TTS: {e}") + + # ---------------------------- VR ---------------------------- + def _vr_flight_loop(self, lastCall, elapsed, counter, refCon): + """Co 1s: VR, wykonanie akcji, TTS, podniesienie STT (glowny watek).""" + vr = self._get_vr_enabled() + if vr != self._last_vr: + self._last_vr = vr + self._apply_vr_mode(vr) + # Wykonaj zakolejkowane akcje (datarefy! musza byc na glownym watku) + try: + self._process_pending_actions() + except Exception as e: + xp.log(f"[XCoPilot] Blad wykonania akcji: {e}") + # Powiedz na glos, co co-pilot zrobil + try: + self._process_pending_say() + except Exception as e: + xp.log(f"[XCoPilot] Blad TTS dispatch: {e}") + # Podnies tekst ze STT + if self._pending_send is not None: + txt = self._pending_send + self._pending_send = None + self.send(txt) + return 1.0 + + def _get_vr_enabled(self): + if self._vr_ref is None: + return 0 + try: + return xp.getDatai(self._vr_ref) + except Exception: + return 0 + + def _apply_vr_mode(self, vr): + for win in (self._imgui_window, self._config_window): + if win is None or win.windowID is None: + continue + try: + if vr: + xp.setWindowPositioningMode(win.windowID, xp.WindowVR, -1) + xp.setWindowGeometryVR(win.windowID, 800, 900) + else: + xp.setWindowPositioningMode(win.windowID, xp.WindowPositionFree, -1) + except Exception as e: + xp.log(f"[XCoPilot] Blad ustawiania VR: {e}") + + # ---------------------------- Okno ImGui ---------------------------- + def _draw(self, windowID, refCon): + imgui.text("XCoPilot - AI co-pilot") + imgui.separator() + + avail_h = imgui.get_content_region_available()[1] + chat_h = max(60.0, avail_h - 260.0) + with imgui.begin_child("chat", 0, chat_h, border=True): + for m in self.messages: + if m["role"] == "user": + imgui.text_colored("Pilot: " + m["text"], 0.5, 0.8, 1.0, 1.0) + else: + imgui.text_wrapped("Co-pilot: " + m["text"]) + if self.streaming: + imgui.text_colored("...", 0.9, 0.9, 0.3, 1.0) + imgui.set_scroll_here_y(1.0) + + changed, self.pending_text = imgui.input_text( + "##msg", self.pending_text, 512, + flags=imgui.INPUT_TEXT_ENTER_RETURNS_TRUE) + imgui.same_line() + if imgui.button("Wyslij (PTT)") or (changed and self.pending_text.strip()): + self.send(self.pending_text) + self.pending_text = "" + imgui.same_line() + if imgui.button("Stop"): + self.stop() + + imgui.text(self.status) + imgui.separator() + + # Aktualny samolot + match + path, _ = self._current_acf() + imgui.text("Samolot: " + (os.path.basename(path) if path else "?")) + imgui.text("Mapping: " + getattr(self, "_matched_acf", "default")) + if imgui.button("Przeladuj controls.json"): + self._load_controls(force=True) + self.status = "controls.json przeladowany." + + imgui.separator() + # Log wykonanych akcji + imgui.text("Wykonane akcje:") + with imgui.begin_child("activity", 0, 100.0, border=True): + for ln in self.activity[-50:]: + imgui.text_wrapped(ln) + + def _draw_config(self, windowID, refCon): + imgui.text("Konfiguracja XCoPilot") + imgui.separator() + + _, self.config["base_url"] = imgui.input_text("Base URL", self.config["base_url"], 256) + _, self.config["model"] = imgui.input_text("Model (puste=auto)", self.config["model"], 512) + _, self.config["temperature"] = imgui.slider_float("Temperature", self.config["temperature"], 0.0, 2.0, "%.2f") + _, self.config["max_tokens"] = imgui.slider_int("Max tokens", self.config["max_tokens"], 64, 4096) + _, self.config["no_think"] = imgui.checkbox("Tryb /no_think (Qwen3)", self.config["no_think"]) + _, self.config["include_flight_context"] = imgui.checkbox("Dolacz kontekst lotu", self.config["include_flight_context"]) + _, self.config["allow_raw_actions"] = imgui.checkbox( + "Pozwol AI na surowe datarefy/komendy (ryzykowne)", self.config["allow_raw_actions"]) + + imgui.separator() + imgui.text("Mapowanie akcji:") + _, self.config["controls_file"] = imgui.input_text( + "Plik controls.json", self.config["controls_file"], 512) + + imgui.separator() + imgui.text("Glos (whisper / piper):") + _, self.config["voice_enabled"] = imgui.checkbox("Glos wlaczony (STT)", self.config["voice_enabled"]) + _, self.config["tts_enabled"] = imgui.checkbox("Odczytywanie odpowiedzi (TTS)", self.config["tts_enabled"]) + _, self.config["whisper_model"] = imgui.input_text("Model whisper", self.config["whisper_model"], 512) + _, self.config["piper_model"] = imgui.input_text("Model piper", self.config["piper_model"], 512) + + imgui.separator() + imgui.text("System prompt (osobowosc i format JSON):") + _, self.config["system_prompt"] = imgui.input_text_multiline( + "##sysprompt", self.config["system_prompt"], 4096, width=0, height=120) + + imgui.separator() + if imgui.button("Zapisz"): + self._save_config() + self._model_cache = None + self.status = "Konfiguracja zapisana." + + imgui.separator() + imgui.text("Kontekst lotu (podglad):") + try: + _, ctx_text = self._collect_context() + imgui.text_wrapped(ctx_text) + except Exception as e: + imgui.text(f"(blad: {e})") + + # ---------------------------- Cykl zycia pluginu ---------------------------- + def XPluginStart(self): + self._ensure_datarefs() + self._load_controls(force=True) + + self._cmd = xp.createCommand("xcopilot/ptt", "XCoPilot push-to-talk") + xp.registerCommandHandler(self._cmd, self._ptt_handler, 1, None) + self._cmd_toggle = xp.createCommand("xcopilot/toggle_window", "XCoPilot toggle window") + xp.registerCommandHandler(self._cmd_toggle, self._toggle_handler, 1, None) + + self._menu = xp.createMenu("XCoPilot", None, 0, self._menu_handler, None) + xp.appendMenuItemWithCommand(self._menu, "Pokaz/ukryj okno", self._cmd_toggle) + self._menu_cfg_idx = xp.appendMenuItem(self._menu, "Konfiguracja", "xcopilot_config") + + self._imgui_window = ImguiWindow( + left=100, top=400, right=600, bottom=100, + visible=0, draw=self._draw, refCon=None, decoration=1, layer=1) + self._imgui_window.setTitle("XCoPilot") + + self._config_window = ImguiWindow( + left=150, top=500, right=700, bottom=120, + visible=0, draw=self._draw_config, refCon=None, decoration=1, layer=1) + self._config_window.setTitle("XCoPilot - Konfiguracja") + + for win in (self._imgui_window, self._config_window): + try: + xp.setWindowResizingLimits(win.windowID, 200, 100, 2000, 2000) + except Exception: + pass + + xp.registerFlightLoopCallback(self._vr_flight_loop, 1.0, None) + self._last_vr = self._get_vr_enabled() + self._apply_vr_mode(self._last_vr) + + return "XCoPilot", "pali112.xcopilot", "AI co-pilot (llama.cpp + datarefy)" + + def XPluginStop(self): + self.stop() + try: + xp.unregisterFlightLoopCallback(self._vr_flight_loop, None) + except Exception: + pass + for win in (self._config_window, self._imgui_window): + if win is not None: + try: + win.delete() + except Exception: + pass + self._config_window = None + self._imgui_window = None + + def XPluginEnable(self): + return 1 + + def XPluginDisable(self): + pass + + def XPluginReceiveMessage(self, inFromWho, inMessage, inParam): + pass + + # ---------------------------- Handlery ---------------------------- + def _ptt_handler(self, cmdRef, phase, refCon): + if self._voice_enabled(): + mode = self.config.get("voice_ptt_mode", "hold") + if mode == "toggle": + if phase == xp.CommandBegin: + if self._recording: + self._stop_recording_and_send() + else: + self._start_recording() + return 0 + else: + if phase == xp.CommandBegin: + self._start_recording() + return 0 + elif phase == xp.CommandEnd: + self._stop_recording_and_send() + return 0 + return 1 + if phase == xp.CommandBegin: + text = self.pending_text.strip() + if text: + self.send(text) + self.pending_text = "" + return 0 + return 1 + + def _toggle_handler(self, cmdRef, phase, refCon): + if phase == xp.CommandBegin: + self._toggle_main_window() + return 0 + return 1 + + def _menu_handler(self, menuRef, itemRef): + if itemRef == "xcopilot_config": + self._toggle_config_window() + + def _toggle_main_window(self): + if self._imgui_window is not None and self._imgui_window.windowID is not None: + cur = xp.getWindowIsVisible(self._imgui_window.windowID) + xp.setWindowIsVisible(self._imgui_window.windowID, 0 if cur else 1) + + def _toggle_config_window(self): + if self._config_window is not None and self._config_window.windowID is not None: + cur = xp.getWindowIsVisible(self._config_window.windowID) + xp.setWindowIsVisible(self._config_window.windowID, 0 if cur else 1) + + +# -------------------------------------------------------------------------- +# Punkt wejscia XPPython3 +# -------------------------------------------------------------------------- + +_plugin = XCoPilot() + + +class PythonInterface: + def XPluginStart(self): + return _plugin.XPluginStart() + + def XPluginStop(self): + _plugin.XPluginStop() + + def XPluginEnable(self): + return _plugin.XPluginEnable() + + def XPluginDisable(self): + _plugin.XPluginDisable() + + def XPluginReceiveMessage(self, inFromWho, inMessage, inParam): + _plugin.XPluginReceiveMessage(inFromWho, inMessage, inParam) diff --git a/PythonPlugins/config.example.json b/PythonPlugins/config.example.json new file mode 100644 index 0000000..85a27f0 --- /dev/null +++ b/PythonPlugins/config.example.json @@ -0,0 +1,20 @@ +{ + "base_url": "http://localhost:8081", + "model": "", + "temperature": 0.3, + "max_tokens": 512, + "no_think": true, + "include_flight_context": true, + "allow_raw_actions": false, + "controls_file": "", + "voice_enabled": true, + "voice_ptt_mode": "hold", + "whisper_cli": "/usr/bin/whisper-cli", + "whisper_model": "/home/pali112/models/ggml-small.bin", + "whisper_language": "auto", + "record_cmd": ["pw-record", "--format=s16", "--rate=16000", "--channels=1"], + "piper": "/opt/piper-tts/piper", + "piper_model": "/home/pali112/.local/share/piper-voices/en_US-lessac-medium.onnx", + "play_cmd": ["pw-play"], + "tts_enabled": true +} diff --git a/PythonPlugins/controls.json b/PythonPlugins/controls.json new file mode 100644 index 0000000..da8b8ab --- /dev/null +++ b/PythonPlugins/controls.json @@ -0,0 +1,106 @@ +{ + "_comment": "Mapowanie akcji (nazw) -> datarefy/komendy X-Plane. Sekcja 'default' stosowana dla wszystkich samolotow; sekcja 'aircraft' nadpisuje/rozszerza default dla pasujacych samolotow (match = fragment sciezki ACF lub kodu ICAO, wielkosc liter bez znaczenia). Akcje z 'value' = '{value}' przyjmuja parametr od AI.", + + "default": { + "controls": { + "gear_up": { "desc": "Chowaj podwozie", "ops": [ { "cmd": "sim/flight_controls/landing_gear_up" } ] }, + "gear_down": { "desc": "Wysun podwozie", "ops": [ { "cmd": "sim/flight_controls/landing_gear_down" } ] }, + "gear_toggle": { "desc": "Przelacz podwozie", "ops": [ { "cmd": "sim/flight_controls/landing_gear_toggle" } ] }, + "flaps_up": { "desc": "Klapy o jeden stopien do gory", "ops": [ { "cmd": "sim/flight_controls/flaps_up" } ] }, + "flaps_down": { "desc": "Klapy o jeden stopien w dol", "ops": [ { "cmd": "sim/flight_controls/flaps_down" } ] }, + "set_flaps": { "desc": "Ustaw klapy (value 0..1)", "ops": [ { "set": "sim/cockpit2/controls/flap_ratio", "value": "{value}" } ] }, + "ap_on": { "desc": "Wlacz autopilota", "ops": [ { "cmd": "sim/autopilot/servos_on" } ] }, + "ap_off": { "desc": "Wylacz autopilota", "ops": [ { "cmd": "sim/autopilot/servos_off" } ] }, + "set_heading": { "desc": "Ustaw kierunek autopilota (value=stopnie magnetyczne)", "ops": [ { "set": "sim/cockpit/autopilot/heading_mag", "value": "{value}" } ] }, + "set_altitude": { "desc": "Ustaw wysokosc autopilota (value=stopy)", "ops": [ { "set": "sim/cockpit/autopilot/altitude", "value": "{value}" } ] }, + "set_speed": { "desc": "Ustaw predkosc autopilota (value=wezly)", "ops": [ { "set": "sim/cockpit/autopilot/airspeed", "value": "{value}" } ] }, + "set_vs": { "desc": "Ustaw predkosc pionowa autopilota (value=fpm)", "ops": [ { "set": "sim/cockpit/autopilot/vertical_velocity", "value": "{value}" } ] }, + "autothrottle_on": { "desc": "Wlacz auto-throttle", "ops": [ { "cmd": "sim/autopilot/autothrottle_on" } ] }, + "autothrottle_off": { "desc": "Wylacz auto-throttle", "ops": [ { "cmd": "sim/autopilot/autothrottle_off" } ] }, + "set_speedbrake": { "desc": "Ustaw hamulec aerodynamiczny (value 0..1)", "ops": [ { "set": "sim/cockpit2/controls/speedbrake_ratio", "value": "{value}" } ] }, + "brake_parking_on": { "desc": "Zaciagnij hamulec postojowy", "ops": [ { "set": "sim/cockpit2/controls/parking_brake_ratio", "value": 1.0 } ] }, + "brake_parking_off":{ "desc": "Zwolnij hamulec postojowy", "ops": [ { "set": "sim/cockpit2/controls/parking_brake_ratio", "value": 0.0 } ] }, + "set_qnh": { "desc": "Ustaw cisnienie barometryczne (value=inHg, np. 29.92)", "ops": [ { "set": "sim/cockpit/misc/barometer_setting", "value": "{value}" } ] }, + "set_squawk": { "desc": "Ustaw kod transpondera (value=4 cyfry)", "ops": [ { "set": "sim/cockpit/radios/transponder_code", "value": "{value}" } ] }, + "set_com1": { "desc": "Ustaw czestotliwosc COM1 (value=kHz, np. 118300)", "ops": [ { "set": "sim/cockpit2/radios/actuators/com1_frequency_hz", "value": "{value}" } ] } + }, + "state": { + "gear_handle": "sim/cockpit2/controls/gear_handle_down", + "flap_ratio": "sim/cockpit2/controls/flap_ratio", + "speedbrake": "sim/cockpit2/controls/speedbrake_ratio", + "parking_brake": "sim/cockpit2/controls/parking_brake_ratio" + } + }, + + "aircraft": [ + { + "_comment": "Zibo 737-800X (B738). Match 'b738' trafia zarowno w kod ICAO (B738) jak i plik b738.acf. Uzywa wlasnych datarefow laminar/B738/*.", + "match": "b738", + "controls": { + "gear_up": { "desc": "Dzwignia podwozia GORA", "ops": [ { "set": "laminar/B738/controls/gear_handle_down", "value": 0 } ] }, + "gear_down": { "desc": "Dzwignia podwozia DOL", "ops": [ { "set": "laminar/B738/controls/gear_handle_down", "value": 1 } ] }, + "gear_off": { "desc": "Dzwignia podwozia OFF", "ops": [ { "set": "laminar/B738/controls/gear_handle_down", "value": 0.5 } ] }, + + "flaps_0": { "desc": "Klapy 0 (up)", "ops": [ { "set": "laminar/B738/flt_ctrls/flap_lever", "value": 0.0 } ] }, + "flaps_1": { "desc": "Klapy 1", "ops": [ { "set": "laminar/B738/flt_ctrls/flap_lever", "value": 0.125 } ] }, + "flaps_2": { "desc": "Klapy 2", "ops": [ { "set": "laminar/B738/flt_ctrls/flap_lever", "value": 0.25 } ] }, + "flaps_5": { "desc": "Klapy 5", "ops": [ { "set": "laminar/B738/flt_ctrls/flap_lever", "value": 0.375 } ] }, + "flaps_10": { "desc": "Klapy 10", "ops": [ { "set": "laminar/B738/flt_ctrls/flap_lever", "value": 0.5 } ] }, + "flaps_15": { "desc": "Klapy 15", "ops": [ { "set": "laminar/B738/flt_ctrls/flap_lever", "value": 0.625 } ] }, + "flaps_25": { "desc": "Klapy 25", "ops": [ { "set": "laminar/B738/flt_ctrls/flap_lever", "value": 0.75 } ] }, + "flaps_30": { "desc": "Klapy 30", "ops": [ { "set": "laminar/B738/flt_ctrls/flap_lever", "value": 0.875 } ] }, + "flaps_40": { "desc": "Klapy 40 (full)", "ops": [ { "set": "laminar/B738/flt_ctrls/flap_lever", "value": 1.0 } ] }, + "flaps_up": { "desc": "Klapy o jeden stopien do gory", "ops": [ { "cmd": "sim/flight_controls/flaps_up" } ] }, + "flaps_down": { "desc": "Klapy o jeden stopien w dol", "ops": [ { "cmd": "sim/flight_controls/flaps_down" } ] }, + + "ap_on": { "desc": "Autopilot CMD A (wlacz/wylacz)", "ops": [ { "cmd": "laminar/B738/autopilot/cmd_a_press" } ] }, + "ap_cmd_b": { "desc": "Autopilot CMD B (wlacz/wylacz)", "ops": [ { "cmd": "laminar/B738/autopilot/cmd_b_press" } ] }, + "autothrottle": { "desc": "Auto-throttle (arm/wylacz)", "ops": [ { "cmd": "laminar/B738/autopilot/autothrottle_arm_toggle" } ] }, + "flight_director": { "desc": "Flight director (wlacz/wylacz)", "ops": [ { "cmd": "laminar/B738/autopilot/flight_director_toggle" } ] }, + + "set_heading": { "desc": "Ustaw kierunek MCP (value=stopnie magnetyczne)", "ops": [ { "set": "laminar/B738/autopilot/mcp_hdg_dial", "value": "{value}" } ] }, + "set_altitude": { "desc": "Ustaw wysokosc MCP (value=stopy)", "ops": [ { "set": "laminar/B738/autopilot/mcp_alt_dial", "value": "{value}" } ] }, + "set_speed": { "desc": "Ustaw predkosc MCP (value=wezly)", "ops": [ { "set": "laminar/B738/autopilot/mcp_speed_dial_kts", "value": "{value}" } ] }, + "set_vs": { "desc": "Ustaw predkosc pionowa MCP (value=fpm)", "ops": [ { "set": "sim/cockpit/autopilot/vertical_velocity", "value": "{value}" } ] }, + + "lnav": { "desc": "LNAV (wlacz/wylacz)", "ops": [ { "cmd": "laminar/B738/autopilot/lnav_press" } ] }, + "vnav": { "desc": "VNAV (wlacz/wylacz)", "ops": [ { "cmd": "laminar/B738/autopilot/vnav_press" } ] }, + "hdg_sel": { "desc": "HDG SEL (wlacz/wylacz)", "ops": [ { "cmd": "laminar/B738/autopilot/hdg_sel_press" } ] }, + "alt_hld": { "desc": "ALT HLD (wlacz/wylacz)", "ops": [ { "cmd": "laminar/B738/autopilot/alt_hld_press" } ] }, + "vs_mode": { "desc": "V/S (wlacz/wylacz)", "ops": [ { "cmd": "laminar/B738/autopilot/vs_press" } ] }, + "lvl_chg": { "desc": "LVL CHG (wlacz/wylacz)", "ops": [ { "cmd": "laminar/B738/autopilot/lvl_chg_press" } ] }, + "speed_mode": { "desc": "SPEED mode (wlacz/wylacz)", "ops": [ { "cmd": "laminar/B738/autopilot/speed_press" } ] }, + "app_mode": { "desc": "APP (wlacz/wylacz)", "ops": [ { "cmd": "laminar/B738/autopilot/app_press" } ] }, + "n1_mode": { "desc": "N1 mode (wlacz/wylacz)", "ops": [ { "cmd": "laminar/B738/autopilot/n1_press" } ] }, + + "set_course1": { "desc": "Ustaw course CRS1 (value=stopnie)", "ops": [ { "set": "sim/cockpit2/radios/actuators/nav1_obs_deg_mag_pilot", "value": "{value}" } ] } + }, + "state": { + "gear_handle": "laminar/B738/controls/gear_handle_down", + "flap_lever": "laminar/B738/flt_ctrls/flap_lever", + "cmd_a": "laminar/B738/autopilot/cmd_a_status", + "autothrottle": "laminar/B738/autopilot/autothrottle_status", + "flight_director": "laminar/B738/autopilot/flight_direct_on", + "lnav": "laminar/B738/autopilot/lnav_status", + "vnav": "laminar/B738/autopilot/vnav_status1", + "hdg_sel": "laminar/B738/autopilot/hdg_sel_status", + "alt_hld": "laminar/B738/autopilot/alt_hld_status", + "vs": "laminar/B738/autopilot/vs_status", + "lvl_chg": "laminar/B738/autopilot/lvl_chg_status", + "app": "laminar/B738/autopilot/app_status", + "n1": "laminar/B738/autopilot/n1_status" + } + }, + { + "_comment": "Przyklad: ToLiss Airbus (A319/A321/A340) uzywa wlasnych datarefow AirbusFBW/*.", + "match": "AirbusFBW", + "controls": { + "gear_up": { "desc": "Dzwignia podwozia GORA", "ops": [ { "set": "AirbusFBW/GearLever", "value": 0 } ] }, + "gear_down": { "desc": "Dzwignia podwozia DOL", "ops": [ { "set": "AirbusFBW/GearLever", "value": 1 } ] } + }, + "state": { + "gear_lever": "AirbusFBW/GearLever" + } + } + ] +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..173af22 --- /dev/null +++ b/README.md @@ -0,0 +1,175 @@ +# XCoPilot + +Lokalny **co-pilot (AI) dla X-Plane 12**, podłączony do własnego serwera **llama.cpp**. +W odróżnieniu od XSayATC (który tylko „gada" jako ATC), co-pilot **realnie steruje samolotem** — wydaje polecenia, a wtyczka wykonuje je na datarefach i komendach X-Plane. + +Wtyczka zbiera kontekst lotu z datarefów, wysyła Twoją wiadomość (tekst lub głos) do lokalnego modelu, a model odpowiada **strukturalnym JSON-em** z listą akcji (np. `gear_up`, `set_heading 270`). Wtyczka parsuje ten JSON i wykonuje akcje. Okno widoczne **także w VR**. + +## Jak to działa + +1. Mówisz/piszesz polecenie: *„schowaj podwozie i ustaw kurs 270"*. +2. Wtyczka dokleja do promptu: kontekst lotu (pozycja, wysokość, prędkość, stan autopilota, podwozia, klap itd.) **oraz listę dostępnych akcji** (nazwa + opis) z `controls.json`. +3. Model odpowiada JSON-em: + ```json + { + "say": "Chowam podwozie i ustawiam kurs dwa siedem zero.", + "actions": [ + { "control": "gear_up" }, + { "control": "set_heading", "value": 270 } + ] + } + ``` +4. Wtyczka wykonuje `actions` na głównym wątku (datarefy/komendy), a `say` czyta na głos (piper) i pokazuje w oknie. + +Dzięki temu AI **nie zgaduje nazw datarefów** — zna tylko nazwy akcji z `controls.json`, a Ty mapujesz je na właściwe datarefy dla danego samolotu. + +## Gotowe profile samolotów + +`controls.json` zawiera już kompletny profil **Zibo 737-800X** (match `b738`) z +własnymi datarefami `laminar/B738/*`: + +- **Podwozie** — dźwignia `laminar/B738/controls/gear_handle_down` (0=GÓRA, 0.5=OFF, 1=DÓŁ). +- **Klapy** — dźwignia `laminar/B738/flt_ctrls/flap_lever` (0=up, 0.125=1, 0.25=2, 0.375=5, 0.5=10, 0.625=15, 0.75=25, 0.875=30, 1.0=40) — gotowe akcje `flaps_0`…`flaps_40`. +- **Autopilot MCP** — `mcp_hdg_dial`, `mcp_alt_dial`, `mcp_speed_dial_kts`, V/S. +- **Tryby** — `lnav`, `vnav`, `hdg_sel`, `alt_hld`, `vs_mode`, `lvl_chg`, `speed_mode`, `app_mode`, `n1_mode`, `ap_on` (CMD A), `autothrottle`, `flight_director`. +- **Odczyt stanu** — statusy CMD/AT/FD/LNAV/VNAV/HDG SEL/ALT HLD/VS/LVL CHG/APP/N1 + dźwignie podwozia/klap. + +Jest też przykładowy profil ToLiss (AirbusFBW). Dopisz własne wpisy w `aircraft[]` +dla kolejnych samolotów. + +## Funkcje + +- **Sterowanie samolotem** — co-pilot wykonuje akcje (podwozie, klapy, autopilot, transponder, radio, hamulec postojowy…). +- **Tylko na Twoje polecenie** — co-pilot reaguje wyłącznie na to, co powiesz/napiszesz (nie działa proaktywnie). +- **Mapowanie akcji → datarefy** — plik `controls.json`, z sekcją `default` i per-samolot (`match` po fragmencie ścieżki ACF / kodzie ICAO). +- **Push-to-talk głosowe** — whisper transkrybuje, piper czyta odpowiedź co-pilota. +- **Tekstowe PTT** — pole tekstowe + Enter lub komenda `xcopilot/ptt`. +- **Okno widoczne w VR** — automatyczne przełączanie monitor ↔ `WindowVR`. +- **Kontekst lotu** doklejany do promptu z datarefów. +- **Podgląd wykonanych akcji** (log w oknie). +- **Konfigurowalny GUI** — adres serwera, model, temperatura, prompt, głos. + +## Wymagania + +- [X-Plane 12](https://www.x-plane.com/) +- [XPPython3](https://xppython3.readthedocs.io/) v4.x (Python 3.12 + `imgui` + `requests`) +- działający serwer **llama.cpp** z endpointem OpenAI-compat (`/v1/chat/completions`) +- **Głos (opcjonalnie):** `whisper-cli` (STT) + `piper` (TTS) + PipeWire (`pw-record` / `pw-play`) + +## Instalacja + +1. Zainstaluj XPPython3 do `X-Plane 12/Resources/plugins/XPPython3/`. +2. Skopiuj `PythonPlugins/PI_XCoPilot.py` oraz `controls.json` do: + ```text + X-Plane 12/Resources/plugins/PythonPlugins/ + ``` +3. (Opcjonalnie) skopiuj `config.example.json` jako `config.json` i dopasuj (adres serwera, ścieżki whisper/piper). +4. Uruchom X-Plane. W menu `Plugins → XCoPilot` znajdziesz okno i konfigurację. + +## Użycie + +1. Uruchom serwer **llama.cpp** (np. port `8081`). +2. Uruchom **X-Plane 12**. +3. Przypisz klawisz PTT: **Settings → Keyboard → Plugins → XCoPilot → push-to-talk** (opcjonalnie `toggle window`). +4. Mów lub pisz polecenia: *„wysuń podwozie"*, *„ustaw wysokość 3500"*, *„włącz autopilota"*, *„ustaw kod 1200"*… + +## Plik `controls.json` (mapowanie akcji) + +To serce wtyczki. Struktura: + +```json +{ + "default": { + "controls": { + "gear_up": { "desc": "Chowaj podwozie", "ops": [ { "cmd": "sim/flight_controls/landing_gear_up" } ] }, + "set_heading": { "desc": "Kurs autopilota (value=stopnie)", "ops": [ { "set": "sim/cockpit/autopilot/heading_mag", "value": "{value}" } ] }, + "brake_parking_on": { "desc": "Hamulec postojowy", "ops": [ { "set": "sim/cockpit2/controls/parking_brake_ratio", "value": 1.0 } ] } + }, + "state": { + "gear_handle": "sim/cockpit2/controls/gear_handle_down", + "flap_ratio": "sim/cockpit2/controls/flap_ratio" + } + }, + "aircraft": [ + { + "match": "AirbusFBW", + "controls": { + "gear_up": { "desc": "Dźwignia podwozia GÓRA", "ops": [ { "set": "AirbusFBW/GearLever", "value": 0 } ] } + }, + "state": { "gear_lever": "AirbusFBW/GearLever" } + } + ] +} +``` + +### Sekcje + +- **`default`** — stosowana dla wszystkich samolotów. +- **`aircraft`** — lista nadpisań; `match` to fragment ścieżki ACF lub kodu ICAO (wielkość liter bez znaczenia). Pierwszy pasujący wpis wygrywa; jego klucze **nadpisują/rozszerzają** `default`. +- **`controls`** — nazwane akcje widoczne dla AI. Każda ma `desc` (opis, który AI widzi) i listę `ops`. +- **`state`** — dodatkowe datarefy odczytywane do kontekstu (AI widzi ich aktualne wartości). + +### Typy operacji (`ops`) + +| Typ | Opis | Przykład | +| --- | --- | --- | +| `{ "cmd": "..." }` | Wyzwala komendę X-Plane | `{ "cmd": "sim/flight_controls/landing_gear_up" }` | +| `{ "set": "...", "value": X }` | Zapisuje wartość do datarefu | `{ "set": "sim/cockpit/autopilot/altitude", "value": 3500 }` | +| `{ "set": "...", "value": "{value}" }` | Wartość podaje AI (akcja z parametrem) | `{ "set": "sim/cockpit/autopilot/heading_mag", "value": "{value}" }` | +| `{ "toggle": "..." }` | Przełącza dataref 0 ↔ 1 | `{ "toggle": "sim/cockpit2/controls/gear_handle_down" }` | + +Wartość `value` może być liczbą, stringiem liczbowym, albo szablonem `{value}` (wtedy AI musi podać `"value"` w akcji). Typ zapisu (int/float/string) dobierany jest automatycznie po typie datarefu. + +### Surowe datarefy (opcjonalnie) + +Gdy w `config.json` ustawisz `allow_raw_actions: true`, AI może też bezpośrednio użyć: +```json +{ "actions": [ { "dref": "sim/cockpit/autopilot/heading_mag", "value": 270 } ] } +{ "actions": [ { "command": "sim/flight_controls/landing_gear_up" } ] } +``` +⚠️ Zalecane trzymać `false` — wtedy AI korzysta tylko z nazwanych akcji i nie wymyśla błędnych ścieżek. + +## Konfiguracja (`config.json`) + +| Klucz | Opis | +| --- | --- | +| `base_url` | Adres serwera llama.cpp (np. `http://localhost:8081`) | +| `model` | Nazwa modelu; puste = auto-wykrycie z `/v1/models` | +| `temperature` | Temperatura próbkowania (niższa = stabilniejsze akcje) | +| `max_tokens` | Maksymalna liczba tokenów odpowiedzi | +| `system_prompt` | Osobowość + format wyjścia (JSON) co-pilota | +| `include_flight_context` | Czy doklejać kontekst lotu | +| `no_think` | Token `/no_think` (Qwen3 reasoning) | +| `controls_file` | Ścieżka `controls.json` (puste = obok wtyczki) | +| `allow_raw_actions` | Pozwól AI na surowe `dref`/`command` | +| `voice_enabled` / `tts_enabled` | Głos wejściowy / wyjściowy | +| `whisper_model`, `piper_model` | Ścieżki modeli STT/TTS | +| `voice_ptt_mode` | `hold` (przytrzymaj) lub `toggle` | + +## Push-to-talk + +Wtyczka rejestruje komendy: +- `xcopilot/ptt` — push-to-talk, +- `xcopilot/toggle_window` — pokaż/ukryj okno. + +Przypisz klawisze w **Settings → Keyboard → Plugins → XCoPilot**. + +## Uwagi techniczne + +- **Bezpieczeństwo wątków:** odczyty i zapisy datarefów oraz komendy (`xp.getData*`, `xp.setData*`, `xp.command*`) muszą działać na głównym wątku X-Plane. Wątek roboczy robi wyłącznie sieć i parsowanie JSON; wynik trafia do kolejki, a główna pętla (flight loop) wykonuje akcje bezpiecznie. +- **Format wyjścia:** model musi zwracać JSON. Wtyczka tolerancyjnie wyciąga pierwszy obiekt JSON (także z code fence ```json). Jeśli parsowanie się nie uda, odpowiedź jest traktowana jako zwykła wypowiedź (bez akcji). +- **`controls.json` można edytować w locie** — wtyczka przeładowuje go przy każdym wysłaniu (i przyciskiem „Przeładuj controls.json"). +- **Polskie znaki** w oknie ImGui mogą się wyświetlać jako `?` (domyślny font). Głos i treść promptu działają poprawnie. + +## Przykłady poleceń + +- „schowaj podwozie" → `gear_up` +- „wysuń klapy" → `flaps_down` +- „ustaw wysokość trzy tysiące pięćset" → `set_altitude 3500` +- „ustaw kurs dwa siedem zero" → `set_heading 270` +- „włącz autopilota i ustaw prędkość dwieście dwadzieścia" → `ap_on` + `set_speed 220` +- „ustaw transponder jeden dwa zero zero" → `set_squawk 1200` + +## Licencja + +Do uzupełnienia.