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 diff --git a/doc/plugins/compute.rst b/doc/plugins/compute.rst new file mode 100644 index 00000000..6b863af0 --- /dev/null +++ b/doc/plugins/compute.rst @@ -0,0 +1,152 @@ +================= +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`` = 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", "NAV1CRS", "NAV2CRS", "GPSCRS"] + output: COURSE + require_leader: false + - function: select + inputs: ["NAVSRC", "NAV1CDI", "NAV2CDI", "GPSCDI"] + output: CDI + require_leader: false + - function: select + inputs: ["NAVSRC", "NAV1GSI", "NAV2GSI", "GPSGSI"] + output: GSI + require_leader: false + +``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: [0, 1, 2] + 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..2d9aac96 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`` = NAV1, ``1`` = NAV2, ``2`` = GPS). +#. The compute plugin's ``select`` function routes the chosen source's + per-source keys (``NAV1CRS`` / ``NAV2CRS`` / ``GPSCRS``, etc., populated by + the ``datarefs`` section above) into the canonical ``COURSE`` / ``CDI`` / + ``GSI`` keys. +#. ``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. + +:: + + 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. diff --git a/src/fixgw/config/connections/compute.yaml b/src/fixgw/config/connections/compute.yaml index f157cc62..7ebc9741 100644 --- a/src/fixgw/config/connections/compute.yaml +++ b/src/fixgw/config/connections/compute.yaml @@ -27,6 +27,69 @@ 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: + # inputs[1]=NAV1, inputs[2]=NAV2, inputs[3]=GPS. require_leader off so it runs + # without a quorum leader. + - function: select + inputs: ["NAVSRC", "NAV1CRS", "NAV2CRS", "GPSCRS"] + output: COURSE + require_leader: false + - function: select + inputs: ["NAVSRC", "NAV1CDI", "NAV2CDI", "GPSCDI"] + output: CDI + require_leader: false + - function: select + 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). + # 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 + 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). + # The xplane plugin's dataref_writes sends XPHSISRC out as a DREF. + - function: remap + inputs: ["NAVSRC"] + output: XPHSISRC + table: [0, 1, 2] + require_leader: false # inputs: [] # output: x # - function: span 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/connections/xplane.yaml b/src/fixgw/config/connections/xplane.yaml index 5b4c96a3..c0cbbde9 100644 --- a/src/fixgw/config/connections/xplane.yaml +++ b/src/fixgw/config/connections/xplane.yaml @@ -1,18 +1,138 @@ xplane: - load: XPLANE - module: fixgw.plugins.xplane - # IP address where the X-Plane simulator is running - 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 + load: XPLANE + module: fixgw.plugins.xplane + # X-Plane host. The simulator must be sending its "Data Output" UDP + # packets to whichever IP the fix-gateway machine answers on; this + # field is the destination address fix-gateway sends DREF writes TO. + ipaddress: 127.0.0.1 + + # Local UDP port fix-gateway BINDS to receive X-Plane's data output. + # Match this against X-Plane's "IP of data receiver" → port. + udp_in: 49001 + + # 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 + + # --------------------------------------------------------------------- + # 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 (X-Plane 12 layout verified by capture) + # slots: [Pitch, Roll, Hdg_true, _, Hdg_mag, MagVar, _, Track] + # 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, _, _, _, _] + # 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, _, _, _, _] + 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: + # 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] + 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. + # 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] + # 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 + # 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 + + # FIX -> X-Plane named-dataref writes (DREF), sent on change. The nav-source + # 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: + 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 + # 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, _, _, _, _, _, _, _] diff --git a/src/fixgw/config/database/ahrs.yaml b/src/fixgw/config/database/ahrs.yaml index 923cf1d5..77ee5b2b 100644 --- a/src/fixgw/config/database/ahrs.yaml +++ b/src/fixgw/config/database/ahrs.yaml @@ -161,6 +161,36 @@ 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 + min: -30.0 + max: 30.0 + units: deg + 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 @@ -204,6 +234,204 @@ items: initial: 0.0 tol: 2000 +# 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. +# +# 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=NAV1, 1=NAV2, 2=GPS) + type: float + min: 0.0 + max: 3.0 + initial: 2.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: 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 + +# 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 + 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 + 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/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/compute.py b/src/fixgw/plugins/compute.py index 1fd0db30..409b07a9 100644 --- a/src/fixgw/plugins/compute.py +++ b/src/fixgw/plugins/compute.py @@ -757,6 +757,111 @@ 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 -- 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: + # 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.fail = src[4] + if o.fail: + o.value = 0.0 + o.bad = src[3] + o.old = src[2] + o.secfail = src[5] + + 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. 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 + 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 + + +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) @@ -776,6 +881,9 @@ def run(self): "altd": altDensity, "encoder": encoderFunction, "set": setFunction, + "select": selectFunction, + "remap": remapFunction, + "wrap360": wrap360Function, } for function in self.config["functions"]: @@ -800,6 +908,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/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 {} diff --git a/src/fixgw/plugins/xplane/__init__.py b/src/fixgw/plugins/xplane/__init__.py index b0c19c18..191e5a67 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,109 +12,371 @@ # 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 DATA/RREF/DREF) + udp_in: 49001 # local UDP port we receive on + 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. + 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 + +# 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) + +# 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. +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.""" + 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 _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.""" + 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) + 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)) + # 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", {})) + self.send_map = _build_index_map(cfg.get("send", {})) + 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)) + # 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)) + + self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self.sock.bind(("0.0.0.0", self.udp_in)) + self.sock.setblocking(False) + # close() idempotency guard. Mirrors upstream's plugin lifecycle: + # Plugin.stop() calls thread.close() after the join. self.sock_closed = False - # 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]) + 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 + 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, v) + except Exception as e: + self.log.warning( + "xplane: db_write %s=%r failed (%s)", key, v, 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("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: + self.log.warning("xplane: RREF subscribe send failed (%s)", e) + + def subscribe_datarefs(self, freq): + for index, (_key, dref, _scale) in self.dataref_map.items(): + self._send_rref(freq, index, dref) + + def _ingest_rref(self, data): + # "RREF," 5-byte header, then N x (int32 index, float32 value). + payload = data[5:] + offset = 0 + while offset + 8 <= len(payload): + index, value = struct.unpack_from(" X-Plane + # ------------------------------------------------------------------ def senddata(self): - """Function that sends data to X-Plane""" - for each in self.inputkeys: - data = b"DATA" + b"\0" - data += struct.pack("i", int(each)) - - for i in range(8): - if self.inputkeys[each][i].lower() == "x": - data += b"\x00\xc0\x79\xc4" - # data += struct.pack("f", 0.0) + for index, slots in self.send_map.items(): + buf = HEADER + b"\x00" + struct.pack(" 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_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) diff --git a/tests/plugins/xplane/test_xplane.py b/tests/plugins/xplane/test_xplane.py index b7af408a..9bb46b18 100644 --- a/tests/plugins/xplane/test_xplane.py +++ b/tests/plugins/xplane/test_xplane.py @@ -1,134 +1,351 @@ +"""Unit tests for the X-Plane fix-gateway plugin. + +Exercises the data-driven recv/send mappings, packet parsing, and the +legacy ``idxN:`` config form. Real UDP sockets are mocked via patches +on ``socket.socket`` so the tests don't bind any ports. +""" + import struct -from unittest.mock import MagicMock, call, patch +from unittest.mock import MagicMock, patch, call import pytest -import fixgw.plugin as plugin_base -import fixgw.plugins.xplane as xplane -from fixgw.plugins.xplane import MainThread, Plugin +from fixgw.plugins.xplane import ( + HEADER, + NO_VALUE, + RREF_BASE, + MainThread, + Plugin, + _build_dataref_map, + _build_index_map, + _normalise_slot, + _parse_slot_list, +) + + +# --------------------------------------------------------------------------- +# Parsers +# --------------------------------------------------------------------------- + +def test_normalise_slot_handles_skip_aliases(): + for empty in (None, "", "_", "x", "X", " _ ", " "): + assert _normalise_slot(empty) is None + assert _normalise_slot("ias") == "IAS" + assert _normalise_slot("LAT") == "LAT" + assert _normalise_slot(" Long ") == "LONG" + + +def test_parse_slot_list_list_form_pads_to_eight(): + slots = _parse_slot_list(["PITCH", "ROLL", "_", "HEAD"]) + assert slots == ["PITCH", "ROLL", None, "HEAD", None, None, None, None] + + +def test_parse_slot_list_legacy_comma_form(): + slots = _parse_slot_list("IAS,X,X,TAS,X,X,X,X") + assert slots == ["IAS", None, None, "TAS", None, None, None, None] + + +def test_parse_slot_list_truncates_to_eight(): + extra = list("ABCDEFGHIJ") # 10 entries + slots = _parse_slot_list(extra) + assert len(slots) == 8 + assert slots == [c.upper() for c in "ABCDEFGH"] + + +def test_build_index_map_str_and_int_keys(): + m = _build_index_map({ + 20: ["LAT", "LONG", "ALT", "AGL", "_", "_", "_", "_"], + "17": "PITCH,ROLL,_,HEAD,_,_,_,_", + "not-an-index": ["IAS"], + }) + assert set(m.keys()) == {17, 20} + assert m[20] == ["LAT", "LONG", "ALT", "AGL", None, None, None, None] + assert m[17] == ["PITCH", "ROLL", None, "HEAD", None, None, None, None] + + +# --------------------------------------------------------------------------- +# Fixtures +# --------------------------------------------------------------------------- @pytest.fixture def mock_parent(): - mock = MagicMock() - mock.config = { - "idx3": "IAS,X,X,TAS,X,X,X,X", - "idx20": "LAT,LONG,ALT,X,X,X,X,X", + parent = MagicMock() + parent.config = { + "ipaddress": "10.0.0.99", + "udp_in": 49001, + "udp_out": 49002, + "recv": { + 3: ["IAS", "_", "TAS", "GS", "_", "_", "_", "_"], + 17: ["PITCH", "ROLL", "_", "HEAD", "_", "_", "_", "_"], + 20: ["LAT", "LONG", "ALT", "AGL", "_", "_", "_", "_"], + }, + "send": { + 25: ["THR1", "_", "_", "_", "_", "_", "_", "_"], + }, } - mock.log = MagicMock() - mock.db_write = MagicMock() - mock.db_read = MagicMock(side_effect=lambda key: 123.45 if key == "IAS" else 0.0) - return mock + parent.log = MagicMock() + parent.db_write = MagicMock() + # db_read returns (value, ...) tuples in the netfix client; some plugin + # builds return scalars. The plugin handles both. + parent.db_read = MagicMock(return_value=(0.75,)) + return parent @pytest.fixture def main_thread(mock_parent): - with patch("socket.socket") as mock_socket: - mock_socket.return_value.recvfrom = MagicMock(return_value=(b"DATA" + b"\x00" * 40, ("127.0.0.1", 12345))) + with patch("socket.socket"): return MainThread(mock_parent) -def test_writedata(mock_parent, main_thread): - main_thread.writedata(3, [100.0, 0.0, 200.0]) +# --------------------------------------------------------------------------- +# writedata — X-Plane -> 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 test_senddata_packs_configured_indexes(mock_parent, main_thread): - main_thread.parent.db_read.side_effect = lambda key: { - "IAS": (101.0, False, False, False, False, False), - "TAS": 202.0, - "LAT": 40.0, - "LONG": -83.0, - "ALT": 1234.0, - }[key] - main_thread.senddata() +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) - packets = [call_args.args[0] for call_args in main_thread.sock.sendto.call_args_list] - assert len(packets) == 2 - assert packets[0].startswith(b"DATA\0" + struct.pack("i", 3)) - assert struct.unpack("f", packets[0][9:13])[0] == pytest.approx(101.0) - assert packets[0][13:17] == b"\x00\xc0\x79\xc4" - assert packets[0][17:21] == b"\x00\xc0\x79\xc4" - assert struct.unpack("f", packets[0][21:25])[0] == pytest.approx(202.0) - assert packets[1].startswith(b"DATA\0" + struct.pack("i", 20)) +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 build_packet(index, values): - packet = b"DATA\0" + struct.pack("i", index) - for value in values: - packet += struct.pack("f", value) - return packet +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_run_handles_bad_packets_and_decodes_data(monkeypatch, mock_parent, main_thread): - packets = [ - b"NOPE\0", - b"DATA\0bad", - build_packet(3, [55.0, 0.0, 66.0, 0.0, 0.0, 0.0, 0.0, 0.0]), - ] - def fake_select(_read, _write, _error, _timeout): - return ([main_thread.sock], [], []) if packets else ([], [], []) +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 - def fake_recvfrom(_size): - packet = packets.pop(0) - if not packets: - main_thread.getout = True - return packet, ("127.0.0.1", 1) - monkeypatch.setattr(xplane.select, "select", fake_select) - main_thread.sock.recvfrom.side_effect = fake_recvfrom - main_thread.senddata = lambda: None +# --------------------------------------------------------------------------- +# Packet parsing +# --------------------------------------------------------------------------- - main_thread.run() +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(" 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"): - plugin = Plugin("test_plugin", mock_parent.config, MagicMock()) - plugin.thread.is_alive = MagicMock(return_value=True) - plugin.thread.join = MagicMock() - with pytest.raises(plugin_base.PluginFail): - plugin.stop() + 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 + dref = buf[13:].rstrip(b"\x00") + assert dref.startswith(b"sim/cockpit/radios/nav1_") + + +def test_no_datarefs_config_means_empty_map(main_thread): + assert main_thread.dataref_map == {} # back-compat: nav RREF is opt-in + + +# --------------------------------------------------------------------------- +# Plugin lifecycle +# --------------------------------------------------------------------------- + +def test_plugin_lifecycle(mock_parent): + with patch("socket.socket"): + plugin_instance = Plugin("xplane", mock_parent.config, MagicMock()) + with patch.object(plugin_instance.thread, "start") as mock_start, \ + patch.object(plugin_instance.thread, "stop") as mock_stop, \ + patch.object(plugin_instance.thread, "is_alive", return_value=False): + plugin_instance.run() + mock_start.assert_called_once() + plugin_instance.stop() + mock_stop.assert_called_once() 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()