From 840718328c3852747f2039667c4e635f9f13ac86 Mon Sep 17 00:00:00 2001 From: Prince Karikari Date: Sun, 8 Nov 2026 22:00:42 -0600 Subject: [PATCH] Issue #184 solved: send both halves so FlightModel and Pilot differ Every iMotions entry declares two fields, FlightModel* and Pilot*, but the plugin sent the pilot half only and the relay filled both with the same number. The reason there are two fields -- comparing the instrument reading against the aircraft's true state -- did not work at all. The plugin now sends 16 values per sample, both halves of each value, flightmodel first, in the relay's entry order. The relay's generic pairing branch already handled that shape correctly but was unreachable behind the 8-field branch; it now has an explicit 16-field branch so a test pins the order. The 4- and 8-field shapes still duplicate, because an older plugin gives the relay nothing else to put there. Two things the issue did not mention, both of which would have been silent: data_logger.py read parts[8], the FlightModel* field. That was the pilot value only because both halves were identical, so this change alone would have repointed the whole ML pipeline from pilot readings to flightmodel readings with nothing failing. It now reads parts[9], keeping the dataset pilot-side as GLOSSARY.md defines it. The two halves were not in the same units. position/elevation is metres and position/true_airspeed is metres per second, while the pilot DataRefs are already feet and knots, so pairing them raw would have reproduced #196 in a new place. The plugin's display code already converted correctly, so the conversion rates moved to file scope and both send sites use them. Airspeed still differs in kind, not only by sensor error: the flightmodel half is true airspeed and the pilot half indicated, so the gap grows with altitude. yaw and g_force have no pilot-side DataRef, so both halves carry the flightmodel value and are equal by design. Both are documented. Tests: relay 25 (2 new, including one pinning that the legacy 8-field shape still duplicates), inference 120 (2 new, using values that differ so the halves can be told apart). The plugin cross-compiles and links for Windows and is clang-format clean under LLVM style. The two failing relay mirror tests on this branch are #251, fixed by #265, not introduced here. --- README.md | 16 +- docs/telemetry_schema.md | 34 + .../pilot_inference/capture/data_logger.py | 8 +- inference/pilot_inference/capture/replay.py | 17 +- inference/tests/capture/test_data_logger.py | 16 + relay/src/state.rs | 112 ++- xplane_plugin/src/pilotdatasync-xp11.cpp | 934 +++++++++--------- 7 files changed, 676 insertions(+), 461 deletions(-) diff --git a/README.md b/README.md index 88044dc..d38e681 100644 --- a/README.md +++ b/README.md @@ -154,10 +154,22 @@ The file is written to your Downloads folder as `iMotions.xml` (`%USERPROFILE%\D The `Id="PilotDataSync"` is what ties the definition to the live stream. Every packet the relay sends carries the same source name: ``` -E;1;PilotDataSync;;;;;AltitudeSync;1250.5;1250.5 +E;1;PilotDataSync;;;;;AltitudeSync;1248.2;1250.5 ``` -Packets are semicolon-delimited and CRLF-terminated. The value appears twice because each sample carries both a `FlightModel*` and a `Pilot*` field. +Packets are semicolon-delimited and CRLF-terminated. Two values appear because +each sample carries both a `FlightModel*` and a `Pilot*` field, in that order: +the aircraft's true state and the pilot's instrument reading, which differ by +the simulated sensor error. Anything reading the stream for pilot performance +wants the second value. + +`yaw` and `g_force` are exceptions. Neither has a pilot-side DataRef, so the +plugin sends the flightmodel value in both halves and the two are always equal. + +Before #184 the plugin sent the pilot half only and the relay copied it into +both fields, so the two values were always identical. A relay running against +an older plugin still behaves that way, since it has nothing else to put +there. ### Which port iMotions listens on diff --git a/docs/telemetry_schema.md b/docs/telemetry_schema.md index 50d3cfa..51bdcf3 100644 --- a/docs/telemetry_schema.md +++ b/docs/telemetry_schema.md @@ -39,6 +39,40 @@ error), not the aircraft's raw physical state — see note 2 in `key_datarefs.md`. `yaw` and `g_force` are exceptions: both come from `sim/flightmodel/*` DataRefs rather than a pilot-side instrument. +### The paired wire payload (#184) + +The plugin sends 16 values per sample, not 8: both halves of every value, +flightmodel first, in the order the relay turns into iMotions entries. + +| position | 0, 1 | 2, 3 | 4, 5 | 6, 7 | 8, 9 | 10, 11 | 12, 13 | 14, 15 | +|---|---|---|---|---|---|---|---|---| +| value | altitude | airspeed | vertical speed | heading | roll | pitch | yaw | g force | + +Each pair becomes one iMotions entry carrying two values, `FlightModel*` then +`Pilot*`, for example `E;1;PilotDataSync;;;;;AltitudeSync;1248.2;1250.5`. +`data_logger.py` records the second value, because the dataset is defined as +pilot-side readings (see GLOSSARY.md, "Pilot reading"). + +Note the order: vertical speed comes before heading. The older pilot-only +payload sent heading third and the relay reordered it on the way out; the +paired payload is in entry order so the relay pairs straight through. + +The flightmodel half is converted into the pilot half's units in the plugin, +since `sim/flightmodel/position/elevation` is metres and +`sim/flightmodel/position/true_airspeed` is metres per second while the pilot +DataRefs are already feet and knots. Airspeed also differs in kind, not only in +sensor error: the flightmodel half is true airspeed and the pilot half is +indicated, so the gap between them grows with altitude. + +`yaw` and `g_force` have no pilot-side DataRef, so both halves carry the +flightmodel value and are always equal. + +**Older plugins send 8 values.** The relay still accepts 8 (and 4) and fills +the flightmodel half with a copy of the pilot value, because it has nothing +else to put there. Data captured that way cannot be used to compare the two +halves, in the same way that pre-#196 data cannot be used at face value for +`altitude` and `velocity`. + **Older data has mis-scaled `altitude` and `velocity` (fixed in #196):** before #196, the plugin multiplied `altitude_ft_pilot` (already feet) by 3.28084 and `airspeed_kts_pilot` (already knots) by 1.94384 before sending. Data collected diff --git a/inference/pilot_inference/capture/data_logger.py b/inference/pilot_inference/capture/data_logger.py index 12163ef..d3c4f94 100644 --- a/inference/pilot_inference/capture/data_logger.py +++ b/inference/pilot_inference/capture/data_logger.py @@ -115,8 +115,14 @@ def parse_packet(line: str) -> tuple[str, float] | None: if event_name not in EVENT_TO_COLUMN: return None + # Each entry carries two values, FlightModel* then Pilot*. The dataset is + # defined as pilot-side instrument readings, carrying simulated sensor + # error rather than the aircraft's true state (see GLOSSARY.md, "Pilot + # reading"), so the second one is the one to record. Before #184 the relay + # sent the pilot value in both slots, which made the first slot look + # correct; it carries the flightmodel value now. try: - value = float(parts[8]) + value = float(parts[9]) except ValueError: return None diff --git a/inference/pilot_inference/capture/replay.py b/inference/pilot_inference/capture/replay.py index 2343df6..b012e1b 100644 --- a/inference/pilot_inference/capture/replay.py +++ b/inference/pilot_inference/capture/replay.py @@ -41,11 +41,22 @@ def packets_for_row(row: dict) -> list[str]: - """One sample as the relay's iMotions packets, with each value sent twice as the relay does.""" + """ + One sample as the relay's iMotions packets. + + Each entry carries two values, FlightModel* then Pilot*. A recorded CSV + holds pilot readings only, so the value goes in the pilot slot and is + repeated in the flightmodel slot as a stand-in: there is no flightmodel + half to replay. Consumers that want the pilot reading must take the second + value, as data_logger.parse_packet does. + """ packets = [] for event, column in RELAY_EVENTS: - value = row.get(column, 0.0) - packets.append(f"E;1;PilotDataSync;;;;;{event};{value:.6f};{value:.6f}\r\n") + pilot = row.get(column, 0.0) + flightmodel = pilot + packets.append( + f"E;1;PilotDataSync;;;;;{event};{flightmodel:.6f};{pilot:.6f}\r\n" + ) return packets diff --git a/inference/tests/capture/test_data_logger.py b/inference/tests/capture/test_data_logger.py index 3ae9bfc..39e61ba 100644 --- a/inference/tests/capture/test_data_logger.py +++ b/inference/tests/capture/test_data_logger.py @@ -26,6 +26,22 @@ def packet(event: str, value: float) -> str: return f"E;1;PilotDataSync;;;;;{event};{value};{value}\r\n" +def test_parse_packet_takes_the_pilot_half_not_the_flightmodel_half(): + """ + #184: each entry carries FlightModel* then Pilot*. The dataset is defined + as pilot-side instrument readings, so the second value is the one logged. + The helper above sends the same number twice, as a pre-#184 relay did, so + it cannot tell the two apart -- this uses values that differ. + """ + line = "E;1;PilotDataSync;;;;;AltitudeSync;1000.0;1234.5\r\n" + assert data_logger.parse_packet(line) == ("AltitudeSync", 1234.5) + + +def test_parse_packet_rejects_an_entry_missing_the_pilot_half(): + """A truncated entry is dropped rather than logged as flightmodel data.""" + assert data_logger.parse_packet("E;1;PilotDataSync;;;;;AltitudeSync;1000.0\r\n") is None + + def test_csv_fields_start_with_identity_columns(): assert data_logger.CSV_FIELDS[:3] == ["timestamp", "pilot_id", "flight_id"] assert data_logger.CSV_FIELDS[3:] == data_logger.TELEMETRY_FIELDS diff --git a/relay/src/state.rs b/relay/src/state.rs index 92fceb1..db7d8a3 100644 --- a/relay/src/state.rs +++ b/relay/src/state.rs @@ -179,14 +179,49 @@ fn normalize_baton_payload(raw: &str) -> Vec { .collect() } +/// One iMotions entry per flight value, in the order the relay sends them. +/// +/// "Event" here is one iMotions entry, not a Sample in the GLOSSARY sense, +/// which is a whole set of telemetry values. +const IMOTIONS_EVENTS: [&str; 8] = [ + "AltitudeSync", + "AirspeedSync", + "VerticalVelocitySync", + "HeadingSync", + "RollSync", + "PitchSync", + "YawSync", + "GForceSync", +]; + /// The iMotions packets one baton sample turns into, in send order. /// /// Pulled out of the TCP thread so the mapping can be tested without a socket, /// and so both destinations are written the same bytes from one list rather /// than each building its own. +/// +/// Every iMotions entry carries two values, `FlightModel*` then `Pilot*`. A +/// 16-field sample has both, paired. The 4- and 8-field shapes are what older +/// plugins send: they carry the pilot half only, so the flightmodel half is +/// filled with the same number and the two cannot be compared (#184). fn packets_for_fields(fields: &[String]) -> Vec { + // Legacy duplication: one value standing in for both halves. Only for the + // field counts that predate the paired payload. let pair = |value: &String| vec![value.clone(), value.clone()]; + // The paired payload: both halves of every value, flightmodel first, in + // iMotions event order. Spelled out rather than left to the generic branch + // at the end so a test pins the order and the halves cannot quietly swap. + if fields.len() == IMOTIONS_EVENTS.len() * 2 { + return IMOTIONS_EVENTS + .iter() + .enumerate() + .map(|(i, name)| { + build_imotions_packet(name, &[fields[i * 2].clone(), fields[i * 2 + 1].clone()]) + }) + .collect(); + } + if fields.len() == 4 { let (alt, air, head, vv) = (&fields[0], &fields[1], &fields[2], &fields[3]); return vec![ @@ -213,18 +248,7 @@ fn packets_for_fields(fields: &[String]) -> Vec { } // Anything else: take the fields two at a time, in event order, and stop - // when they run out. "Event" here is one iMotions entry, not a Sample in - // the GLOSSARY sense, which is a whole set of telemetry values. - const IMOTIONS_EVENTS: [&str; 8] = [ - "AltitudeSync", - "AirspeedSync", - "VerticalVelocitySync", - "HeadingSync", - "RollSync", - "PitchSync", - "YawSync", - "GForceSync", - ]; + // when they run out. let mut packets = Vec::new(); let mut idx = 0usize; for name in IMOTIONS_EVENTS { @@ -1034,6 +1058,70 @@ mod tests { assert_eq!(packets[3], "E;1;PilotDataSync;;;;;HeadingSync;90;90\r\n"); } + // The point of #184: both halves reach iMotions, so the instrument reading + // and the aircraft's true state can be compared. + #[test] + fn sixteen_fields_pair_flightmodel_with_pilot() { + let packets = packets_for_fields(&fields(&[ + "1000", "1001", // altitude: flightmodel, pilot + "120", "121", // airspeed + "500", "501", // vertical velocity + "90", "91", // heading + "2", "3", // roll + "4", "5", // pitch + "91", "91", // yaw: no pilot DataRef exists, so both are flightmodel + "1.0", "1.1", // g force + ])); + + assert_eq!(packets.len(), 8); + assert_eq!( + packets[0], + "E;1;PilotDataSync;;;;;AltitudeSync;1000;1001\r\n" + ); + assert_eq!( + packets[1], + "E;1;PilotDataSync;;;;;AirspeedSync;120;121\r\n" + ); + // Vertical velocity before heading, as in the 8-field shape. The pairs + // are in event order, which is not baton's old field order. + assert_eq!( + packets[2], + "E;1;PilotDataSync;;;;;VerticalVelocitySync;500;501\r\n" + ); + assert_eq!(packets[3], "E;1;PilotDataSync;;;;;HeadingSync;90;91\r\n"); + assert_eq!( + packets[7], + "E;1;PilotDataSync;;;;;GForceSync;1.0;1.1\r\n" + ); + } + + // The regression #184 describes: with only the pilot half, the flightmodel + // field is a copy, so nothing can be compared. Pinned so the legacy shape + // is not mistaken for correct behaviour. + #[test] + fn eight_fields_still_duplicate_because_the_flightmodel_half_is_absent() { + let packets = packets_for_fields(&fields(&[ + "1000", "120", "90", "500", "2", "3", "91", "1.0", + ])); + + for packet in &packets { + let values: Vec<&str> = packet + .trim_end() + .split(';') + .skip(8) + .collect(); + assert_eq!( + values.len(), + 2, + "every entry carries two values: {packet:?}" + ); + assert_eq!( + values[0], values[1], + "the 8-field shape has no flightmodel half to send: {packet:?}" + ); + } + } + #[test] fn four_fields_send_only_the_flight_dynamics_factors() { let packets = packets_for_fields(&fields(&["1000", "120", "90", "500"])); diff --git a/xplane_plugin/src/pilotdatasync-xp11.cpp b/xplane_plugin/src/pilotdatasync-xp11.cpp index 2f7ecf4..fdafd0a 100644 --- a/xplane_plugin/src/pilotdatasync-xp11.cpp +++ b/xplane_plugin/src/pilotdatasync-xp11.cpp @@ -1,443 +1,491 @@ -// This basic plugin is a modified and de-commented version of the sample -// "Hello, World" plugin code found here: -// https://developer.x-plane.com/code-sample/hello-world-sdk-3/ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "subprojects/baton/lib.rs.h" - -using std::string; -using std::vector; - -#ifdef __cplusplus -extern "C" { -#endif - -#include "XPLMDataAccess.h" -#include "XPLMDisplay.h" -#include "XPLMGraphics.h" -#include "XPLMProcessing.h" -#include "XPLMUtilities.h" -#include - -#ifdef __cplusplus -} -#endif - -BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, - LPVOID lpReserved) { - switch (ul_reason_for_call) { - case DLL_PROCESS_ATTACH: - case DLL_THREAD_ATTACH: - case DLL_THREAD_DETACH: - case DLL_PROCESS_DETACH: - break; - } - return TRUE; -} - -#ifndef XPLM300 -#error This is made to be compiled against the XPLM300 SDK -#endif - -// An opaque handle to the window we will create -static XPLMWindowID g_window; - -// DataRef Identifiers (use lowercase variable names consistently) -static XPLMDataRef elevationFlightmodelRef; -static XPLMDataRef elevationPilotRef; -static XPLMDataRef airspeedFlightmodelRef; -static XPLMDataRef airspeedPilotRef; -static XPLMDataRef verticalVelocityFlightmodelRef; -static XPLMDataRef verticalVelocityPilotRef; -static XPLMDataRef headingFlightmodelRef; -static XPLMDataRef headingPilotRef; -// Additional DataRefs for roll/pitch/yaw/g-force (note: no yawPilotRef — yaw -// pilot gauge not available) -static XPLMDataRef yawFlightmodelRef; -static XPLMDataRef rollFlightmodelRef; -static XPLMDataRef rollPilotRef; -static XPLMDataRef pitchFlightmodelRef; -static XPLMDataRef pitchPilotRef; -// g-force now provided as horizontal (side) and vertical (normal) components -static XPLMDataRef gforceHorizontalRef; -static XPLMDataRef gforceVerticalRef; - -// baton handle -- a "Box" is the name for a Rust pointer. This Box is handled -// by the cxx crate interface and acts like a normal pointer. -rust::cxxbridge1::Box baton = new_baton_handle(); - -// Throttling mechanism to limit send frequency -static std::chrono::steady_clock::time_point last_send_time = - std::chrono::steady_clock::now(); -static const int SEND_INTERVAL_MS = - 50; // Send every 50ms (20 Hz) instead of every frame - -// Callbacks we will register when we create our window -void draw_pilotdatasync_plugin(XPLMWindowID in_window_id, void *in_refcon); - -int dummy_mouse_handler(XPLMWindowID in_window_id, int x, int y, int is_down, - void *in_refcon) { - return 0; -} - -XPLMCursorStatus dummy_cursor_status_handler(XPLMWindowID in_window_id, int x, - int y, void *in_refcon) { - return xplm_CursorDefault; -} - -int dummy_wheel_handler(XPLMWindowID in_window_id, int x, int y, int wheel, - int clicks, void *in_refcon) { - return 0; -} - -void dummy_key_handler(XPLMWindowID in_window_id, char key, XPLMKeyFlags flags, - char virtual_key, void *in_refcon, int losing_focus) {} - -volatile bool stop_exec = false; - -static int button_left = 0, button_top = 0, button_right = 0, button_bottom = 0; -static std::string last_send_timestamp = ""; - -// Helper to get current timestamp as string -std::string get_current_timestamp() { - std::time_t now = std::time(nullptr); - char buf[32]; - std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&now)); - return buf; -} - -// Update the mouse handler to detect button clicks -int mouse_handler(XPLMWindowID in_window_id, int x, int y, int is_down, - void *in_refcon) { - if (is_down) { - // Button bounds are set in draw_pilotdatasync_plugin - if (x >= button_left && x <= button_right && y >= button_bottom && - y <= button_top) { - // Gather data as in draw_pilotdatasync_plugin. The pilot datarefs are - // already in feet and knots, so no conversion is applied. - float currentPilotElevation = XPLMGetDataf(elevationPilotRef); - float currentPilotAirspeed = XPLMGetDataf(airspeedPilotRef); - float currentPilotHeading = XPLMGetDataf(headingPilotRef); - float currentPilotVerticalVelocity = - XPLMGetDataf(verticalVelocityPilotRef); - - // New fields - float currentPilotRoll = XPLMGetDataf(rollPilotRef); - float currentPilotPitch = XPLMGetDataf(pitchPilotRef); - // Yaw pilot DataRef isn't available; use flightmodel yaw as fallback - float currentPilotYaw = XPLMGetDataf(yawFlightmodelRef); - // Use vertical (normal) g for the "Pilot G" value to preserve previous - // single-G field behavior - float currentPilotGForce = XPLMGetDataf(gforceVerticalRef); - - std::vector send_to_baton = { - currentPilotElevation, currentPilotAirspeed, - currentPilotHeading, currentPilotVerticalVelocity, - currentPilotRoll, currentPilotPitch, - currentPilotYaw, currentPilotGForce, - }; - baton->send(send_to_baton); - - last_send_timestamp = get_current_timestamp(); - } - } - return 0; -} - -// - -PLUGIN_API int XPluginStart(char *outName, char *outSig, char *outDesc) { - strcpy(outName, "PilotDataSyncPlugin"); - strcpy(outSig, "oss.pilotdatasyncplugin"); - strcpy(outDesc, "A plug-in that collects and transmits X-Plane 11 data to " - "the iMotions platform for data collection and research"); - - XPLMCreateWindow_t params; - params.structSize = sizeof(params); - params.visible = 1; - params.drawWindowFunc = draw_pilotdatasync_plugin; - params.handleMouseClickFunc = mouse_handler; - params.handleRightClickFunc = dummy_mouse_handler; - params.handleMouseWheelFunc = dummy_wheel_handler; - params.handleKeyFunc = dummy_key_handler; - params.handleCursorFunc = dummy_cursor_status_handler; - params.refcon = NULL; - params.layer = xplm_WindowLayerFloatingWindows; - // Opt-in to styling our window like an X-Plane 11 native window - params.decorateAsFloatingWindow = xplm_WindowDecorationRoundRectangle; - - // Set the window's initial bounds - int left, bottom, right, top; - XPLMGetScreenBoundsGlobal(&left, &top, &right, &bottom); - params.left = left + 50; - params.bottom = bottom + 150; - params.right = params.left + 350; - params.top = params.bottom + 200; - - // Obtain datarefs for MSL and AGL elevation, respectively - elevationFlightmodelRef = - XPLMFindDataRef("sim/flightmodel/position/elevation"); - elevationPilotRef = - XPLMFindDataRef("sim/cockpit2/gauges/indicators/altitude_ft_pilot"); - - // Obtain datarefs for Airspeed - airspeedFlightmodelRef = - XPLMFindDataRef("sim/flightmodel/position/true_airspeed"); - airspeedPilotRef = - XPLMFindDataRef("sim/cockpit2/gauges/indicators/airspeed_kts_pilot"); - - // DataRefs for Vertical Velocity - verticalVelocityFlightmodelRef = - XPLMFindDataRef("sim/flightmodel/position/vh_ind_fpm"); - verticalVelocityPilotRef = - XPLMFindDataRef("sim/cockpit2/gauges/indicators/vvi_fpm_pilot"); - - // Obtain dataref for Pilot heading and True Magnetic Heading - headingFlightmodelRef = XPLMFindDataRef("sim/flightmodel/position/mag_psi"); - headingPilotRef = XPLMFindDataRef( - "sim/cockpit2/gauges/indicators/heading_AHARS_deg_mag_pilot"); - - // Obtain datarefs for Yaw, Roll, Pitch - yawFlightmodelRef = XPLMFindDataRef("sim/flightmodel/position/psi"); - rollFlightmodelRef = XPLMFindDataRef("sim/flightmodel/position/phi"); - rollPilotRef = - XPLMFindDataRef("sim/cockpit2/gauges/indicators/roll_AHARS_deg_pilot"); - - pitchFlightmodelRef = XPLMFindDataRef("sim/flightmodel/position/theta"); - pitchPilotRef = - XPLMFindDataRef("sim/cockpit2/gauges/indicators/pitch_AHARS_deg_pilot"); - - // g-force components (horizontal/side and vertical/normal) - gforceHorizontalRef = XPLMFindDataRef("sim/flightmodel/forces/g_side"); - gforceVerticalRef = XPLMFindDataRef("sim/flightmodel/forces/g_nrml"); - - g_window = XPLMCreateWindowEx(¶ms); - - // Position the window as a "free" floating window, - // which the user can drag around - XPLMSetWindowPositioningMode(g_window, xplm_WindowPositionFree, -1); - XPLMSetWindowTitle(g_window, "Positional Flight Data"); - - return g_window != NULL; -} - -PLUGIN_API void XPluginStop() { - XPLMDestroyWindow(g_window); - g_window = NULL; -} - -PLUGIN_API void XPluginDisable(void) { baton->stop(); } - -PLUGIN_API int XPluginEnable(void) { - baton->start(); - - return 1; -} - -PLUGIN_API void XPluginReceiveMessage(XPLMPluginID inFrom, int inMsg, - void *inParam) {} - -void draw_pilotdatasync_plugin(XPLMWindowID in_window_id, void *in_refcon) { - XPLMSetGraphicsState(0 /* no fog */, 0 /* 0 texture units */, - 0 /* no lighting */, 0 /* no alpha testing */, - 1 /* do alpha blend */, 1 /* do depth testing */, - 0 /* no depth writing */ - ); - - int l, t, r, b; - XPLMGetWindowGeometry(in_window_id, &l, &t, &r, &b); - - float col_white[] = {1.0, 1.0, 1.0}; // RGB - - // The flightmodel datarefs are in meters and meters per second, so they are - // converted to feet and knots. The pilot datarefs are already in feet and - // knots. - float msToFeetRate = 3.28084f; - float msToKnotsRate = 1.94384f; - - auto build_str = [](string label, string unit, float value) { - string suffix = !std::isnan(value) ? std::to_string(value) + " " + unit - : "(Error Reading Data)"; - return label + ": " + suffix; - }; - - // Create strings from DataRefs to display in plugin window - float currentFlightmodelElevation = - XPLMGetDataf(elevationFlightmodelRef) * msToFeetRate; - string elevationFlightmodelStr = build_str("Elevation, Flightmodel (MSL)", - "ft", currentFlightmodelElevation); - - float currentPilotElevation = XPLMGetDataf(elevationPilotRef); - string elevationPilotStr = - build_str("Elevation, Pilot (MSL)", "ft", currentPilotElevation); - - float currentFlightmodelAirspeed = - XPLMGetDataf(airspeedFlightmodelRef) * msToKnotsRate; - string airspeedFlightmodelStr = - build_str("Airspeed, Flightmodel", "knots", currentFlightmodelAirspeed); - - float currentPilotAirspeed = XPLMGetDataf(airspeedPilotRef); - string airspeedPilotStr = - build_str("Airspeed, Pilot", "knots", currentPilotAirspeed); - - float currentFlightmodelVerticalVelocity = - XPLMGetDataf(verticalVelocityFlightmodelRef); - string verticalVelocityFlightmodelStr = - build_str("Vertical Velocity, Flightmodel", "ft/min", - currentFlightmodelVerticalVelocity); - - float currentPilotVerticalVelocity = XPLMGetDataf(verticalVelocityPilotRef); - string verticalVelocityPilotStr = build_str( - "Vertical Velocity, Pilot", "ft/min", currentPilotVerticalVelocity); - - float currentFlightmodelHeading = XPLMGetDataf(headingFlightmodelRef); - string headingFlightmodelStr = - build_str("Heading, Flightmodel", "°M", currentFlightmodelHeading); - - float currentPilotHeading = XPLMGetDataf(headingPilotRef); - string headingPilotStr = - build_str("Heading, Pilot", "°M", currentPilotHeading); - - // New parameters (roll, pitch, yaw, g-force) - float currentFlightmodelRoll = XPLMGetDataf(rollFlightmodelRef); - string rollFlightmodelStr = - build_str("Roll, Flightmodel", "°", currentFlightmodelRoll); - float currentPilotRoll = XPLMGetDataf(rollPilotRef); - string rollPilotStr = build_str("Roll, Pilot", "°", currentPilotRoll); - - float currentFlightmodelPitch = XPLMGetDataf(pitchFlightmodelRef); - string pitchFlightmodelStr = - build_str("Pitch, Flightmodel", "°", currentFlightmodelPitch); - float currentPilotPitch = XPLMGetDataf(pitchPilotRef); - string pitchPilotStr = build_str("Pitch, Pilot", "°", currentPilotPitch); - - float currentFlightmodelYaw = XPLMGetDataf(yawFlightmodelRef); - // use flightmodel yaw as the pilot yaw value since yaw pilot DataRef is not - // available - float currentPilotYaw = currentFlightmodelYaw; - string yawPilotStr = - build_str("Yaw, Pilot (from Flightmodel)", "°", currentPilotYaw); - string yawFlightmodelStr = - build_str("Yaw, Flightmodel", "°", currentFlightmodelYaw); - - // g-force: show both vertical (normal) and horizontal (side) components. - float currentFlightmodelGVert = XPLMGetDataf(gforceVerticalRef); - string gFlightmodelVertStr = - build_str("G-Force, Flightmodel (Vert)", "G", currentFlightmodelGVert); - float currentFlightmodelGHoriz = XPLMGetDataf(gforceHorizontalRef); - string gFlightmodelHorizStr = - build_str("G-Force, Flightmodel (Horiz)", "G", currentFlightmodelGHoriz); - - // For backward compatibility use vertical G as the single "Pilot G" value - float currentPilotG = currentFlightmodelGVert; - string gPilotStr = build_str("G-Force, Pilot (Vert)", "G", currentPilotG); - - // use this get_next_y_offset() lambda function to find the next vertical - // pixel start position on the window for string rendering for you. - int last_offset = 10; - auto get_next_y_offset = [&last_offset, t]() { - last_offset = last_offset + 10; - return t - last_offset; - }; - - vector draw_order = { - elevationFlightmodelStr, - elevationPilotStr, - airspeedFlightmodelStr, - verticalVelocityFlightmodelStr, - verticalVelocityPilotStr, - headingFlightmodelStr, - headingPilotStr, - rollFlightmodelStr, - rollPilotStr, - pitchFlightmodelStr, - pitchPilotStr, - yawPilotStr, - yawPilotStr, - gFlightmodelVertStr, - gFlightmodelHorizStr, - gPilotStr, - }; - - // print each line in order on the window - for (string line : draw_order) { - XPLMDrawString(col_white, l + 10, get_next_y_offset(), (char *)line.c_str(), - NULL, xplmFont_Proportional); - } - - // Button dimensions - int button_width = 120; - int button_height = 30; - int button_x = l + 10; - int button_y = b + 40; - - button_left = button_x; - button_right = button_x + button_width; - button_bottom = button_y; - button_top = button_y + button_height; - - // Draw button rectangle (simple filled rectangle) - float col_button[] = {0.2f, 0.5f, 0.8f, 1.0f}; - glColor4fv(col_button); - glBegin(GL_QUADS); - glVertex2i(button_left, button_bottom); - glVertex2i(button_right, button_bottom); - glVertex2i(button_right, button_top); - glVertex2i(button_left, button_top); - glEnd(); - - // Draw button label - float col_text[] = {1.0f, 1.0f, 1.0f}; - std::string button_label = "Send Packet"; - XPLMDrawString(col_text, button_left + 10, button_bottom + 8, - (char *)button_label.c_str(), NULL, xplmFont_Proportional); - - // Draw timestamp next to button - std::string ts_label = - "Last sent: " + - (last_send_timestamp.empty() ? "Never" : last_send_timestamp); - XPLMDrawString(col_text, button_right + 10, button_bottom + 8, - (char *)ts_label.c_str(), NULL, xplmFont_Proportional); - - // THROTTLE SENDING TO PREVENT SOCKET OVERFLOW - auto now = std::chrono::steady_clock::now(); - auto elapsed_ms = std::chrono::duration_cast( - now - last_send_time) - .count(); - - if (elapsed_ms >= SEND_INTERVAL_MS) { - // Send flight data to Relay via Baton. Order must match Relay expectations: - // current behavior: plugin sends Pilot-only values in order: - // [Altitude, Airspeed, Heading, VerticalVelocity, Roll, Pitch, Yaw, - // G-Force] - // Keep that order and use flightmodel yaw and vertical G for compatibility. - vector send_to_baton = { - currentPilotElevation, currentPilotAirspeed, - currentPilotHeading, currentPilotVerticalVelocity, - currentPilotRoll, currentPilotPitch, - currentPilotYaw, currentPilotG, - }; - - { - char dbg[256]; - std::snprintf(dbg, sizeof(dbg), - "[PDS PLUGIN] Draw send -> alt=%.3f air=%.3f hdg=%.3f " - "vv=%.3f roll=%.3f pitch=%.3f yaw=%.3f g=%.3f\n", - send_to_baton[0], send_to_baton[1], send_to_baton[2], - send_to_baton[3], send_to_baton[4], send_to_baton[5], - send_to_baton[6], send_to_baton[7]); - XPLMDebugString(dbg); - } - baton->send(send_to_baton); - - last_send_time = now; - } -} +// This basic plugin is a modified and de-commented version of the sample +// "Hello, World" plugin code found here: +// https://developer.x-plane.com/code-sample/hello-world-sdk-3/ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "subprojects/baton/lib.rs.h" + +using std::string; +using std::vector; + +#ifdef __cplusplus +extern "C" { +#endif + +#include "XPLMDataAccess.h" +#include "XPLMDisplay.h" +#include "XPLMGraphics.h" +#include "XPLMProcessing.h" +#include "XPLMUtilities.h" +#include + +#ifdef __cplusplus +} +#endif + +BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, + LPVOID lpReserved) { + switch (ul_reason_for_call) { + case DLL_PROCESS_ATTACH: + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + case DLL_PROCESS_DETACH: + break; + } + return TRUE; +} + +#ifndef XPLM300 +#error This is made to be compiled against the XPLM300 SDK +#endif + +// An opaque handle to the window we will create +static XPLMWindowID g_window; + +// DataRef Identifiers (use lowercase variable names consistently) +// The flightmodel datarefs are in meters and meters per second, so they are +// converted to feet and knots. The pilot datarefs are already in feet and +// knots. Both send sites need these, so they live here rather than in one of +// them: the two halves of a pair must arrive in the same unit (#184). +static const float msToFeetRate = 3.28084f; +static const float msToKnotsRate = 1.94384f; + +static XPLMDataRef elevationFlightmodelRef; +static XPLMDataRef elevationPilotRef; +static XPLMDataRef airspeedFlightmodelRef; +static XPLMDataRef airspeedPilotRef; +static XPLMDataRef verticalVelocityFlightmodelRef; +static XPLMDataRef verticalVelocityPilotRef; +static XPLMDataRef headingFlightmodelRef; +static XPLMDataRef headingPilotRef; +// Additional DataRefs for roll/pitch/yaw/g-force (note: no yawPilotRef — yaw +// pilot gauge not available) +static XPLMDataRef yawFlightmodelRef; +static XPLMDataRef rollFlightmodelRef; +static XPLMDataRef rollPilotRef; +static XPLMDataRef pitchFlightmodelRef; +static XPLMDataRef pitchPilotRef; +// g-force now provided as horizontal (side) and vertical (normal) components +static XPLMDataRef gforceHorizontalRef; +static XPLMDataRef gforceVerticalRef; + +// baton handle -- a "Box" is the name for a Rust pointer. This Box is handled +// by the cxx crate interface and acts like a normal pointer. +rust::cxxbridge1::Box baton = new_baton_handle(); + +// Throttling mechanism to limit send frequency +static std::chrono::steady_clock::time_point last_send_time = + std::chrono::steady_clock::now(); +static const int SEND_INTERVAL_MS = + 50; // Send every 50ms (20 Hz) instead of every frame + +// Callbacks we will register when we create our window +void draw_pilotdatasync_plugin(XPLMWindowID in_window_id, void *in_refcon); + +int dummy_mouse_handler(XPLMWindowID in_window_id, int x, int y, int is_down, + void *in_refcon) { + return 0; +} + +XPLMCursorStatus dummy_cursor_status_handler(XPLMWindowID in_window_id, int x, + int y, void *in_refcon) { + return xplm_CursorDefault; +} + +int dummy_wheel_handler(XPLMWindowID in_window_id, int x, int y, int wheel, + int clicks, void *in_refcon) { + return 0; +} + +void dummy_key_handler(XPLMWindowID in_window_id, char key, XPLMKeyFlags flags, + char virtual_key, void *in_refcon, int losing_focus) {} + +volatile bool stop_exec = false; + +static int button_left = 0, button_top = 0, button_right = 0, button_bottom = 0; +static std::string last_send_timestamp = ""; + +// Helper to get current timestamp as string +std::string get_current_timestamp() { + std::time_t now = std::time(nullptr); + char buf[32]; + std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&now)); + return buf; +} + +// Update the mouse handler to detect button clicks +int mouse_handler(XPLMWindowID in_window_id, int x, int y, int is_down, + void *in_refcon) { + if (is_down) { + // Button bounds are set in draw_pilotdatasync_plugin + if (x >= button_left && x <= button_right && y >= button_bottom && + y <= button_top) { + // Gather data as in draw_pilotdatasync_plugin. The pilot datarefs are + // already in feet and knots, so no conversion is applied. + float currentPilotElevation = XPLMGetDataf(elevationPilotRef); + float currentPilotAirspeed = XPLMGetDataf(airspeedPilotRef); + float currentPilotHeading = XPLMGetDataf(headingPilotRef); + float currentPilotVerticalVelocity = + XPLMGetDataf(verticalVelocityPilotRef); + + // New fields + float currentPilotRoll = XPLMGetDataf(rollPilotRef); + float currentPilotPitch = XPLMGetDataf(pitchPilotRef); + // Yaw pilot DataRef isn't available; use flightmodel yaw as fallback + float currentPilotYaw = XPLMGetDataf(yawFlightmodelRef); + // Use vertical (normal) g for the "Pilot G" value to preserve previous + // single-G field behavior + float currentPilotGForce = XPLMGetDataf(gforceVerticalRef); + + // The flightmodel half, converted into the pilot half's units so the + // two are comparable. + float currentFlightmodelElevation = + XPLMGetDataf(elevationFlightmodelRef) * msToFeetRate; + float currentFlightmodelAirspeed = + XPLMGetDataf(airspeedFlightmodelRef) * msToKnotsRate; + float currentFlightmodelVerticalVelocity = + XPLMGetDataf(verticalVelocityFlightmodelRef); + float currentFlightmodelHeading = XPLMGetDataf(headingFlightmodelRef); + float currentFlightmodelRoll = XPLMGetDataf(rollFlightmodelRef); + float currentFlightmodelPitch = XPLMGetDataf(pitchFlightmodelRef); + float currentFlightmodelYaw = XPLMGetDataf(yawFlightmodelRef); + float currentFlightmodelGForce = XPLMGetDataf(gforceVerticalRef); + + // Both halves of every value, flightmodel first, in the relay's + // iMotions entry order. See the comment on the draw callback's send. + std::vector send_to_baton = { + currentFlightmodelElevation, + currentPilotElevation, + currentFlightmodelAirspeed, + currentPilotAirspeed, + currentFlightmodelVerticalVelocity, + currentPilotVerticalVelocity, + currentFlightmodelHeading, + currentPilotHeading, + currentFlightmodelRoll, + currentPilotRoll, + currentFlightmodelPitch, + currentPilotPitch, + currentFlightmodelYaw, + currentPilotYaw, + currentFlightmodelGForce, + currentPilotGForce, + }; + baton->send(send_to_baton); + + last_send_timestamp = get_current_timestamp(); + } + } + return 0; +} + +// + +PLUGIN_API int XPluginStart(char *outName, char *outSig, char *outDesc) { + strcpy(outName, "PilotDataSyncPlugin"); + strcpy(outSig, "oss.pilotdatasyncplugin"); + strcpy(outDesc, "A plug-in that collects and transmits X-Plane 11 data to " + "the iMotions platform for data collection and research"); + + XPLMCreateWindow_t params; + params.structSize = sizeof(params); + params.visible = 1; + params.drawWindowFunc = draw_pilotdatasync_plugin; + params.handleMouseClickFunc = mouse_handler; + params.handleRightClickFunc = dummy_mouse_handler; + params.handleMouseWheelFunc = dummy_wheel_handler; + params.handleKeyFunc = dummy_key_handler; + params.handleCursorFunc = dummy_cursor_status_handler; + params.refcon = NULL; + params.layer = xplm_WindowLayerFloatingWindows; + // Opt-in to styling our window like an X-Plane 11 native window + params.decorateAsFloatingWindow = xplm_WindowDecorationRoundRectangle; + + // Set the window's initial bounds + int left, bottom, right, top; + XPLMGetScreenBoundsGlobal(&left, &top, &right, &bottom); + params.left = left + 50; + params.bottom = bottom + 150; + params.right = params.left + 350; + params.top = params.bottom + 200; + + // Obtain datarefs for MSL and AGL elevation, respectively + elevationFlightmodelRef = + XPLMFindDataRef("sim/flightmodel/position/elevation"); + elevationPilotRef = + XPLMFindDataRef("sim/cockpit2/gauges/indicators/altitude_ft_pilot"); + + // Obtain datarefs for Airspeed + airspeedFlightmodelRef = + XPLMFindDataRef("sim/flightmodel/position/true_airspeed"); + airspeedPilotRef = + XPLMFindDataRef("sim/cockpit2/gauges/indicators/airspeed_kts_pilot"); + + // DataRefs for Vertical Velocity + verticalVelocityFlightmodelRef = + XPLMFindDataRef("sim/flightmodel/position/vh_ind_fpm"); + verticalVelocityPilotRef = + XPLMFindDataRef("sim/cockpit2/gauges/indicators/vvi_fpm_pilot"); + + // Obtain dataref for Pilot heading and True Magnetic Heading + headingFlightmodelRef = XPLMFindDataRef("sim/flightmodel/position/mag_psi"); + headingPilotRef = XPLMFindDataRef( + "sim/cockpit2/gauges/indicators/heading_AHARS_deg_mag_pilot"); + + // Obtain datarefs for Yaw, Roll, Pitch + yawFlightmodelRef = XPLMFindDataRef("sim/flightmodel/position/psi"); + rollFlightmodelRef = XPLMFindDataRef("sim/flightmodel/position/phi"); + rollPilotRef = + XPLMFindDataRef("sim/cockpit2/gauges/indicators/roll_AHARS_deg_pilot"); + + pitchFlightmodelRef = XPLMFindDataRef("sim/flightmodel/position/theta"); + pitchPilotRef = + XPLMFindDataRef("sim/cockpit2/gauges/indicators/pitch_AHARS_deg_pilot"); + + // g-force components (horizontal/side and vertical/normal) + gforceHorizontalRef = XPLMFindDataRef("sim/flightmodel/forces/g_side"); + gforceVerticalRef = XPLMFindDataRef("sim/flightmodel/forces/g_nrml"); + + g_window = XPLMCreateWindowEx(¶ms); + + // Position the window as a "free" floating window, + // which the user can drag around + XPLMSetWindowPositioningMode(g_window, xplm_WindowPositionFree, -1); + XPLMSetWindowTitle(g_window, "Positional Flight Data"); + + return g_window != NULL; +} + +PLUGIN_API void XPluginStop() { + XPLMDestroyWindow(g_window); + g_window = NULL; +} + +PLUGIN_API void XPluginDisable(void) { baton->stop(); } + +PLUGIN_API int XPluginEnable(void) { + baton->start(); + + return 1; +} + +PLUGIN_API void XPluginReceiveMessage(XPLMPluginID inFrom, int inMsg, + void *inParam) {} + +void draw_pilotdatasync_plugin(XPLMWindowID in_window_id, void *in_refcon) { + XPLMSetGraphicsState(0 /* no fog */, 0 /* 0 texture units */, + 0 /* no lighting */, 0 /* no alpha testing */, + 1 /* do alpha blend */, 1 /* do depth testing */, + 0 /* no depth writing */ + ); + + int l, t, r, b; + XPLMGetWindowGeometry(in_window_id, &l, &t, &r, &b); + + float col_white[] = {1.0, 1.0, 1.0}; // RGB + + auto build_str = [](string label, string unit, float value) { + string suffix = !std::isnan(value) ? std::to_string(value) + " " + unit + : "(Error Reading Data)"; + return label + ": " + suffix; + }; + + // Create strings from DataRefs to display in plugin window + float currentFlightmodelElevation = + XPLMGetDataf(elevationFlightmodelRef) * msToFeetRate; + string elevationFlightmodelStr = build_str("Elevation, Flightmodel (MSL)", + "ft", currentFlightmodelElevation); + + float currentPilotElevation = XPLMGetDataf(elevationPilotRef); + string elevationPilotStr = + build_str("Elevation, Pilot (MSL)", "ft", currentPilotElevation); + + float currentFlightmodelAirspeed = + XPLMGetDataf(airspeedFlightmodelRef) * msToKnotsRate; + string airspeedFlightmodelStr = + build_str("Airspeed, Flightmodel", "knots", currentFlightmodelAirspeed); + + float currentPilotAirspeed = XPLMGetDataf(airspeedPilotRef); + string airspeedPilotStr = + build_str("Airspeed, Pilot", "knots", currentPilotAirspeed); + + float currentFlightmodelVerticalVelocity = + XPLMGetDataf(verticalVelocityFlightmodelRef); + string verticalVelocityFlightmodelStr = + build_str("Vertical Velocity, Flightmodel", "ft/min", + currentFlightmodelVerticalVelocity); + + float currentPilotVerticalVelocity = XPLMGetDataf(verticalVelocityPilotRef); + string verticalVelocityPilotStr = build_str( + "Vertical Velocity, Pilot", "ft/min", currentPilotVerticalVelocity); + + float currentFlightmodelHeading = XPLMGetDataf(headingFlightmodelRef); + string headingFlightmodelStr = + build_str("Heading, Flightmodel", "°M", currentFlightmodelHeading); + + float currentPilotHeading = XPLMGetDataf(headingPilotRef); + string headingPilotStr = + build_str("Heading, Pilot", "°M", currentPilotHeading); + + // New parameters (roll, pitch, yaw, g-force) + float currentFlightmodelRoll = XPLMGetDataf(rollFlightmodelRef); + string rollFlightmodelStr = + build_str("Roll, Flightmodel", "°", currentFlightmodelRoll); + float currentPilotRoll = XPLMGetDataf(rollPilotRef); + string rollPilotStr = build_str("Roll, Pilot", "°", currentPilotRoll); + + float currentFlightmodelPitch = XPLMGetDataf(pitchFlightmodelRef); + string pitchFlightmodelStr = + build_str("Pitch, Flightmodel", "°", currentFlightmodelPitch); + float currentPilotPitch = XPLMGetDataf(pitchPilotRef); + string pitchPilotStr = build_str("Pitch, Pilot", "°", currentPilotPitch); + + float currentFlightmodelYaw = XPLMGetDataf(yawFlightmodelRef); + // use flightmodel yaw as the pilot yaw value since yaw pilot DataRef is not + // available + float currentPilotYaw = currentFlightmodelYaw; + string yawPilotStr = + build_str("Yaw, Pilot (from Flightmodel)", "°", currentPilotYaw); + string yawFlightmodelStr = + build_str("Yaw, Flightmodel", "°", currentFlightmodelYaw); + + // g-force: show both vertical (normal) and horizontal (side) components. + float currentFlightmodelGVert = XPLMGetDataf(gforceVerticalRef); + string gFlightmodelVertStr = + build_str("G-Force, Flightmodel (Vert)", "G", currentFlightmodelGVert); + float currentFlightmodelGHoriz = XPLMGetDataf(gforceHorizontalRef); + string gFlightmodelHorizStr = + build_str("G-Force, Flightmodel (Horiz)", "G", currentFlightmodelGHoriz); + + // For backward compatibility use vertical G as the single "Pilot G" value + float currentPilotG = currentFlightmodelGVert; + string gPilotStr = build_str("G-Force, Pilot (Vert)", "G", currentPilotG); + + // use this get_next_y_offset() lambda function to find the next vertical + // pixel start position on the window for string rendering for you. + int last_offset = 10; + auto get_next_y_offset = [&last_offset, t]() { + last_offset = last_offset + 10; + return t - last_offset; + }; + + vector draw_order = { + elevationFlightmodelStr, + elevationPilotStr, + airspeedFlightmodelStr, + verticalVelocityFlightmodelStr, + verticalVelocityPilotStr, + headingFlightmodelStr, + headingPilotStr, + rollFlightmodelStr, + rollPilotStr, + pitchFlightmodelStr, + pitchPilotStr, + yawPilotStr, + yawPilotStr, + gFlightmodelVertStr, + gFlightmodelHorizStr, + gPilotStr, + }; + + // print each line in order on the window + for (string line : draw_order) { + XPLMDrawString(col_white, l + 10, get_next_y_offset(), (char *)line.c_str(), + NULL, xplmFont_Proportional); + } + + // Button dimensions + int button_width = 120; + int button_height = 30; + int button_x = l + 10; + int button_y = b + 40; + + button_left = button_x; + button_right = button_x + button_width; + button_bottom = button_y; + button_top = button_y + button_height; + + // Draw button rectangle (simple filled rectangle) + float col_button[] = {0.2f, 0.5f, 0.8f, 1.0f}; + glColor4fv(col_button); + glBegin(GL_QUADS); + glVertex2i(button_left, button_bottom); + glVertex2i(button_right, button_bottom); + glVertex2i(button_right, button_top); + glVertex2i(button_left, button_top); + glEnd(); + + // Draw button label + float col_text[] = {1.0f, 1.0f, 1.0f}; + std::string button_label = "Send Packet"; + XPLMDrawString(col_text, button_left + 10, button_bottom + 8, + (char *)button_label.c_str(), NULL, xplmFont_Proportional); + + // Draw timestamp next to button + std::string ts_label = + "Last sent: " + + (last_send_timestamp.empty() ? "Never" : last_send_timestamp); + XPLMDrawString(col_text, button_right + 10, button_bottom + 8, + (char *)ts_label.c_str(), NULL, xplmFont_Proportional); + + // THROTTLE SENDING TO PREVENT SOCKET OVERFLOW + auto now = std::chrono::steady_clock::now(); + auto elapsed_ms = std::chrono::duration_cast( + now - last_send_time) + .count(); + + if (elapsed_ms >= SEND_INTERVAL_MS) { + // Send flight data to Relay via Baton. Both halves of every value, + // flightmodel first, in the order the relay turns into iMotions entries: + // [Altitude, Airspeed, VerticalVelocity, Heading, Roll, Pitch, Yaw, + // G-Force] + // + // Note vertical velocity comes before heading. The old pilot-only payload + // sent heading third and the relay reordered it; the paired payload is in + // entry order instead, so the relay pairs straight through. Sending 16 + // values is what lets FlightModel* and Pilot* differ at all (#184). + // + // Yaw and G-Force have no pilot-side DataRef, so both halves carry the + // flightmodel value and stay equal by design. + vector send_to_baton = { + currentFlightmodelElevation, + currentPilotElevation, + currentFlightmodelAirspeed, + currentPilotAirspeed, + currentFlightmodelVerticalVelocity, + currentPilotVerticalVelocity, + currentFlightmodelHeading, + currentPilotHeading, + currentFlightmodelRoll, + currentPilotRoll, + currentFlightmodelPitch, + currentPilotPitch, + currentFlightmodelYaw, + currentPilotYaw, + currentFlightmodelGVert, + currentPilotG, + }; + + { + char dbg[320]; + std::snprintf(dbg, sizeof(dbg), + "[PDS PLUGIN] Draw send -> alt=%.3f/%.3f air=%.3f/%.3f " + "vv=%.3f/%.3f hdg=%.3f/%.3f (flightmodel/pilot)\n", + send_to_baton[0], send_to_baton[1], send_to_baton[2], + send_to_baton[3], send_to_baton[4], send_to_baton[5], + send_to_baton[6], send_to_baton[7]); + XPLMDebugString(dbg); + } + baton->send(send_to_baton); + + last_send_time = now; + } +}