From 90913df7de98e6dcb9eb0a2fe19d36a70e7c1660 Mon Sep 17 00:00:00 2001 From: Alex Klimaj Date: Thu, 16 Jul 2026 14:24:07 -0600 Subject: [PATCH] feat(gps): inject SPARTN corrections alongside RTCM (#27919) * feat(gps): inject SPARTN corrections alongside RTCM Add a SPARTN transport-layer framer and feed gps_inject_data through both RTCM3 and SPARTN parsers so PointPerfect-style SPARTN streams can be reassembled and written to the receiver the same way RTCM already is. Gated by CONFIG_GPS_SPARTN (default on). Disabled on px4_fmu-v6x where flash is already at the limit; enabled on ark_can-rtk-gps. Depends on PX4-GPSDrivers for automatic u-blox SPARTN input enable. Signed-off-by: alexklimaj * fix(gnss): avoid undefined shift in SPARTN CRC-32 Use uint64_t for the CRC working register so n==32 does not perform 1u << 32 (clang-analyzer BitwiseShift). Signed-off-by: alexklimaj * make format * feat(gps): enable SPARTN support in board configurations * feat(gps): enhance SPARTN support with additional frame tracking and status reporting * fix(gps): frame RTCM3 and SPARTN from a single buffer Feeding every inject chunk to an independent framer per protocol let each one resync inside the other's payloads. That is not symmetric: RTCM3 is covered by CRC-24Q, but SPARTN's header carries no usable integrity check (TF006 is 4 bits over a non-byte-aligned field) and TF005 permits an 8-bit message CRC, so a stray 0x73 in an RTCM3 payload is framed as SPARTN at roughly 1 in 1024. RTCM3-only is what every board actually runs, and over 50 MB of it the two framers produced 211 bogus SPARTN frames (210 declaring CRC-8), each re-injecting up to 1 kB of the stream back into the receiver. The reverse direction produced none. Frame both protocols from one buffer instead: whichever preamble comes first is framed, and a valid frame consumes its own payload, so bytes inside one protocol's frame never start the other's. The same 50 MB now yields zero. Frames are also injected in arrival order rather than all RTCM3 then all SPARTN, and one buffer replaces two (2248 B/instance, down from ~4350 B). Also reject TF002 message types 5-119, which SPARTN reserves, as the one header field with a checkable range. CONFIG_GPS_SPARTN was default y, so it built into every target with a GPS including px4_fmu-v6x, which the flash report showed gaining the framer despite the intent to keep it off. Default it to n and enable it explicitly where it is wanted; the ark GPS boards already opt in, and SITL opts in so the framing tests keep running in CI. Rtcm3Parser and SpartnParser are replaced by CorrectionFramer; their tests carry over to it. RtcmStress fed "garbage" drawn from 0x01-0xD2 to avoid a preamble, which includes 0x73, and RtcmBustedSender ended its stream on a candidate the framer was still waiting to complete; both now avoid every preamble and flush respectively. * feat(gps): enable SPARTN on ARK flight controllers Covers receivers attached over UART rather than CAN. All four targets link with margin; fmu-v6xrt has no px4board on this branch yet. Signed-off-by: Jacob Dahl --------- Signed-off-by: alexklimaj Signed-off-by: Jacob Dahl Co-authored-by: Jacob Dahl --- boards/ark/can-rtk-gps/default.px4board | 1 + boards/ark/f9p-gps/default.px4board | 1 + boards/ark/fmu-v6s/default.px4board | 1 + boards/ark/fmu-v6x/default.px4board | 1 + boards/ark/fpv/default.px4board | 1 + boards/ark/pi6x/default.px4board | 1 + boards/ark/x20-gps/default.px4board | 1 + boards/px4/sitl/default.px4board | 1 + msg/RtcmData.msg | 2 +- src/drivers/gnss/septentrio/septentrio.cpp | 14 +- src/drivers/gnss/septentrio/septentrio.h | 10 +- src/drivers/gps/Kconfig | 10 + src/drivers/gps/gps.cpp | 117 ++++++--- src/lib/gnss/CMakeLists.txt | 11 +- src/lib/gnss/correction_framer.cpp | 265 +++++++++++++++++++ src/lib/gnss/correction_framer.h | 181 +++++++++++++ src/lib/gnss/rtcm.cpp | 90 ------- src/lib/gnss/rtcm.h | 104 -------- src/lib/gnss/spartn.cpp | 75 ++++++ src/lib/gnss/spartn.h | 121 +++++++++ src/lib/gnss/test/CMakeLists.txt | 4 + src/lib/gnss/test/RtcmBustedSenderTest.cpp | 7 + src/lib/gnss/test/RtcmParserTest.cpp | 4 +- src/lib/gnss/test/RtcmStressTest.cpp | 6 +- src/lib/gnss/test/RtcmTestCommon.hpp | 4 +- src/lib/gnss/test/SpartnFramerTest.cpp | 288 +++++++++++++++++++++ 26 files changed, 1070 insertions(+), 251 deletions(-) create mode 100644 src/lib/gnss/correction_framer.cpp create mode 100644 src/lib/gnss/correction_framer.h create mode 100644 src/lib/gnss/spartn.cpp create mode 100644 src/lib/gnss/spartn.h create mode 100644 src/lib/gnss/test/SpartnFramerTest.cpp diff --git a/boards/ark/can-rtk-gps/default.px4board b/boards/ark/can-rtk-gps/default.px4board index 5e92d73959c..e98c85fe773 100644 --- a/boards/ark/can-rtk-gps/default.px4board +++ b/boards/ark/can-rtk-gps/default.px4board @@ -7,6 +7,7 @@ CONFIG_BOARD_CONSTRAINED_MEMORY=y CONFIG_DRIVERS_BAROMETER_BMP388=y CONFIG_DRIVERS_BOOTLOADERS=y CONFIG_DRIVERS_GPS=y +CONFIG_GPS_SPARTN=y CONFIG_DRIVERS_IMU_INVENSENSE_ICM42688P=y CONFIG_DRIVERS_MAGNETOMETER_BOSCH_BMM150=y CONFIG_DRIVERS_PPS_CAPTURE=y diff --git a/boards/ark/f9p-gps/default.px4board b/boards/ark/f9p-gps/default.px4board index 6c79012be7a..fbb7b17c751 100644 --- a/boards/ark/f9p-gps/default.px4board +++ b/boards/ark/f9p-gps/default.px4board @@ -5,6 +5,7 @@ CONFIG_BOARD_CONSTRAINED_MEMORY=y CONFIG_DRIVERS_BAROMETER_BMP388=y CONFIG_DRIVERS_BOOTLOADERS=y CONFIG_DRIVERS_GPS=y +CONFIG_GPS_SPARTN=y CONFIG_DRIVERS_IMU_INVENSENSE_ICM42688P=y CONFIG_DRIVERS_MAGNETOMETER_ST_IIS2MDC=y CONFIG_DRIVERS_SAFETY_BUTTON=y diff --git a/boards/ark/fmu-v6s/default.px4board b/boards/ark/fmu-v6s/default.px4board index 4552203c56b..7a16191ab3a 100644 --- a/boards/ark/fmu-v6s/default.px4board +++ b/boards/ark/fmu-v6s/default.px4board @@ -19,6 +19,7 @@ CONFIG_DRIVERS_DIFFERENTIAL_PRESSURE_AUAV=y CONFIG_COMMON_DISTANCE_SENSOR=y CONFIG_DRIVERS_DSHOT=y CONFIG_DRIVERS_GPS=y +CONFIG_GPS_SPARTN=y CONFIG_DRIVERS_PPS_CAPTURE=y CONFIG_DRIVERS_HEATER=y CONFIG_DRIVERS_IMU_INVENSENSE_IIM42653=y diff --git a/boards/ark/fmu-v6x/default.px4board b/boards/ark/fmu-v6x/default.px4board index 6e9c03f0ddf..336e7339070 100644 --- a/boards/ark/fmu-v6x/default.px4board +++ b/boards/ark/fmu-v6x/default.px4board @@ -19,6 +19,7 @@ CONFIG_DRIVERS_DIFFERENTIAL_PRESSURE_AUAV=y CONFIG_COMMON_DISTANCE_SENSOR=y CONFIG_DRIVERS_DSHOT=y CONFIG_DRIVERS_GPS=y +CONFIG_GPS_SPARTN=y CONFIG_DRIVERS_PPS_CAPTURE=y CONFIG_DRIVERS_HEATER=y CONFIG_DRIVERS_IMU_ANALOG_DEVICES_ADIS16507=y diff --git a/boards/ark/fpv/default.px4board b/boards/ark/fpv/default.px4board index bc6ffdd1752..20d0cb3fbcf 100644 --- a/boards/ark/fpv/default.px4board +++ b/boards/ark/fpv/default.px4board @@ -15,6 +15,7 @@ CONFIG_COMMON_DIFFERENTIAL_PRESSURE=y CONFIG_COMMON_DISTANCE_SENSOR=y CONFIG_DRIVERS_DSHOT=y CONFIG_DRIVERS_GPS=y +CONFIG_GPS_SPARTN=y CONFIG_DRIVERS_HEATER=y CONFIG_DRIVERS_IMU_INVENSENSE_IIM42653=y CONFIG_DRIVERS_IMU_MURATA_SCH16T=y diff --git a/boards/ark/pi6x/default.px4board b/boards/ark/pi6x/default.px4board index 7724886ee43..a319c05b759 100644 --- a/boards/ark/pi6x/default.px4board +++ b/boards/ark/pi6x/default.px4board @@ -13,6 +13,7 @@ CONFIG_DRIVERS_DISTANCE_SENSOR_BROADCOM_AFBRS50=y CONFIG_DRIVERS_DISTANCE_SENSOR_VL53L0X=y CONFIG_DRIVERS_DSHOT=y CONFIG_DRIVERS_GPS=y +CONFIG_GPS_SPARTN=y CONFIG_DRIVERS_HEATER=y CONFIG_DRIVERS_IMU_INVENSENSE_ICM42688P=y CONFIG_COMMON_LIGHT=y diff --git a/boards/ark/x20-gps/default.px4board b/boards/ark/x20-gps/default.px4board index 6c79012be7a..fbb7b17c751 100644 --- a/boards/ark/x20-gps/default.px4board +++ b/boards/ark/x20-gps/default.px4board @@ -5,6 +5,7 @@ CONFIG_BOARD_CONSTRAINED_MEMORY=y CONFIG_DRIVERS_BAROMETER_BMP388=y CONFIG_DRIVERS_BOOTLOADERS=y CONFIG_DRIVERS_GPS=y +CONFIG_GPS_SPARTN=y CONFIG_DRIVERS_IMU_INVENSENSE_ICM42688P=y CONFIG_DRIVERS_MAGNETOMETER_ST_IIS2MDC=y CONFIG_DRIVERS_SAFETY_BUTTON=y diff --git a/boards/px4/sitl/default.px4board b/boards/px4/sitl/default.px4board index 118ddb48d3d..7c3f78d7e95 100644 --- a/boards/px4/sitl/default.px4board +++ b/boards/px4/sitl/default.px4board @@ -4,6 +4,7 @@ CONFIG_BOARD_ETHERNET=y CONFIG_BOARD_ROOT_PATH="." CONFIG_DRIVERS_CAMERA_TRIGGER=y CONFIG_DRIVERS_GPS=y +CONFIG_GPS_SPARTN=y CONFIG_DRIVERS_GNSS_SEPTENTRIO=y CONFIG_DRIVERS_OSD_MSP_OSD=y CONFIG_DRIVERS_TONE_ALARM=y diff --git a/msg/RtcmData.msg b/msg/RtcmData.msg index 03c47790cf2..b28fe2d76f7 100644 --- a/msg/RtcmData.msg +++ b/msg/RtcmData.msg @@ -17,7 +17,7 @@ uint32 device_id # [-] Unique device ID of the publisher that produced this RTCM uint16 len # [-] Length of data uint8 flags # [-] LSB: 1=fragmented -uint8[300] data # RTCM3 payload (fixed-base corrections, or moving-baseline data) +uint8[300] data # Correction payload (fixed-base RTCM3 and/or SPARTN frames, or moving-baseline RTCM3) uint8 ORB_QUEUE_LENGTH = 16 diff --git a/src/drivers/gnss/septentrio/septentrio.cpp b/src/drivers/gnss/septentrio/septentrio.cpp index a681029d6a9..87dd5245b12 100644 --- a/src/drivers/gnss/septentrio/septentrio.cpp +++ b/src/drivers/gnss/septentrio/septentrio.cpp @@ -1656,7 +1656,7 @@ void SeptentrioDriver::drain_rtcm_corrections() // Prevent injection of data from self if (msg.device_id != get_device_id()) { - _rtcm_corrections_parser.addData(msg.data, msg.len); + _rtcm_corrections_framer.addData(msg.data, msg.len); _last_rtcm_injection_time = hrt_absolute_time(); } } @@ -1695,19 +1695,19 @@ void SeptentrioDriver::drain_moving_baseline() // Prevent injection of data from self if (msg.device_id != get_device_id()) { - _rtcm_moving_baseline_parser.addData(msg.data, msg.len); + _rtcm_moving_baseline_framer.addData(msg.data, msg.len); } } } -void SeptentrioDriver::inject_rtcm_frames(gnss::Rtcm3Parser &parser) +void SeptentrioDriver::inject_rtcm_frames(gnss::CorrectionFramer &framer) { size_t frame_len = {}; const uint8_t *frame_ptr = {}; - while ((frame_ptr = parser.getNextMessage(&frame_len)) != nullptr) { + while ((frame_ptr = framer.getNextMessage(&frame_len)) != nullptr) { write(frame_ptr, frame_len); - parser.consumeMessage(frame_len); + framer.consumeMessage(frame_len); ++_current_interval_rtcm_injections; } } @@ -1717,13 +1717,13 @@ void SeptentrioDriver::handle_inject_data_topic() // Fixed-base RTCM corrections (from MAVLink GPS_RTCM_DATA, UAVCAN RTCMStream). // Both the moving-base (Secondary) and the rover (Main) can benefit from external RTCM. drain_rtcm_corrections(); - inject_rtcm_frames(_rtcm_corrections_parser); + inject_rtcm_frames(_rtcm_corrections_framer); // Moving-baseline RTCM is only consumed by the rover (Main instance) in a moving-base setup. // Single publisher, so no instance selection - just drain it into the receiver. if (_receiver_setup == ReceiverSetup::MovingBase && _instance == Instance::Main) { drain_moving_baseline(); - inject_rtcm_frames(_rtcm_moving_baseline_parser); + inject_rtcm_frames(_rtcm_moving_baseline_framer); } } diff --git a/src/drivers/gnss/septentrio/septentrio.h b/src/drivers/gnss/septentrio/septentrio.h index 54c1a5af831..b6ff74c3609 100644 --- a/src/drivers/gnss/septentrio/septentrio.h +++ b/src/drivers/gnss/septentrio/septentrio.h @@ -57,7 +57,7 @@ #include #include #include -#include +#include #include #include #include @@ -546,7 +546,7 @@ private: * The two inject streams are written frame-atomically so chunks of a fragmented frame on * one stream can never interleave with the other stream's bytes mid-frame. */ - void inject_rtcm_frames(gnss::Rtcm3Parser &parser); + void inject_rtcm_frames(gnss::CorrectionFramer &framer); /** * @brief Send data to the receiver, such as RTCM injections. @@ -747,10 +747,10 @@ private: char _port[20] {}; ///< The path of the used serial device hrt_abstime _last_rtcm_injection_time {0}; ///< Time of last RTCM corrections injection uint8_t _selected_rtcm_instance {0}; ///< uORB instance that is being used for RTCM corrections - // Separate parser per inject stream: frames are only written to the receiver once complete, + // Separate framer per inject stream: frames are only written to the receiver once complete, // so fixed-base corrections and moving-baseline bytes cannot interleave mid-frame. - gnss::Rtcm3Parser _rtcm_corrections_parser {}; ///< Frame reassembly for rtcm_corrections - gnss::Rtcm3Parser _rtcm_moving_baseline_parser {}; ///< Frame reassembly for rtcm_moving_baseline + gnss::CorrectionFramer _rtcm_corrections_framer {}; ///< Frame reassembly for rtcm_corrections + gnss::CorrectionFramer _rtcm_moving_baseline_framer {}; ///< Frame reassembly for rtcm_moving_baseline uint8_t _spoofing_state {0}; ///< Receiver spoofing state uint8_t _jamming_state {0}; ///< Receiver jamming state bool _time_synced {false}; ///< Receiver time in sync with GPS time diff --git a/src/drivers/gps/Kconfig b/src/drivers/gps/Kconfig index b1630926f9f..ddb602c8f38 100644 --- a/src/drivers/gps/Kconfig +++ b/src/drivers/gps/Kconfig @@ -42,6 +42,16 @@ if DRIVERS_GPS Generic NMEA driver, including Unicore extensions. Never auto-detected: it must be selected explicitly via GPS_x_PROTOCOL or the -p command line option. + + config GPS_SPARTN + bool "SPARTN correction framing (e.g. PointPerfect)" + default n + ---help--- + Frame and inject SPARTN corrections (e.g. u-blox PointPerfect) + from gps_inject_data alongside RTCM3. + Enable on targets that receive a SPARTN correction service. + Left off, the SPARTN framer is not built and the receiver only + ever sees RTCM3, which is the common RTK setup. endif # DRIVERS_GPS menuconfig USER_GPS diff --git a/src/drivers/gps/gps.cpp b/src/drivers/gps/gps.cpp index 020b6066cd2..46112cef90a 100644 --- a/src/drivers/gps/gps.cpp +++ b/src/drivers/gps/gps.cpp @@ -70,7 +70,7 @@ #include #include -#include +#include #include "devices/src/gps_helper.h" @@ -248,12 +248,16 @@ private: failure_injection::Stuck _stuck; float _rate{0.0f}; ///< position update rate - float _rtcm_injection_rate{0.0f}; ///< RTCM corrections injection rate (Hz) + float _rtcm_injection_rate{0.0f}; ///< corrections injection rate (Hz, RTCM3 and SPARTN) uint64_t _last_rtcm_corrections_injection_count{0}; ///< corrections-injection perf snapshot for rate calc + unsigned _rtcm_frames_in_rate_window{0}; ///< corrections-stream RTCM3 frames in rate window + unsigned _spartn_frames_in_rate_window {0}; ///< corrections-stream SPARTN frames in rate window + bool _injecting_rtcm {false}; ///< latched: RTCM3 corrections injected in last rate window + bool _injecting_spartn {false}; ///< latched: SPARTN injected in last rate window unsigned _num_bytes_read{0}; ///< counter for number of read bytes from the UART (within update interval) unsigned _rate_reading{0}; ///< reading rate in B/s - hrt_abstime _last_rtcm_injection_time{0}; ///< time of last RTCM corrections injection - uint8_t _selected_rtcm_instance{0}; ///< uorb instance that is being used for RTCM corrections + hrt_abstime _last_rtcm_injection_time{0}; ///< time of last corrections injection + uint8_t _selected_rtcm_instance{0}; ///< uorb instance that is being used for corrections const Instance _instance; @@ -266,14 +270,16 @@ private: gps_dump_s *_dump_from_device{nullptr}; gps_dump_comm_mode_t _dump_communication_mode{gps_dump_comm_mode_t::Disabled}; - // Separate RTCM parsers per source. A fragmented fixed-base frame must not be corrupted by - // moving-baseline bytes appended mid-frame (e.g. fixed-base + moving-base + rover setups, where - // the rover injects both streams), so each stream reassembles in its own buffer. - gnss::Rtcm3Parser _rtcm_corrections_parser{}; - gnss::Rtcm3Parser _rtcm_moving_baseline_parser{}; + // Each stream reassembles in its own framer: a fragmented fixed-base frame must not be + // corrupted by moving-baseline bytes appended mid-frame (e.g. fixed-base + moving-base + + // rover setups, where the rover injects both streams). Within a framer, RTCM3 and SPARTN + // share one buffer so neither protocol can resync inside the other's payloads (see + // correction_framer.h); SPARTN only ever arrives on the corrections stream. + gnss::CorrectionFramer _rtcm_corrections_framer{}; + gnss::CorrectionFramer _rtcm_moving_baseline_framer{}; perf_counter_t _uart_tx_buffer_full_perf{perf_alloc(PC_COUNT, MODULE_NAME": tx buf full")}; - perf_counter_t _rtcm_buffer_full_perf{perf_alloc(PC_COUNT, MODULE_NAME": rtcm buf full")}; + perf_counter_t _correction_buffer_full_perf{perf_alloc(PC_COUNT, MODULE_NAME": corrections buf full")}; perf_counter_t _rtcm_corrections_injection_perf{perf_alloc(PC_COUNT, MODULE_NAME": rtcm corrections injected")}; perf_counter_t _rtcm_moving_baseline_injection_perf{perf_alloc(PC_COUNT, MODULE_NAME": rtcm moving baseline injected")}; @@ -333,10 +339,12 @@ private: void drainMovingBaseline(); /** - * Inject all complete RTCM frames reassembled in a parser into the receiver, counting each - * injected frame on the given perf counter. + * Inject all complete frames reassembled in a framer (RTCM3 and/or SPARTN) into the receiver, + * counting each injected frame on the given perf counter and optional per-protocol rate-window + * counters. */ - void injectRtcmFrames(gnss::Rtcm3Parser &parser, perf_counter_t injection_perf); + void injectRtcmFrames(gnss::CorrectionFramer &framer, perf_counter_t injection_perf, + unsigned *rtcm_frames_in_window = nullptr, unsigned *spartn_frames_in_window = nullptr); /** * send data to the device, such as an RTCM stream @@ -484,7 +492,7 @@ GPS::~GPS() } perf_free(_uart_tx_buffer_full_perf); - perf_free(_rtcm_buffer_full_perf); + perf_free(_correction_buffer_full_perf); perf_free(_rtcm_corrections_injection_perf); perf_free(_rtcm_moving_baseline_injection_perf); @@ -671,8 +679,9 @@ void GPS::drainRtcmCorrections() // Prevent injection of data from self if (msg.device_id != get_device_id()) { - if (_rtcm_corrections_parser.addData(msg.data, msg.len) < msg.len) { - perf_count(_rtcm_buffer_full_perf); + // Add data to the framer buffer for frame reassembly + if (_rtcm_corrections_framer.addData(msg.data, msg.len) < msg.len) { + perf_count(_correction_buffer_full_perf); } _last_rtcm_injection_time = hrt_absolute_time(); @@ -714,8 +723,8 @@ void GPS::drainMovingBaseline() // Prevent injection of data from self if (msg.device_id != get_device_id()) { - if (_rtcm_moving_baseline_parser.addData(msg.data, msg.len) < msg.len) { - perf_count(_rtcm_buffer_full_perf); + if (_rtcm_moving_baseline_framer.addData(msg.data, msg.len) < msg.len) { + perf_count(_correction_buffer_full_perf); } } } @@ -729,45 +738,57 @@ void GPS::handleInjectDataTopic() return; } - // Fixed-base RTCM corrections (MAVLink GPS_RTCM_DATA, UAVCAN RTCMStream). Every configured - // receiver can use these - including a UART2 moving-base rover, whose baseline arrives in - // hardware but which still wants fixed-base corrections over its main link. Reassemble and inject - // them through their own parser before touching the moving-baseline stream. + // Fixed-base corrections (MAVLink GPS_RTCM_DATA, UAVCAN RTCMStream): RTCM3 and, when enabled, + // SPARTN framed from one buffer in arrival order. Every configured receiver can use these - + // including a UART2 moving-base rover, whose baseline arrives in hardware but which still wants + // fixed-base corrections over its main link. drainRtcmCorrections(); - injectRtcmFrames(_rtcm_corrections_parser, _rtcm_corrections_injection_perf); + injectRtcmFrames(_rtcm_corrections_framer, _rtcm_corrections_injection_perf, + &_rtcm_frames_in_rate_window, &_spartn_frames_in_rate_window); // Moving-baseline RTCM (RTCM 4072 etc.) from a peer moving-base GPS. Only a heading rover that // receives the baseline through the flight controller (UART1 / CAN) injects it here; a UART2 // rover gets it in hardware and a moving base produces it. Single publisher, so no instance - // selection - and a separate parser keeps the two byte streams from interleaving into corrupt + // selection - and a separate framer keeps the two byte streams from interleaving into corrupt // frames. if (_helper->shouldInjectMovingBaseline()) { drainMovingBaseline(); - injectRtcmFrames(_rtcm_moving_baseline_parser, _rtcm_moving_baseline_injection_perf); + injectRtcmFrames(_rtcm_moving_baseline_framer, _rtcm_moving_baseline_injection_perf); } } -void GPS::injectRtcmFrames(gnss::Rtcm3Parser &parser, perf_counter_t injection_perf) +void GPS::injectRtcmFrames(gnss::CorrectionFramer &framer, perf_counter_t injection_perf, + unsigned *rtcm_frames_in_window, unsigned *spartn_frames_in_window) { - // Inject all complete RTCM frames reassembled in this parser. + // Inject all complete frames reassembled in this framer, in arrival order size_t frame_len = {}; const uint8_t *frame_ptr = {}; + gnss::CorrectionProtocol protocol = gnss::CorrectionProtocol::Rtcm3; - while ((frame_ptr = parser.getNextMessage(&frame_len)) != nullptr) { + while ((frame_ptr = framer.getNextMessage(&frame_len, &protocol)) != nullptr) { // Check TX buffer space before writing if (_interface == GPSHelper::Interface::UART) { - ssize_t tx_available = _uart.txSpaceAvailable(); + const ssize_t tx_available = _uart.txSpaceAvailable(); if ((ssize_t)frame_len > tx_available) { - // TX buffer full, stop and let it drain - frames stay in parser buffer + // TX buffer full, stop and let it drain - frames stay in the framer buffer perf_count(_uart_tx_buffer_full_perf); break; } } injectData(frame_ptr, frame_len); - parser.consumeMessage(frame_len); + framer.consumeMessage(frame_len); perf_count(injection_perf); + + if (protocol == gnss::CorrectionProtocol::Rtcm3) { + if (rtcm_frames_in_window != nullptr) { + (*rtcm_frames_in_window)++; + } + + } else if (spartn_frames_in_window != nullptr) { + (*spartn_frames_in_window)++; + } } } @@ -1294,9 +1315,13 @@ GPS::run() const uint64_t corrections_count = perf_event_count(_rtcm_corrections_injection_perf); _rtcm_injection_rate = (corrections_count - _last_rtcm_corrections_injection_count) / dt; _last_rtcm_corrections_injection_count = corrections_count; + _injecting_rtcm = _rtcm_frames_in_rate_window > 0; + _injecting_spartn = _spartn_frames_in_rate_window > 0; _rate_reading = _num_bytes_read / dt; last_rate_measurement = now; last_rate_count = 0; + _rtcm_frames_in_rate_window = 0; + _spartn_frames_in_rate_window = 0; _num_bytes_read = 0; _helper->storeUpdateRates(); _helper->resetUpdateRates(); @@ -1346,6 +1371,8 @@ GPS::run() _healthy = false; _rate = 0.0f; _rtcm_injection_rate = 0.0f; + _injecting_rtcm = false; + _injecting_spartn = false; } } @@ -1445,22 +1472,38 @@ GPS::print_status() PX4_INFO("status: %s, port: %s, baudrate: %d", _healthy ? "OK" : "NOT OK", _port, _baudrate); PX4_INFO("sat info: %s", (_p_report_sat_info != nullptr) ? "enabled" : "disabled"); - PX4_INFO("rate reading: \t\t%6i B/s", _rate_reading); + // Fixed-width labels so values stay aligned (longest: "rate RTCM injection") + PX4_INFO("rate reading: %6i B/s", _rate_reading); if (_sensor_gps.timestamp != 0) { if (_helper) { - PX4_INFO("rate position: \t\t%6.2f Hz", (double)_helper->getPositionUpdateRate()); - PX4_INFO("rate velocity: \t\t%6.2f Hz", (double)_helper->getVelocityUpdateRate()); + PX4_INFO("rate position: %6.2f Hz", (double)_helper->getPositionUpdateRate()); + PX4_INFO("rate velocity: %6.2f Hz", (double)_helper->getVelocityUpdateRate()); } - PX4_INFO("rate publication:\t\t%6.2f Hz", (double)_rate); - PX4_INFO("rate RTCM injection:\t%6.2f Hz", (double)_rtcm_injection_rate); + PX4_INFO("rate publication: %6.2f Hz", (double)_rate); + PX4_INFO("rate RTCM injection: %6.2f Hz", (double)_rtcm_injection_rate); + + // _injecting_spartn stays false when CONFIG_GPS_SPARTN is disabled + const char *corrections = "none"; + + if (_injecting_rtcm && _injecting_spartn) { + corrections = "RTCM + SPARTN"; + + } else if (_injecting_rtcm) { + corrections = "RTCM"; + + } else if (_injecting_spartn) { + corrections = "SPARTN"; + } + + PX4_INFO("corrections: %s", corrections); print_message(ORB_ID(sensor_gps), _sensor_gps); } perf_print_counter(_uart_tx_buffer_full_perf); - perf_print_counter(_rtcm_buffer_full_perf); + perf_print_counter(_correction_buffer_full_perf); perf_print_counter(_rtcm_corrections_injection_perf); perf_print_counter(_rtcm_moving_baseline_injection_perf); diff --git a/src/lib/gnss/CMakeLists.txt b/src/lib/gnss/CMakeLists.txt index a577c75b92e..0cbcbbe97ed 100644 --- a/src/lib/gnss/CMakeLists.txt +++ b/src/lib/gnss/CMakeLists.txt @@ -31,7 +31,16 @@ # ############################################################################ -px4_add_library(gnss rtcm.cpp) +set(GNSS_SRCS + rtcm.cpp + correction_framer.cpp +) + +if(CONFIG_GPS_SPARTN) + list(APPEND GNSS_SRCS spartn.cpp) +endif() + +px4_add_library(gnss ${GNSS_SRCS}) target_include_directories(gnss PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/src/lib/gnss/correction_framer.cpp b/src/lib/gnss/correction_framer.cpp new file mode 100644 index 00000000000..9eaf6dc8ba1 --- /dev/null +++ b/src/lib/gnss/correction_framer.cpp @@ -0,0 +1,265 @@ +/**************************************************************************** + * + * Copyright (c) 2026 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/** + * @file correction_framer.cpp + * + * GNSS correction stream framing implementation. + */ + +#include "correction_framer.h" + +#include + +namespace gnss +{ + +bool CorrectionFramer::isPreamble(uint8_t byte) +{ + if (byte == RTCM3_PREAMBLE) { + return true; + } + +#if defined(CONFIG_GPS_SPARTN) + + if (byte == SPARTN_PREAMBLE) { + return true; + } + +#endif + + return false; +} + +size_t CorrectionFramer::addData(const uint8_t *data, size_t len) +{ + const size_t space_available = BUFFER_SIZE - _buffer_len; + const size_t to_copy = (len < space_available) ? len : space_available; + + if (to_copy > 0) { + memcpy(&_buffer[_buffer_len], data, to_copy); + _buffer_len += to_copy; + } + + return to_copy; +} + +CorrectionFramer::Probe CorrectionFramer::probeRtcm3(size_t *frame_len) const +{ + // Need at least the header to read the length + if (_buffer_len < RTCM3_HEADER_LEN) { + return Probe::NeedMoreData; + } + + // The 10-bit field cannot exceed RTCM3_MAX_PAYLOAD_LEN, so the length alone + // never rejects a candidate: CRC-24Q is what validates the frame. + const size_t payload_len = rtcm3_payload_length(_buffer); + const size_t len = RTCM3_HEADER_LEN + payload_len + RTCM3_CRC_LEN; + + if (_buffer_len < len) { + return Probe::NeedMoreData; + } + + const uint32_t calculated_crc = rtcm3_crc24q(_buffer, RTCM3_HEADER_LEN + payload_len); + const uint32_t received_crc = (static_cast(_buffer[len - 3]) << 16) | + (static_cast(_buffer[len - 2]) << 8) | + _buffer[len - 1]; + + if (calculated_crc != received_crc) { + return Probe::CrcError; + } + + *frame_len = len; + return Probe::Complete; +} + +#if defined(CONFIG_GPS_SPARTN) +CorrectionFramer::Probe CorrectionFramer::probeSpartn(size_t *frame_len) const +{ + // Need TF002..TF006 to read the length and CRC type + if (_buffer_len < SPARTN_FRAME_START_LEN) { + return Probe::NeedMoreData; + } + + const uint8_t b1 = _buffer[1]; + const uint8_t b2 = _buffer[2]; + const uint8_t b3 = _buffer[3]; + + // TF002 is the only header field with a checkable range. The 10-bit length + // spans its full range and TF006 is a 4-bit CRC over a non-byte-aligned + // field, so this is the only cheap guard before the message CRC. + if (!spartn_message_type_defined(b1 >> 1)) { + return Probe::InvalidHeader; + } + + const uint16_t payload_len = static_cast(((b1 & 0x01) << 9) | (b2 << 1) | (b3 >> 7)); + const bool eaf = ((b3 >> 6) & 0x01) != 0; + const uint8_t crc_type = (b3 >> 4) & 0x03; + const size_t crc_bytes = static_cast(crc_type) + 1; + + // TF008 (time tag type) sets the description block length + if (_buffer_len < SPARTN_FRAME_START_LEN + 1) { + return Probe::NeedMoreData; + } + + const bool time_tag_32bit = ((_buffer[4] >> 3) & 0x01) != 0; + const size_t desc_len = spartn_desc_length_bytes(eaf, time_tag_32bit); + + if (_buffer_len < SPARTN_FRAME_START_LEN + desc_len) { + return Probe::NeedMoreData; + } + + size_t auth_bytes = 0; + + if (eaf) { + // TF014/TF015 occupy the low 6 bits of the last description byte + const uint8_t last = _buffer[SPARTN_FRAME_START_LEN + desc_len - 1]; + auth_bytes = spartn_auth_length_bytes(true, (last >> 3) & 0x07, last & 0x07); + } + + const size_t len = SPARTN_FRAME_START_LEN + desc_len + payload_len + auth_bytes + crc_bytes; + + if (_buffer_len < len) { + return Probe::NeedMoreData; + } + + // Message CRC (TF018) covers TF002..TF017 + const size_t core_len = len - 1 - crc_bytes; + const uint32_t calculated_crc = spartn_message_crc(&_buffer[1], core_len, crc_type); + uint32_t received_crc = 0; + + for (size_t i = 0; i < crc_bytes; i++) { + received_crc = (received_crc << 8) | _buffer[len - crc_bytes + i]; + } + + if (calculated_crc != received_crc) { + return Probe::CrcError; + } + + *frame_len = len; + return Probe::Complete; +} +#endif // CONFIG_GPS_SPARTN + +const uint8_t *CorrectionFramer::getNextMessage(size_t *out_len, CorrectionProtocol *out_protocol) +{ + while (_buffer_len > 0) { + // Drop everything that cannot start a frame of either protocol + size_t to_drop = 0; + + while ((to_drop < _buffer_len) && !isPreamble(_buffer[to_drop])) { + to_drop++; + } + + if (to_drop > 0) { + _bytes_discarded += to_drop; + discardBytes(to_drop); + } + + if (_buffer_len == 0) { + return nullptr; + } + + size_t frame_len = 0; + CorrectionProtocol protocol = CorrectionProtocol::Rtcm3; + Probe result; + +#if defined(CONFIG_GPS_SPARTN) + + if (_buffer[0] == SPARTN_PREAMBLE) { + protocol = CorrectionProtocol::Spartn; + result = probeSpartn(&frame_len); + + } else { + result = probeRtcm3(&frame_len); + } + +#else + result = probeRtcm3(&frame_len); +#endif + + switch (result) { + case Probe::NeedMoreData: + return nullptr; + + case Probe::InvalidHeader: + _bytes_discarded++; + discardBytes(1); + continue; + + case Probe::CrcError: + _crc_errors++; + discardBytes(1); + continue; + + case Probe::Complete: + _pending_protocol = protocol; + *out_len = frame_len; + + if (out_protocol != nullptr) { + *out_protocol = protocol; + } + + return _buffer; + } + } + + return nullptr; +} + +void CorrectionFramer::consumeMessage(size_t len) +{ + discardBytes(len); + _messages_parsed++; + _total_frame_bytes += len; + + if (_pending_protocol == CorrectionProtocol::Rtcm3) { + _rtcm3_messages++; + + } else { + _spartn_messages++; + } +} + +void CorrectionFramer::discardBytes(size_t count) +{ + if (count >= _buffer_len) { + _buffer_len = 0; + + } else { + memmove(_buffer, &_buffer[count], _buffer_len - count); + _buffer_len -= count; + } +} + +} // namespace gnss diff --git a/src/lib/gnss/correction_framer.h b/src/lib/gnss/correction_framer.h new file mode 100644 index 00000000000..1d94a911bad --- /dev/null +++ b/src/lib/gnss/correction_framer.h @@ -0,0 +1,181 @@ +/**************************************************************************** + * + * Copyright (c) 2026 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/** + * @file correction_framer.h + * + * Frame parser for GNSS correction streams: RTCM3, plus SPARTN when + * CONFIG_GPS_SPARTN is enabled. + * + * Corrections arrive as arbitrary byte chunks (uORB gps_inject_data, serial), + * so frame boundaries have to be recovered from the byte stream. Both protocols + * share one buffer: whichever preamble appears first is framed, and a valid + * frame consumes its own payload. + * + * That sharing is what makes the framing safe. A separate framer per protocol + * fed the same bytes would each scan inside the other's payloads, and SPARTN's + * header carries no usable integrity check - TF006 is the only candidate and it + * is 4 bits over a non-byte-aligned field - leaving only the message CRC, which + * TF005 permits to be 8 bits wide. A stray 0x73 in an RTCM3 payload would then + * be framed as SPARTN roughly once per 1024 occurrences. + * + * Usage: + * CorrectionFramer framer; + * framer.addData(chunk, len); + * + * size_t frame_len; + * CorrectionProtocol protocol; + * const uint8_t *frame; + * while ((frame = framer.getNextMessage(&frame_len, &protocol)) != nullptr) { + * // ... use the frame ... + * framer.consumeMessage(frame_len); + * } + */ + +#pragma once + +#include // CONFIG_GPS_SPARTN + +#include +#include + +#include "rtcm.h" + +#if defined(CONFIG_GPS_SPARTN) +# include "spartn.h" +#endif + +namespace gnss +{ + +enum class CorrectionProtocol : uint8_t { + Rtcm3, + Spartn, +}; + +struct CorrectionFramerStats { + uint32_t messages_parsed; ///< Frames successfully parsed and consumed + uint32_t crc_errors; ///< Frames rejected by their CRC + uint32_t bytes_discarded; ///< Bytes discarded while searching for a frame + uint32_t total_frame_bytes; ///< Total bytes in successfully parsed frames + uint32_t rtcm3_messages; ///< Subset of messages_parsed that were RTCM3 + uint32_t spartn_messages; ///< Subset of messages_parsed that were SPARTN +}; + +class CorrectionFramer +{ +public: +#if defined(CONFIG_GPS_SPARTN) + static constexpr size_t MAX_FRAME_LEN = + (SPARTN_MAX_FRAME_LEN > RTCM3_MAX_FRAME_LEN) ? SPARTN_MAX_FRAME_LEN : RTCM3_MAX_FRAME_LEN; +#else + static constexpr size_t MAX_FRAME_LEN = RTCM3_MAX_FRAME_LEN; +#endif + + // Enough for 2 max-size frames to handle overlap + static constexpr size_t BUFFER_SIZE = MAX_FRAME_LEN * 2; + + CorrectionFramer() = default; + + /** + * Add data to the framer buffer. + * + * @param data Pointer to incoming data + * @param len Number of bytes to add + * @return Number of bytes actually added (may be less if the buffer is full) + */ + size_t addData(const uint8_t *data, size_t len); + + /** + * Get a pointer to the next complete frame without consuming it. + * + * Returns a pointer into the framer's internal buffer. Invalid bytes at the + * buffer start are discarded during the search. The returned pointer remains + * valid until the next call to addData() or consumeMessage(). + * + * @param out_len Set to the total frame length + * @param out_protocol If non-null, set to the protocol the frame was framed as + * @return Pointer to the frame, or nullptr if no complete valid + * frame is available + */ + const uint8_t *getNextMessage(size_t *out_len, CorrectionProtocol *out_protocol = nullptr); + + /** + * Consume (remove) the frame returned by the preceding getNextMessage(). + * + * @param len Number of bytes to remove, as returned by getNextMessage() + */ + void consumeMessage(size_t len); + + size_t bufferedBytes() const { return _buffer_len; } + + CorrectionFramerStats getStats() const + { + return {_messages_parsed, _crc_errors, _bytes_discarded, _total_frame_bytes, + _rtcm3_messages, _spartn_messages}; + } + +private: + enum class Probe { + NeedMoreData, ///< Could still become a valid frame, wait for more bytes + InvalidHeader, ///< Cannot be a frame start + CrcError, ///< Frame is complete but failed its CRC + Complete, + }; + + static bool isPreamble(uint8_t byte); + + Probe probeRtcm3(size_t *frame_len) const; +#if defined(CONFIG_GPS_SPARTN) + Probe probeSpartn(size_t *frame_len) const; +#endif + + void discardBytes(size_t count); + + uint8_t _buffer[BUFFER_SIZE] {}; + size_t _buffer_len {0}; + + // Protocol of the frame returned by the last getNextMessage(), applied to + // the per-protocol counters once consumeMessage() commits it. + CorrectionProtocol _pending_protocol {CorrectionProtocol::Rtcm3}; + + // Statistics + uint32_t _messages_parsed {0}; + uint32_t _crc_errors {0}; + uint32_t _bytes_discarded {0}; + uint32_t _total_frame_bytes {0}; + uint32_t _rtcm3_messages {0}; + uint32_t _spartn_messages {0}; +}; + +} // namespace gnss diff --git a/src/lib/gnss/rtcm.cpp b/src/lib/gnss/rtcm.cpp index 73d55a3cee1..01ddfe47e8c 100644 --- a/src/lib/gnss/rtcm.cpp +++ b/src/lib/gnss/rtcm.cpp @@ -318,94 +318,4 @@ size_t GpsRtcmMessageAssembler::lastFragmentIndex() const (GPS_RTCM_MAX_FRAGMENTS - 1); } -size_t Rtcm3Parser::addData(const uint8_t *data, size_t len) -{ - size_t space_available = BUFFER_SIZE - _buffer_len; - size_t to_copy = (len < space_available) ? len : space_available; - - if (to_copy > 0) { - memcpy(&_buffer[_buffer_len], data, to_copy); - _buffer_len += to_copy; - } - - return to_copy; -} - -const uint8_t *Rtcm3Parser::getNextMessage(size_t *out_len) -{ - while (_buffer_len > 0) { - int to_drop = 0; - - // Find preamble - for (size_t i = 0; i < _buffer_len; i++) { - if (_buffer[i] == RTCM3_PREAMBLE) { - break; - } - - to_drop++; - } - - // Drop everything not being the preamble - if (to_drop > 0) { - _bytes_discarded += to_drop; - discardBytes(to_drop); - } - - // Need at least header to check length - if (_buffer_len < RTCM3_HEADER_LEN) { - return nullptr; - } - - size_t payload_len = rtcm3_payload_length(_buffer); - - if (payload_len > RTCM3_MAX_PAYLOAD_LEN) { - // Invalid length - not a valid frame, discard preamble - _bytes_discarded++; - discardBytes(1); - continue; - } - - size_t frame_len = RTCM3_HEADER_LEN + payload_len + RTCM3_CRC_LEN; - - // Check if we have the complete frame - if (_buffer_len < frame_len) { - return nullptr; - } - - uint32_t calculated_crc = rtcm3_crc24q(_buffer, RTCM3_HEADER_LEN + payload_len); - uint32_t received_crc = (static_cast(_buffer[frame_len - 3]) << 16) | - (static_cast(_buffer[frame_len - 2]) << 8) | - _buffer[frame_len - 1]; - - if (calculated_crc != received_crc) { - _crc_errors++; - discardBytes(1); - continue; - } - - *out_len = frame_len; - return _buffer; - } - - return nullptr; -} - -void Rtcm3Parser::consumeMessage(size_t len) -{ - discardBytes(len); - _messages_parsed++; - _total_frame_bytes += len; -} - -void Rtcm3Parser::discardBytes(size_t count) -{ - if (count >= _buffer_len) { - _buffer_len = 0; - - } else { - memmove(_buffer, &_buffer[count], _buffer_len - count); - _buffer_len -= count; - } -} - } // namespace gnss diff --git a/src/lib/gnss/rtcm.h b/src/lib/gnss/rtcm.h index 30ed663f819..534f06c83e7 100644 --- a/src/lib/gnss/rtcm.h +++ b/src/lib/gnss/rtcm.h @@ -225,108 +225,4 @@ private: SequenceState _active_sequence {}; }; -/** - * RTCM3 parser statistics. - */ -struct Rtcm3ParserStats { - uint32_t messages_parsed; ///< Messages successfully parsed and consumed - uint32_t crc_errors; ///< Messages with CRC failures - uint32_t bytes_discarded; ///< Bytes discarded while searching for valid frames - uint32_t total_frame_bytes; ///< Total bytes in successfully parsed frames -}; - -/** - * RTCM3 frame parser for detecting message boundaries in a byte stream. - * - * This parser is designed for scenarios where RTCM data arrives in arbitrary - * chunks (e.g., from uORB messages, serial ports) and needs to be reassembled - * into complete, CRC-validated RTCM messages. - * - * Usage: - * Rtcm3Parser parser; - * parser.addData(chunk1, len1); - * parser.addData(chunk2, len2); - * - * size_t frame_len; - * const uint8_t *frame; - * while ((frame = parser.getNextMessage(&frame_len)) != nullptr) { - * // Process complete RTCM message - * uint16_t msg_type = rtcm3_message_type(frame); - * // ... use the frame ... - * parser.consumeMessage(frame_len); - * } - */ -class Rtcm3Parser -{ -public: - // Buffer size: enough for 2 max-size messages to handle overlap - static constexpr size_t BUFFER_SIZE = RTCM3_MAX_FRAME_LEN * 2; - - Rtcm3Parser() = default; - - /** - * Add data to the parser buffer. - * - * @param data Pointer to incoming data - * @param len Number of bytes to add - * @return Number of bytes actually added (may be less if buffer is full) - */ - size_t addData(const uint8_t *data, size_t len); - - /** - * Get a pointer to the next complete RTCM3 message without consuming it. - * - * Returns a pointer directly into the parser's internal buffer where the - * valid frame starts. Invalid bytes at the buffer start are discarded - * during the search. The returned pointer remains valid until the next - * call to addData() or consumeMessage(). - * - * After processing the message, call consumeMessage() to remove it from - * the buffer. - * - * @param out_len Set to the total frame length - * @return Pointer to the frame in internal buffer, or nullptr - * if no complete valid frame is available - */ - const uint8_t *getNextMessage(size_t *out_len); - - /** - * Consume (remove) the next message from the buffer. - * - * Call this after successfully processing a message obtained via - * getNextMessage(). The length should match what getNextMessage returned. - * - * @param len Number of bytes to remove from the buffer - */ - void consumeMessage(size_t len); - - /** - * Get the number of bytes currently buffered. - */ - size_t bufferedBytes() const { return _buffer_len; } - - /** - * Get parser statistics. - */ - Rtcm3ParserStats getStats() const - { - return {_messages_parsed, _crc_errors, _bytes_discarded, _total_frame_bytes}; - } - -private: - /** - * Remove bytes from the beginning of the buffer. - */ - void discardBytes(size_t count); - - uint8_t _buffer[BUFFER_SIZE] {}; - size_t _buffer_len {0}; - - // Statistics - uint32_t _messages_parsed {0}; - uint32_t _crc_errors {0}; - uint32_t _bytes_discarded {0}; - uint32_t _total_frame_bytes {0}; -}; - } // namespace gnss diff --git a/src/lib/gnss/spartn.cpp b/src/lib/gnss/spartn.cpp new file mode 100644 index 00000000000..1cd8d03f16e --- /dev/null +++ b/src/lib/gnss/spartn.cpp @@ -0,0 +1,75 @@ +/**************************************************************************** + * + * Copyright (c) 2026 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/** + * @file spartn.cpp + * + * SPARTN transport-layer implementation. + */ + +#include "spartn.h" + +namespace gnss +{ + +uint32_t spartn_message_crc(const uint8_t *data, size_t len, uint8_t crc_type) +{ + // Use uint64_t so n==32 (CRC-32) does not shift a 32-bit value by 32. + const unsigned n = 8u * (static_cast(crc_type) + 1u); + const uint64_t poly = (crc_type == 0) ? 0x07ull : + (crc_type == 1) ? 0x1021ull : + (crc_type == 2) ? 0x864CFBull : 0x04C11DB7ull; + const uint64_t top = 1ull << n; + const uint64_t g = top | poly; + uint64_t crc = (crc_type == 3) ? 0xFFFFFFFFull : 0ull; + + for (size_t i = 0; i < len; i++) { + crc ^= static_cast(data[i]) << (n - 8); + + for (int b = 0; b < 8; b++) { + crc <<= 1; + + if (crc & top) { + crc ^= g; + } + } + } + + if (crc_type == 3) { + crc ^= 0xFFFFFFFFull; + } + + return static_cast(crc & (top - 1ull)); +} + +} // namespace gnss diff --git a/src/lib/gnss/spartn.h b/src/lib/gnss/spartn.h new file mode 100644 index 00000000000..2fd4334df47 --- /dev/null +++ b/src/lib/gnss/spartn.h @@ -0,0 +1,121 @@ +/**************************************************************************** + * + * Copyright (c) 2026 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/** + * @file spartn.h + * + * SPARTN transport-layer definitions used to locate frame boundaries. + * Payload content is not decoded. Framing lives in CorrectionFramer. + * + * Frame layout (SPARTN ICD v2.x): preamble 0x73, then bit-packed TF002-TF018: + * TF002 message type 7 bits + * TF003 payload length 10 bits + * TF004 EAF 1 bit (encryption and authentication flag) + * TF005 message CRC type 2 bits + * TF006 frame CRC 4 bits + * TF007..TF015 (description block, 4-8 bytes) + * TF016 payload + * TF017 embedded authentication (if EAF) + * TF018 message CRC 1-4 bytes + * + * Reference: https://www.spartnformat.org/ + */ + +#pragma once + +#include +#include + +namespace gnss +{ + +static constexpr uint8_t SPARTN_PREAMBLE = 0x73; +static constexpr size_t SPARTN_FRAME_START_LEN = 4; +static constexpr size_t SPARTN_MAX_PAYLOAD_LEN = 1023; +static constexpr size_t SPARTN_MAX_AUTH_LEN = 64; +static constexpr size_t SPARTN_MAX_DESC_LEN = 8; +static constexpr size_t SPARTN_MAX_CRC_LEN = 4; +static constexpr size_t SPARTN_MAX_FRAME_LEN = + SPARTN_FRAME_START_LEN + SPARTN_MAX_DESC_LEN + SPARTN_MAX_PAYLOAD_LEN + + SPARTN_MAX_AUTH_LEN + SPARTN_MAX_CRC_LEN; + +/** + * Whether TF002 names a message type the format defines. + * + * 0-4 are defined by SPARTN 2.x (OCB, HPAC, GAD, BPAC, EAS), 120-127 are + * proprietary, and 5-119 are reserved. Reserved types are rejected: TF003 spans + * its full range and TF006 is only 4 bits over a non-byte-aligned field, so this + * is the sole header check standing between a stray preamble and the message CRC. + */ +inline bool spartn_message_type_defined(uint8_t message_type) +{ + return (message_type <= 4) || (message_type >= 120); +} + +/** + * Length of TF017 (embedded authentication). + * + * @param auth_ind TF014, authentication indicator; TF017 is present only above 1 + * @param emb_auth_len TF015, 0=64b, 1=96b, 2=128b, 3=256b, 4=512b + */ +inline size_t spartn_auth_length_bytes(bool eaf, uint8_t auth_ind, uint8_t emb_auth_len) +{ + if (!eaf || auth_ind <= 1) { + return 0; + } + + static constexpr uint8_t kBytes[] = {8, 12, 16, 32, 64}; + return (emb_auth_len < 5) ? kBytes[emb_auth_len] : 64; +} + +/** + * Length of the description block (TF007..TF015), which follows the 4-byte + * frame start and precedes the payload. + */ +inline size_t spartn_desc_length_bytes(bool eaf, bool time_tag_32bit) +{ + return (time_tag_32bit ? 6u : 4u) + (eaf ? 2u : 0u); +} + +/** + * Calculate the SPARTN message CRC (TF018) over TF002..TF017. + * + * @param data Pointer to TF002 (i.e. the byte after the preamble) + * @param len Number of bytes covered + * @param crc_type TF005: 0=CRC-8 poly 0x07, 1=CRC-16 poly 0x1021, + * 2=CRC-24 poly 0x864CFB, 3=CRC-32 poly 0x04C11DB7 init/xor ~0 + * @return CRC value, in the low crc_type+1 bytes + */ +uint32_t spartn_message_crc(const uint8_t *data, size_t len, uint8_t crc_type); + +} // namespace gnss diff --git a/src/lib/gnss/test/CMakeLists.txt b/src/lib/gnss/test/CMakeLists.txt index e693e1f0157..0c553fd1358 100644 --- a/src/lib/gnss/test/CMakeLists.txt +++ b/src/lib/gnss/test/CMakeLists.txt @@ -35,3 +35,7 @@ px4_add_unit_gtest(SRC RtcmCrcTest.cpp LINKLIBS gnss) px4_add_unit_gtest(SRC RtcmParserTest.cpp LINKLIBS gnss) px4_add_unit_gtest(SRC RtcmBustedSenderTest.cpp LINKLIBS gnss) px4_add_unit_gtest(SRC RtcmStressTest.cpp LINKLIBS gnss) + +if(CONFIG_GPS_SPARTN) + px4_add_unit_gtest(SRC SpartnFramerTest.cpp LINKLIBS gnss) +endif() diff --git a/src/lib/gnss/test/RtcmBustedSenderTest.cpp b/src/lib/gnss/test/RtcmBustedSenderTest.cpp index edb7ad54639..ed76f4e1274 100644 --- a/src/lib/gnss/test/RtcmBustedSenderTest.cpp +++ b/src/lib/gnss/test/RtcmBustedSenderTest.cpp @@ -105,6 +105,13 @@ TEST_F(RtcmTest, BustedSender_RepeatedBadCrcFrames) parser.addData(bad.data(), bad.size()); } + // Re-scanning after a failure can land on a byte that claims a frame longer + // than what is buffered, which parks the framer until the rest arrives (see + // BustedSender_AllPreambles). Feed a frame's worth of non-preamble filler so + // every pending candidate can be resolved, as a live stream would. + const std::vector filler(CorrectionFramer::MAX_FRAME_LEN, 0x00); + parser.addData(filler.data(), filler.size()); + size_t len; while (parser.getNextMessage(&len) != nullptr) { diff --git a/src/lib/gnss/test/RtcmParserTest.cpp b/src/lib/gnss/test/RtcmParserTest.cpp index 617af866e70..928890a27fb 100644 --- a/src/lib/gnss/test/RtcmParserTest.cpp +++ b/src/lib/gnss/test/RtcmParserTest.cpp @@ -185,10 +185,10 @@ TEST_F(RtcmTest, ValidFrameBadFrameValid) TEST_F(RtcmTest, BufferOverflowProtection) { - std::vector large_data(Rtcm3Parser::BUFFER_SIZE + 1000, 0xAA); + std::vector large_data(CorrectionFramer::BUFFER_SIZE + 1000, 0xAA); size_t added = parser.addData(large_data.data(), large_data.size()); - EXPECT_EQ(added, Rtcm3Parser::BUFFER_SIZE); + EXPECT_EQ(added, CorrectionFramer::BUFFER_SIZE); } TEST_F(RtcmTest, EmptyPayloadFrame) diff --git a/src/lib/gnss/test/RtcmStressTest.cpp b/src/lib/gnss/test/RtcmStressTest.cpp index 0b115c86125..515c9b017db 100644 --- a/src/lib/gnss/test/RtcmStressTest.cpp +++ b/src/lib/gnss/test/RtcmStressTest.cpp @@ -69,8 +69,10 @@ TEST_F(RtcmTest, Stress_LongGarbageStreamThenValid) std::mt19937 rng(99); for (auto &byte : garbage) { - // Avoid preamble to ensure maximum discards - byte = (rng() % 0xD2) + 1; // 0x01 to 0xD2, never 0xD3 + // Avoid every protocol preamble to ensure maximum discards: 0xD3 (RTCM3) + // and 0x73 (SPARTN), which the framer also treats as a frame start when + // CONFIG_GPS_SPARTN is enabled. + byte = (rng() % 0x72) + 1; // 0x01 to 0x72, never 0x73 or 0xD3 } // Add in chunks to simulate streaming diff --git a/src/lib/gnss/test/RtcmTestCommon.hpp b/src/lib/gnss/test/RtcmTestCommon.hpp index 662011eff3c..54880e4dbb8 100644 --- a/src/lib/gnss/test/RtcmTestCommon.hpp +++ b/src/lib/gnss/test/RtcmTestCommon.hpp @@ -34,7 +34,7 @@ #pragma once #include -#include "rtcm.h" +#include "correction_framer.h" #include #include #include @@ -45,7 +45,7 @@ using namespace gnss; class RtcmTest : public ::testing::Test { protected: - Rtcm3Parser parser; + CorrectionFramer parser; GpsRtcmMessageAssembler gps_rtcm_assembler; uint8_t buildGpsRtcmFlags(bool fragmented, uint8_t fragment_id = 0, uint8_t sequence_id = 0) diff --git a/src/lib/gnss/test/SpartnFramerTest.cpp b/src/lib/gnss/test/SpartnFramerTest.cpp new file mode 100644 index 00000000000..b2815be987d --- /dev/null +++ b/src/lib/gnss/test/SpartnFramerTest.cpp @@ -0,0 +1,288 @@ +/**************************************************************************** + * + * Copyright (c) 2026 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/** + * @file SpartnFramerTest.cpp + * + * SPARTN framing tests for CorrectionFramer, including the RTCM3/SPARTN + * cross-protocol resync behaviour that motivates sharing one buffer. + */ + +#include +#include "correction_framer.h" + +#include +#include +#include + +using namespace gnss; + +class SpartnTest : public ::testing::Test +{ +protected: + CorrectionFramer parser; + + // Build unencrypted frame with 16-bit time tag and given CRC type. + std::vector buildFrame(uint8_t msg_type, uint8_t msg_subtype, + const std::vector &payload, + uint8_t crc_type = 0) + { + const size_t payload_len = payload.size(); + std::vector frame; + frame.push_back(SPARTN_PREAMBLE); + + // TF002-TF006 (frame CRC nibble left 0; not checked by the framer) + uint8_t b1 = static_cast(((msg_type & 0x7F) << 1) | ((payload_len >> 9) & 0x01)); + uint8_t b2 = static_cast((payload_len >> 1) & 0xFF); + uint8_t b3 = static_cast(((payload_len & 0x01) << 7) | ((crc_type & 0x03) << 4)); + frame.push_back(b1); + frame.push_back(b2); + frame.push_back(b3); + + // 4-byte description, 16-bit time tag + frame.push_back(static_cast((msg_subtype & 0x0F) << 4)); + frame.push_back(0x00); + frame.push_back(0x00); + frame.push_back(0x00); + + frame.insert(frame.end(), payload.begin(), payload.end()); + + // Message CRC over TF002..end of payload + const uint32_t crc = spartn_message_crc(&frame[1], frame.size() - 1, crc_type); + const size_t crc_bytes = static_cast(crc_type) + 1; + + for (int i = static_cast(crc_bytes) - 1; i >= 0; i--) { + frame.push_back(static_cast((crc >>(8 * i)) & 0xFF)); + } + + return frame; + } + + // Build a well-formed RTCM3 frame with a deterministic pseudo-random payload. + std::vector buildRtcmFrame(std::mt19937 &rng, size_t payload_len) + { + std::vector frame; + frame.push_back(RTCM3_PREAMBLE); + frame.push_back(static_cast((payload_len >> 8) & 0x03)); + frame.push_back(static_cast(payload_len & 0xFF)); + + std::uniform_int_distribution byte(0, 255); + + for (size_t i = 0; i < payload_len; i++) { + frame.push_back(static_cast(byte(rng))); + } + + const uint32_t crc = rtcm3_crc24q(frame.data(), frame.size()); + frame.push_back((crc >> 16) & 0xFF); + frame.push_back((crc >> 8) & 0xFF); + frame.push_back(crc & 0xFF); + return frame; + } +}; + +// ============================================================================= +// Message CRC (TF018) +// ============================================================================= + +// Vectors taken from the pyspartn reference implementation's test suite +// (semuconsulting/pyspartn, tests/test_static.py), which computes the same +// TF018 CRCs independently of this code. +TEST_F(SpartnTest, MessageCrcMatchesReferenceVectors) +{ + const uint8_t msg[] = {'H', 'i', '!'}; + + EXPECT_EQ(spartn_message_crc(msg, sizeof(msg), 0), 0x78u); + EXPECT_EQ(spartn_message_crc(msg, sizeof(msg), 1), 0x31FDu); + EXPECT_EQ(spartn_message_crc(msg, sizeof(msg), 2), 0x33220Fu); + EXPECT_EQ(spartn_message_crc(msg, sizeof(msg), 3), 0x9523B4B4u); +} + +// ============================================================================= +// Framing +// ============================================================================= + +TEST_F(SpartnTest, SingleMinimalFrame) +{ + auto frame = buildFrame(0, 0, {0xAA, 0xBB}); + parser.addData(frame.data(), frame.size()); + + size_t len = 0; + CorrectionProtocol protocol = CorrectionProtocol::Rtcm3; + const uint8_t *msg = parser.getNextMessage(&len, &protocol); + ASSERT_NE(msg, nullptr); + EXPECT_EQ(protocol, CorrectionProtocol::Spartn); + EXPECT_EQ(len, frame.size()); + EXPECT_EQ(0, memcmp(msg, frame.data(), frame.size())); + parser.consumeMessage(len); + EXPECT_EQ(parser.getStats().messages_parsed, 1u); + EXPECT_EQ(parser.getStats().spartn_messages, 1u); + EXPECT_EQ(parser.getStats().crc_errors, 0u); +} + +TEST_F(SpartnTest, MultipleFrames) +{ + auto f1 = buildFrame(0, 0, {0x01}); + auto f2 = buildFrame(1, 0, {0x02, 0x03}); + std::vector stream; + stream.insert(stream.end(), f1.begin(), f1.end()); + stream.insert(stream.end(), f2.begin(), f2.end()); + parser.addData(stream.data(), stream.size()); + + int count = 0; + size_t len = 0; + + while (parser.getNextMessage(&len) != nullptr) { + parser.consumeMessage(len); + count++; + } + + EXPECT_EQ(count, 2); + EXPECT_EQ(parser.getStats().spartn_messages, 2u); +} + +TEST_F(SpartnTest, ChunkedArrival) +{ + auto frame = buildFrame(0, 1, {0x10, 0x20, 0x30}); + + for (size_t i = 0; i < frame.size(); i++) { + parser.addData(&frame[i], 1); + } + + size_t len = 0; + ASSERT_NE(parser.getNextMessage(&len), nullptr); + EXPECT_EQ(len, frame.size()); +} + +TEST_F(SpartnTest, NoiseBeforeFrame) +{ + auto frame = buildFrame(0, 0, {0x55}); + std::vector stream = {0x00, 0xFF, 0x01}; + stream.insert(stream.end(), frame.begin(), frame.end()); + parser.addData(stream.data(), stream.size()); + + size_t len = 0; + ASSERT_NE(parser.getNextMessage(&len), nullptr); + EXPECT_GT(parser.getStats().bytes_discarded, 0u); +} + +TEST_F(SpartnTest, BadMessageCrc) +{ + auto frame = buildFrame(0, 0, {0x11, 0x22}); + frame.back() ^= 0xFF; + parser.addData(frame.data(), frame.size()); + + size_t len = 0; + EXPECT_EQ(parser.getNextMessage(&len), nullptr); + EXPECT_GE(parser.getStats().crc_errors, 1u); +} + +TEST_F(SpartnTest, Crc16Frame) +{ + auto frame = buildFrame(0, 0, {0xDE, 0xAD}, 1); + parser.addData(frame.data(), frame.size()); + + size_t len = 0; + ASSERT_NE(parser.getNextMessage(&len), nullptr); + parser.consumeMessage(len); + EXPECT_EQ(parser.getStats().crc_errors, 0u); +} + +// TF002 5-119 is reserved by SPARTN 2.x, so a frame claiming one cannot be real +// even if its message CRC checks out. +TEST_F(SpartnTest, RejectsReservedMessageType) +{ + EXPECT_TRUE(spartn_message_type_defined(0)); + EXPECT_TRUE(spartn_message_type_defined(4)); + EXPECT_FALSE(spartn_message_type_defined(5)); + EXPECT_FALSE(spartn_message_type_defined(119)); + EXPECT_TRUE(spartn_message_type_defined(120)); + EXPECT_TRUE(spartn_message_type_defined(127)); + + auto frame = buildFrame(50, 0, {0x11, 0x22}); + parser.addData(frame.data(), frame.size()); + + size_t len = 0; + EXPECT_EQ(parser.getNextMessage(&len), nullptr); + EXPECT_EQ(parser.getStats().spartn_messages, 0u); +} + +// ============================================================================= +// Cross-protocol resync +// ============================================================================= + +// An RTCM3 payload is dense binary, so it carries stray 0x73 SPARTN preambles at +// roughly 1 byte in 256. Framing both protocols from one buffer means a valid +// RTCM3 frame consumes its own payload, so those bytes never start a frame. An +// independent SPARTN framer over the same bytes would instead scan inside RTCM3 +// payloads, where the only remaining check is the message CRC that TF005 permits +// to be 8 bits wide. +TEST_F(SpartnTest, RtcmStreamIsNeverFramedAsSpartn) +{ + std::mt19937 rng(1); + std::uniform_int_distribution payload_len(60, 500); + + size_t frames_in = 0; + size_t frames_out = 0; + size_t generated = 0; + std::vector stream; + + // ~1 MB of RTCM3, about 17 min of a 1 kB/s RTK correction stream + while (generated < 1000000) { + auto frame = buildRtcmFrame(rng, payload_len(rng)); + generated += frame.size(); + frames_in++; + stream.insert(stream.end(), frame.begin(), frame.end()); + + // Feed in MAVLink GPS_RTCM_DATA sized chunks + while (stream.size() >= 180) { + parser.addData(stream.data(), 180); + + size_t len = 0; + CorrectionProtocol protocol = CorrectionProtocol::Spartn; + + while (parser.getNextMessage(&len, &protocol) != nullptr) { + EXPECT_EQ(protocol, CorrectionProtocol::Rtcm3); + parser.consumeMessage(len); + frames_out++; + } + + stream.erase(stream.begin(), stream.begin() + 180); + } + } + + // Every RTCM3 frame is recovered, and no part of the stream is framed as SPARTN + EXPECT_EQ(parser.getStats().spartn_messages, 0u); + EXPECT_EQ(parser.getStats().rtcm3_messages, frames_out); + EXPECT_GE(frames_out, frames_in - 1); + EXPECT_EQ(parser.getStats().crc_errors, 0u); +}