feat(gps): frame UBX AssistNow MGA and harden the correction injection path (#27935)

* feat(gps): frame UBX AssistNow MGA in CorrectionFramer

PointPerfect -MGA mountpoints deliver a UBX-MGA burst before RTCM3/SPARTN.
The shared framer only recognized RTCM3/SPARTN preambles, so MGA bytes were
discarded before reaching the receiver. Add transport-layer UBX framing
(sync, length, Fletcher checksum) with no sticky protocol lock so MGA then
corrections frame in arrival order.

* fix(gps): stop injecting corrections into a receiver that is resetting

handleInjectDataTopic() gates on receiverReady(), which GPSDriverUBX backs with
_configured — and reset() left that true while the receiver rebooted onto its
saved configuration. Corrections kept being written into it until the receive
timeout re-ran configure(), and every byte in that window was discarded.

That matters most for AssistNow (MGA), which the framer now passes through: a
caster sends the assistance burst once per connection, so a burst delivered
during the reboot is lost until the client reconnects for another one.

Bumps GpsDrivers to dakejahl/PX4-GPSDrivers@4f9a086, which clears the flag.

* fix(gps): keep the driver mode across a reset we issued

Leaving the receive loop is normally how a wrong protocol guess shows up, so
auto-detect advances to the next driver. A commanded reset now leaves that loop
too — the receiver stops being configured the moment we send UBX-CFG-RST — and
advancing there walks a receiver we were already talking to through every other
protocol before coming back to the one that worked.

Remember that the reset was ours and hold the mode, so the driver waits for the
same receiver to come back on the same protocol.

* chore(gps): point GpsDrivers at the merged reset fix

f24a03c bumped the submodule to a fork branch to stop corrections being written
into a receiver that is resetting. That landed upstream as
PX4/PX4-GPSDrivers#220, so point at it instead — a fork pointer is not
mergeable here.

Moving off 1925b37 also brings #216 (NAV-DAHEADING for X20 dual antenna
heading), #218 (automatic_gain_control logging) and #219 (disable unused
NAV-TIMEGPS and RXM-RAWX/SFRBX msgout).

* fix(gps): keep draining corrections while the receiver is unconfigured

handleInjectDataTopic() returned early until receiverReady(), so nothing read
rtcm_corrections during configuration. The topic is queued 16 deep and the CAN
and MAVLink publishers keep filling it, so a burst arriving in that window
overflows, and the first read afterwards silently discards whatever fell off
the back.

Measured on an ARK X20 CAN node: the client forwarded 58 AssistNow messages and
the node injected 57, with the drain logging "rtcm_corrections lost, generation
0 -> 2". By the queue arithmetic that jump is only reachable at
generation = current - o_queue + 1, so 17 messages had been published against
16 slots. What falls off is the oldest, and for an AssistNow burst that is the
leading UBX-MGA-INI - the ephemeris behind it has no time base, so the receiver
cannot use any of the 57 that did arrive.

Drain regardless of readiness and drop what cannot be injected, so the
subscription stays current instead of accumulating a backlog that eats the head
of the next burst.

* fix(gps): stop discarding the message that trips the injection budget

Both correction drains read one message past their budget and threw it away.
The do/while injects what the previous iteration read, then reads again before
testing num_injections, so the read that finds the budget spent takes a message
off the queue and exits without injecting it. Exactly one message is lost per
capped pass, silently - the generation stays consistent, so nothing warns.

That is the missing frame: an ARK X20 node received 57 of the 58 AssistNow
messages the client forwarded, on two different firmwares, with the framer
buffer and UART TX counters both clean. A burst of 58 at 20-50ms outruns a
drain capped at 16 per pass, so it caps at least once and drops one. Assistance
is one-shot and the ephemeris is useless without the MGA-INI that leads it, so
a single dropped message costs the whole burst.

Check the budget before reading instead of after, in the GPS driver and in the
UAVCAN bridge that feeds CAN nodes.

Also name each injected UBX frame on the console. Assistance is rare enough to
afford it, and inferring which frame went missing from perf counts is what made
this take three rounds. Drop that log once the path is trusted.

* chore(gps): point GpsDrivers at the stale-UTC-time fix

* feat(gps): raise the ark x20-gps receiver link to 921600 via GPS_UBX_BAUD1

New param plumbs the ubx driver's uart1_baudrate target: the link is
still auto-detected, only the rate both ends move to afterwards
changes, so a receiver at its power-on default always connects. The
x20-gps node defaults to 921600 (USART1 runs RX DMA with 2KB buffers)
to give the injection path and nav output headroom.

* style(gps): trim comments

* chore(gps): point GpsDrivers at the merged stale-time fix

* chore(gps): demote the per-frame UBX injection log to debug

The naming was added at INFO to make a missing assistance message
findable, with a note to drop it once the path was trusted. It is: a
full burst now injects cleanly, and 58 lines in two seconds is console
spam. Keep the naming for debug builds.

Assisted-by: Claude:claude-opus-5
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>

* feat(gps): print correction framer stats in gps status

The per-frame injection log is debug-only, so a release build had no way
to show whether a one-shot assistance burst fully reached the receiver.
Print the per-protocol frame counts, CRC errors and discarded bytes from
each framer; moving baseline only when it has seen traffic.

Assisted-by: Claude:claude-opus-5
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>

* feat(uavcan): count failed RTCM stream broadcasts

PublishRTCMStream ignores the broadcast result, so a TX-queue or pool
allocation failure drops the rest of the message silently - the
receiver-side framer sees a partial frame and fails its CRC. RTCM also
publishes at NumericallyMax, the lowest arbitration priority, making its
frames the first casualties under TX pressure. Count the failures so
perf / uavcan status shows them.

Assisted-by: Claude:claude-opus-5
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>

* chore(gps): point GpsDrivers at UART1 baud source-of-truth fix

PX4/PX4-GPSDrivers#224 removes the heading-mode 921600 hardcode so
GPS_UBX_BAUD1 is the only UART1 target in all modes.

* docs(gps): trim GPS_UBX_BAUD1/BAUD2 and drop mode 3/4 921600 labels

GPS_UBX_BAUD1 is the UART1 target in all modes; mode labels no longer
imply a hard-coded baud. Align BAUD2 description with the trimmed style.

* feat(gps): default ark can-rtk-gps UART1 to 921600 via GPS_UBX_BAUD1

On-module F9P link is short and uses RX DMA; keep the prior heading-mode
rate via the board default now that modes no longer hard-code it.

* chore(gps): point GpsDrivers at the merged UART1 baud fix

PX4/PX4-GPSDrivers#224 landed on main; replace the fork-branch pointer
with the merge commit.

* docs(gps): document GPS_UBX_BAUD1 and GPS_UBX_BAUD2

Cover UART1/UART2 baud targets in the dual F9P heading guide and on
the ARK RTK / X20 node parameter tables so users know defaults, when
to raise the rate, and when to keep it low on long cables.

* docs(gps): tighten GPS_UBX_BAUD docs to match surrounding style

Drop the hard-code and MCU-link notes; keep baud coverage as short setup
bullets and param-table rows like the rest of the pages.

---------

Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
This commit is contained in:
Jacob Dahl authored and GitHub committed 2026-08-06 17:40:16 -06:00
1 parent ff7c73d714
commit e194513f2c
15 files changed
+722 -74

No files matched your search

@@ -7,6 +7,7 @@ param set-default CBRK_IO_SAFETY 0
param set-default CANNODE_SUB_MBD 1
param set-default CANNODE_SUB_RTCM 1
param set-default GPS_1_GNSS 63
param set-default GPS_UBX_BAUD1 921600
param set-default MBE_ENABLE 0
param set-default SENS_IMU_CLPNOTI 0
@@ -7,6 +7,7 @@ param set-default CBRK_IO_SAFETY 0
param set-default CANNODE_SUB_MBD 1
param set-default CANNODE_SUB_RTCM 1
param set-default GPS_1_GNSS 47
param set-default GPS_UBX_BAUD1 921600
param set-default SENS_IMU_CLPNOTI 0
safety_button start
+2
View File
@@ -96,6 +96,8 @@ You may need to [configure the following parameters](../dronecan/index.md#qgc-ca
| -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| <a id="CANNODE_NODE_ID"></a>[CANNODE_NODE_ID](../advanced_config/parameter_reference.md#CANNODE_NODE_ID) | CAN node ID (0 for dynamic allocation). If set to 0 (default), dynamic node allocation is used. Set to 1-125 to use a static node ID. |
| <a id="CANNODE_TERM"></a>[CANNODE_TERM](../advanced_config/parameter_reference.md#CANNODE_TERM) | CAN built-in bus termination. Set to `1` if this is the last node on the CAN bus. |
| <a id="GPS_UBX_BAUD1"></a>[GPS_UBX_BAUD1](../advanced_config/parameter_reference.md#GPS_UBX_BAUD1) | UART1 baudrate after the link is auto-detected. Board default is `921600`. |
| <a id="GPS_UBX_BAUD2"></a>[GPS_UBX_BAUD2](../advanced_config/parameter_reference.md#GPS_UBX_BAUD2) | UART2 baudrate (default `230400`). |
### Setting Up Rover and Fixed Base
+2
View File
@@ -98,6 +98,8 @@ You may need to [configure the following parameters](../dronecan/index.md#qgc-ca
| -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| <a id="CANNODE_NODE_ID"></a>[CANNODE_NODE_ID](../advanced_config/parameter_reference.md#CANNODE_NODE_ID) | CAN node ID (0 for dynamic allocation). If set to 0 (default), dynamic node allocation is used. Set to 1-125 to use a static node ID. |
| <a id="CANNODE_TERM"></a>[CANNODE_TERM](../advanced_config/parameter_reference.md#CANNODE_TERM) | CAN built-in bus termination. Set to `1` if this is the last node on the CAN bus. |
| <a id="GPS_UBX_BAUD1"></a>[GPS_UBX_BAUD1](../advanced_config/parameter_reference.md#GPS_UBX_BAUD1) | UART1 baudrate after the link is auto-detected. Board default is `921600`. |
| <a id="GPS_UBX_BAUD2"></a>[GPS_UBX_BAUD2](../advanced_config/parameter_reference.md#GPS_UBX_BAUD2) | UART2 baudrate (default `230400`). |
### Setting Up Rover and Fixed Base
@@ -39,6 +39,8 @@ Ideally the two antennas should be identical, on the same level/horizontal plane
- Main GPS = Rover
- Secondary GPS = Moving Base
- Set [GPS_UBX_MODE](../advanced_config/parameter_reference.md#GPS_UBX_MODE) to `Heading` (1)
- Set [GPS_UBX_BAUD1](../advanced_config/parameter_reference.md#GPS_UBX_BAUD1) if a UART1 rate other than the default is required (0 keeps 115200). Use a higher rate for high update rates or when RTCM is sent on UART1 ([GPS_UBX_MODE](../advanced_config/parameter_reference.md#GPS_UBX_MODE) 3/4), and a lower rate on long serial cables.
- Set [GPS_UBX_BAUD2](../advanced_config/parameter_reference.md#GPS_UBX_BAUD2) if a UART2 rate other than the default (230400) is required. UART2 carries RTCM between the modules in this setup.
- [EKF2_GPS_CTRL](../advanced_config/parameter_reference.md#EKF2_GPS_CTRL) parameter bit 3 must be set (see [RTK GPS > GPS as Yaw/Heading Source](../gps_compass/rtk_gps.md#configuring-gps-as-yaw-heading-source)).
- [GPS_YAW_OFFSET](../advanced_config/parameter_reference.md#GPS_YAW_OFFSET) may need to be set (see [RTK GPS > GPS as Yaw/Heading Source](../gps_compass/rtk_gps.md#configuring-gps-as-yaw-heading-source)).
- Reboot and wait until both devices have GPS reception.
+74 -29
View File
@@ -290,6 +290,7 @@ private:
static px4::atomic<GPS *> _secondary_instance;
px4::atomic<int> _scheduled_reset{(int)GPSRestartType::None};
bool _reset_performed{false}; ///< a reset we issued dropped the receiver, so _mode is still known good
/**
* Publish the gps struct
@@ -330,9 +331,11 @@ private:
/**
* Drain the multi-instance rtcm_corrections subscription into its RTCM parser, selecting an
* active instance if the current one goes stale.
* active instance if the current one goes stale. With inject false the messages are dropped
* rather than framed, which keeps the subscription current while the receiver cannot be
* written to.
*/
void drainRtcmCorrections();
void drainRtcmCorrections(bool inject);
/**
* Drain the single-publisher rtcm_moving_baseline subscription into its RTCM parser.
@@ -646,7 +649,7 @@ int GPS::pollOrRead(uint8_t *buf, size_t buf_length, int timeout)
return ret;
}
void GPS::drainRtcmCorrections()
void GPS::drainRtcmCorrections(bool inject)
{
// rtcm_corrections may have several sources (MAVLink plus CAN nodes), one uORB instance each.
rtcm_data_s msg;
@@ -671,35 +674,39 @@ void GPS::drainRtcmCorrections()
}
}
bool updated = already_copied;
bool have_msg = already_copied;
size_t num_injections = 0;
// Limit maximum number of injections per call so a burst can't starve the driver loop.
do {
if (updated) {
num_injections++;
// Cap injections per call so a burst can't starve the loop. Checked before
// reading, never after: a message taken off the queue and left behind is gone.
while (num_injections < rtcm_data_s::ORB_QUEUE_LENGTH) {
if (!have_msg) {
auto &sub = _rtcm_corrections_sub[_selected_rtcm_instance];
const unsigned last_generation = sub.get_last_generation();
// Prevent injection of data from self
if (msg.device_id != get_device_id()) {
// 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);
}
if (!sub.update(&msg)) {
break;
}
_last_rtcm_injection_time = hrt_absolute_time();
if (sub.get_last_generation() != last_generation + 1) {
PX4_WARN("%s lost, generation %u -> %u", sub.get_topic()->o_name,
last_generation, sub.get_last_generation());
}
}
auto &sub = _rtcm_corrections_sub[_selected_rtcm_instance];
const unsigned last_generation = sub.get_last_generation();
have_msg = false;
num_injections++;
updated = sub.update(&msg);
// Prevent injection of data from self
if (inject && msg.device_id != get_device_id()) {
// 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);
}
if (updated && sub.get_last_generation() != last_generation + 1) {
PX4_WARN("%s lost, generation %u -> %u", sub.get_topic()->o_name,
last_generation, sub.get_last_generation());
_last_rtcm_injection_time = hrt_absolute_time();
}
} while (updated && num_injections < rtcm_data_s::ORB_QUEUE_LENGTH);
}
}
void GPS::drainMovingBaseline()
@@ -734,9 +741,14 @@ void GPS::drainMovingBaseline()
void GPS::handleInjectDataTopic()
{
// receiverReady() is false until the receiver is configured, which keeps us from writing to the
// device mid-configuration.
if (!_helper->receiverReady()) {
// receiverReady() is false mid-configuration, so no writing to the device —
// but keep draining: a burst piling past the uORB queue depth silently
// drops the oldest messages.
const bool receiver_ready = _helper->receiverReady();
drainRtcmCorrections(receiver_ready);
if (!receiver_ready) {
return;
}
@@ -744,7 +756,6 @@ void GPS::handleInjectDataTopic()
// 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_framer, _rtcm_corrections_injection_perf,
&_rtcm_frames_in_rate_window, &_spartn_frames_in_rate_window);
@@ -788,8 +799,14 @@ void GPS::injectRtcmFrames(gnss::CorrectionFramer &framer, perf_counter_t inject
(*rtcm_frames_in_window)++;
}
} else if (spartn_frames_in_window != nullptr) {
(*spartn_frames_in_window)++;
} else if (protocol == gnss::CorrectionProtocol::Spartn) {
if (spartn_frames_in_window != nullptr) {
(*spartn_frames_in_window)++;
}
} else if (protocol == gnss::CorrectionProtocol::Ubx && frame_len >= 4) {
// One-shot billed burst: name each message as it goes to the receiver.
PX4_DEBUG("injected UBX-%02X-%02X, %u bytes", frame_ptr[2], frame_ptr[3], (unsigned)frame_len);
}
}
}
@@ -997,6 +1014,13 @@ GPS::run()
}
}
handle = param_find("GPS_UBX_BAUD1");
int32_t ubx_uart1_baudrate = 0;
if (handle != PARAM_INVALID) {
param_get(handle, &ubx_uart1_baudrate);
}
handle = param_find("GPS_UBX_BAUD2");
int32_t f9p_uart2_baudrate = 57600;
@@ -1120,6 +1144,7 @@ GPS::run()
.min_elev = (int8_t)gps_ubx_min_elev,
.output_rate = (uint8_t)gps_ubx_rate,
.heading_offset = heading_offset,
.uart1_baudrate = ubx_uart1_baudrate,
.uart2_baudrate = f9p_uart2_baudrate,
.ppk_output = ppk_output > 0,
.jam_det_sensitivity_hi = jam_det_sensitivity_hi > 0,
@@ -1389,7 +1414,12 @@ GPS::run()
#endif
}
if (_mode_auto) {
// Dropping out of the receive loop normally means the protocol guess was
// wrong; after a reset we issued, keep the known-good mode.
const bool keep_mode = _reset_performed;
_reset_performed = false;
if (_mode_auto && !keep_mode) {
size_t i = 0;
while (kAutoDetectModes[i] != _mode && kAutoDetectModes[i] != gps_driver_mode_t::None) {
@@ -1509,6 +1539,20 @@ GPS::print_status()
perf_print_counter(_rtcm_corrections_injection_perf);
perf_print_counter(_rtcm_moving_baseline_injection_perf);
const gnss::CorrectionFramerStats corrections_stats = _rtcm_corrections_framer.getStats();
PX4_INFO("corrections framed: %u RTCM3, %u SPARTN, %u UBX, %u CRC errors, %u bytes discarded",
(unsigned)corrections_stats.rtcm3_messages, (unsigned)corrections_stats.spartn_messages,
(unsigned)corrections_stats.ubx_messages, (unsigned)corrections_stats.crc_errors,
(unsigned)corrections_stats.bytes_discarded);
const gnss::CorrectionFramerStats mb_stats = _rtcm_moving_baseline_framer.getStats();
if (mb_stats.messages_parsed > 0 || mb_stats.crc_errors > 0 || mb_stats.bytes_discarded > 0) {
PX4_INFO("moving baseline framed: %u RTCM3, %u CRC errors, %u bytes discarded",
(unsigned)mb_stats.rtcm3_messages, (unsigned)mb_stats.crc_errors,
(unsigned)mb_stats.bytes_discarded);
}
if (_instance == Instance::Main && _secondary_instance.load()) {
GPS *secondary_instance = _secondary_instance.load();
secondary_instance->print_status();
@@ -1544,6 +1588,7 @@ GPS::reset_if_scheduled()
PX4_INFO("Reset failed.");
} else {
_reset_performed = true;
PX4_INFO("Reset succeeded.");
}
}
+17 -8
View File
@@ -118,9 +118,8 @@ parameters:
1: Heading (Rover With Moving Base UART1 Connected To Autopilot, UART2 Connected
To Moving Base)
2: Moving Base (UART1 Connected To Autopilot, UART2 Connected To Rover)
3: Heading (Rover With Moving Base UART1 Connected to Autopilot Or Can Node
At 921600)
4: Moving Base (Moving Base UART1 Connected to Autopilot Or Can Node At 921600)
3: Heading (Rover With Moving Base UART1 Connected to Autopilot Or Can Node)
4: Moving Base (Moving Base UART1 Connected to Autopilot Or Can Node)
5: Rover with Static Base on UART2 (similar to Default, except coming in on
UART2)
6: Ground Control Station (UART2 outputs NMEA)
@@ -128,13 +127,23 @@ parameters:
min: 0
max: 6
reboot_required: true
GPS_UBX_BAUD1:
description:
short: u-blox UART1 target baudrate
long: |-
Baudrate applied to the receiver UART1 after the link is auto-detected.
0 keeps the driver default (115200). Modes that share UART1 with RTCM
(GPS_UBX_MODE 3/4) may need a higher rate on short/reliable links.
type: int32
default: 0
min: 0
max: 3000000
unit: B/s
reboot_required: true
GPS_UBX_BAUD2:
description:
short: u-blox F9P UART2 Baudrate
long: |-
Select a baudrate for the F9P's UART2 port.
In GPS_UBX_MODE 1, 2, and 3, the F9P's UART2 port is configured to send/receive RTCM corrections.
Set this to 57600 if you want to attach a telemetry radio on UART2.
short: u-blox UART2 baudrate
long: Baudrate for the receiver UART2 port.
type: int32
default: 230400
min: 0
+40 -17
View File
@@ -76,7 +76,9 @@ UavcanGnssBridge::~UavcanGnssBridge()
{
delete [] _channel_using_fix2;
perf_free(_rtcm_stream_pub_perf);
perf_free(_rtcm_stream_pub_failed_perf);
perf_free(_moving_baseline_data_pub_perf);
perf_free(_moving_baseline_data_pub_failed_perf);
perf_free(_moving_baseline_data_sub_perf);
}
@@ -119,6 +121,7 @@ UavcanGnssBridge::init()
_publish_rtcm_stream = true;
_pub_rtcm_stream.setPriority(uavcan::TransferPriority::NumericallyMax);
_rtcm_stream_pub_perf = perf_alloc(PC_INTERVAL, "uavcan: gnss: rtcm stream pub");
_rtcm_stream_pub_failed_perf = perf_alloc(PC_COUNT, "uavcan: gnss: rtcm stream pub failed");
}
// UAVCAN_PUB_MBD
@@ -129,6 +132,7 @@ UavcanGnssBridge::init()
_publish_moving_baseline_data = true;
_pub_moving_baseline_data.setPriority(uavcan::TransferPriority::NumericallyMax);
_moving_baseline_data_pub_perf = perf_alloc(PC_INTERVAL, "uavcan: gnss: moving baseline data rtcm stream pub");
_moving_baseline_data_pub_failed_perf = perf_alloc(PC_COUNT, "uavcan: gnss: moving baseline data rtcm stream pub failed");
}
// UAVCAN_SUB_MBD
@@ -647,27 +651,32 @@ void UavcanGnssBridge::drainRtcmCorrections()
}
}
bool updated = already_copied;
bool have_msg = already_copied;
size_t num_injections = 0;
do {
if (updated) {
num_injections++;
PublishRTCMStream(msg.data, msg.len);
_rtcm_injection_rate_message_count++;
_last_rtcm_injection_time = hrt_absolute_time();
// Budget checked before reading, never after: a message taken off the queue
// and left behind is gone.
while (num_injections < rtcm_data_s::ORB_QUEUE_LENGTH) {
if (!have_msg) {
auto &sub = _rtcm_corrections_sub[_selected_rtcm_instance];
const unsigned last_generation = sub.get_last_generation();
if (!sub.update(&msg)) {
break;
}
if (sub.get_last_generation() != last_generation + 1) {
PX4_WARN("%s lost, generation %u -> %u", sub.get_topic()->o_name,
last_generation, sub.get_last_generation());
}
}
auto &sub = _rtcm_corrections_sub[_selected_rtcm_instance];
const unsigned last_generation = sub.get_last_generation();
updated = sub.update(&msg);
if (updated && sub.get_last_generation() != last_generation + 1) {
PX4_WARN("%s lost, generation %u -> %u", sub.get_topic()->o_name,
last_generation, sub.get_last_generation());
}
} while (updated && num_injections < rtcm_data_s::ORB_QUEUE_LENGTH);
have_msg = false;
num_injections++;
PublishRTCMStream(msg.data, msg.len);
_rtcm_injection_rate_message_count++;
_last_rtcm_injection_time = hrt_absolute_time();
}
}
// Drains rtcm_moving_baseline (moving-base RTCM 4072 from a peer GPS) to
@@ -744,6 +753,13 @@ bool UavcanGnssBridge::PublishRTCMStream(const uint8_t *const data, const size_t
result = _pub_rtcm_stream.broadcast(msg) >= 0;
perf_count(_rtcm_stream_pub_perf);
if (!result) {
// TX queue / pool exhaustion drops the rest of this message silently -
// the receiver-side framer sees a partial frame and fails its CRC.
perf_count(_rtcm_stream_pub_failed_perf);
}
msg.data.clear();
}
@@ -772,6 +788,11 @@ bool UavcanGnssBridge::PublishMovingBaselineData(const uint8_t *data, size_t dat
result = _pub_moving_baseline_data.broadcast(msg) >= 0;
perf_count(_moving_baseline_data_pub_perf);
if (!result) {
perf_count(_moving_baseline_data_pub_failed_perf);
}
msg.data.clear();
}
@@ -782,6 +803,8 @@ void UavcanGnssBridge::print_status() const
{
UavcanSensorBridgeBase::print_status();
perf_print_counter(_rtcm_stream_pub_perf);
perf_print_counter(_rtcm_stream_pub_failed_perf);
perf_print_counter(_moving_baseline_data_pub_perf);
perf_print_counter(_moving_baseline_data_pub_failed_perf);
perf_print_counter(_moving_baseline_data_sub_perf);
}
+2
View File
@@ -179,7 +179,9 @@ private:
bool _rel_heading_valid{false};
perf_counter_t _rtcm_stream_pub_perf{nullptr};
perf_counter_t _rtcm_stream_pub_failed_perf{nullptr};
perf_counter_t _moving_baseline_data_pub_perf{nullptr};
perf_counter_t _moving_baseline_data_pub_failed_perf{nullptr};
perf_counter_t _moving_baseline_data_sub_perf{nullptr};
hrt_abstime _last_rate_measurement{0};
+66 -8
View File
@@ -50,6 +50,10 @@ bool CorrectionFramer::isPreamble(uint8_t byte)
return true;
}
if (byte == UBX_SYNC1) {
return true;
}
#if defined(CONFIG_GPS_SPARTN)
if (byte == SPARTN_PREAMBLE) {
@@ -103,6 +107,49 @@ CorrectionFramer::Probe CorrectionFramer::probeRtcm3(size_t *frame_len) const
return Probe::Complete;
}
CorrectionFramer::Probe CorrectionFramer::probeUbx(size_t *frame_len) const
{
// Need sync1 + sync2 at minimum to reject a false preamble quickly
if (_buffer_len < 2) {
return Probe::NeedMoreData;
}
if (_buffer[1] != UBX_SYNC2) {
return Probe::InvalidHeader;
}
if (_buffer_len < UBX_HEADER_LEN) {
return Probe::NeedMoreData;
}
const size_t payload_len = static_cast<size_t>(_buffer[4]) |
(static_cast<size_t>(_buffer[5]) << 8);
// Protocol allows larger payloads; reject beyond the injection cap so a
// garbage length cannot pin the buffer waiting for thousands of bytes.
if (payload_len > UBX_MAX_PAYLOAD_LEN) {
return Probe::InvalidHeader;
}
const size_t len = UBX_HEADER_LEN + payload_len + UBX_CK_LEN;
if (_buffer_len < len) {
return Probe::NeedMoreData;
}
// CK_A/CK_B cover Class..end of payload (not the sync bytes)
uint8_t ck_a = 0;
uint8_t ck_b = 0;
ubx_checksum(&_buffer[2], UBX_HEADER_LEN - 2 + payload_len, &ck_a, &ck_b);
if ((ck_a != _buffer[len - 2]) || (ck_b != _buffer[len - 1])) {
return Probe::CrcError;
}
*frame_len = len;
return Probe::Complete;
}
#if defined(CONFIG_GPS_SPARTN)
CorrectionFramer::Probe CorrectionFramer::probeSpartn(size_t *frame_len) const
{
@@ -174,7 +221,7 @@ CorrectionFramer::Probe CorrectionFramer::probeSpartn(size_t *frame_len) const
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
// Drop everything that cannot start a frame of any supported protocol
size_t to_drop = 0;
while ((to_drop < _buffer_len) && !isPreamble(_buffer[to_drop])) {
@@ -194,20 +241,24 @@ const uint8_t *CorrectionFramer::getNextMessage(size_t *out_len, CorrectionProto
CorrectionProtocol protocol = CorrectionProtocol::Rtcm3;
Probe result;
if (_buffer[0] == UBX_SYNC1) {
protocol = CorrectionProtocol::Ubx;
result = probeUbx(&frame_len);
#if defined(CONFIG_GPS_SPARTN)
if (_buffer[0] == SPARTN_PREAMBLE) {
} else if (_buffer[0] == SPARTN_PREAMBLE) {
protocol = CorrectionProtocol::Spartn;
result = probeSpartn(&frame_len);
#endif
} else {
// RTCM3 preamble (isPreamble already filtered other bytes)
protocol = CorrectionProtocol::Rtcm3;
result = probeRtcm3(&frame_len);
}
#else
result = probeRtcm3(&frame_len);
#endif
switch (result) {
case Probe::NeedMoreData:
return nullptr;
@@ -243,11 +294,18 @@ void CorrectionFramer::consumeMessage(size_t len)
_messages_parsed++;
_total_frame_bytes += len;
if (_pending_protocol == CorrectionProtocol::Rtcm3) {
switch (_pending_protocol) {
case CorrectionProtocol::Rtcm3:
_rtcm3_messages++;
break;
} else {
case CorrectionProtocol::Spartn:
_spartn_messages++;
break;
case CorrectionProtocol::Ubx:
_ubx_messages++;
break;
}
}
+20 -11
View File
@@ -34,13 +34,15 @@
/**
* @file correction_framer.h
*
* Frame parser for GNSS correction streams: RTCM3, plus SPARTN when
* CONFIG_GPS_SPARTN is enabled.
* Frame parser for GNSS correction streams: RTCM3, UBX (AssistNow MGA),
* 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
* Corrections arrive as arbitrary byte chunks (uORB rtcm_corrections, serial),
* so frame boundaries have to be recovered from the byte stream. All protocols
* share one buffer: whichever preamble appears first is framed, and a valid
* frame consumes its own payload.
* frame consumes its own payload. There is no sticky protocol selection — an
* MGA (UBX) burst followed by SPARTN or RTCM3 is framed frame-by-frame in
* arrival order.
*
* 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
@@ -70,6 +72,7 @@
#include <cstddef>
#include "rtcm.h"
#include "ubx.h"
#if defined(CONFIG_GPS_SPARTN)
# include "spartn.h"
@@ -81,25 +84,29 @@ namespace gnss
enum class CorrectionProtocol : uint8_t {
Rtcm3,
Spartn,
Ubx,
};
struct CorrectionFramerStats {
uint32_t messages_parsed; ///< Frames successfully parsed and consumed
uint32_t crc_errors; ///< Frames rejected by their CRC
uint32_t crc_errors; ///< Frames rejected by their CRC / checksum
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
uint32_t ubx_messages; ///< Subset of messages_parsed that were UBX
};
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;
#if defined(CONFIG_GPS_SPARTN)
(SPARTN_MAX_FRAME_LEN > RTCM3_MAX_FRAME_LEN)
? ((SPARTN_MAX_FRAME_LEN > UBX_MAX_FRAME_LEN) ? SPARTN_MAX_FRAME_LEN : UBX_MAX_FRAME_LEN)
: ((RTCM3_MAX_FRAME_LEN > UBX_MAX_FRAME_LEN) ? RTCM3_MAX_FRAME_LEN : UBX_MAX_FRAME_LEN);
#else
static constexpr size_t MAX_FRAME_LEN = RTCM3_MAX_FRAME_LEN;
(RTCM3_MAX_FRAME_LEN > UBX_MAX_FRAME_LEN) ? RTCM3_MAX_FRAME_LEN : UBX_MAX_FRAME_LEN;
#endif
// Enough for 2 max-size frames to handle overlap
@@ -142,20 +149,21 @@ public:
CorrectionFramerStats getStats() const
{
return {_messages_parsed, _crc_errors, _bytes_discarded, _total_frame_bytes,
_rtcm3_messages, _spartn_messages};
_rtcm3_messages, _spartn_messages, _ubx_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
CrcError, ///< Frame is complete but failed its CRC / checksum
Complete,
};
static bool isPreamble(uint8_t byte);
Probe probeRtcm3(size_t *frame_len) const;
Probe probeUbx(size_t *frame_len) const;
#if defined(CONFIG_GPS_SPARTN)
Probe probeSpartn(size_t *frame_len) const;
#endif
@@ -176,6 +184,7 @@ private:
uint32_t _total_frame_bytes {0};
uint32_t _rtcm3_messages {0};
uint32_t _spartn_messages {0};
uint32_t _ubx_messages {0};
};
} // namespace gnss
+1
View File
@@ -35,6 +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)
px4_add_unit_gtest(SRC UbxFramerTest.cpp LINKLIBS gnss)
if(CONFIG_GPS_SPARTN)
px4_add_unit_gtest(SRC SpartnFramerTest.cpp LINKLIBS gnss)
+398
View File
@@ -0,0 +1,398 @@
/****************************************************************************
*
* 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 UbxFramerTest.cpp
*
* UBX framing tests for CorrectionFramer (AssistNow MGA pass-through), including
* interleaved UBX then RTCM3/SPARTN streams that mirror PointPerfect -MGA
* mountpoints.
*/
#include <gtest/gtest.h>
#include "correction_framer.h"
#include <vector>
#include <cstring>
#include <random>
using namespace gnss;
class UbxTest : public ::testing::Test
{
protected:
CorrectionFramer parser;
// Build a valid UBX frame (class/id arbitrary; content not decoded).
std::vector<uint8_t> buildUbxFrame(uint8_t msg_class, uint8_t msg_id,
const std::vector<uint8_t> &payload)
{
const size_t payload_len = payload.size();
std::vector<uint8_t> frame;
frame.push_back(UBX_SYNC1);
frame.push_back(UBX_SYNC2);
frame.push_back(msg_class);
frame.push_back(msg_id);
frame.push_back(static_cast<uint8_t>(payload_len & 0xFF));
frame.push_back(static_cast<uint8_t>((payload_len >> 8) & 0xFF));
frame.insert(frame.end(), payload.begin(), payload.end());
uint8_t ck_a = 0;
uint8_t ck_b = 0;
ubx_checksum(&frame[2], UBX_HEADER_LEN - 2 + payload_len, &ck_a, &ck_b);
frame.push_back(ck_a);
frame.push_back(ck_b);
return frame;
}
std::vector<uint8_t> buildRtcmFrame(std::mt19937 &rng, size_t payload_len)
{
std::vector<uint8_t> frame;
frame.push_back(RTCM3_PREAMBLE);
frame.push_back(static_cast<uint8_t>((payload_len >> 8) & 0x03));
frame.push_back(static_cast<uint8_t>(payload_len & 0xFF));
std::uniform_int_distribution<int> byte(0, 255);
for (size_t i = 0; i < payload_len; i++) {
frame.push_back(static_cast<uint8_t>(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;
}
#if defined(CONFIG_GPS_SPARTN)
std::vector<uint8_t> buildSpartnFrame(uint8_t msg_type, const std::vector<uint8_t> &payload,
uint8_t crc_type = 0)
{
const size_t payload_len = payload.size();
std::vector<uint8_t> frame;
frame.push_back(SPARTN_PREAMBLE);
uint8_t b1 = static_cast<uint8_t>(((msg_type & 0x7F) << 1) | ((payload_len >> 9) & 0x01));
uint8_t b2 = static_cast<uint8_t>((payload_len >> 1) & 0xFF);
uint8_t b3 = static_cast<uint8_t>(((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(0x00);
frame.push_back(0x00);
frame.push_back(0x00);
frame.push_back(0x00);
frame.insert(frame.end(), payload.begin(), payload.end());
const uint32_t crc = spartn_message_crc(&frame[1], frame.size() - 1, crc_type);
const size_t crc_bytes = static_cast<size_t>(crc_type) + 1;
for (int i = static_cast<int>(crc_bytes) - 1; i >= 0; i--) {
frame.push_back(static_cast<uint8_t>((crc >>(8 * i)) & 0xFF));
}
return frame;
}
#endif
};
// =============================================================================
// Checksum
// =============================================================================
// Empty ACK-ACK (class=0x05, id=0x01, length=0): covered bytes 05 01 00 00.
// 8-bit Fletcher: a runs 5,6,6,6 and b runs 5,11,17,23 → CK_A=0x06, CK_B=0x17.
TEST_F(UbxTest, ChecksumKnownVector)
{
const uint8_t covered[] = {0x05, 0x01, 0x00, 0x00};
uint8_t ck_a = 0;
uint8_t ck_b = 0;
ubx_checksum(covered, sizeof(covered), &ck_a, &ck_b);
EXPECT_EQ(ck_a, 0x06u);
EXPECT_EQ(ck_b, 0x17u);
}
// =============================================================================
// Framing
// =============================================================================
TEST_F(UbxTest, SingleMinimalFrame)
{
// UBX-MGA class is 0x13; any class/id is fine for framing
auto frame = buildUbxFrame(0x13, 0x00, {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::Ubx);
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().ubx_messages, 1u);
EXPECT_EQ(parser.getStats().crc_errors, 0u);
}
TEST_F(UbxTest, EmptyPayloadFrame)
{
auto frame = buildUbxFrame(0x05, 0x01, {});
parser.addData(frame.data(), frame.size());
size_t len = 0;
ASSERT_NE(parser.getNextMessage(&len), nullptr);
EXPECT_EQ(len, UBX_HEADER_LEN + UBX_CK_LEN);
parser.consumeMessage(len);
EXPECT_EQ(parser.getStats().ubx_messages, 1u);
}
TEST_F(UbxTest, MultipleFrames)
{
auto f1 = buildUbxFrame(0x13, 0x00, {0x01});
auto f2 = buildUbxFrame(0x13, 0x02, {0x02, 0x03, 0x04});
std::vector<uint8_t> 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().ubx_messages, 2u);
}
TEST_F(UbxTest, ChunkedArrival)
{
auto frame = buildUbxFrame(0x13, 0x01, {0x10, 0x20, 0x30, 0x40});
for (size_t i = 0; i < frame.size(); i++) {
parser.addData(&frame[i], 1);
// No complete frame until the last byte
}
size_t len = 0;
ASSERT_NE(parser.getNextMessage(&len), nullptr);
EXPECT_EQ(len, frame.size());
}
TEST_F(UbxTest, NoiseBeforeFrame)
{
auto frame = buildUbxFrame(0x13, 0x00, {0x55});
std::vector<uint8_t> 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);
parser.consumeMessage(len);
EXPECT_EQ(parser.getStats().ubx_messages, 1u);
}
TEST_F(UbxTest, BadSync2)
{
// 0xB5 followed by something other than 0x62 is not a frame start
std::vector<uint8_t> stream = {UBX_SYNC1, 0x00, 0x11, 0x22};
auto frame = buildUbxFrame(0x13, 0x00, {0x01});
stream.insert(stream.end(), frame.begin(), frame.end());
parser.addData(stream.data(), stream.size());
size_t len = 0;
CorrectionProtocol protocol = CorrectionProtocol::Rtcm3;
ASSERT_NE(parser.getNextMessage(&len, &protocol), nullptr);
EXPECT_EQ(protocol, CorrectionProtocol::Ubx);
parser.consumeMessage(len);
EXPECT_EQ(parser.getStats().ubx_messages, 1u);
EXPECT_GT(parser.getStats().bytes_discarded, 0u);
}
TEST_F(UbxTest, BadChecksum)
{
auto frame = buildUbxFrame(0x13, 0x00, {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);
EXPECT_EQ(parser.getStats().ubx_messages, 0u);
}
TEST_F(UbxTest, RejectsOversizedPayload)
{
// Length field claims UBX_MAX_PAYLOAD_LEN + 1 — must not pin the buffer
std::vector<uint8_t> header = {
UBX_SYNC1, UBX_SYNC2,
0x13, 0x00,
static_cast<uint8_t>((UBX_MAX_PAYLOAD_LEN + 1) & 0xFF),
static_cast<uint8_t>(((UBX_MAX_PAYLOAD_LEN + 1) >> 8) & 0xFF),
};
auto good = buildUbxFrame(0x13, 0x00, {0xAB});
header.insert(header.end(), good.begin(), good.end());
parser.addData(header.data(), header.size());
size_t len = 0;
CorrectionProtocol protocol = CorrectionProtocol::Rtcm3;
ASSERT_NE(parser.getNextMessage(&len, &protocol), nullptr);
EXPECT_EQ(protocol, CorrectionProtocol::Ubx);
EXPECT_EQ(len, good.size());
parser.consumeMessage(len);
EXPECT_EQ(parser.getStats().ubx_messages, 1u);
}
// =============================================================================
// Cross-protocol: MGA then corrections (the PointPerfect -MGA case)
// =============================================================================
// PointPerfect -MGA mountpoints deliver a UBX-MGA burst once on connect, then
// the normal correction stream (RTCM3 or SPARTN). The framer must not lock onto
// UBX and reject everything after — each complete frame is consumed and the next
// preamble (of any protocol) starts the next frame.
TEST_F(UbxTest, MgaThenRtcm3)
{
std::mt19937 rng(42);
auto mga1 = buildUbxFrame(0x13, 0x00, {0x01, 0x02, 0x03});
auto mga2 = buildUbxFrame(0x13, 0x02, {0x10, 0x20});
auto rtcm = buildRtcmFrame(rng, 40);
std::vector<uint8_t> stream;
stream.insert(stream.end(), mga1.begin(), mga1.end());
stream.insert(stream.end(), mga2.begin(), mga2.end());
stream.insert(stream.end(), rtcm.begin(), rtcm.end());
parser.addData(stream.data(), stream.size());
std::vector<CorrectionProtocol> seen;
size_t len = 0;
CorrectionProtocol protocol = CorrectionProtocol::Rtcm3;
while (parser.getNextMessage(&len, &protocol) != nullptr) {
seen.push_back(protocol);
parser.consumeMessage(len);
}
ASSERT_EQ(seen.size(), 3u);
EXPECT_EQ(seen[0], CorrectionProtocol::Ubx);
EXPECT_EQ(seen[1], CorrectionProtocol::Ubx);
EXPECT_EQ(seen[2], CorrectionProtocol::Rtcm3);
EXPECT_EQ(parser.getStats().ubx_messages, 2u);
EXPECT_EQ(parser.getStats().rtcm3_messages, 1u);
EXPECT_EQ(parser.getStats().crc_errors, 0u);
}
#if defined(CONFIG_GPS_SPARTN)
TEST_F(UbxTest, MgaThenSpartn)
{
auto mga = buildUbxFrame(0x13, 0x00, {0xDE, 0xAD});
auto spartn = buildSpartnFrame(0, {0xAA, 0xBB});
std::vector<uint8_t> stream;
stream.insert(stream.end(), mga.begin(), mga.end());
stream.insert(stream.end(), spartn.begin(), spartn.end());
// Another MGA mid-stream should also work (reconnect-style)
auto mga2 = buildUbxFrame(0x13, 0x01, {0x01});
stream.insert(stream.end(), mga2.begin(), mga2.end());
parser.addData(stream.data(), stream.size());
std::vector<CorrectionProtocol> seen;
size_t len = 0;
CorrectionProtocol protocol = CorrectionProtocol::Rtcm3;
while (parser.getNextMessage(&len, &protocol) != nullptr) {
seen.push_back(protocol);
parser.consumeMessage(len);
}
ASSERT_EQ(seen.size(), 3u);
EXPECT_EQ(seen[0], CorrectionProtocol::Ubx);
EXPECT_EQ(seen[1], CorrectionProtocol::Spartn);
EXPECT_EQ(seen[2], CorrectionProtocol::Ubx);
EXPECT_EQ(parser.getStats().ubx_messages, 2u);
EXPECT_EQ(parser.getStats().spartn_messages, 1u);
}
#endif
// A complete RTCM3 frame consumes its payload, so a 0xB5 that happens to sit
// inside that payload is never considered as a UBX start.
TEST_F(UbxTest, RtcmPayloadStrayB5IsNotFramedAsUbx)
{
// Craft an RTCM3 frame whose payload contains a UBX-looking prefix.
// buildRtcmFrame randomizes payload; force a 0xB5 0x62 sequence in raw form.
std::vector<uint8_t> payload(32, 0x00);
payload[4] = UBX_SYNC1;
payload[5] = UBX_SYNC2;
payload[6] = 0x13;
payload[7] = 0x00;
payload[8] = 0x02; // fake length
payload[9] = 0x00;
std::vector<uint8_t> frame;
frame.push_back(RTCM3_PREAMBLE);
frame.push_back(0x00);
frame.push_back(static_cast<uint8_t>(payload.size()));
frame.insert(frame.end(), payload.begin(), payload.end());
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);
// Follow with a real UBX so we know the framer still works after
auto ubx = buildUbxFrame(0x13, 0x00, {0x99});
std::vector<uint8_t> stream = frame;
stream.insert(stream.end(), ubx.begin(), ubx.end());
parser.addData(stream.data(), stream.size());
size_t len = 0;
CorrectionProtocol protocol = CorrectionProtocol::Ubx;
ASSERT_NE(parser.getNextMessage(&len, &protocol), nullptr);
EXPECT_EQ(protocol, CorrectionProtocol::Rtcm3);
parser.consumeMessage(len);
ASSERT_NE(parser.getNextMessage(&len, &protocol), nullptr);
EXPECT_EQ(protocol, CorrectionProtocol::Ubx);
parser.consumeMessage(len);
EXPECT_EQ(parser.getStats().rtcm3_messages, 1u);
EXPECT_EQ(parser.getStats().ubx_messages, 1u);
EXPECT_EQ(parser.getStats().crc_errors, 0u);
}
+95
View File
@@ -0,0 +1,95 @@
/****************************************************************************
*
* 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 ubx.h
*
* UBX transport-layer definitions used to locate frame boundaries.
* Payload content is not decoded. Framing lives in CorrectionFramer.
*
* Used for AssistNow MGA (UBX-MGA-*) delivered ahead of RTCM3/SPARTN
* corrections on PointPerfect -MGA NTRIP mountpoints.
*
* Frame layout (u-blox UBX protocol):
* Byte 0: Sync1 (0xB5)
* Byte 1: Sync2 (0x62)
* Byte 2: Class
* Byte 3: ID
* Byte 4-5: Payload length (uint16 little-endian)
* Byte 6..N: Payload
* Last 2: CK_A, CK_B (8-bit Fletcher over class..end of payload)
*/
#pragma once
#include <cstdint>
#include <cstddef>
namespace gnss
{
static constexpr uint8_t UBX_SYNC1 = 0xB5;
static constexpr uint8_t UBX_SYNC2 = 0x62;
static constexpr size_t UBX_HEADER_LEN = 6; // sync1, sync2, class, id, len_lo, len_hi
static constexpr size_t UBX_CK_LEN = 2;
// Cap below the protocol's 65535 payload bytes so a garbage length cannot pin
// the shared framer buffer; MGA messages are well under this.
static constexpr size_t UBX_MAX_PAYLOAD_LEN = 1024;
static constexpr size_t UBX_MAX_FRAME_LEN = UBX_HEADER_LEN + UBX_MAX_PAYLOAD_LEN + UBX_CK_LEN;
/**
* 8-bit Fletcher checksum used by UBX (CK_A, CK_B).
*
* Covers every byte from Class through the end of the payload (not the sync
* bytes and not the two checksum bytes themselves).
*
* @param data Pointer to Class (first covered byte)
* @param len Number of covered bytes (class + id + length field + payload)
* @param ck_a Out: CK_A
* @param ck_b Out: CK_B
*/
inline void ubx_checksum(const uint8_t *data, size_t len, uint8_t *ck_a, uint8_t *ck_b)
{
uint8_t a = 0;
uint8_t b = 0;
for (size_t i = 0; i < len; i++) {
a = static_cast<uint8_t>(a + data[i]);
b = static_cast<uint8_t>(b + a);
}
*ck_a = a;
*ck_b = b;
}
} // namespace gnss