From 7a892c1779ab8ee753dee2fefad6d5a7f5cb53f2 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Sat, 18 Apr 2026 06:36:02 -0500 Subject: [PATCH 01/26] =?UTF-8?q?Add=20comprehensive=20README.md=20?= =?UTF-8?q?=E2=80=94=20architecture=20diagram,=20plugin=20list,=20database?= =?UTF-8?q?=20keys,=20and=20MAOS=20integration=20path?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 122 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 00000000..76545b6a --- /dev/null +++ b/README.md @@ -0,0 +1,122 @@ +# FIX-Gateway + +**Status:** Open Source — Experimental Amateur-Built Category +**License:** GPL v2 +**Language:** Python 3 +**Snap:** `fixgateway` on snapcraft.io + +[![snapcraft.io](https://snapcraft.io/fixgateway/badge.svg)](https://snapcraft.io/fixgateway) +[![Coverage](https://raw.githubusercontent.com/makerplane/FIX-Gateway/python-coverage-comment-action-data/badge.svg)](https://htmlpreview.github.io/?https://github.com/makerplane/FIX-Gateway/blob/python-coverage-comment-action-data/htmlcov/index.html) + +--- + +## What This Is + +FIX-Gateway is the **central avionics data broker** for the MakerPlane and MAOS avionics ecosystem. It is a Python daemon that maintains a real-time database of named flight parameters and routes data between heterogeneous sources and consumers via a plugin architecture. + +Think of it as an avionics middleware bus: any sensor, protocol, or simulator can publish data to one standard parameter namespace, and any display or system can subscribe without knowing where the data came from. + +## Architecture + +``` +[CAN-FIX bus] ─────────────────────────────────┐ +[GPS / gpsd] ───────────────────────────────────┤ +[Stratux ADS-B] ────────────────────────────────┤ +[MAVLink autopilot / MAOS-FCS] ─────────────────┤ +[X-Plane / FlightGear simulator] ───────────────┤→ [FIX-Gateway database] ─→ [pyEfis EFIS display] +[RPi IMU (BNO055)] ─────────────────────────────┤ ─→ [pyAvMap moving map] +[RPi barometer (BMP085)] ───────────────────────┤ ─→ [NetFIX network clients] +[MGL / Dynon / GrandRapids EGS serial] ─────────┤ ─→ [CAN-FIX output nodes] +[Compute plugin (derived values)] ──────────────┘ +``` + +## Parameter Database + +The central database maps named keys to typed, bounded, toleranced values. Key domains include: + +| Domain | Example Keys | +|---|---| +| Navigation | `LAT`, `LONG`, `ALT`, `IAS`, `TAS`, `GS`, `HEAD`, `TRACK`, `XTE` | +| AHRS | `PITCH`, `ROLL`, `YAW`, `ALAT`, `ALONG`, `ANORM` | +| Engine | `RPM1`, `MAP1`, `EGT11`–`EGT16`, `CHT11`–`CHT16`, `OILP1`, `OILT1`, `FFLOW1` | +| Control surfaces | `CTLPTCH`, `CTLROLL`, `CTLYAW`, `CTLFLAP`, `CTLATP`, `CTLCOLL` | +| Electrical | `VOLT1`, `CURR1`, `ALT1` | +| COM/NAV radios | `COM1ACT`, `COM1SBY`, `NAV1ACT`, `NAV1SBY` | +| Trims | `PITCHTRIM`, `ROLLTRIM`, `YAWTRIM` | +| Autopilot | `APENG`, `APALT`, `APHDG`, `APSPD` | + +Each key has defined type, min/max bounds, units, and a **tolerance (stale data) timer** — if a key is not updated within its tol window it is marked stale, which pyEfis can display as a failure flag. + +## Plugin Ecosystem + +Input/output plugins currently available: + +| Plugin | Description | +|---|---| +| `canfix` | CAN-FIX bus via SocketCAN or MCP2515 | +| `gpsd` | GPS position and ground track from gpsd | +| `stratux` | ADS-B traffic and GPS from Stratux receiver | +| `mavlink` | MAVLink autopilot/FCS data (compatible with MAOS-FCS) | +| `netfix` | TCP/IP network interface for distributed avionics | +| `xplane` | X-Plane 11/12 flight simulator | +| `fgfs` | FlightGear flight simulator | +| `dynon` | Dynon serial protocol | +| `mgl` / `mgl_serial` | MGL Avionics serial protocol | +| `grand_rapids_eis` | Grand Rapids Technologies EIS serial | +| `megasquirt` | MegaSquirt ECU data | +| `rpi_bno055` | Raspberry Pi IMU (attitude) | +| `rpi_bmp085` | Raspberry Pi barometric sensor | +| `rpi_mcp3008` | Raspberry Pi 8-channel SPI ADC | +| `rpi_rotary_encoder` | Rotary encoder inputs (altimeter, heading bugs) | +| `rpi_button` | GPIO button inputs | +| `compute` | Derived value computation (e.g., density altitude, TAS from IAS/OAT/ALT) | +| `data_recorder` | Log all parameters to file | +| `data_playback` | Replay recorded flight data | +| `quorum` | Multi-source data arbitration / voting | +| `annunciate` | Generate warning/caution/advisory annunciations from parameter limits | +| `demo` | Simulated flight data for display testing | + +## Installation + +```bash +git clone https://github.com/makerplane/FIX-Gateway.git fixgw +cd fixgw +make venv +source venv/bin/activate +make init +``` + +Run the server: +```bash +./fixGw.py +``` + +Run the debug client: +```bash +./fixGwClient.py # console +./fixGwClient.py --gui # GUI client +``` + +## Configuration + +Configuration files live in `src/fixgw/config/`: + +- `default.yaml` — main server config; selects which plugins load +- `database.yaml` — parameter namespace definition +- `database/custom.yaml` — add or override parameters without touching upstream files +- `init_data/custom.ini` — set initial parameter values for your specific aircraft + +## Role in the MAOS Ecosystem + +FIX-Gateway is the **recommended avionics data bus layer** for MAOS. Its MAVLink plugin makes it directly compatible with MAOS-FCS serial/network output. The `CTLPTCH`, `CTLROLL`, `CTLYAW` control keys in the database provide a natural bridge between FCS commanded surfaces and cockpit display confirmation. + +For MAOS integration: +- **MAOS-FCS** publishes attitude, airspeed, altitude, and control state via MAVLink → FIX-Gateway MAVLink plugin +- **MAOS-VISION** can publish track/position data via a custom plugin or MAVLink +- **pyEfis** consumes all published keys for display +- The `quorum` plugin can arbitrate between redundant sensor sources before values reach the display + +## Important Disclaimer + +> FIX-Gateway is developed for Experimental Amateur-Built aircraft use only. +> It is not FAA-approved avionics software. Aircraft builders are responsible for all integration and safety decisions. From 1779b11989b36081ab1563daa7c215f5d77d95f3 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Sat, 18 Apr 2026 07:20:26 -0500 Subject: [PATCH 02/26] Revert README: Remove MAOS-specific ecosystem sections for upstream PR compatibility --- README.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/README.md b/README.md index 76545b6a..476dd2f7 100644 --- a/README.md +++ b/README.md @@ -106,16 +106,6 @@ Configuration files live in `src/fixgw/config/`: - `database/custom.yaml` — add or override parameters without touching upstream files - `init_data/custom.ini` — set initial parameter values for your specific aircraft -## Role in the MAOS Ecosystem - -FIX-Gateway is the **recommended avionics data bus layer** for MAOS. Its MAVLink plugin makes it directly compatible with MAOS-FCS serial/network output. The `CTLPTCH`, `CTLROLL`, `CTLYAW` control keys in the database provide a natural bridge between FCS commanded surfaces and cockpit display confirmation. - -For MAOS integration: -- **MAOS-FCS** publishes attitude, airspeed, altitude, and control state via MAVLink → FIX-Gateway MAVLink plugin -- **MAOS-VISION** can publish track/position data via a custom plugin or MAVLink -- **pyEfis** consumes all published keys for display -- The `quorum` plugin can arbitrate between redundant sensor sources before values reach the display - ## Important Disclaimer > FIX-Gateway is developed for Experimental Amateur-Built aircraft use only. From e94bfd0042fa1017d3b28e87534d949e58044605 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Mon, 1 Jun 2026 15:07:30 -0500 Subject: [PATCH 03/26] xplane plugin: Py3, data-driven recv/send mapping, full SVS data set MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous X-Plane plugin was Python 2 code that crashed on import under Python 3 (ord(int) TypeError, integer-division /, str vs bytes header compare) and hard-coded UDP_IP and UDP_PORT at module scope. The receive path also only knew about two data-output indices, so a real X-Plane session would deliver IAS, TAS, ALT, LAT, LONG and nothing else — no pitch, roll, heading, vertical speed, AGL, AOA, or turn rate. That left the AI horizon static, the HSI inert, and SVS clearance shading wrong (no AGL means auto-range can't compute). Rewrite as a small data-driven plugin: * Py3-clean packet parsing (struct.unpack_from " X-Plane bursts. 0.1 = 10 Hz. + send_interval: 0.1 + + # --------------------------------------------------------------------- + # X-Plane -> FIX. Eight slots per data-output index match the slot + # order in X-Plane's "Net Connections → Data Set" enable list. Use + # "_" (or "x" / blank) to skip a slot. + # + # Indices below cover the data SVS, AI, HSI, airspeed and altimeter + # widgets in pyEfis need to behave naturally with X-Plane in the loop. + # --------------------------------------------------------------------- + recv: + # idx 3 — Speeds + # slots: [Vind_kias, Vind_keas, Vtrue_ktas, Vtrue_ktgs, _, V_mph, ...] + 3: [IAS, _, TAS, GS, _, _, _, _] + + # idx 4 — Mach, VVI, g-loads + # slots: [Mach, _, VVI_fpm, Gnormal, Gaxial, Gside, _, _] + 4: [_, _, VS, _, _, ALAT, _, _] + + # idx 16 — Angular velocities + # slots: [Qrad_sec, Prad_sec, Rrad_sec, ...] (pitch/roll/yaw rates) + 16: [_, _, ROT, _, _, _, _, _] + + # idx 17 — Pitch, roll, headings + # slots: [Pitch_deg, Roll_deg, Heading_true, Heading_mag, _, _, _, _] + 17: [PITCH, ROLL, _, HEAD, _, _, _, _] + + # idx 18 — AOA, sideslip, paths + # slots: [alpha, beta, hpath, vpath, _, _, _, _] + 18: [AOA, _, TRACK, _, _, _, _, _] + + # idx 20 — Lat, lon, altitude + # slots: [lat, lon, alt_ft_msl, alt_ft_agl, _, _, _, _] + 20: [LAT, LONG, ALT, AGL, _, _, _, _] + + # --------------------------------------------------------------------- + # FIX -> X-Plane. pyEfis writes its controls back so a hardware + # throttle/mixture / autopilot can drive the simulator. Same per-index + # 8-slot format. Omit a slot with "_" to leave that X-Plane control + # untouched. + # --------------------------------------------------------------------- + send: + # idx 25 — Throttle command (1.0 = full throttle) + 25: [THR1, _, _, _, _, _, _, _] + + # idx 29 — Mixture command + 29: [MIX1, _, _, _, _, _, _, _] diff --git a/src/fixgw/plugins/xplane/__init__.py b/src/fixgw/plugins/xplane/__init__.py index 021d95d3..95a2b075 100644 --- a/src/fixgw/plugins/xplane/__init__.py +++ b/src/fixgw/plugins/xplane/__init__.py @@ -1,6 +1,7 @@ #!/usr/bin/env python # Copyright (c) 2014 Phil Birkelbach +# Copyright (c) 2026 Bill Mallard — data-driven rewrite # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -11,111 +12,226 @@ # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - -# X-Plane Plugin +"""X-Plane fix-gateway plugin. + +Speaks X-Plane's UDP "DATA" packet protocol used by +``Settings → Network → Data Output → Send network data output via UDP``. +Each packet carries a 5-byte header (``"DATA\\0"``) followed by 36-byte +rows: an int32 index plus eight float32 slots. The slot layout per +index is defined by X-Plane; this plugin maps row index -> list of +eight FIX keys via YAML, so adding a new index means a single config +edit, not a code patch. + +Config schema (``connections/xplane.yaml``): + + xplane: + load: XPLANE + module: fixgw.plugins.xplane + ipaddress: 127.0.0.1 # X-Plane host (for outgoing DREF writes) + udp_in: 49001 # local UDP port we receive on + udp_out: 49002 # X-Plane UDP port we send to + send_interval: 0.1 # seconds between FIX -> X-Plane bursts + + # X-Plane -> FIX. Eight slots per index. ``_`` / ``x`` / blank skip. + recv: + 3: [IAS, _, TAS, GS, _, _, _, _] # speeds + 4: [_, _, VS, _, _, _, _, _] # mach/VVI/g + 17: [PITCH, ROLL, _, HEAD, _, _, _, _] # pitch/roll/headings + 18: [AOA, _, TRACK, _, _, _, _, _] # AOA/sideslip/paths + 20: [LAT, LONG, ALT, AGL, _, _, _, _] # position + + # FIX -> X-Plane. Same format. (Optional; omit for read-only.) + send: + 25: [THR1, _, _, _, _, _, _, _] # throttle command + +Legacy ``idxN: KEY1,KEY2,...`` entries at the top level are still +honoured and treated as ``send`` mappings (matching the old plugin's +behaviour). +""" import threading import socket import select import struct + import fixgw.plugin as plugin -# TODO Replace with configuration -UDP_IP = "127.0.0.1" -UDP_PORT = 49203 + +# X-Plane packet framing. +HEADER = b"DATA" +HEADER_LEN = 5 # "DATA" + one reserved byte +ROW_SIZE = 36 # i32 index + 8 * f32 +SLOTS_PER_ROW = 8 + +# X-Plane's "no value" sentinel float (negative NaN-ish). Lifted from +# the original plugin so existing X-Plane UI / aircraft code that +# checks for "this slot intentionally not sent" still works. +NO_VALUE = b"\x00\xc0\x79\xc4" + + +def _normalise_slot(value): + """Return the FIX key for a slot, or None when it should be skipped.""" + if value is None: + return None + s = str(value).strip() + if not s or s.lower() in ("_", "x"): + return None + return s.upper() + + +def _parse_slot_list(value): + """Accept either a YAML list or the legacy comma-separated string.""" + if isinstance(value, (list, tuple)): + items = list(value) + else: + items = [s for s in str(value).split(",")] + items = (items + [None] * SLOTS_PER_ROW)[:SLOTS_PER_ROW] + return [_normalise_slot(s) for s in items] + + +def _build_index_map(spec): + """Turn a {idx: slot_list} dict (with int or str keys) into + {int: [8 keys or None]}.""" + out = {} + if not isinstance(spec, dict): + return out + for raw_key, raw_val in spec.items(): + try: + idx = int(raw_key) + except (TypeError, ValueError): + continue + out[idx] = _parse_slot_list(raw_val) + return out + + +def _legacy_send_map(config): + """Top-level ``idxN`` entries in the legacy schema meant "send to + X-Plane at index N". Promote them into the new send_map shape.""" + legacy = {} + for k, v in config.items(): + ks = str(k) + if ks.lower().startswith("idx") and ks[3:].isdigit(): + legacy[int(ks[3:])] = v + return _build_index_map(legacy) class MainThread(threading.Thread): def __init__(self, parent): - super(MainThread, self).__init__() - self.getout = False # indicator for when to stop - self.parent = parent # parent plugin object - self.log = parent.log # simplifies logging - - self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Internet # UDP - self.sock.bind((UDP_IP, UDP_PORT)) - self.sock.setblocking(0) - - # inputkeys is a dictionary that holds the data out indexes from X-Plane - # and the keys to use for that data in FixGW to know what to send. It's - # read from the config file. Only data that is found in this config - # will be read from the database and sent to X-Plane - self.inputkeys = {} - for each in self.parent.config: - if each[:3].lower() == "idx": - index = int(each[3:]) - l = self.parent.config[each].replace(" ", "").split(",") - self.inputkeys[index] = l - - def writedata(self, index, data): - if index == 3: - self.parent.db_write("IAS", data[0]) - self.parent.db_write("TAS", data[2]) - elif index == 20: - self.parent.db_write("ALT", data[2]) - self.parent.db_write("LAT", data[0]) - self.parent.db_write("LONG", data[1]) - else: - self.parent.log.debug("Dunno Index:" + str(index)) - # self.parent.db_write("",data[0]) - + super().__init__() + self.getout = False + self.parent = parent + self.log = parent.log + cfg = parent.config + + self.xplane_ip = cfg.get("ipaddress", "127.0.0.1") + self.udp_in = int(cfg.get("udp_in", 49001)) + self.udp_out = int(cfg.get("udp_out", 49002)) + self.send_interval = float(cfg.get("send_interval", 0.1)) + + self.recv_map = _build_index_map(cfg.get("recv", {})) + self.send_map = _build_index_map(cfg.get("send", {})) + if not self.send_map: + self.send_map = _legacy_send_map(cfg) + + self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self.sock.bind(("0.0.0.0", self.udp_in)) + self.sock.setblocking(False) + + self.log.info( + "xplane: listening udp:%d, dest %s:%d; recv indices=%s, send indices=%s", + self.udp_in, self.xplane_ip, self.udp_out, + sorted(self.recv_map.keys()), sorted(self.send_map.keys())) + + # ------------------------------------------------------------------ + # X-Plane -> FIX + # ------------------------------------------------------------------ + def writedata(self, index, values): + slots = self.recv_map.get(index) + if not slots: + self.log.debug("xplane: unmapped index %d", index) + return + for slot_i, key in enumerate(slots): + if key is None or slot_i >= len(values): + continue + try: + self.parent.db_write(key, float(values[slot_i])) + except Exception as e: + self.log.warning( + "xplane: db_write %s=%r failed (%s)", + key, values[slot_i], e) + + def _ingest_packet(self, data): + if len(data) < HEADER_LEN or data[:4] != HEADER: + self.log.error("xplane: bad header on packet length %d", len(data)) + return + body = data[HEADER_LEN:] + if len(body) % ROW_SIZE != 0: + self.log.error( + "xplane: bad packet length %d (body %d, row %d)", + len(data), len(body), ROW_SIZE) + return + for r in range(len(body) // ROW_SIZE): + base = r * ROW_SIZE + idx = struct.unpack_from(" X-Plane + # ------------------------------------------------------------------ def senddata(self): - """Function that sends data to X-Plane""" - for each in self.inputkeys: - data = "DATA" + chr(0) - data += struct.pack("i", int(each)) - - for i in range(8): - if self.inputkeys[each][i].lower() == "x": - data += chr(0) + chr(192) + chr(121) + chr(196) - # data += struct.pack("f", 0.0) + for index, slots in self.send_map.items(): + buf = HEADER + b"\x00" + struct.pack(" FIX +# --------------------------------------------------------------------------- + +def test_writedata_speeds(mock_parent, main_thread): + main_thread.writedata(3, [105.0, 102.0, 110.0, 95.0, 0, 0, 0, 0]) mock_parent.db_write.assert_has_calls([ - call("IAS", 100.0), - call("TAS", 200.0), + call("IAS", 105.0), + call("TAS", 110.0), + call("GS", 95.0), ], any_order=True) + # "_" slots must not produce writes + written_keys = [c.args[0] for c in mock_parent.db_write.call_args_list] + assert "X" not in written_keys + assert "_" not in written_keys - main_thread.writedata(20, [40.7128, -74.0060, 1000.0]) + +def test_writedata_attitude(mock_parent, main_thread): + main_thread.writedata(17, [-2.5, 8.3, 271.0, 273.0, 0, 0, 0, 0]) mock_parent.db_write.assert_has_calls([ - call("LAT", 40.7128), - call("LONG", -74.0060), - call("ALT", 1000.0), + call("PITCH", -2.5), + call("ROLL", 8.3), + call("HEAD", 273.0), ], any_order=True) - main_thread.writedata(99, [0.0, 0.0, 0.0]) - mock_parent.log.debug.assert_called_with("Dunno Index:99") +def test_writedata_position(mock_parent, main_thread): + main_thread.writedata(20, [34.42, -119.85, 12000.0, 11500.0, 0, 0, 0, 0]) + mock_parent.db_write.assert_has_calls([ + call("LAT", 34.42), + call("LONG", -119.85), + call("ALT", 12000.0), + call("AGL", 11500.0), + ], any_order=True) -def senddata(self): - """Function that sends data to X-Plane""" - for each in self.inputkeys: - data = b"DATA" + b"\x00" # Start with bytes - data += struct.pack("i", int(each)) - for i in range(8): - if self.inputkeys[each][i].lower() == "x": - data += b"\x00\xc0\x79\xc4" # Append fixed bytes - else: - value = float(self.parent.db_read(self.inputkeys[each][i].upper())) - data += struct.pack("f", value) # Pack as float and append - - self.sock.sendto(data, ('127.0.0.1', 49200)) +def test_writedata_unmapped_index_is_silent(mock_parent, main_thread): + main_thread.writedata(99, [0.0] * 8) + mock_parent.db_write.assert_not_called() + mock_parent.log.debug.assert_called_with("xplane: unmapped index %d", 99) + + +def test_writedata_db_failure_is_logged_not_raised(mock_parent, main_thread): + mock_parent.db_write.side_effect = RuntimeError("no such key") + # Should not propagate; the loop must keep running across bad keys. + main_thread.writedata(20, [34.0, -120.0, 1000.0, 800.0, 0, 0, 0, 0]) + assert mock_parent.log.warning.called + + +# --------------------------------------------------------------------------- +# Packet parsing +# --------------------------------------------------------------------------- + +def _make_packet(rows): + """Build a well-formed X-Plane DATA packet from (index, [8 floats]).""" + buf = HEADER + b"\x00" + for idx, floats in rows: + pad = list(floats) + [0.0] * (8 - len(floats)) + buf += struct.pack(" X-Plane +# --------------------------------------------------------------------------- + +def test_senddata_packs_one_row_per_index(mock_parent, main_thread): + sent = [] + main_thread.sock.sendto = MagicMock(side_effect=lambda buf, addr: sent.append((buf, addr))) + main_thread.senddata() + assert len(sent) == 1 + buf, addr = sent[0] + assert addr == ("10.0.0.99", 49002) + assert buf[:4] == HEADER + # idx i32 + 8 floats + idx = struct.unpack_from(" Date: Mon, 1 Jun 2026 15:18:00 -0500 Subject: [PATCH 04/26] xplane: HEAD maps to idx 17 slot 4 (magnetic heading) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Verified live against X-Plane 12 by capturing a real DATA packet on the Pi: idx 17 emits [Pitch, Roll, Hdg_true, _, Hdg_mag, MagVar, _, Track] Slot 3 carries the X-Plane "not enabled" sentinel (-999) — writing that to HEAD silently fails inside fix-gateway, which is why the HSI sat at zero in the first live test. Magnetic heading actually lives in slot 4. The previous header-comment guess (slot 3 = Hdg_mag) came from an older X-Plane layout. --- src/fixgw/config/connections/xplane.yaml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/fixgw/config/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index 5fb01341..80c7459a 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -41,9 +41,11 @@ xplane: # slots: [Qrad_sec, Prad_sec, Rrad_sec, ...] (pitch/roll/yaw rates) 16: [_, _, ROT, _, _, _, _, _] - # idx 17 — Pitch, roll, headings - # slots: [Pitch_deg, Roll_deg, Heading_true, Heading_mag, _, _, _, _] - 17: [PITCH, ROLL, _, HEAD, _, _, _, _] + # idx 17 — Pitch, roll, headings (X-Plane 12 layout verified by capture) + # slots: [Pitch, Roll, Hdg_true, _, Hdg_mag, MagVar, _, Track] + # HEAD = magnetic heading (slot 4); TRACK from slot 7 if you'd rather + # use idx 17's ground-track-from-north instead of idx 18 slot 2. + 17: [PITCH, ROLL, _, _, HEAD, _, _, _] # idx 18 — AOA, sideslip, paths # slots: [alpha, beta, hpath, vpath, _, _, _, _] From c591fe0e96ee0419ca737dcf31002835a6bdda91 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Mon, 1 Jun 2026 17:22:08 -0500 Subject: [PATCH 05/26] xplane: filter -999 sentinel + publish MAGVAR MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Plane fills data-set slots that aren't enabled in the Net Connections "Data Output" panel with -999.0. The plugin used to write that straight through to the FIX database, which silently broke any downstream consumer that took the value at face value — most importantly, MAGVAR=-999 would turn pyEfis's true-heading correction (HEAD - MAGVAR) into HEAD + 999 and rotate the SVS picture by ~999 deg. Anything within +/- 0.5 of -999 is now treated as "this slot is disabled" and skipped. Map idx 17 slot 5 to a new FIX key MAGVAR (X-Plane "magnetic variation"). pyEfis's AI widget uses it to derive TRUE heading from the magnetic HEAD before passing it to the SVS, which does its geographic projection in true-north coordinates. Add two tests for sentinel filtering (all-sentinel row writes nothing; mixed-sentinel row publishes only valid slots). --- src/fixgw/config/connections/xplane.yaml | 8 +++++--- src/fixgw/plugins/xplane/__init__.py | 20 +++++++++++++++++--- tests/plugins/xplane/test_xplane.py | 24 ++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 6 deletions(-) diff --git a/src/fixgw/config/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index 80c7459a..65edd41c 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -43,9 +43,11 @@ xplane: # idx 17 — Pitch, roll, headings (X-Plane 12 layout verified by capture) # slots: [Pitch, Roll, Hdg_true, _, Hdg_mag, MagVar, _, Track] - # HEAD = magnetic heading (slot 4); TRACK from slot 7 if you'd rather - # use idx 17's ground-track-from-north instead of idx 18 slot 2. - 17: [PITCH, ROLL, _, _, HEAD, _, _, _] + # HEAD = magnetic heading (slot 4) — what the HSI displays. + # MAGVAR = magnetic variation (slot 5) — used by the AI widget to + # derive true heading for SVS geographic projection + # (TRUE = HEAD - MAGVAR; positive MAGVAR = west variation). + 17: [PITCH, ROLL, _, _, HEAD, MAGVAR, _, _] # idx 18 — AOA, sideslip, paths # slots: [alpha, beta, hpath, vpath, _, _, _, _] diff --git a/src/fixgw/plugins/xplane/__init__.py b/src/fixgw/plugins/xplane/__init__.py index 95a2b075..f93d971a 100644 --- a/src/fixgw/plugins/xplane/__init__.py +++ b/src/fixgw/plugins/xplane/__init__.py @@ -68,6 +68,14 @@ # checks for "this slot intentionally not sent" still works. NO_VALUE = b"\x00\xc0\x79\xc4" +# X-Plane fills disabled slots in a data row with -999.0. Writing that +# value into the FIX database would publish a bogus reading downstream +# (e.g. MAGVAR=-999 silently turning HEAD into HEAD+999 wherever it's +# used as a true-heading correction). Anything magnitude-comparable +# to the sentinel is treated as "no data" and skipped. +NO_VALUE_SENTINEL = -999.0 +NO_VALUE_TOL = 0.5 + def _normalise_slot(value): """Return the FIX key for a slot, or None when it should be skipped.""" @@ -153,12 +161,18 @@ def writedata(self, index, values): for slot_i, key in enumerate(slots): if key is None or slot_i >= len(values): continue + v = float(values[slot_i]) + # Skip X-Plane's "this slot is disabled" sentinel — don't + # let -999 reach the FIX database where it would corrupt + # any downstream consumer that takes the value at face + # value (e.g. ``HEAD - MAGVAR`` for true-heading correction). + if abs(v - NO_VALUE_SENTINEL) < NO_VALUE_TOL: + continue try: - self.parent.db_write(key, float(values[slot_i])) + self.parent.db_write(key, v) except Exception as e: self.log.warning( - "xplane: db_write %s=%r failed (%s)", - key, values[slot_i], e) + "xplane: db_write %s=%r failed (%s)", key, v, e) def _ingest_packet(self, data): if len(data) < HEADER_LEN or data[:4] != HEADER: diff --git a/tests/plugins/xplane/test_xplane.py b/tests/plugins/xplane/test_xplane.py index dbb77151..3cb177f7 100644 --- a/tests/plugins/xplane/test_xplane.py +++ b/tests/plugins/xplane/test_xplane.py @@ -137,6 +137,30 @@ def test_writedata_unmapped_index_is_silent(mock_parent, main_thread): mock_parent.log.debug.assert_called_with("xplane: unmapped index %d", 99) +def test_writedata_filters_no_value_sentinel(mock_parent, main_thread): + """X-Plane fills slots that aren't enabled in the data-output + panel with -999.0. The plugin must NOT propagate that value to the + FIX database — it would silently turn downstream consumers (e.g. + ``HEAD - MAGVAR`` correction in pyEfis) into nonsense.""" + main_thread.writedata(20, [-999.0, -999.0, -999.0, -999.0, 0, 0, 0, 0]) + # No db_write call should have fired for the four sentinel slots + # (the remaining four are mapped to "_" so they wouldn't write anyway). + mock_parent.db_write.assert_not_called() + + +def test_writedata_filters_sentinel_per_slot(mock_parent, main_thread): + """A mixed row with some valid floats and some -999 sentinels must + publish only the valid slots.""" + # idx 20 slots: [LAT, LONG, ALT, AGL, _, _, _, _] + main_thread.writedata(20, [34.5, -999.0, 1000.0, -999.0, 0, 0, 0, 0]) + keys_written = sorted(c.args[0] for c in mock_parent.db_write.call_args_list) + assert keys_written == ["ALT", "LAT"] + # And the values came through unmodified + by_key = {c.args[0]: c.args[1] for c in mock_parent.db_write.call_args_list} + assert by_key["LAT"] == 34.5 + assert by_key["ALT"] == 1000.0 + + def test_writedata_db_failure_is_logged_not_raised(mock_parent, main_thread): mock_parent.db_write.side_effect = RuntimeError("no such key") # Should not propagate; the loop must keep running across bad keys. From 6032d628db55ec458a862c50e2fed104bb1aa788 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Mon, 1 Jun 2026 17:25:27 -0500 Subject: [PATCH 06/26] ahrs db: register MAGVAR key for true-heading correction Adds a MAGVAR entry to the AHRS database group so the X-Plane plugin (and any future GPS or AHRS plugin that has the value) can db_write it without the netfix server returning "key not found". Used by pyEfis to derive true heading from magnetic for the SVS geographic projection. TRUE = MAG - MAGVAR (positive MAGVAR = west variation, per FAA "West is best" convention) --- src/fixgw/config/database/ahrs.yaml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/fixgw/config/database/ahrs.yaml b/src/fixgw/config/database/ahrs.yaml index 923cf1d5..67c07aba 100644 --- a/src/fixgw/config/database/ahrs.yaml +++ b/src/fixgw/config/database/ahrs.yaml @@ -161,6 +161,15 @@ items: initial: 0.0 tol: 2000 +- key: MAGVAR + description: Local Magnetic Variation (positive = west variation, MAG = TRUE + VAR) + type: float + min: -30.0 + max: 30.0 + units: deg + initial: 0.0 + tol: 60000 + - key: TRACK description: Current Aircraft Bearing type: float From 097b74fea3aaf0560ae99856f6d81dd6510632b3 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Tue, 2 Jun 2026 07:26:41 -0500 Subject: [PATCH 07/26] xplane: publish VPATH (idx 18 slot 3) for use by FPM rendering MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Plane's idx 18 slot 3 is "vpath" — the vertical flight path angle X-Plane uses for its OWN primary-flight-display FPM symbol. It's computed from instantaneous velocity components and matches what a pilot sees in X-Plane's avionics. pyEfis's current FPM computes the angle as atan2(VS, GS), which is the steady-state correct formula but lags vpath during transient descents because X-Plane's VVI (vertical velocity indicator, idx 4 slot 2) is a vario reading with its own lag. Add a VPATH FIX key in the AHRS database and map idx 18 slot 3 to it so pyEfis can use it directly when available. Real-world GPS / AHRS data sources don't publish VPATH; pyEfis falls back to atan2(VS, GS) in that case (unchanged behavior from before). --- src/fixgw/config/connections/xplane.yaml | 6 +++++- src/fixgw/config/database/ahrs.yaml | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/fixgw/config/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index 65edd41c..c2e3df14 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -51,7 +51,11 @@ xplane: # idx 18 — AOA, sideslip, paths # slots: [alpha, beta, hpath, vpath, _, _, _, _] - 18: [AOA, _, TRACK, _, _, _, _, _] + # VPATH = X-Plane's authoritative vertical flight path angle + # (negative = descending). Matches X-Plane's own FPM symbol; + # pyEfis uses it directly so the two displays agree even + # during transient descents where atan2(VS, GS) lags vpath. + 18: [AOA, _, TRACK, VPATH, _, _, _, _] # idx 20 — Lat, lon, altitude # slots: [lat, lon, alt_ft_msl, alt_ft_agl, _, _, _, _] diff --git a/src/fixgw/config/database/ahrs.yaml b/src/fixgw/config/database/ahrs.yaml index 67c07aba..e5cc3025 100644 --- a/src/fixgw/config/database/ahrs.yaml +++ b/src/fixgw/config/database/ahrs.yaml @@ -170,6 +170,18 @@ items: initial: 0.0 tol: 60000 +- key: VPATH + description: Vertical Flight Path Angle (negative = descending). Authoritative + when source can compute it from instantaneous velocity components (e.g. a sim + or AHRS with inertial state); pyEfis FPM falls back to atan2(VS, GS) when + VPATH is not published. + type: float + min: -90.0 + max: 90.0 + units: deg + initial: 0.0 + tol: 2000 + - key: TRACK description: Current Aircraft Bearing type: float From 7bc7a1b25ac140ac34dd07caa1a2c8c3075584e2 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Wed, 17 Jun 2026 09:23:34 -0500 Subject: [PATCH 08/26] xplane: subscribe to nav-radio datarefs (RREF) for HSI COURSE/CDI The indexed "Data Output" UDP rows X-Plane sends don't carry the nav-radio OBS course or lateral deflection, so the HSI magenta course bug and CDI needle had nothing to read. Add RREF (named-dataref) subscription support so fix-gateway requests those values by name. - _build_dataref_map() assigns RREF indices (from RREF_BASE) to a configurable FIX_KEY -> dataref map, with optional per-key scale (FIX_KEY: [dataref, scale]). - subscribe_datarefs()/_send_rref() send the RREF requests; run() re-subscribes every ~5s so a mid-stream X-Plane restart recovers, and stop() cancels the streams (freq 0). - _ingest_rref() parses the "RREF," response (int32 index + float32 value pairs), maps each back to its FIX key, and db_writes value*scale. - xplane.yaml: COURSE <- nav1_obs_degm (deg mag, used as-is), CDI <- nav1_hdef_dot x0.4 (X-Plane +/-2.5 dots -> HSI +/-1.0 full scale). Named-dataref support is opt-in: no `datarefs:` block => empty map, so existing configs are unaffected. Covered by no-network unit tests for the map builder, RREF parse+scale, unknown-index drop, and the subscription request packets. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/fixgw/config/connections/xplane.yaml | 18 +++++ src/fixgw/plugins/xplane/__init__.py | 89 +++++++++++++++++++++++- tests/plugins/xplane/test_xplane.py | 67 ++++++++++++++++++ 3 files changed, 173 insertions(+), 1 deletion(-) diff --git a/src/fixgw/config/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index c2e3df14..5c938d74 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -61,6 +61,24 @@ xplane: # slots: [lat, lon, alt_ft_msl, alt_ft_agl, _, _, _, _] 20: [LAT, LONG, ALT, AGL, _, _, _, _] + # --------------------------------------------------------------------- + # X-Plane -> FIX via named datarefs (RREF subscriptions). Use for values + # the indexed "Data Output" rows above don't carry -- notably the nav-radio + # OBS course and lateral deflection the HSI course bug + CDI need. fix-gateway + # requests these by name, so X-Plane needs no extra Data Output checkboxes. + # FIX_KEY: dataref -> written as-is + # FIX_KEY: [dataref, scale] -> written * scale + # Defaults use NAV1; swap nav1_ for nav2_ or gps_ for those sources. + # --------------------------------------------------------------------- + datarefs: + # Selected OBS course (degrees magnetic) -> magenta course bug. + COURSE: sim/cockpit/radios/nav1_obs_degm + # Lateral deviation: X-Plane reports +/-2.5 dots full scale; the HSI + # needle is +/-1.0 full scale, so scale by 1/2.5 = 0.4. + CDI: [sim/cockpit/radios/nav1_hdef_dot, 0.4] + # RREF stream rate (Hz). + dataref_hz: 10 + # --------------------------------------------------------------------- # FIX -> X-Plane. pyEfis writes its controls back so a hardware # throttle/mixture / autopilot can drive the simulator. Same per-index diff --git a/src/fixgw/plugins/xplane/__init__.py b/src/fixgw/plugins/xplane/__init__.py index f93d971a..1be80815 100644 --- a/src/fixgw/plugins/xplane/__init__.py +++ b/src/fixgw/plugins/xplane/__init__.py @@ -63,6 +63,15 @@ ROW_SIZE = 36 # i32 index + 8 * f32 SLOTS_PER_ROW = 8 +# Named-dataref (RREF) subscription support. Some values pyEfis needs are not +# in the indexed "Data Output" rows (notably nav-radio OBS course / deflection +# for the HSI). RREF lets us request specific datarefs by name; X-Plane streams +# them back as (int index, float value) pairs under a "RREF" header. We assign +# each configured dataref a request index from RREF_BASE and map the echoed +# index back to a FIX key. Protocol mirrors the proven MAOS-FCS xplane_bridge. +RREF_HEADER = b"RREF" +RREF_BASE = 1000 # first request index (X-Plane echoes it back) + # X-Plane's "no value" sentinel float (negative NaN-ish). Lifted from # the original plugin so existing X-Plane UI / aircraft code that # checks for "this slot intentionally not sent" still works. @@ -112,6 +121,31 @@ def _build_index_map(spec): return out +def _build_dataref_map(spec): + """Turn a ``{FIX_KEY: dataref}`` (or ``{FIX_KEY: [dataref, scale]}``) dict + into ``{rref_index: (key, dataref, scale)}`` with sequential request + indices. ``scale`` multiplies the raw dataref value before it's written to + FIX (e.g. nav deflection dots +/-2.5 -> HSI +/-1 needs scale 0.4).""" + out = {} + if not isinstance(spec, dict): + return out + idx = RREF_BASE + for raw_key, raw_val in spec.items(): + key = _normalise_slot(raw_key) + if key is None: + continue + if isinstance(raw_val, (list, tuple)): + dref = str(raw_val[0]).strip() + scale = float(raw_val[1]) if len(raw_val) > 1 else 1.0 + else: + dref, scale = str(raw_val).strip(), 1.0 + if not dref: + continue + out[idx] = (key, dref, scale) + idx += 1 + return out + + def _legacy_send_map(config): """Top-level ``idxN`` entries in the legacy schema meant "send to X-Plane at index N". Promote them into the new send_map shape.""" @@ -141,6 +175,13 @@ def __init__(self, parent): if not self.send_map: self.send_map = _legacy_send_map(cfg) + # Named-dataref (RREF) subscriptions: {rref_index: (key, dataref, scale)}. + self.dataref_map = _build_dataref_map(cfg.get("datarefs", {})) + self.dataref_hz = int(cfg.get("dataref_hz", 10)) + # Re-send subscriptions every ~5s so they survive an X-Plane (re)start + # or a lost subscribe packet, expressed in select-loop iterations. + self._resub_every = max(1, int(5.0 / self.send_interval)) + self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(("0.0.0.0", self.udp_in)) self.sock.setblocking(False) @@ -190,6 +231,38 @@ def _ingest_packet(self, data): slots = struct.unpack_from("<8f", body, base + 4) self.writedata(idx, list(slots)) + # ------------------------------------------------------------------ + # X-Plane named-dataref (RREF) subscriptions + # ------------------------------------------------------------------ + def _send_rref(self, freq, index, dref): + """Subscribe (freq>0, Hz) or cancel (freq=0) one dataref.""" + packet = (RREF_HEADER + b"\x00" + struct.pack(" X-Plane # ------------------------------------------------------------------ @@ -222,6 +295,9 @@ def senddata(self): # Loop # ------------------------------------------------------------------ def run(self): + if self.dataref_map: + self.subscribe_datarefs(self.dataref_hz) + loops = 0 while not self.getout: ready, _, _ = select.select( [self.sock], [], [], self.send_interval) @@ -231,12 +307,23 @@ def run(self): except OSError as e: self.log.warning("xplane: recv error (%s)", e) continue - self._ingest_packet(data) + if data[:4] == HEADER: # "DATA" — indexed rows + self._ingest_packet(data) + elif data[:4] == RREF_HEADER: # "RREF" — subscribed datarefs + self._ingest_rref(data) if self.send_map: self.senddata() + loops += 1 + if self.dataref_map and loops % self._resub_every == 0: + self.subscribe_datarefs(self.dataref_hz) # survive X-Plane restart def stop(self): self.getout = True + if self.dataref_map: + try: + self.subscribe_datarefs(0) # freq 0 cancels the subscriptions + except Exception: + pass try: self.sock.close() except Exception: diff --git a/tests/plugins/xplane/test_xplane.py b/tests/plugins/xplane/test_xplane.py index 3cb177f7..f5a2750d 100644 --- a/tests/plugins/xplane/test_xplane.py +++ b/tests/plugins/xplane/test_xplane.py @@ -13,8 +13,10 @@ from fixgw.plugins.xplane import ( HEADER, NO_VALUE, + RREF_BASE, MainThread, Plugin, + _build_dataref_map, _build_index_map, _normalise_slot, _parse_slot_list, @@ -262,6 +264,71 @@ def test_legacy_idx_keys_become_send_map(): assert t.recv_map == {} +# --------------------------------------------------------------------------- +# Named-dataref (RREF) subscriptions — X-Plane nav radios -> FIX +# --------------------------------------------------------------------------- + +def test_build_dataref_map_assigns_indices_and_scale(): + m = _build_dataref_map({ + "COURSE": "sim/cockpit/radios/nav1_obs_degm", + "CDI": ["sim/cockpit/radios/nav1_hdef_dot", 0.4], + "_": "skip/me", # skip-alias key dropped + }) + assert len(m) == 2 + by_key = {e[0]: e for e in m.values()} + assert set(by_key) == {"COURSE", "CDI"} + assert by_key["CDI"][1] == "sim/cockpit/radios/nav1_hdef_dot" + assert by_key["CDI"][2] == 0.4 # scale parsed + assert by_key["COURSE"][2] == 1.0 # default scale + assert min(m.keys()) == RREF_BASE # indices start at RREF_BASE + + +@pytest.fixture +def main_thread_nav(mock_parent): + cfg = dict(mock_parent.config) + cfg["datarefs"] = { + "COURSE": "sim/cockpit/radios/nav1_obs_degm", + "CDI": ["sim/cockpit/radios/nav1_hdef_dot", 0.4], + } + mock_parent.config = cfg + with patch("socket.socket"): + return MainThread(mock_parent) + + +def test_ingest_rref_writes_scaled_values(mock_parent, main_thread_nav): + idx_by_key = {e[0]: i for i, e in main_thread_nav.dataref_map.items()} + # RREF response: "RREF," 5-byte header + (int32 index, float32 value) pairs + pkt = (b"RREF," + + struct.pack("= RREF_BASE + + +def test_no_datarefs_config_means_empty_map(main_thread): + assert main_thread.dataref_map == {} # back-compat: nav RREF is opt-in + + # --------------------------------------------------------------------------- # Plugin lifecycle # --------------------------------------------------------------------------- From e7bc77c00de8b6ea6aec97b1b767b3ca2adfcac1 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Wed, 17 Jun 2026 10:32:52 -0500 Subject: [PATCH 09/26] =?UTF-8?q?xplane:=20fix=20RREF=20requests=20?= =?UTF-8?q?=E2=80=94=20pad=20dref=20to=20400=20bytes,=20send=20to=2049000?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The named-dataref subscriptions never delivered values. Two bugs, both found by probing a live X-Plane 12 over localhost: 1. The dref field must be a fixed 400-byte block ("<4sxii400s"). X-Plane silently ignores a short "dref + NUL" request — it still replies, but echoes index 0 / value 0 instead of the requested index, so it looked like it was working while carrying nothing. Padded requests echo the index and the real value (verified: nav1_obs_degm came back 31.0, the set OBS course). 2. RREF (and the DATA control writes) must go to X-Plane's "port we receive on", default 49000 — the legacy UDP receiver. The previous udp_out 49002 was a stale, never-validated value, and X-Plane's newer receive port (49010) does not speak the RREF protocol. Default udp_out is now 49000. Note: the X-Plane host must also allow inbound UDP on this port through its firewall; Data Output keeps flowing regardless because that traffic is outbound from X-Plane. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/fixgw/config/connections/xplane.yaml | 14 +++++++++----- src/fixgw/plugins/xplane/__init__.py | 23 +++++++++++++++++------ tests/plugins/xplane/test_xplane.py | 8 +++++++- 3 files changed, 33 insertions(+), 12 deletions(-) diff --git a/src/fixgw/config/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index 5c938d74..c245d8a0 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -11,11 +11,15 @@ xplane: # Match this against X-Plane's "IP of data receiver" → port. udp_in: 49001 - # X-Plane's UDP port for incoming DATA writes (throttle, mixture, etc). - # Default X-Plane "Port we send to other computers" is 49000; the - # legacy fix-gateway plugin used 49200 — kept here for compatibility - # with the old behaviour. - udp_out: 49002 + # X-Plane's "Port we receive on" — where fix-gateway SENDS to X-Plane + # (DATA control writes AND named-dataref RREF requests). In X-Plane's + # Settings -> Network -> UDP PORTS this is the LEGACY receive port, + # default 49000. The newer "Port we receive on" (default 49010) does + # NOT accept the RREF protocol, so it must be the legacy port here. + # NOTE: X-Plane must allow inbound UDP on this port through the host + # firewall, or the requests are silently dropped (Data Output still + # flows, since that's outbound from X-Plane). + udp_out: 49000 # Seconds between FIX -> X-Plane bursts. 0.1 = 10 Hz. send_interval: 0.1 diff --git a/src/fixgw/plugins/xplane/__init__.py b/src/fixgw/plugins/xplane/__init__.py index 1be80815..a6ddd405 100644 --- a/src/fixgw/plugins/xplane/__init__.py +++ b/src/fixgw/plugins/xplane/__init__.py @@ -28,9 +28,9 @@ xplane: load: XPLANE module: fixgw.plugins.xplane - ipaddress: 127.0.0.1 # X-Plane host (for outgoing DREF writes) + ipaddress: 127.0.0.1 # X-Plane host (for outgoing DATA/RREF/DREF) udp_in: 49001 # local UDP port we receive on - udp_out: 49002 # X-Plane UDP port we send to + udp_out: 49000 # X-Plane's "port we receive on" (commands) send_interval: 0.1 # seconds between FIX -> X-Plane bursts # X-Plane -> FIX. Eight slots per index. ``_`` / ``x`` / blank skip. @@ -167,7 +167,10 @@ def __init__(self, parent): self.xplane_ip = cfg.get("ipaddress", "127.0.0.1") self.udp_in = int(cfg.get("udp_in", 49001)) - self.udp_out = int(cfg.get("udp_out", 49002)) + # X-Plane's "port we receive on" -- where DATA writes and RREF/DREF + # requests must be sent. Default 49000 is X-Plane's legacy receiver; + # the modern port (default 49010) does NOT accept the RREF protocol. + self.udp_out = int(cfg.get("udp_out", 49000)) self.send_interval = float(cfg.get("send_interval", 0.1)) self.recv_map = _build_index_map(cfg.get("recv", {})) @@ -235,9 +238,17 @@ def _ingest_packet(self, data): # X-Plane named-dataref (RREF) subscriptions # ------------------------------------------------------------------ def _send_rref(self, freq, index, dref): - """Subscribe (freq>0, Hz) or cancel (freq=0) one dataref.""" - packet = (RREF_HEADER + b"\x00" + struct.pack("0, Hz) or cancel (freq=0) one dataref. + + The dataref string MUST be packed into a fixed 400-byte field + (``<4sxii400s`` = "RREF" + pad byte + int freq + int index + 400-byte + dref). X-Plane silently ignores requests where the dref field is the + wrong length -- it answers with index 0 / value 0 instead of echoing + the request index, so a short ``dref + b"\\x00"`` looks like it works + (a reply arrives) but never carries the value. Verified against + X-Plane 12's legacy UDP receiver.""" + packet = struct.pack( + "<4sxii400s", RREF_HEADER, int(freq), int(index), dref.encode("ascii")) try: self.sock.sendto(packet, (self.xplane_ip, self.udp_out)) except OSError as e: diff --git a/tests/plugins/xplane/test_xplane.py b/tests/plugins/xplane/test_xplane.py index f5a2750d..9bb46b18 100644 --- a/tests/plugins/xplane/test_xplane.py +++ b/tests/plugins/xplane/test_xplane.py @@ -320,9 +320,15 @@ def test_subscribe_datarefs_sends_rref_requests(mock_parent, main_thread_nav): assert len(sent) == 2 for buf, addr in sent: assert buf[:4] == b"RREF" - assert addr == ("10.0.0.99", 49002) + assert addr == ("10.0.0.99", 49002) # sent to udp_out (X-Plane receiver) + # "<4sxii400s": "RREF" + pad byte + freq + index + 400-byte dref field. + # X-Plane silently drops RREF requests whose dref field isn't 400 bytes, + # so the packet must be exactly 4 + 1 + 4 + 4 + 400 = 413 bytes. + assert len(buf) == 413 freq, index = struct.unpack_from("= RREF_BASE + dref = buf[13:].rstrip(b"\x00") + assert dref.startswith(b"sim/cockpit/radios/nav1_") def test_no_datarefs_config_means_empty_map(main_thread): From e82a68c7779e61b9544ffe3c48b44f033380f17e Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Wed, 17 Jun 2026 16:16:20 -0500 Subject: [PATCH 10/26] xplane config: disable FIX->X-Plane send (throttle/mixture) by default Now that udp_out points at X-Plane's real command port (49000) so RREF nav works, the DATA send rows actually land in the sim. With THR1/MIX1 not driven by real hardware they read 0, so fix-gateway was commanding throttle CLOSED / mixture CUTOFF every cycle and killing the engine mid-test. The send path is only meaningful when a hardware throttle/mixture publishes those keys, which is the opposite of the normal X-Plane -> pyEfis test. Comment the send block out by default with a warning; users with real hardware can re-enable it. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/fixgw/config/connections/xplane.yaml | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/fixgw/config/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index c245d8a0..0f104400 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -84,14 +84,21 @@ xplane: dataref_hz: 10 # --------------------------------------------------------------------- - # FIX -> X-Plane. pyEfis writes its controls back so a hardware - # throttle/mixture / autopilot can drive the simulator. Same per-index + # FIX -> X-Plane. pyEfis/hardware writes its controls back so a hardware + # throttle/mixture / autopilot can DRIVE the simulator. Same per-index # 8-slot format. Omit a slot with "_" to leave that X-Plane control # untouched. + # + # DISABLED BY DEFAULT. These rows are sent to udp_out (X-Plane's command + # port) every send_interval. If the mapped FIX keys are NOT actively driven + # by real hardware, they read 0 and will command X-Plane's throttle CLOSED + # and mixture to CUTOFF — killing the engine. Only enable this when a + # hardware throttle/mixture is genuinely publishing THR1/MIX1. For a normal + # X-Plane -> pyEfis test (the sim drives the display), leave it commented. # --------------------------------------------------------------------- - send: - # idx 25 — Throttle command (1.0 = full throttle) - 25: [THR1, _, _, _, _, _, _, _] - - # idx 29 — Mixture command - 29: [MIX1, _, _, _, _, _, _, _] + # send: + # # idx 25 — Throttle command (1.0 = full throttle) + # 25: [THR1, _, _, _, _, _, _, _] + # + # # idx 29 — Mixture command + # 29: [MIX1, _, _, _, _, _, _, _] From 26a14cc96676b32761047396240d8f442db88c19 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Sun, 28 Jun 2026 19:39:11 -0500 Subject: [PATCH 11/26] database: add HEADBUG (Selected Heading Bug) key A selected-heading setpoint for the pyEfis HSI heading bug, driven by the heading-bug buttons (or a rotary encoder). deg, 0-359.9, mirrors HEAD. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/fixgw/config/database/ahrs.yaml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/fixgw/config/database/ahrs.yaml b/src/fixgw/config/database/ahrs.yaml index e5cc3025..7e4cff1c 100644 --- a/src/fixgw/config/database/ahrs.yaml +++ b/src/fixgw/config/database/ahrs.yaml @@ -161,6 +161,15 @@ items: initial: 0.0 tol: 2000 +- key: HEADBUG + description: Selected Heading Bug + type: float + min: 0.0 + max: 359.9 + units: deg + initial: 0.0 + tol: 2000 + - key: MAGVAR description: Local Magnetic Variation (positive = west variation, MAG = TRUE + VAR) type: float From fc5542a0b508d84f17c49a8ae57b2179b3c7552f Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Sun, 28 Jun 2026 19:41:59 -0500 Subject: [PATCH 12/26] gitignore: anchor config/ to repo root config/ (unanchored) matched src/fixgw/config/ too. Anchor to /config/ so only a runtime root ./config/ is ignored and new database/connection yaml tracks without git add -f. Co-Authored-By: Claude Opus 4.8 (1M context) --- .gitignore | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 89c80a6b..e7ccdc5d 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,10 @@ doc/_* .ropeproject/* .directory -config/ +# Anchored to the repo root: ignore a runtime ./config/, NOT the tracked +# package config under src/fixgw/config/ (so new database/connection yaml is +# tracked normally without git add -f). +/config/ init.marker venv.marker From 1e8688eb93d63a06fe181059bbc49abd18aca8b2 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Sun, 28 Jun 2026 20:30:24 -0500 Subject: [PATCH 13/26] tools: dump_fix_keys.py -- FIX key catalog for the configurator Reuses fixgw.database.init so templated keys (CHTec, EGTec, ANLGa, ...) expand to runtime form (CHT11.., EGT11.., ANLG1..) exactly as the gateway sees them. Emits {key, description, type, units} JSON the configurator serves as the type-ahead dbkey catalog (fix_keys.json). Co-Authored-By: Claude Opus 4.8 (1M context) --- tools/dump_fix_keys.py | 60 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 tools/dump_fix_keys.py diff --git a/tools/dump_fix_keys.py b/tools/dump_fix_keys.py new file mode 100644 index 00000000..09c5f970 --- /dev/null +++ b/tools/dump_fix_keys.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Dump the FIX database key catalog as JSON for the configurator's type-ahead +dbkey field. + +Reuses the real database loader (fixgw.database.init), so templated keys +(CHTec, EGTec, ANLGa, ...) are expanded into their runtime form (CHT1, EGT1, +ANLG1, ...) exactly as the running gateway sees them. + +Usage: + python tools/dump_fix_keys.py [-c CONFIG] [-o OUTPUT] + +Defaults: -c src/fixgw/config/database.yaml -o fix_keys.json +""" +import argparse +import json +import logging +import os +import sys + +# Make the package importable when run from the repo root without install. +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) + + +def build_catalog(config_path): + from fixgw import database + logging.basicConfig(level=logging.ERROR) + database.init(config_path) + try: + database._stop_update_thread() + except Exception: + pass + keys = [] + for key in sorted(database.listkeys()): + item = database.get_raw_item(key) + keys.append({ + "key": key, + "description": getattr(item, "description", "") or "", + "type": getattr(item, "typestring", "") or "", + "units": getattr(item, "units", "") or "", + }) + return keys + + +def main(): + here = os.path.dirname(__file__) + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("-c", "--config", + default=os.path.join(here, "..", "src", "fixgw", "config", + "database.yaml")) + ap.add_argument("-o", "--output", default="fix_keys.json") + args = ap.parse_args() + + keys = build_catalog(args.config) + with open(args.output, "w") as fh: + json.dump({"keys": keys}, fh, indent=2) + print("wrote {} ({} FIX keys)".format(args.output, len(keys))) + + +if __name__ == "__main__": + main() From 73b620b39c064187244db981760020aa3b0e5621 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Sun, 28 Jun 2026 21:36:31 -0500 Subject: [PATCH 14/26] xplane: COURSE from GPS course, add HEADBUG from autopilot heading bug - COURSE now reads sim/cockpit/radios/gps_course_degtm (the magenta GPS CRS the EFIS shows) instead of nav1's OBS knob, which is a separate value. Comment documents swapping to nav1_obs_degm or the source-adaptive HSI indicator. - HEADBUG reads sim/cockpit/autopilot/heading_mag so the cyan heading bug tracks X-Plane's autopilot heading bug. (Note: this makes X-Plane drive HEADBUG, so it overrides the local HDG +/- buttons.) Verified live on the Pi against X-Plane: COURSE 7.4 == EFIS CRS 007, HEADBUG 84. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/fixgw/config/connections/xplane.yaml | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/fixgw/config/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index 0f104400..53bb1492 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -75,11 +75,20 @@ xplane: # Defaults use NAV1; swap nav1_ for nav2_ or gps_ for those sources. # --------------------------------------------------------------------- datarefs: - # Selected OBS course (degrees magnetic) -> magenta course bug. - COURSE: sim/cockpit/radios/nav1_obs_degm + # Selected course (deg mag) -> the magenta course pointer. GPS course by + # default, matching a magenta GPS CRS on the EFIS. Swap to + # nav1_obs_degm for a VOR/LOC OBS course, or to + # sim/cockpit2/radios/indicators/hsi_obs_deg_mag_pilot to auto-follow + # whichever source the EFIS HSI is currently using. + COURSE: sim/cockpit/radios/gps_course_degtm # Lateral deviation: X-Plane reports +/-2.5 dots full scale; the HSI # needle is +/-1.0 full scale, so scale by 1/2.5 = 0.4. CDI: [sim/cockpit/radios/nav1_hdef_dot, 0.4] + # Autopilot selected heading (deg mag) -> cyan heading bug. X-Plane + # always publishes this (no nav tuning needed), so it doubles as an + # RREF health check. NOTE: this makes X-Plane drive HEADBUG, so it will + # override the HDG +/- buttons (which write HEADBUG locally). + HEADBUG: sim/cockpit/autopilot/heading_mag # RREF stream rate (Hz). dataref_hz: 10 From 8d8133a9d7e4de296f5e3d6e9ccb0d2963c51587 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Mon, 29 Jun 2026 10:16:23 -0500 Subject: [PATCH 15/26] xplane: CDI from GPS deviation (match the GPS course) The CDI was on nav1_hdef_dot (nav1 lateral deviation), which reads ~0 with no VOR/LOC tuned. Point it at gps_hdef_dot so the needle mirrors the GPS course the EFIS is flying, matching the COURSE change. Comment documents the nav/ source-adaptive swaps and the sign flip. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/fixgw/config/connections/xplane.yaml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/fixgw/config/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index 53bb1492..f22bbb60 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -81,9 +81,13 @@ xplane: # sim/cockpit2/radios/indicators/hsi_obs_deg_mag_pilot to auto-follow # whichever source the EFIS HSI is currently using. COURSE: sim/cockpit/radios/gps_course_degtm - # Lateral deviation: X-Plane reports +/-2.5 dots full scale; the HSI - # needle is +/-1.0 full scale, so scale by 1/2.5 = 0.4. - CDI: [sim/cockpit/radios/nav1_hdef_dot, 0.4] + # Lateral deviation -> the HSI CDI needle. GPS deviation by default to + # match the GPS course above; swap nav1_/nav2_hdef_dot for a VOR/LOC, or + # cockpit2/radios/indicators/hsi_hdef_dots_pilot to auto-follow the EFIS + # source. X-Plane reports +/-2.5 dots full scale and the HSI needle is + # +/-1.0, so scale by 1/2.5 = 0.4 (use -0.4 if the needle deflects the + # wrong way). + CDI: [sim/cockpit/radios/gps_hdef_dot, 0.4] # Autopilot selected heading (deg mag) -> cyan heading bug. X-Plane # always publishes this (no nav tuning needed), so it doubles as an # RREF health check. NOTE: this makes X-Plane drive HEADBUG, so it will From 996bb25811008ae7378c886b89630774e0cdf554 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Mon, 29 Jun 2026 11:03:44 -0500 Subject: [PATCH 16/26] nav-source selector: compute "select" + NAVSRC routing Adds an EFIS-style nav-source selector so one canonical CDI/COURSE always carries the selected source -- which the HSI display and the autopilot both read. - compute.py: a "select" function. NAVSRC (0=GPS, 1=NAV1, 2=NAV2) picks which of its source inputs is copied to the output, propagating bad/fail. - ahrs.yaml: NAVSRC + per-source GPSCRS/GPSCDI/NAV1CRS/NAV1CDI keys. - xplane.yaml: publish each source's course + deviation to the per-source keys (was writing COURSE/CDI directly). - compute.yaml: select NAVSRC -> COURSE and -> CDI. GPS<->NAV1 lateral for now; NAV2, glideslope, and the X-Plane AP-follow write are follow-ups. A pyEfis button will cycle NAVSRC. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/fixgw/config/connections/compute.yaml | 11 ++++++ src/fixgw/config/connections/xplane.yaml | 22 +++++------ src/fixgw/config/database/ahrs.yaml | 45 +++++++++++++++++++++++ src/fixgw/plugins/compute.py | 32 ++++++++++++++++ 4 files changed, 97 insertions(+), 13 deletions(-) diff --git a/src/fixgw/config/connections/compute.yaml b/src/fixgw/config/connections/compute.yaml index f157cc62..796b0da3 100644 --- a/src/fixgw/config/connections/compute.yaml +++ b/src/fixgw/config/connections/compute.yaml @@ -27,6 +27,17 @@ compute: - function: xte inputs: ["LAT", "LONG", "WPLAT", "WPLON", "COURSE"] output: XTRACK + # EFIS nav-source selector: NAVSRC (0=GPS, 1=NAV1; add NAV2 inputs later) + # routes the selected source into the canonical COURSE/CDI the HSI + + # autopilot read. require_leader off so it runs without a quorum leader. + - function: select + inputs: ["NAVSRC", "GPSCRS", "NAV1CRS"] + output: COURSE + require_leader: false + - function: select + inputs: ["NAVSRC", "GPSCDI", "NAV1CDI"] + output: CDI + require_leader: false # inputs: [] # output: x # - function: span diff --git a/src/fixgw/config/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index f22bbb60..4dd13f6e 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -75,19 +75,15 @@ xplane: # Defaults use NAV1; swap nav1_ for nav2_ or gps_ for those sources. # --------------------------------------------------------------------- datarefs: - # Selected course (deg mag) -> the magenta course pointer. GPS course by - # default, matching a magenta GPS CRS on the EFIS. Swap to - # nav1_obs_degm for a VOR/LOC OBS course, or to - # sim/cockpit2/radios/indicators/hsi_obs_deg_mag_pilot to auto-follow - # whichever source the EFIS HSI is currently using. - COURSE: sim/cockpit/radios/gps_course_degtm - # Lateral deviation -> the HSI CDI needle. GPS deviation by default to - # match the GPS course above; swap nav1_/nav2_hdef_dot for a VOR/LOC, or - # cockpit2/radios/indicators/hsi_hdef_dots_pilot to auto-follow the EFIS - # source. X-Plane reports +/-2.5 dots full scale and the HSI needle is - # +/-1.0, so scale by 1/2.5 = 0.4 (use -0.4 if the needle deflects the - # wrong way). - CDI: [sim/cockpit/radios/gps_hdef_dot, 0.4] + # Per-source course + lateral deviation. The compute "select" function + # (connections/compute.yaml) routes the NAVSRC-selected source into the + # canonical COURSE/CDI keys the HSI + autopilot read -- an EFIS + # nav-source selector. hdef is +/-2.5 dots full scale and the HSI needle + # is +/-1.0, so scale by 0.4 (use -0.4 to flip the deflection sense). + GPSCRS: sim/cockpit/radios/gps_course_degtm + GPSCDI: [sim/cockpit/radios/gps_hdef_dot, 0.4] + NAV1CRS: sim/cockpit/radios/nav1_obs_degm + NAV1CDI: [sim/cockpit/radios/nav1_hdef_dot, 0.4] # Autopilot selected heading (deg mag) -> cyan heading bug. X-Plane # always publishes this (no nav tuning needed), so it doubles as an # RREF health check. NOTE: this makes X-Plane drive HEADBUG, so it will diff --git a/src/fixgw/config/database/ahrs.yaml b/src/fixgw/config/database/ahrs.yaml index 7e4cff1c..81d2db3b 100644 --- a/src/fixgw/config/database/ahrs.yaml +++ b/src/fixgw/config/database/ahrs.yaml @@ -234,6 +234,51 @@ items: initial: 0.0 tol: 2000 +# Nav-source selector + per-source course/deviation. A button sets NAVSRC; the +# compute "select" function routes the chosen source into the canonical +# COURSE/CDI above, which the HSI and autopilot read. +- key: NAVSRC + description: Selected Nav Source (0=GPS, 1=NAV1, 2=NAV2) + type: float + min: 0.0 + max: 2.0 + initial: 0.0 + tol: 2000 + +- key: GPSCRS + description: GPS Course + type: float + min: 0.0 + max: 359.9 + units: deg + initial: 0.0 + tol: 2000 + +- key: GPSCDI + description: GPS Course Deviation + type: float + min: -1.0 + max: 1.0 + initial: 0.0 + tol: 2000 + +- key: NAV1CRS + description: NAV1 OBS Course + type: float + min: 0.0 + max: 359.9 + units: deg + initial: 0.0 + tol: 2000 + +- key: NAV1CDI + description: NAV1 Course Deviation + type: float + min: -1.0 + max: 1.0 + initial: 0.0 + tol: 2000 + - key: XTRACK description: Signed Cross Track Error (left/right of desired course) type: float diff --git a/src/fixgw/plugins/compute.py b/src/fixgw/plugins/compute.py index 1fd0db30..d1ddfa06 100644 --- a/src/fixgw/plugins/compute.py +++ b/src/fixgw/plugins/compute.py @@ -757,6 +757,37 @@ def func(key, value, parent): return func +def selectFunction(inputs, output, require_leader): + # inputs[0] is the selector key; inputs[1:] are the source options. The + # selector's (rounded, clamped) value picks which source is copied to the + # output, so ONE canonical key (e.g. CDI / COURSE) always carries the + # selected source -- which the HSI display and the autopilot both read. + # Models an EFIS nav-source selector (GPS / NAV1 / NAV2). + vals = {} + for each in inputs: + vals[each] = None + + def func(key, value, parent): + if not quorum.leader and require_leader: + return # Only the leader can do calculations + if type(value) != tuple: + return # aux data, ignore + vals[key] = value + sel = vals[inputs[0]] + if sel is None: + return # no selection yet + idx = max(0, min(len(inputs) - 2, int(round(sel[0])))) + src = vals[inputs[idx + 1]] + if src is None: + return # selected source has no value yet + o = parent.db_get_item(output) + o.value = src[0] + o.bad = src[3] + o.fail = src[4] + + return func + + class Plugin(plugin.PluginBase): # def __init__(self, name, config): # super(Plugin, self).__init__(name, config) @@ -776,6 +807,7 @@ def run(self): "altd": altDensity, "encoder": encoderFunction, "set": setFunction, + "select": selectFunction, } for function in self.config["functions"]: From fef1bd805e4b872f3cf65037245dd6149b2f269c Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Mon, 29 Jun 2026 11:15:31 -0500 Subject: [PATCH 17/26] nav-source selector: add NAV2 + glideslope (GSI) Extends the selector to three sources and vertical guidance: - ahrs.yaml: NAV2CRS/NAV2CDI + per-source GPSGSI/NAV1GSI/NAV2GSI; NAVSRC max 3. - xplane.yaml: nav2 course/deviation + gps/nav1/nav2 vertical deviation (vdef). - compute.yaml: COURSE/CDI selects gain NAV2; new GSI select. NAVSRC 0=GPS, 1=NAV1, 2=NAV2 now routes course + CDI + glideslope. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/fixgw/config/connections/compute.yaml | 15 ++++--- src/fixgw/config/connections/xplane.yaml | 7 ++++ src/fixgw/config/database/ahrs.yaml | 50 +++++++++++++++++++++-- 3 files changed, 63 insertions(+), 9 deletions(-) diff --git a/src/fixgw/config/connections/compute.yaml b/src/fixgw/config/connections/compute.yaml index 796b0da3..fe177c49 100644 --- a/src/fixgw/config/connections/compute.yaml +++ b/src/fixgw/config/connections/compute.yaml @@ -27,17 +27,22 @@ compute: - function: xte inputs: ["LAT", "LONG", "WPLAT", "WPLON", "COURSE"] output: XTRACK - # EFIS nav-source selector: NAVSRC (0=GPS, 1=NAV1; add NAV2 inputs later) - # routes the selected source into the canonical COURSE/CDI the HSI + - # autopilot read. require_leader off so it runs without a quorum leader. + # EFIS nav-source selector: NAVSRC (0=GPS, 1=NAV1, 2=NAV2) routes the + # selected source's course / lateral / vertical deviation into the canonical + # COURSE / CDI / GSI the HSI + autopilot read. require_leader off so it runs + # without a quorum leader. - function: select - inputs: ["NAVSRC", "GPSCRS", "NAV1CRS"] + inputs: ["NAVSRC", "GPSCRS", "NAV1CRS", "NAV2CRS"] output: COURSE require_leader: false - function: select - inputs: ["NAVSRC", "GPSCDI", "NAV1CDI"] + inputs: ["NAVSRC", "GPSCDI", "NAV1CDI", "NAV2CDI"] output: CDI require_leader: false + - function: select + inputs: ["NAVSRC", "GPSGSI", "NAV1GSI", "NAV2GSI"] + output: GSI + require_leader: false # inputs: [] # output: x # - function: span diff --git a/src/fixgw/config/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index 4dd13f6e..3a2b81d0 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -84,6 +84,13 @@ xplane: GPSCDI: [sim/cockpit/radios/gps_hdef_dot, 0.4] NAV1CRS: sim/cockpit/radios/nav1_obs_degm NAV1CDI: [sim/cockpit/radios/nav1_hdef_dot, 0.4] + NAV2CRS: sim/cockpit/radios/nav2_obs_degm + NAV2CDI: [sim/cockpit/radios/nav2_hdef_dot, 0.4] + # Vertical deviation (glidepath / glideslope) -> the GSI needle, same + # +/-2.5-dot -> +/-1.0 scaling. gps_vdef is the GPS LPV/glidepath. + GPSGSI: [sim/cockpit/radios/gps_vdef_dot, 0.4] + NAV1GSI: [sim/cockpit/radios/nav1_vdef_dot, 0.4] + NAV2GSI: [sim/cockpit/radios/nav2_vdef_dot, 0.4] # Autopilot selected heading (deg mag) -> cyan heading bug. X-Plane # always publishes this (no nav tuning needed), so it doubles as an # RREF health check. NOTE: this makes X-Plane drive HEADBUG, so it will diff --git a/src/fixgw/config/database/ahrs.yaml b/src/fixgw/config/database/ahrs.yaml index 81d2db3b..a9b780ec 100644 --- a/src/fixgw/config/database/ahrs.yaml +++ b/src/fixgw/config/database/ahrs.yaml @@ -234,14 +234,15 @@ items: initial: 0.0 tol: 2000 -# Nav-source selector + per-source course/deviation. A button sets NAVSRC; the -# compute "select" function routes the chosen source into the canonical -# COURSE/CDI above, which the HSI and autopilot read. +# Nav-source selector + per-source course / lateral / vertical deviation. A +# button cycles NAVSRC; the compute "select" routes the chosen source into the +# canonical COURSE/CDI/GSI the HSI and autopilot read. max = the cycle modulus +# (3 sources) so change-value-wrap steps 0 -> 1 -> 2 -> 0. - key: NAVSRC description: Selected Nav Source (0=GPS, 1=NAV1, 2=NAV2) type: float min: 0.0 - max: 2.0 + max: 3.0 initial: 0.0 tol: 2000 @@ -279,6 +280,47 @@ items: initial: 0.0 tol: 2000 +- key: NAV2CRS + description: NAV2 OBS Course + type: float + min: 0.0 + max: 359.9 + units: deg + initial: 0.0 + tol: 2000 + +- key: NAV2CDI + description: NAV2 Course Deviation + type: float + min: -1.0 + max: 1.0 + initial: 0.0 + tol: 2000 + +- key: GPSGSI + description: GPS Vertical Deviation (glidepath) + type: float + min: -1.0 + max: 1.0 + initial: 0.0 + tol: 2000 + +- key: NAV1GSI + description: NAV1 Glideslope Deviation + type: float + min: -1.0 + max: 1.0 + initial: 0.0 + tol: 2000 + +- key: NAV2GSI + description: NAV2 Glideslope Deviation + type: float + min: -1.0 + max: 1.0 + initial: 0.0 + tol: 2000 + - key: XTRACK description: Signed Cross Track Error (left/right of desired course) type: float From 55613a426824d617dd03b14c3e3b95133acbe166 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Mon, 29 Jun 2026 12:13:54 -0500 Subject: [PATCH 18/26] xplane: DREF write + nav-source AP-follow (HSI_source_select) Closes the EFIS -> autopilot loop in the sim. The X-Plane plugin gains a named-dataref WRITE path (DREF), sent on change over the existing UDP socket: dataref_writes: {FIX_KEY: dataref} A compute "remap" translates NAVSRC (0=GPS,1=NAV1,2=NAV2) -> X-Plane's HSI_source_select_pilot (0=NAV1,1=NAV2,2=GPS) via the XPHSISRC key, which dataref_writes transmits. Selecting a nav source on the EFIS now switches X-Plane's CDI source so its native autopilot follows. DREF packet (509B) + remap translation unit-tested; AP behaviour is Pi-verified. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/fixgw/config/connections/compute.yaml | 8 ++++++ src/fixgw/config/connections/xplane.yaml | 7 +++++ src/fixgw/config/database/ahrs.yaml | 8 ++++++ src/fixgw/plugins/compute.py | 25 ++++++++++++++++ src/fixgw/plugins/xplane/__init__.py | 35 +++++++++++++++++++++++ 5 files changed, 83 insertions(+) diff --git a/src/fixgw/config/connections/compute.yaml b/src/fixgw/config/connections/compute.yaml index fe177c49..5525f80e 100644 --- a/src/fixgw/config/connections/compute.yaml +++ b/src/fixgw/config/connections/compute.yaml @@ -43,6 +43,14 @@ compute: inputs: ["NAVSRC", "GPSGSI", "NAV1GSI", "NAV2GSI"] output: GSI require_leader: false + # Translate NAVSRC (0=GPS,1=NAV1,2=NAV2) -> X-Plane HSI_source_select + # (0=NAV1,1=NAV2,2=GPS) so the sim's native autopilot follows the selection. + # The xplane plugin's dataref_writes sends XPHSISRC out as a DREF. + - function: remap + inputs: ["NAVSRC"] + output: XPHSISRC + table: [2, 0, 1] + require_leader: false # inputs: [] # output: x # - function: span diff --git a/src/fixgw/config/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index 3a2b81d0..bc6a8522 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -99,6 +99,13 @@ xplane: # RREF stream rate (Hz). dataref_hz: 10 + # FIX -> X-Plane named-dataref writes (DREF), sent on change. The nav-source + # selector's XPHSISRC (remapped from NAVSRC by the compute plugin) drives + # X-Plane's pilot HSI source, so the sim's native autopilot tracks whatever + # source the EFIS has selected. + dataref_writes: + XPHSISRC: sim/cockpit2/radios/actuators/HSI_source_select_pilot + # --------------------------------------------------------------------- # FIX -> X-Plane. pyEfis/hardware writes its controls back so a hardware # throttle/mixture / autopilot can DRIVE the simulator. Same per-index diff --git a/src/fixgw/config/database/ahrs.yaml b/src/fixgw/config/database/ahrs.yaml index a9b780ec..b3b8c555 100644 --- a/src/fixgw/config/database/ahrs.yaml +++ b/src/fixgw/config/database/ahrs.yaml @@ -321,6 +321,14 @@ items: initial: 0.0 tol: 2000 +- key: XPHSISRC + description: X-Plane HSI source index (0=NAV1, 1=NAV2, 2=GPS), remapped from NAVSRC + type: float + min: 0.0 + max: 2.0 + initial: 2.0 + tol: 2000 + - key: XTRACK description: Signed Cross Track Error (left/right of desired course) type: float diff --git a/src/fixgw/plugins/compute.py b/src/fixgw/plugins/compute.py index d1ddfa06..d68597cc 100644 --- a/src/fixgw/plugins/compute.py +++ b/src/fixgw/plugins/compute.py @@ -788,6 +788,23 @@ def func(key, value, parent): return func +def remapFunction(inputs, output, table, require_leader): + # inputs[0] is an index key; table is a list of output values. Emits + # table[round(index)] (clamped). Translates one selector scheme into + # another -- e.g. NAVSRC (0=GPS,1=NAV1,2=NAV2) -> X-Plane HSI_source_select + # (0=NAV1,1=NAV2,2=GPS) via table [2, 0, 1]. + def func(key, value, parent): + if not quorum.leader and require_leader: + return + if type(value) != tuple: + return + i = max(0, min(len(table) - 1, int(round(value[0])))) + o = parent.db_get_item(output) + o.value = float(table[i]) + + return func + + class Plugin(plugin.PluginBase): # def __init__(self, name, config): # super(Plugin, self).__init__(name, config) @@ -808,6 +825,7 @@ def run(self): "encoder": encoderFunction, "set": setFunction, "select": selectFunction, + "remap": remapFunction, } for function in self.config["functions"]: @@ -832,6 +850,13 @@ def run(self): function["value"], req_lead, ) + elif fname == "remap": + f = aggregate_functions[fname]( + function["inputs"], + function["output"], + function["table"], + req_lead, + ) else: f = aggregate_functions[fname]( function["inputs"], function["output"], req_lead diff --git a/src/fixgw/plugins/xplane/__init__.py b/src/fixgw/plugins/xplane/__init__.py index e5838f7b..191e5a67 100644 --- a/src/fixgw/plugins/xplane/__init__.py +++ b/src/fixgw/plugins/xplane/__init__.py @@ -72,6 +72,13 @@ RREF_HEADER = b"RREF" RREF_BASE = 1000 # first request index (X-Plane echoes it back) +# DREF: write a named dataref back to X-Plane. Packet is "DREF" + null + a +# 4-byte float value + the 500-byte null-padded dataref path (509 bytes total). +# Lets a FIX key drive a sim control (e.g. the EFIS nav-source selector setting +# X-Plane's HSI source so the native autopilot follows). Same UDP socket / dest +# as RREF, so it needs no extra reachability beyond the proven read path. +DREF_HEADER = b"DREF" + # X-Plane's "no value" sentinel float (negative NaN-ish). Lifted from # the original plugin so existing X-Plane UI / aircraft code that # checks for "this slot intentionally not sent" still works. @@ -181,6 +188,11 @@ def __init__(self, parent): # Named-dataref (RREF) subscriptions: {rref_index: (key, dataref, scale)}. self.dataref_map = _build_dataref_map(cfg.get("datarefs", {})) self.dataref_hz = int(cfg.get("dataref_hz", 10)) + # FIX -> X-Plane named-dataref writes: {fix_key: dataref}. Sent (DREF) + # only when the FIX value changes, so a slow setpoint like the HSI + # source isn't blasted at the loop rate. + self.dref_writes = dict(cfg.get("dataref_writes", {})) + self._dref_last = {} # Re-send subscriptions every ~5s so they survive an X-Plane (re)start # or a lost subscribe packet, expressed in select-loop iterations. self._resub_every = max(1, int(5.0 / self.send_interval)) @@ -305,6 +317,27 @@ def senddata(self): except OSError as e: self.log.warning("xplane: sendto failed (%s)", e) + def senddref(self): + for key, dref in self.dref_writes.items(): + try: + v = float(self.parent.db_read(key)[0]) + except (TypeError, IndexError, ValueError): + try: + v = float(self.parent.db_read(key)) + except Exception: + continue + except Exception: + continue + if self._dref_last.get(key) == v: + continue # only transmit on change + self._dref_last[key] = v + packet = struct.pack( + "<4sxf500s", DREF_HEADER, v, dref.encode("ascii")) + try: + self.sock.sendto(packet, (self.xplane_ip, self.udp_out)) + except OSError as e: + self.log.warning("xplane: DREF %s failed (%s)", dref, e) + # ------------------------------------------------------------------ # Loop # ------------------------------------------------------------------ @@ -327,6 +360,8 @@ def run(self): self._ingest_rref(data) if self.send_map: self.senddata() + if self.dref_writes: + self.senddref() loops += 1 if self.dataref_map and loops % self._resub_every == 0: self.subscribe_datarefs(self.dataref_hz) # survive X-Plane restart From c8fdb9b8f5e2f6e24230ca87f0481474b7d366c8 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Mon, 29 Jun 2026 12:38:44 -0500 Subject: [PATCH 19/26] doc: rewrite X-Plane plugin doc (data-driven) + add compute plugin doc The X-Plane plugin doc predated the data-driven rewrite and was stale ("not really usable", old idx-list syntax, wrong module path, wrong ports, nothing about recv/datarefs/dataref_writes). Rewrite it to cover all four data paths and add a "Nav-source selection and autopilot follow" section documenting the NAVSRC -> XPHSISRC -> HSI_source_select chain. Add a compute plugin reference (it had none): the full function catalog (average/sum/max/min/span/xte/aoa/altp/altd/encoder/set/select/remap), require_leader semantics, and a worked nav-source-selector example using select + remap. Co-Authored-By: Claude Opus 4.8 (1M context) --- doc/plugins/compute.rst | 150 +++++++++++++++++++++++++++++++ doc/plugins/xplane.rst | 190 +++++++++++++++++++++++++++++++++++----- 2 files changed, 320 insertions(+), 20 deletions(-) create mode 100644 doc/plugins/compute.rst diff --git a/doc/plugins/compute.rst b/doc/plugins/compute.rst new file mode 100644 index 00000000..28d67ade --- /dev/null +++ b/doc/plugins/compute.rst @@ -0,0 +1,150 @@ +================= +Compute Plugin +================= + +The compute plugin derives new FIX database keys from existing ones. It is how +FIX-Gateway produces values that are not measured directly but calculated from +other points -- averages and maxima across a bank of cylinders, density +altitude from pressure and temperature, cross-track error from position and a +flight plan, and so on. It also hosts the small *routing* primitives that +implement an EFIS nav-source selector (see `Nav-source selection`_). + +The plugin watches the ``inputs`` of each configured function; whenever an input +changes it recomputes and writes the function's ``output`` key. Most functions +propagate the input quality flags (``old`` / ``bad`` / ``fail``) to the output +and force the output to ``0`` when an input has failed. + +Configuration +============= + +The plugin is configured with a list of ``functions``. Each function names a +``function`` type, its ``inputs`` (a list of FIX keys), and its ``output`` key. + +:: + + compute: + load: COMPUTE + module: fixgw.plugins.compute + functions: + - function: max + inputs: ["CHT11", "CHT12", "CHT13", "CHT14"] + output: CHTMAX1 + + - function: altd + inputs: ["PALT", "TALT", "OAT"] + output: DALT + +Every function also accepts an optional ``require_leader`` flag: + +* ``require_leader: true`` (the default) -- the function only computes on the + node that is the current *quorum leader*. Use this in a redundant, + multi-node installation so a derived key has a single writer. +* ``require_leader: false`` -- the function always computes. Use this on a + single-node system (and for the nav-source routing below, which must run + regardless of quorum). + +A few function types take an extra configuration key (``multiplier``, ``value`` +or ``table``) noted in the catalog. + +Function catalog +================ + +``average`` + Arithmetic mean of all ``inputs`` written to ``output``. + +``sum`` + Sum of all ``inputs``. + +``max`` + Largest of the ``inputs`` (e.g. hottest CHT). + +``min`` + Smallest of the ``inputs``. + +``span`` + Difference between the largest and smallest input (e.g. EGT spread). + +``altp`` + Pressure altitude from ``inputs: [BARO, ALT_MSL]``:: + + PALT = ALT_MSL + 145442.2 * (1 - (BARO / 29.92126) ** 0.190261) + +``altd`` + Density altitude from ``inputs: [PALT, ALT_MSL, OAT]`` (OAT in degrees C):: + + std_temp = 15 - 1.98 * ALT_MSL / 1000 + DALT = PALT + 120 * (OAT - std_temp) + +``xte`` + Signed cross-track error in nautical miles from + ``inputs: [ac_lat, ac_lon, wp_lat, wp_lon, desired_course]`` (course in + degrees true). Positive = right of the desired course. + +``aoa`` + Angle-of-attack estimator. ``inputs`` are + ``[PITCH, IAS, ANORM, VS, HEAD, ]`` followed by nine tuning + constants; it learns a lift constant during steady, straight-and-level + flight and derives alpha from normal acceleration and airspeed. See the + source for the full input list and constants. + +``encoder`` + Adds ``input * multiplier`` to ``output`` (an accumulator driven by a + rotary encoder). Requires an extra ``multiplier`` key. + +``set`` + When an input is truthy, writes a fixed ``value`` to ``output``. Requires + an extra ``value`` key. + +``select`` + Routes one of several source keys to a single output, chosen by a selector + key. ``inputs[0]`` is the selector; ``inputs[1:]`` are the sources. The + selector value is rounded and clamped to pick a source, whose value (and its + ``bad`` / ``fail`` flags) is copied to ``output``. This is the heart of the + nav-source selector -- one canonical key always carries the *selected* + source. + +``remap`` + Emits ``table[round(index)]`` (clamped to the table) to ``output``, where + ``inputs[0]`` is the index. Requires an extra ``table`` key (a list). + Translates one selector numbering into another. + +Nav-source selection +==================== + +``select`` and ``remap`` together implement an EFIS navigation-source selector, +so the EFIS can both *display* the selected source and *publish* its guidance to +the keys the autopilot reads -- and, with the :doc:`xplane` plugin, drive a +simulator's autopilot to match. + +A single selector key, ``NAVSRC`` (``0`` = GPS, ``1`` = NAV1, ``2`` = NAV2), is +cycled by a button on the EFIS. ``select`` routes the chosen source's +per-source keys into the canonical ``COURSE`` / ``CDI`` / ``GSI`` keys that the +HSI and autopilot consume:: + + functions: + - function: select + inputs: ["NAVSRC", "GPSCRS", "NAV1CRS", "NAV2CRS"] + output: COURSE + require_leader: false + - function: select + inputs: ["NAVSRC", "GPSCDI", "NAV1CDI", "NAV2CDI"] + output: CDI + require_leader: false + - function: select + inputs: ["NAVSRC", "GPSGSI", "NAV1GSI", "NAV2GSI"] + output: GSI + require_leader: false + +A ``remap`` then translates ``NAVSRC`` into X-Plane's own HSI source numbering +(X-Plane uses ``0`` = NAV1, ``1`` = NAV2, ``2`` = GPS) for the +:doc:`xplane` plugin's ``dataref_writes`` to send out:: + + - function: remap + inputs: ["NAVSRC"] + output: XPHSISRC + table: [2, 0, 1] + require_leader: false + +The per-source keys (``GPSCRS``, ``NAV1CRS``, ...) are populated by the +:doc:`xplane` plugin's ``datarefs`` subscriptions; on a real aircraft they would +come from the GPS / nav-radio source plugins instead. diff --git a/doc/plugins/xplane.rst b/doc/plugins/xplane.rst index b4e6f325..2293a9ba 100644 --- a/doc/plugins/xplane.rst +++ b/doc/plugins/xplane.rst @@ -1,32 +1,182 @@ =================================== -XPlane Flight Simulator Plugin +X-Plane Flight Simulator Plugin =================================== -This plugin allows FIX-Gateway to be used to communicate to the very popular *X-Plane -Flight Simulator* +This plugin connects FIX-Gateway to the +`X-Plane `_ flight simulator over UDP. It lets +X-Plane act as a data *source* -- so a pyEfis display (or any other FIX client) +can be developed and exercised against the simulator -- and as a data *sink*, +so the EFIS can write selected values back into X-Plane. The headline use of +the write path is **nav-source follow**: when the pilot selects GPS / NAV1 / +NAV2 on the EFIS, the plugin tells X-Plane which source to drive its HSI from, +and X-Plane's own autopilot follows the EFIS (see `Nav-source selection and +autopilot follow`_ below). -**This plugin lacks a lot of work and is not really usable in it's current state** +The plugin is **data-driven**. The mapping between X-Plane's data and FIX +database keys is declared entirely in the plugin's configuration block -- new +values are wired up by editing YAML, with no code changes. The shipped +``connections/xplane.yaml`` is heavily commented and is the best line-by-line +reference; this page explains the concepts and each configuration section. +Data paths +========== + +Data moves in four ways, each its own configuration section: + +* ``recv`` -- *X-Plane to FIX* via X-Plane's indexed *Data Output* UDP stream. +* ``datarefs`` -- *X-Plane to FIX* via named datarefs requested with the + ``RREF`` protocol (for values the indexed Data Output rows do not carry). +* ``dataref_writes`` -- *FIX to X-Plane* via named-dataref ``DREF`` writes, + transmitted on change. +* ``send`` -- *FIX to X-Plane* via the indexed Data Output control stream + (disabled by default; see the warning below). + +Setting up X-Plane +================== + +In X-Plane open **Settings -> Data Output** (named *Net Connections* in older +versions) and: + +#. Enable **Send network data output** to the IP of the machine running + FIX-Gateway, at the port you set as ``udp_in`` below. +#. Check the *Data Set* rows you intend to map. The index numbers used in the + ``recv`` section correspond to these rows, and the eight columns of each row + map to the eight slots of that index. +#. In **Settings -> Network -> UDP Ports**, note the **legacy** receive port + (default ``49000``). FIX-Gateway sends control writes and both ``RREF`` and + ``DREF`` dataref traffic there as ``udp_out``. The newer "Port we receive + on" (default ``49010``) does **not** accept the ``RREF`` protocol, so the + legacy port must be used. + +.. note:: + + X-Plane must allow inbound UDP on ``udp_out`` through the host firewall, or + the requests are silently dropped. (X-Plane's outbound Data Output still + flows, so ``recv`` can appear to work while ``datarefs`` / ``dataref_writes`` + do nothing -- check the firewall first.) Configuration --------------- +============= :: xplane: - load: yes - module: plugins.xplane - # IP address where the X-Plane simulator is running + load: XPLANE + module: fixgw.plugins.xplane + + # IP of the machine running X-Plane -- the destination for FIX -> X-Plane + # writes and for RREF/DREF dataref requests. ipaddress: 127.0.0.1 - # UDP Ports to use for sending and receiving data - # These should match the configuration in the - # "Net Connections" Menu of X-Plane - udp_in: 49001 # Port to received data from X-Plane - udp_out: 49002 # Port to send data to X-Plane - - # These are the X-Plane data indexes that we will write. These - # would match the - #idx8 : CTLPTCH, CTLROLL, CTLYAW, x, x, x, x, x - idx25: THR1, THR2, x, x, x, x, x, x - #idx28: PROP1, PROP2, x, x, x, x, x, x - idx29: MIX1, MIX2, x, x, x, x, x, x + + # Local UDP port FIX-Gateway BINDS to receive X-Plane's Data Output. + udp_in: 49001 + # X-Plane's LEGACY receive port -- where FIX-Gateway SENDS data, RREF and + # DREF. Must be the legacy port (default 49000), not the newer 49010. + udp_out: 49000 + + # Seconds between FIX -> X-Plane control bursts (0.1 = 10 Hz). + send_interval: 0.1 + + # RREF stream rate, Hz (how often X-Plane sends subscribed datarefs back). + dataref_hz: 10 + +recv -- indexed Data Output (X-Plane to FIX) +-------------------------------------------- + +Each key under ``recv`` is an X-Plane Data Output *index*; its value is a list +of up to eight FIX keys, one per slot, in the same order X-Plane lists that +row's columns. Use ``_`` (or ``x`` / blank) to skip a slot. + +:: + + recv: + # idx 3 -- Speeds: [Vind_kias, Vind_keas, Vtrue_ktas, Vtrue_ktgs, ...] + 3: [IAS, _, TAS, GS, _, _, _, _] + # idx 17 -- Pitch, roll, headings: [Pitch, Roll, Hdg_true, _, Hdg_mag, MagVar, _, Track] + 17: [PITCH, ROLL, _, _, HEAD, MAGVAR, _, _] + # idx 20 -- Position: [lat, lon, alt_ft_msl, alt_ft_agl, ...] + 20: [LAT, LONG, ALT, AGL, _, _, _, _] + +datarefs -- RREF subscriptions (X-Plane to FIX) +----------------------------------------------- + +For values the indexed rows do not carry -- notably the nav-radio OBS course and +lateral/vertical deflection the HSI needs -- subscribe to X-Plane datarefs by +name. FIX-Gateway issues an ``RREF`` request for each, so X-Plane needs no +extra Data Output checkboxes. Two forms are accepted: + +* ``FIX_KEY: dataref`` -- written to the key as-is. +* ``FIX_KEY: [dataref, scale]`` -- written multiplied by ``scale``. + +:: + + datarefs: + # X-Plane hdef is +/-2.5 dots full scale; the HSI needle is +/-1.0, so + # scale by 0.4 (use -0.4 to flip the deflection sense). + GPSCRS: sim/cockpit/radios/gps_course_degtm + GPSCDI: [sim/cockpit/radios/gps_hdef_dot, 0.4] + NAV1CRS: sim/cockpit/radios/nav1_obs_degm + NAV1CDI: [sim/cockpit/radios/nav1_hdef_dot, 0.4] + HEADBUG: sim/cockpit/autopilot/heading_mag + +dataref_writes -- DREF writes (FIX to X-Plane) +---------------------------------------------- + +Each ``FIX_KEY: dataref`` entry sends the FIX key's current value to a named +X-Plane dataref as a ``DREF`` packet, **on change** (the plugin tracks the last +value sent and only transmits when it differs). This reuses the same UDP +socket as the rest of the plugin. + +:: + + dataref_writes: + XPHSISRC: sim/cockpit2/radios/actuators/HSI_source_select_pilot + +send -- indexed control output (FIX to X-Plane) +----------------------------------------------- + +The mirror of ``recv``: each index maps FIX keys onto the eight slots of an +X-Plane Data Output control row, so hardware (a throttle/mixture quadrant, an +autopilot, etc.) publishing those FIX keys can *drive* the simulator. + +.. warning:: + + ``send`` is **disabled by default** and should stay that way for an ordinary + X-Plane -> pyEfis test. These rows are transmitted every ``send_interval``; + if the mapped FIX keys are not actively driven by real hardware they read + ``0`` and will command X-Plane's throttle **closed** and mixture to + **cutoff**, killing the engine. Only enable it when genuine hardware is + publishing those keys. + +Nav-source selection and autopilot follow +========================================= + +In a real panel the EFIS is an active node in the navigation system: the pilot +selects which navigation source (GPS, NAV1, NAV2) the HSI displays, and the EFIS +publishes *that selected source's* guidance onto canonical FIX keys +(``COURSE`` / ``CDI`` / ``GSI``) that both the HSI **and the autopilot** read. +This plugin lets the same selection drive X-Plane so the simulator's native +autopilot tracks whatever the EFIS has selected. + +The mechanism uses this plugin together with the :doc:`compute` plugin: + +#. A button on the EFIS cycles the ``NAVSRC`` selector key + (``0`` = GPS, ``1`` = NAV1, ``2`` = NAV2). +#. The compute plugin's ``select`` function routes the chosen source's + per-source keys (``GPSCRS`` / ``NAV1CRS`` / ``NAV2CRS``, etc., populated by + the ``datarefs`` section above) into the canonical ``COURSE`` / ``CDI`` / + ``GSI`` keys. +#. The compute plugin's ``remap`` function translates ``NAVSRC`` into X-Plane's + own source ordering (X-Plane uses ``0`` = NAV1, ``1`` = NAV2, ``2`` = GPS) and + writes it to ``XPHSISRC``. +#. ``dataref_writes`` sends ``XPHSISRC`` out to + ``sim/cockpit2/radios/actuators/HSI_source_select_pilot``, so X-Plane + switches its HSI source and its autopilot follows. + +:: + + EFIS button -> NAVSRC --select--> COURSE/CDI/GSI (HSI + autopilot read these) + \--remap---> XPHSISRC --DREF--> X-Plane HSI source + AP + +See the :doc:`compute` plugin page for the ``select`` and ``remap`` function +definitions, and ``connections/compute.yaml`` for the shipped rules. From e0e26aa5b1e5a9840a5a34d3466872affb17ae7a Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Tue, 30 Jun 2026 14:45:00 -0500 Subject: [PATCH 20/26] nav: migrate NAVSRC to bus-native ordering (0=NAV1, 1=NAV2, 2=GPS) NAVSRC was the only GPS-first scheme in the stack; CAN-FiX OBI Flags (id 450 b1:b2) and X-Plane's HSI_source_select are both NAV-first. Aligning NAVSRC collapses all three encodings into one: - XPHSISRC becomes an identity map (remap table [2,0,1] -> [0,1,2]); the table is kept as the seam that collapses an optional GPS2 onto X-Plane's single GPS. - A real CAN-FiX nav radio's OBI Flags b1:b2 now decodes straight into NAVSRC with no table. - Leaves room for dual GPS (3=GPS2). Changes: ahrs.yaml NAVSRC description + initial 2.0 (boot stays on GPS); compute.yaml select input order -> [NAVSRC, NAV1*, NAV2*, GPS*] and the XPHSISRC remap table -> identity; compute.py / compute.rst / xplane.rst / xplane.yaml comments updated. The nav-source button still cycles 0->1->2 (now NAV1->NAV2->GPS) and writes NAVSRC dynamically, so no saved panel shifts meaning. Verified locally: configs parse; select routes NAV1/NAV2/GPS correctly; the remap is identity; compute + xplane test suites pass. To be bench-tested in X-Plane separately (the sim HSI source should still follow the selection). Co-Authored-By: Claude Opus 4.8 (1M context) --- doc/plugins/compute.rst | 18 ++++++++++-------- doc/plugins/xplane.rst | 10 +++++----- src/fixgw/config/connections/compute.yaml | 18 ++++++++++-------- src/fixgw/config/connections/xplane.yaml | 2 +- src/fixgw/config/database/ahrs.yaml | 11 ++++++++--- src/fixgw/plugins/compute.py | 4 ++-- 6 files changed, 36 insertions(+), 27 deletions(-) diff --git a/doc/plugins/compute.rst b/doc/plugins/compute.rst index 28d67ade..6b863af0 100644 --- a/doc/plugins/compute.rst +++ b/doc/plugins/compute.rst @@ -116,33 +116,35 @@ so the EFIS can both *display* the selected source and *publish* its guidance to the keys the autopilot reads -- and, with the :doc:`xplane` plugin, drive a simulator's autopilot to match. -A single selector key, ``NAVSRC`` (``0`` = GPS, ``1`` = NAV1, ``2`` = NAV2), is +A single selector key, ``NAVSRC`` (``0`` = NAV1, ``1`` = NAV2, ``2`` = GPS), is cycled by a button on the EFIS. ``select`` routes the chosen source's per-source keys into the canonical ``COURSE`` / ``CDI`` / ``GSI`` keys that the HSI and autopilot consume:: functions: - function: select - inputs: ["NAVSRC", "GPSCRS", "NAV1CRS", "NAV2CRS"] + inputs: ["NAVSRC", "NAV1CRS", "NAV2CRS", "GPSCRS"] output: COURSE require_leader: false - function: select - inputs: ["NAVSRC", "GPSCDI", "NAV1CDI", "NAV2CDI"] + inputs: ["NAVSRC", "NAV1CDI", "NAV2CDI", "GPSCDI"] output: CDI require_leader: false - function: select - inputs: ["NAVSRC", "GPSGSI", "NAV1GSI", "NAV2GSI"] + inputs: ["NAVSRC", "NAV1GSI", "NAV2GSI", "GPSGSI"] output: GSI require_leader: false -A ``remap`` then translates ``NAVSRC`` into X-Plane's own HSI source numbering -(X-Plane uses ``0`` = NAV1, ``1`` = NAV2, ``2`` = GPS) for the -:doc:`xplane` plugin's ``dataref_writes`` to send out:: +``NAVSRC`` already uses X-Plane's HSI source numbering (``0`` = NAV1, +``1`` = NAV2, ``2`` = GPS), so the ``remap`` to ``XPHSISRC`` is an identity map; +the table is kept as the seam that collapses an optional second GPS (``3`` = +GPS2) onto X-Plane's single GPS, for the :doc:`xplane` plugin's +``dataref_writes`` to send out:: - function: remap inputs: ["NAVSRC"] output: XPHSISRC - table: [2, 0, 1] + table: [0, 1, 2] require_leader: false The per-source keys (``GPSCRS``, ``NAV1CRS``, ...) are populated by the diff --git a/doc/plugins/xplane.rst b/doc/plugins/xplane.rst index 2293a9ba..2d9aac96 100644 --- a/doc/plugins/xplane.rst +++ b/doc/plugins/xplane.rst @@ -161,14 +161,14 @@ autopilot tracks whatever the EFIS has selected. The mechanism uses this plugin together with the :doc:`compute` plugin: #. A button on the EFIS cycles the ``NAVSRC`` selector key - (``0`` = GPS, ``1`` = NAV1, ``2`` = NAV2). + (``0`` = NAV1, ``1`` = NAV2, ``2`` = GPS). #. The compute plugin's ``select`` function routes the chosen source's - per-source keys (``GPSCRS`` / ``NAV1CRS`` / ``NAV2CRS``, etc., populated by + per-source keys (``NAV1CRS`` / ``NAV2CRS`` / ``GPSCRS``, etc., populated by the ``datarefs`` section above) into the canonical ``COURSE`` / ``CDI`` / ``GSI`` keys. -#. The compute plugin's ``remap`` function translates ``NAVSRC`` into X-Plane's - own source ordering (X-Plane uses ``0`` = NAV1, ``1`` = NAV2, ``2`` = GPS) and - writes it to ``XPHSISRC``. +#. ``NAVSRC`` already matches X-Plane's own source ordering (``0`` = NAV1, + ``1`` = NAV2, ``2`` = GPS), so the compute plugin's ``remap`` copies it to + ``XPHSISRC`` unchanged (an identity map). #. ``dataref_writes`` sends ``XPHSISRC`` out to ``sim/cockpit2/radios/actuators/HSI_source_select_pilot``, so X-Plane switches its HSI source and its autopilot follows. diff --git a/src/fixgw/config/connections/compute.yaml b/src/fixgw/config/connections/compute.yaml index 5525f80e..f93f353e 100644 --- a/src/fixgw/config/connections/compute.yaml +++ b/src/fixgw/config/connections/compute.yaml @@ -27,29 +27,31 @@ compute: - function: xte inputs: ["LAT", "LONG", "WPLAT", "WPLON", "COURSE"] output: XTRACK - # EFIS nav-source selector: NAVSRC (0=GPS, 1=NAV1, 2=NAV2) routes the + # EFIS nav-source selector: NAVSRC (0=NAV1, 1=NAV2, 2=GPS) routes the # selected source's course / lateral / vertical deviation into the canonical - # COURSE / CDI / GSI the HSI + autopilot read. require_leader off so it runs + # COURSE / CDI / GSI the HSI + autopilot read. Source order matches NAVSRC: + # inputs[1]=NAV1, inputs[2]=NAV2, inputs[3]=GPS. require_leader off so it runs # without a quorum leader. - function: select - inputs: ["NAVSRC", "GPSCRS", "NAV1CRS", "NAV2CRS"] + inputs: ["NAVSRC", "NAV1CRS", "NAV2CRS", "GPSCRS"] output: COURSE require_leader: false - function: select - inputs: ["NAVSRC", "GPSCDI", "NAV1CDI", "NAV2CDI"] + inputs: ["NAVSRC", "NAV1CDI", "NAV2CDI", "GPSCDI"] output: CDI require_leader: false - function: select - inputs: ["NAVSRC", "GPSGSI", "NAV1GSI", "NAV2GSI"] + inputs: ["NAVSRC", "NAV1GSI", "NAV2GSI", "GPSGSI"] output: GSI require_leader: false - # Translate NAVSRC (0=GPS,1=NAV1,2=NAV2) -> X-Plane HSI_source_select - # (0=NAV1,1=NAV2,2=GPS) so the sim's native autopilot follows the selection. + # NAVSRC already matches X-Plane's HSI_source_select numbering + # (0=NAV1, 1=NAV2, 2=GPS), so XPHSISRC is an identity map; the table is kept + # as the seam that collapses an optional GPS2 (3) onto X-Plane's GPS (2). # The xplane plugin's dataref_writes sends XPHSISRC out as a DREF. - function: remap inputs: ["NAVSRC"] output: XPHSISRC - table: [2, 0, 1] + table: [0, 1, 2] require_leader: false # inputs: [] # output: x diff --git a/src/fixgw/config/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index bc6a8522..8ae3df0b 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -100,7 +100,7 @@ xplane: dataref_hz: 10 # FIX -> X-Plane named-dataref writes (DREF), sent on change. The nav-source - # selector's XPHSISRC (remapped from NAVSRC by the compute plugin) drives + # selector's XPHSISRC (= NAVSRC via the compute plugin, identity map) drives # X-Plane's pilot HSI source, so the sim's native autopilot tracks whatever # source the EFIS has selected. dataref_writes: diff --git a/src/fixgw/config/database/ahrs.yaml b/src/fixgw/config/database/ahrs.yaml index b3b8c555..9333cb39 100644 --- a/src/fixgw/config/database/ahrs.yaml +++ b/src/fixgw/config/database/ahrs.yaml @@ -238,12 +238,17 @@ items: # button cycles NAVSRC; the compute "select" routes the chosen source into the # canonical COURSE/CDI/GSI the HSI and autopilot read. max = the cycle modulus # (3 sources) so change-value-wrap steps 0 -> 1 -> 2 -> 0. +# +# Ordering is bus-native: 0=NAV1, 1=NAV2, 2=GPS matches CAN-FiX OBI Flags (id 450 +# b1:b2) and X-Plane's HSI_source_select, so XPHSISRC is an identity map (no table +# inversion) and a real nav radio's OBI Flags decodes straight into NAVSRC. +# initial 2.0 keeps the boot default on GPS. Extensible to 3=GPS2 (max 4). - key: NAVSRC - description: Selected Nav Source (0=GPS, 1=NAV1, 2=NAV2) + description: Selected Nav Source (0=NAV1, 1=NAV2, 2=GPS) type: float min: 0.0 max: 3.0 - initial: 0.0 + initial: 2.0 tol: 2000 - key: GPSCRS @@ -322,7 +327,7 @@ items: tol: 2000 - key: XPHSISRC - description: X-Plane HSI source index (0=NAV1, 1=NAV2, 2=GPS), remapped from NAVSRC + description: X-Plane HSI source index (0=NAV1, 1=NAV2, 2=GPS); = NAVSRC (identity map) type: float min: 0.0 max: 2.0 diff --git a/src/fixgw/plugins/compute.py b/src/fixgw/plugins/compute.py index d68597cc..7038e7ee 100644 --- a/src/fixgw/plugins/compute.py +++ b/src/fixgw/plugins/compute.py @@ -791,8 +791,8 @@ def func(key, value, parent): def remapFunction(inputs, output, table, require_leader): # inputs[0] is an index key; table is a list of output values. Emits # table[round(index)] (clamped). Translates one selector scheme into - # another -- e.g. NAVSRC (0=GPS,1=NAV1,2=NAV2) -> X-Plane HSI_source_select - # (0=NAV1,1=NAV2,2=GPS) via table [2, 0, 1]. + # another -- e.g. collapsing NAVSRC's optional dual GPS (GPS1=2, GPS2=3) onto + # X-Plane's single HSI_source_select GPS (2) via table [0, 1, 2, 2]. def func(key, value, parent): if not quorum.leader and require_leader: return From c33ff8f74ee7cc908f0d1a16eefda82b2234a91a Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Tue, 30 Jun 2026 15:22:42 -0500 Subject: [PATCH 21/26] nav: derive magnetic ground track (TRACKM) for the HSI rose The HSI compass rose is magnetic (HEAD), but the ground-track diamond was reading TRACK -- which is true ground track (CAN-FiX 454, X-Plane hpath). On a magnetic rose a true track sits off by the full local magnetic variation (~5-20 deg), showing a constant false drift. Add a wrap360 compute function (sum of inputs mod 360 -- modular heading/track addition) and use it to populate TRACKM = (TRACK + MAGVAR) mod 360, both already in the feed. TRACKM is CAN-FiX 455 "Magnetic Ground Track"; a real CAN-FiX GPS would publish it directly. The HSI widget switches the diamond to TRACKM in a companion pyEfis change (the two must deploy together). Unit tests cover the wrap (350+15->5, 10-20->350) and quality-flag combining. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/fixgw/config/connections/compute.yaml | 8 ++++ src/fixgw/plugins/compute.py | 44 ++++++++++++++++++++++ tests/plugins/compute/test_compute_unit.py | 28 ++++++++++++++ 3 files changed, 80 insertions(+) diff --git a/src/fixgw/config/connections/compute.yaml b/src/fixgw/config/connections/compute.yaml index f93f353e..db665ead 100644 --- a/src/fixgw/config/connections/compute.yaml +++ b/src/fixgw/config/connections/compute.yaml @@ -27,6 +27,14 @@ compute: - function: xte inputs: ["LAT", "LONG", "WPLAT", "WPLON", "COURSE"] output: XTRACK + # Magnetic ground track = true ground track (TRACK) + magnetic variation + # (MAGVAR), wrapped to [0,360). The HSI compass rose is magnetic (HEAD), so + # its ground-track diamond must read TRACKM, not TRACK (true) -- otherwise the + # diamond sits off by the full magnetic variation. + - function: wrap360 + inputs: ["TRACK", "MAGVAR"] + output: TRACKM + require_leader: false # EFIS nav-source selector: NAVSRC (0=NAV1, 1=NAV2, 2=GPS) routes the # selected source's course / lateral / vertical deviation into the canonical # COURSE / CDI / GSI the HSI + autopilot read. Source order matches NAVSRC: diff --git a/src/fixgw/plugins/compute.py b/src/fixgw/plugins/compute.py index 7038e7ee..9d007144 100644 --- a/src/fixgw/plugins/compute.py +++ b/src/fixgw/plugins/compute.py @@ -805,6 +805,49 @@ def func(key, value, parent): return func +def wrap360Function(inputs, output, require_leader): + """Sum of the inputs wrapped to [0, 360) -- modular heading/track addition. + e.g. magnetic ground track = true ground track + magnetic variation + (TRACKM = TRACK + MAGVAR), since MAG = TRUE + VAR.""" + vals = {} + for each in inputs: + vals[each] = None + + def func(key, value, parent): + if type(value) != tuple: + return # This might be a meta data update + if not quorum.leader and require_leader: + return # Only the leader can do calculations + vals[key] = value + arrsum = 0 + flag_old = False + flag_bad = False + flag_fail = False + flag_secfail = False + for each in vals: + if vals[each] is None: + return # We don't have one of each yet + arrsum += vals[each][0] + if vals[each][2]: + flag_old = True + if vals[each][3]: + flag_bad = True + if vals[each][4]: + flag_fail = True + if vals[each][5]: + flag_secfail = True + o = parent.db_get_item(output) + o.value = arrsum % 360.0 + o.fail = flag_fail + if o.fail: + o.value = 0.0 + o.bad = flag_bad + o.old = flag_old + o.secfail = flag_secfail + + return func + + class Plugin(plugin.PluginBase): # def __init__(self, name, config): # super(Plugin, self).__init__(name, config) @@ -826,6 +869,7 @@ def run(self): "set": setFunction, "select": selectFunction, "remap": remapFunction, + "wrap360": wrap360Function, } for function in self.config["functions"]: diff --git a/tests/plugins/compute/test_compute_unit.py b/tests/plugins/compute/test_compute_unit.py index 4ba67be5..c4e93eb3 100644 --- a/tests/plugins/compute/test_compute_unit.py +++ b/tests/plugins/compute/test_compute_unit.py @@ -211,6 +211,34 @@ def test_sum_function_combines_values_and_quality_flags(): assert output.secfail is True +def test_wrap360_function_adds_inputs_modulo_360(): + parent = FakeParent() + func = compute.wrap360Function(["TRACK", "MAGVAR"], "TRACKM", require_leader=False) + + # 350 true track + 15 variation wraps to 5 magnetic + func("TRACK", value_tuple(350.0), parent) + func("MAGVAR", value_tuple(15.0), parent) + assert parent.db_get_item("TRACKM").value == 5.0 + + # negative variation wraps the other way: 10 + (-20) -> 350 + func("MAGVAR", value_tuple(-20.0), parent) + func("TRACK", value_tuple(10.0), parent) + assert parent.db_get_item("TRACKM").value == 350.0 + + +def test_wrap360_function_combines_quality_flags(): + parent = FakeParent() + func = compute.wrap360Function(["TRACK", "MAGVAR"], "TRACKM", require_leader=False) + + func("TRACK", value_tuple(100.0, old=True), parent) + func("MAGVAR", value_tuple(10.0, fail=True), parent) + + out = parent.db_get_item("TRACKM") + assert out.old is True + assert out.fail is True + assert out.value == 0.0 # fail forces value to 0.0 + + def test_max_and_min_forward_aux_metadata(): parent = FakeParent() max_func = compute.maxFunction(["A", "B"], "MAX", require_leader=False) From df8545fe74bcb672ff2394b3299d8cb40dbcc4b9 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Tue, 30 Jun 2026 17:00:03 -0500 Subject: [PATCH 22/26] nav: derive GSV (glideslope-valid) + TOFROM per source for the HSI Per-source vertical-guidance validity (NAV#GSV from X-Plane nav#_display_vertical) and VOR TO/FROM (NAV#TF from nav#_fromto), each routed by NAVSRC through a compute select into the canonical GSV / TOFROM the HSI reads. GSV=0 lets the HSI hide the GS needle for a VOR; TOFROM drives the TO/FROM triangle. GPS has no TO/FROM (GPSTF stays 0). Co-Authored-By: Claude Opus 4.8 (1M context) --- src/fixgw/config/connections/compute.yaml | 10 ++++ src/fixgw/config/connections/xplane.yaml | 8 +++ src/fixgw/config/database/ahrs.yaml | 71 +++++++++++++++++++++++ 3 files changed, 89 insertions(+) diff --git a/src/fixgw/config/connections/compute.yaml b/src/fixgw/config/connections/compute.yaml index db665ead..264720ee 100644 --- a/src/fixgw/config/connections/compute.yaml +++ b/src/fixgw/config/connections/compute.yaml @@ -52,6 +52,16 @@ compute: inputs: ["NAVSRC", "NAV1GSI", "NAV2GSI", "GPSGSI"] output: GSI require_leader: false + # Per-source glideslope-valid + TO/FROM, routed to the canonical GSV / TOFROM + # the HSI reads (GSV=0 hides the GS needle; TOFROM drives the TO/FROM triangle). + - function: select + inputs: ["NAVSRC", "NAV1GSV", "NAV2GSV", "GPSGSV"] + output: GSV + require_leader: false + - function: select + inputs: ["NAVSRC", "NAV1TF", "NAV2TF", "GPSTF"] + output: TOFROM + require_leader: false # NAVSRC already matches X-Plane's HSI_source_select numbering # (0=NAV1, 1=NAV2, 2=GPS), so XPHSISRC is an identity map; the table is kept # as the seam that collapses an optional GPS2 (3) onto X-Plane's GPS (2). diff --git a/src/fixgw/config/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index 8ae3df0b..b21d87e4 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -91,6 +91,14 @@ xplane: GPSGSI: [sim/cockpit/radios/gps_vdef_dot, 0.4] NAV1GSI: [sim/cockpit/radios/nav1_vdef_dot, 0.4] NAV2GSI: [sim/cockpit/radios/nav2_vdef_dot, 0.4] + # Vertical-guidance validity (1=GS present, 0=none) -> hides the GS needle + # for a VOR. nav#_display_vertical / gps_display_vertical indicators. + NAV1GSV: sim/cockpit2/radios/indicators/nav1_display_vertical + NAV2GSV: sim/cockpit2/radios/indicators/nav2_display_vertical + GPSGSV: sim/cockpit2/radios/indicators/gps_display_vertical + # VOR TO/FROM (0=off, 1=TO, 2=FROM) -> the HSI TO/FROM triangle. + NAV1TF: sim/cockpit/radios/nav1_fromto + NAV2TF: sim/cockpit/radios/nav2_fromto # Autopilot selected heading (deg mag) -> cyan heading bug. X-Plane # always publishes this (no nav tuning needed), so it doubles as an # RREF health check. NOTE: this makes X-Plane drive HEADBUG, so it will diff --git a/src/fixgw/config/database/ahrs.yaml b/src/fixgw/config/database/ahrs.yaml index 9333cb39..caad81c2 100644 --- a/src/fixgw/config/database/ahrs.yaml +++ b/src/fixgw/config/database/ahrs.yaml @@ -326,6 +326,77 @@ items: initial: 0.0 tol: 2000 +# Glideslope/glidepath validity per source (1 = GS present, 0 = none). A VOR has +# no glideslope, so the HSI hides the GS needle when the selected source's GSV is +# 0. From X-Plane's nav#_display_vertical indicators; a real GPS / nav radio +# reports it directly. +- key: NAV1GSV + description: NAV1 vertical guidance valid (1=GS present) + type: float + min: 0.0 + max: 1.0 + initial: 0.0 + tol: 2000 + +- key: NAV2GSV + description: NAV2 vertical guidance valid (1=GS present) + type: float + min: 0.0 + max: 1.0 + initial: 0.0 + tol: 2000 + +- key: GPSGSV + description: GPS vertical guidance valid (1=glidepath present) + type: float + min: 0.0 + max: 1.0 + initial: 0.0 + tol: 2000 + +- key: GSV + description: Selected-source glideslope/glidepath valid (1=show GS needle) + type: float + min: 0.0 + max: 1.0 + initial: 0.0 + tol: 2000 + +# VOR TO/FROM per source (0=off/flag, 1=TO, 2=FROM). From X-Plane nav#_fromto; +# GPS has no TO/FROM so GPSTF stays 0. The HSI draws a TO/FROM triangle on the +# course line for the selected source. +- key: NAV1TF + description: NAV1 TO/FROM (0=off, 1=TO, 2=FROM) + type: float + min: 0.0 + max: 2.0 + initial: 0.0 + tol: 2000 + +- key: NAV2TF + description: NAV2 TO/FROM (0=off, 1=TO, 2=FROM) + type: float + min: 0.0 + max: 2.0 + initial: 0.0 + tol: 2000 + +- key: GPSTF + description: GPS TO/FROM (always 0; GPS has no TO/FROM) + type: float + min: 0.0 + max: 2.0 + initial: 0.0 + tol: 2000 + +- key: TOFROM + description: Selected-source TO/FROM (0=off, 1=TO, 2=FROM) + type: float + min: 0.0 + max: 2.0 + initial: 0.0 + tol: 2000 + - key: XPHSISRC description: X-Plane HSI source index (0=NAV1, 1=NAV2, 2=GPS); = NAVSRC (identity map) type: float From 949c9b709af8093f89a35e584dbe157c7806eaff Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Tue, 30 Jun 2026 20:08:53 -0500 Subject: [PATCH 23/26] xplane: flip GS vertical deviation sense (below glideslope -> diamond up) nav#_vdef_dot / gps_vdef_dot are negative when below the glideslope; the HSI puts negative deviation at the bottom, so the GS diamond pegged DOWN when below (should be UP -- fly up to intercept). Negate the vdef scale (0.4 -> -0.4). Lateral hdef keeps +0.4 (CDI sense already correct). Confirmed live: GSI was -1.0 full-scale while below the glideslope. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/fixgw/config/connections/xplane.yaml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/fixgw/config/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index b21d87e4..f6e1d0af 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -88,9 +88,11 @@ xplane: NAV2CDI: [sim/cockpit/radios/nav2_hdef_dot, 0.4] # Vertical deviation (glidepath / glideslope) -> the GSI needle, same # +/-2.5-dot -> +/-1.0 scaling. gps_vdef is the GPS LPV/glidepath. - GPSGSI: [sim/cockpit/radios/gps_vdef_dot, 0.4] - NAV1GSI: [sim/cockpit/radios/nav1_vdef_dot, 0.4] - NAV2GSI: [sim/cockpit/radios/nav2_vdef_dot, 0.4] + # Vertical deviation: negative scale flips X-Plane's vdef sense so that + # below the glideslope drives the GS diamond UP (fly up), per HSI convention. + GPSGSI: [sim/cockpit/radios/gps_vdef_dot, -0.4] + NAV1GSI: [sim/cockpit/radios/nav1_vdef_dot, -0.4] + NAV2GSI: [sim/cockpit/radios/nav2_vdef_dot, -0.4] # Vertical-guidance validity (1=GS present, 0=none) -> hides the GS needle # for a VOR. nav#_display_vertical / gps_display_vertical indicators. NAV1GSV: sim/cockpit2/radios/indicators/nav1_display_vertical From 972c0d61ae8a4dde5a038599203c72242a1daa09 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Tue, 30 Jun 2026 20:16:44 -0500 Subject: [PATCH 24/26] nav: GS validity from glideslope flag (flag/hide until in the cone) GSV was derived from nav#_display_vertical (GS *capability* -- always 1 for an ILS, even before capture), so the GS diamond sat centred outside the reception cone. Switch to nav#_flag_glideslope (1 = no valid GS: a VOR, or an ILS outside the cone; 0 = captured), inverted per source into NAV#GSV by a compute remap ([1,0]) and selected into GSV. So the diamond flags/hides until the glideslope is actually received, and still hides on a VOR. GSF keys default 1 (flagged). Co-Authored-By: Claude Opus 4.8 (1M context) --- src/fixgw/config/connections/compute.yaml | 19 ++++++++++++ src/fixgw/config/connections/xplane.yaml | 11 +++---- src/fixgw/config/database/ahrs.yaml | 35 ++++++++++++++++++++--- 3 files changed, 56 insertions(+), 9 deletions(-) diff --git a/src/fixgw/config/connections/compute.yaml b/src/fixgw/config/connections/compute.yaml index 264720ee..7ebc9741 100644 --- a/src/fixgw/config/connections/compute.yaml +++ b/src/fixgw/config/connections/compute.yaml @@ -54,6 +54,25 @@ compute: require_leader: false # Per-source glideslope-valid + TO/FROM, routed to the canonical GSV / TOFROM # the HSI reads (GSV=0 hides the GS needle; TOFROM drives the TO/FROM triangle). + # Invert each source's glideslope flag (1=no valid GS) into a "valid" signal, + # then select the active source into GSV. So the GS diamond shows only with a + # real glideslope (ILS in the cone) and flags/hides otherwise (VOR / outside + # the cone). + - function: remap + inputs: ["NAV1GSF"] + output: NAV1GSV + table: [1, 0] + require_leader: false + - function: remap + inputs: ["NAV2GSF"] + output: NAV2GSV + table: [1, 0] + require_leader: false + - function: remap + inputs: ["GPSGSF"] + output: GPSGSV + table: [1, 0] + require_leader: false - function: select inputs: ["NAVSRC", "NAV1GSV", "NAV2GSV", "GPSGSV"] output: GSV diff --git a/src/fixgw/config/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index f6e1d0af..c0cbbde9 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -93,11 +93,12 @@ xplane: GPSGSI: [sim/cockpit/radios/gps_vdef_dot, -0.4] NAV1GSI: [sim/cockpit/radios/nav1_vdef_dot, -0.4] NAV2GSI: [sim/cockpit/radios/nav2_vdef_dot, -0.4] - # Vertical-guidance validity (1=GS present, 0=none) -> hides the GS needle - # for a VOR. nav#_display_vertical / gps_display_vertical indicators. - NAV1GSV: sim/cockpit2/radios/indicators/nav1_display_vertical - NAV2GSV: sim/cockpit2/radios/indicators/nav2_display_vertical - GPSGSV: sim/cockpit2/radios/indicators/gps_display_vertical + # Glideslope flag (1 = no valid GS: a VOR, or an ILS outside the cone; + # 0 = valid GS). Inverted into the GSV "valid" keys by a compute remap, so + # the GS diamond flags/hides until the glideslope is actually received. + NAV1GSF: sim/cockpit2/radios/indicators/nav1_flag_glideslope + NAV2GSF: sim/cockpit2/radios/indicators/nav2_flag_glideslope + GPSGSF: sim/cockpit2/radios/indicators/gps_flag_glideslope # VOR TO/FROM (0=off, 1=TO, 2=FROM) -> the HSI TO/FROM triangle. NAV1TF: sim/cockpit/radios/nav1_fromto NAV2TF: sim/cockpit/radios/nav2_fromto diff --git a/src/fixgw/config/database/ahrs.yaml b/src/fixgw/config/database/ahrs.yaml index caad81c2..77ee5b2b 100644 --- a/src/fixgw/config/database/ahrs.yaml +++ b/src/fixgw/config/database/ahrs.yaml @@ -326,10 +326,37 @@ items: initial: 0.0 tol: 2000 -# Glideslope/glidepath validity per source (1 = GS present, 0 = none). A VOR has -# no glideslope, so the HSI hides the GS needle when the selected source's GSV is -# 0. From X-Plane's nav#_display_vertical indicators; a real GPS / nav radio -# reports it directly. +# Raw glideslope flag per source (X-Plane nav#_flag_glideslope: 1 = flagged / no +# valid GS -- a VOR, or an ILS outside the reception cone; 0 = valid GS). A compute +# remap inverts these into the NAV#GSV "valid" keys below. Default 1 so the GS is +# flagged/hidden until a glideslope is actually received. +- key: NAV1GSF + description: NAV1 glideslope flag (1=no valid GS) + type: float + min: 0.0 + max: 1.0 + initial: 1.0 + tol: 2000 + +- key: NAV2GSF + description: NAV2 glideslope flag (1=no valid GS) + type: float + min: 0.0 + max: 1.0 + initial: 1.0 + tol: 2000 + +- key: GPSGSF + description: GPS glidepath flag (1=no valid glidepath) + type: float + min: 0.0 + max: 1.0 + initial: 1.0 + tol: 2000 + +# Glideslope/glidepath validity per source (1 = show the GS), derived from the +# flag above by a compute remap. GSV=0 hides the GS diamond (VOR, or ILS outside +# the cone); GSV=1 shows it (glideslope actually received). - key: NAV1GSV description: NAV1 vertical guidance valid (1=GS present) type: float From a7001bd1e8176eae9959094706ddb0898507b457 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Sun, 5 Jul 2026 18:46:49 -0500 Subject: [PATCH 25/26] compute: select flags the canonical output when the source is absent/invalid The nav-source select (COURSE/CDI/GSI = select(NAVSRC, [NAV1,NAV2,GPS])) used to `return` silently when the selected source had never published, leaving the PREVIOUSLY selected source's value showing as if it were valid -- a stale, sourceless indication. Now it flags the output failed instead (honest "no source"; the HSI removes/flags the needle), and self-heals when the source appears. Also propagate the source's full quality flags (old/bad/fail/secfail, zeroing value on fail) so a stale or bad source reads honestly downstream, mirroring wrap360Function. Unit tests: routing, absent-source invalidation + self-heal, flag propagation. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: Bill Mallard --- src/fixgw/plugins/compute.py | 22 ++++++++-- tests/plugins/compute/test_compute_unit.py | 48 ++++++++++++++++++++++ 2 files changed, 66 insertions(+), 4 deletions(-) diff --git a/src/fixgw/plugins/compute.py b/src/fixgw/plugins/compute.py index 9d007144..409b07a9 100644 --- a/src/fixgw/plugins/compute.py +++ b/src/fixgw/plugins/compute.py @@ -775,15 +775,29 @@ def func(key, value, parent): vals[key] = value sel = vals[inputs[0]] if sel is None: - return # no selection yet + return # no selection yet -- leave the output untouched at boot + o = parent.db_get_item(output) idx = max(0, min(len(inputs) - 2, int(round(sel[0])))) src = vals[inputs[idx + 1]] if src is None: - return # selected source has no value yet - o = parent.db_get_item(output) + # The selected source has never published a value. Do NOT leave the + # previously selected source's value showing as if it were valid -- + # mark the canonical output FAILED so the HSI removes/flags the + # needle (an honest "no source"), rather than a stale, sourceless + # indication. Self-heals when the source starts publishing. + o.fail = True + return + # Copy the selected source's value AND its quality flags, so a stale, + # bad or failed source reads honestly downstream (the HSI greys/flags + # instead of showing a frozen or sourceless needle). Mirrors + # wrap360Function's flag handling. o.value = src[0] - o.bad = src[3] o.fail = src[4] + if o.fail: + o.value = 0.0 + o.bad = src[3] + o.old = src[2] + o.secfail = src[5] return func diff --git a/tests/plugins/compute/test_compute_unit.py b/tests/plugins/compute/test_compute_unit.py index c4e93eb3..82499cf3 100644 --- a/tests/plugins/compute/test_compute_unit.py +++ b/tests/plugins/compute/test_compute_unit.py @@ -239,6 +239,54 @@ def test_wrap360_function_combines_quality_flags(): assert out.value == 0.0 # fail forces value to 0.0 +def test_select_routes_the_selected_source(): + parent = FakeParent() + func = compute.selectFunction( + ["NAVSRC", "NAV1CRS", "NAV2CRS", "GPSCRS"], "COURSE", require_leader=False) + + func("NAV1CRS", value_tuple(241.0), parent) + func("GPSCRS", value_tuple(7.7), parent) + + func("NAVSRC", value_tuple(2.0), parent) # 2 = GPS + assert parent.db_get_item("COURSE").value == 7.7 + func("NAVSRC", value_tuple(0.0), parent) # 0 = NAV1 + assert parent.db_get_item("COURSE").value == 241.0 + + +def test_select_invalidates_output_when_selected_source_absent(): + # Issue #84 companion: selecting a source that has never published must NOT + # leave the previously selected source's value showing as valid -- the + # canonical output is flagged failed (honest "no source"), then self-heals. + parent = FakeParent() + func = compute.selectFunction( + ["NAVSRC", "NAV1CRS", "NAV2CRS", "GPSCRS"], "COURSE", require_leader=False) + + func("GPSCRS", value_tuple(7.7), parent) + func("NAVSRC", value_tuple(2.0), parent) # GPS -> COURSE 7.7 + course = parent.db_get_item("COURSE") + assert course.value == 7.7 and course.fail is False + + func("NAVSRC", value_tuple(1.0), parent) # NAV2, never published + assert course.fail is True # flagged, not stale-7.7 + + func("NAV2CRS", value_tuple(123.0), parent) # source appears + assert course.value == 123.0 and course.fail is False + + +def test_select_propagates_quality_flags(): + parent = FakeParent() + func = compute.selectFunction( + ["NAVSRC", "NAV1CRS", "GPSCRS"], "COURSE", require_leader=False) + + func("NAVSRC", value_tuple(0.0), parent) # NAV1 + func("NAV1CRS", value_tuple(241.0, old=True, bad=True), parent) + course = parent.db_get_item("COURSE") + assert course.old is True and course.bad is True + + func("NAV1CRS", value_tuple(241.0, fail=True), parent) + assert course.fail is True and course.value == 0.0 + + def test_max_and_min_forward_aux_metadata(): parent = FakeParent() max_func = compute.maxFunction(["A", "B"], "MAX", require_leader=False) From 1eac772dc1961233ff09be4820c0d776228bdb82 Mon Sep 17 00:00:00 2001 From: Bill Mallard Date: Sun, 5 Jul 2026 18:46:58 -0500 Subject: [PATCH 26/26] state_persist: persist pilot selections (NAVSRC) across restarts (#84) NAVSRC (the HSI nav-source selector) is a pilot SELECTION, not sensed data, but it was not persisted -- so it reset to a default on every boot and the pilot had to re-select GPS/VLOC after each restart. Add a small dependency-free plugin that restores the last value of each configured key at startup (deferred a couple seconds so the compute select + source feeds have subscribed, so the restored selection routes immediately) and saves it back on change to a JSON file written atomically. Wired as a connection (load: yes), persisting NAVSRC; generic key list so COURSE/HEADBUG/baro can persist later. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: Bill Mallard --- .../config/connections/state_persist.yaml | 12 ++ src/fixgw/config/default.yaml | 1 + src/fixgw/config/preferences.yaml | 1 + src/fixgw/plugins/state_persist/__init__.py | 148 ++++++++++++++++++ 4 files changed, 162 insertions(+) create mode 100644 src/fixgw/config/connections/state_persist.yaml create mode 100644 src/fixgw/plugins/state_persist/__init__.py diff --git a/src/fixgw/config/connections/state_persist.yaml b/src/fixgw/config/connections/state_persist.yaml new file mode 100644 index 00000000..c7fbe223 --- /dev/null +++ b/src/fixgw/config/connections/state_persist.yaml @@ -0,0 +1,12 @@ +# Persist pilot selections across restarts (issue #84). +# Restores the last value of each listed key at startup and saves it back on +# change. See fixgw/plugins/state_persist. NAVSRC (the HSI nav-source selector) +# is the first consumer -- so a chosen GPS/VLOC source survives a reboot instead +# of resetting to the default every boot. +state_persist: + load: yes + module: fixgw.plugins.state_persist + keys: + - NAVSRC + # state_file: "{CONFIG}/persist_state.json" # optional; default shown + # restore_delay: 2.0 # seconds before restoring diff --git a/src/fixgw/config/default.yaml b/src/fixgw/config/default.yaml index 599d80e3..f586de18 100644 --- a/src/fixgw/config/default.yaml +++ b/src/fixgw/config/default.yaml @@ -54,6 +54,7 @@ connections: - MCP3008_CONFIG - RAIS_CONFIG - COMPUTE_CONFIG + - STATE_PERSIST_CONFIG - DIMMER_CONFIG - GRAND_RAPIDS_EIS_CONFIG - STRATUX_CONFIG diff --git a/src/fixgw/config/preferences.yaml b/src/fixgw/config/preferences.yaml index f5a38e5a..b655400b 100644 --- a/src/fixgw/config/preferences.yaml +++ b/src/fixgw/config/preferences.yaml @@ -39,6 +39,7 @@ includes: DYNON_CONFIG: connections/dynon.yaml DEMO_CONFIG: connections/demo.yaml RTL_433_CONFIG: connections/rtl_433.yaml + STATE_PERSIST_CONFIG: connections/state_persist.yaml # This section is used to turn things on or off enabled: QUORUM: false diff --git a/src/fixgw/plugins/state_persist/__init__.py b/src/fixgw/plugins/state_persist/__init__.py new file mode 100644 index 00000000..f8e4e1e4 --- /dev/null +++ b/src/fixgw/plugins/state_persist/__init__.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python +# SPDX-License-Identifier: GPL-2.0-or-later +# +# Persist selected FIX keys across restarts (issue #84). + +"""Persist a small set of FIX keys across fix-gateway restarts. + +Some FIX values are *pilot selections*, not sensed data -- e.g. ``NAVSRC`` +(the HSI nav-source selector). Without persistence they reset to a default on +every boot, so the pilot has to re-select the source after each restart. This +plugin restores the last value of each configured key at startup and saves it +back whenever it changes. + +Storage is a small JSON file written atomically (temp + ``os.replace``); no +external dependencies. Configuration (a ``connections`` entry):: + + state_persist: + load: yes + module: fixgw.plugins.state_persist + keys: # FIX keys whose last value should survive + - NAVSRC + # state_file: "{CONFIG}/persist_state.json" # optional; default shown + # restore_delay: 2.0 # seconds to wait before restoring (see run()) + +The restore is deferred a couple of seconds so the other plugins (the compute +``select`` router, the source feeds) have subscribed and published first -- then +writing the restored ``NAVSRC`` immediately routes the correct ``COURSE``. +""" + +import json +import os +import threading +import time + +import fixgw.plugin as plugin + + +class MainThread(threading.Thread): + def __init__(self, parent): + super(MainThread, self).__init__() + self.getout = False + self.parent = parent + self.log = parent.log + cfg = parent.config + + default_path = os.path.join(cfg.get("CONFIGPATH", "."), "persist_state.json") + self.path = cfg.get("state_file", default_path) + self.keys = list(cfg.get("keys", [])) + self.restore_delay = float(cfg.get("restore_delay", 2.0)) + self._lock = threading.Lock() + self.dirty = False + # The values to restore, read once from disk. `state` starts as a copy + # and only diverges when the pilot changes a key AFTER restore. + self._to_restore = self._load() + self.state = dict(self._to_restore) + # Gate: do NOT save changes until the restore has run. At startup each + # key gets its db default (e.g. NAVSRC -> GPS); capturing that would + # clobber the persisted selection before we get to restore it. + self._restored = False + + # Subscribe now, but ignore changes until restored (see _on_change). + for key in self.keys: + self.parent.db_callback_add(key, self._on_change) + + def _load(self): + """Read the persisted state, keeping only currently-configured keys.""" + try: + with open(self.path, "r") as f: + data = json.load(f) + return {k: v for k, v in data.items() if k in self.keys} + except FileNotFoundError: + return {} + except Exception as e: + self.log.warning(f"state_persist: could not read {self.path}: {e}") + return {} + + def _on_change(self, key, value, udata=None): + # value is the item tuple (value, annunciate, old, bad, fail, secfail); + # meta/aux updates arrive as non-tuples and are ignored. + if not isinstance(value, tuple): + return + if not self._restored: + return # ignore startup defaults until we've restored the saved value + with self._lock: + if self.state.get(key) != value[0]: + self.state[key] = value[0] + self.dirty = True + + def _flush(self): + with self._lock: + if not self.dirty: + return + data = dict(self.state) + self.dirty = False + tmp = self.path + ".tmp" + try: + with open(tmp, "w") as f: + json.dump(data, f) + os.replace(tmp, self.path) # atomic: never a half-written file + except Exception as e: + self.log.error(f"state_persist: could not write {self.path}: {e}") + + def _restore(self): + for key, val in self._to_restore.items(): + try: + self.parent.db_write(key, val) + self.log.info(f"state_persist: restored {key} = {val}") + except Exception as e: + self.log.warning(f"state_persist: could not restore {key}: {e}") + # From here on, real changes are captured and saved. (The db_write above + # fires _on_change while still gated, so it is not re-saved.) + self._restored = True + + def run(self): + # Let the other plugins subscribe + publish before restoring, so the + # restored selection routes immediately (and does not get lost writing + # into a compute select that has not subscribed yet). + deadline = time.time() + self.restore_delay + while not self.getout and time.time() < deadline: + time.sleep(0.1) + if not self.getout: + self._restore() + while not self.getout: + time.sleep(1.0) + self._flush() + self._flush() # final save on shutdown + + def stop(self): + self.getout = True + + +class Plugin(plugin.PluginBase): + def __init__(self, name, config, config_meta): + super(Plugin, self).__init__(name, config, config_meta) + self.thread = MainThread(self) + + def run(self): + self.thread.start() + + def stop(self): + self.thread.stop() + if self.thread.is_alive(): + self.thread.join(2.0) + if self.thread.is_alive(): + raise plugin.PluginFail + + def get_status(self): + return {}