From 323d1ab8fe01ea4d7da74ef7993b43adddb94681 Mon Sep 17 00:00:00 2001 From: ObvMamut Date: Mon, 19 Oct 2026 19:36:45 +0200 Subject: [PATCH 01/11] Force tracking loss of lock regardless of max_carrier_lock_fail Two fail-safes in the tracking blocks force a loss of lock: the bit or secondary code synchronization time limit (bit_synchronization_time_limit_s), and the telemetry fault message sent by the telemetry decoders. Both did it by writing a large value into d_carrier_lock_fail_counter (300000 and 200000, respectively) and relying on the lock check to find it above max_carrier_lock_fail. When max_carrier_lock_fail is configured above those values, neither fail-safe drops the channel: unless the lock detectors drop it for other reasons, a channel that never achieves bit synchronization keeps tracking past the time limit, and a channel whose telemetry decoder reports a fault keeps tracking. Replace the magic counter values with a d_force_loss_of_lock flag. Both fail-safes set it, cn0_and_tracking_lock_status() declares the loss of lock when it is set, whatever the lock fail counters, and it is cleared when the loss of lock is declared and when a new tracking attempt starts. The loss-of-lock log line now says when the loss was forced, since the counter values no longer show it. The same change is applied to dll_pll_veml_tracking, dll_pll_veml_tracking_fpga and kf_tracking, the three blocks that used this pattern. Add two tests to trk_test that set max_carrier_lock_fail = 1000000 and check that a telemetry fault and the synchronization time limit still drop the channel. Signed-off-by: ObvMamut --- .../gnuradio_blocks/dll_pll_veml_tracking.cc | 11 ++- .../gnuradio_blocks/dll_pll_veml_tracking.h | 1 + .../dll_pll_veml_tracking_fpga.cc | 11 ++- .../dll_pll_veml_tracking_fpga.h | 1 + .../tracking/gnuradio_blocks/kf_tracking.cc | 11 ++- .../tracking/gnuradio_blocks/kf_tracking.h | 1 + .../frequency_error_reduction_test.cc | 73 ++++++++++++++++++- 7 files changed, 96 insertions(+), 13 deletions(-) diff --git a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.cc b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.cc index e5d43111a..a5a93dc17 100644 --- a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.cc +++ b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.cc @@ -867,7 +867,7 @@ void dll_pll_veml_tracking::msg_handler_telemetry_to_trk(const pmt::pmt_t &msg) { gr::thread::scoped_lock lock(d_setlock); DLOG(INFO) << "Telemetry fault received in ch " << this->d_channel; - d_carrier_lock_fail_counter = 200000; // force loss-of-lock condition + d_force_loss_of_lock = true; } } if (d_trk_parameters.tow_to_trk && pmt::any_ref(msg).type().hash_code() == d_tow_to_trk_type_hash_code) @@ -1195,6 +1195,7 @@ void dll_pll_veml_tracking::start_tracking() d_carrier_lock_fail_counter = 0; d_code_lock_fail_counter = 0; + d_force_loss_of_lock = false; d_rem_code_phase_samples = 0.0; d_rem_carr_phase_rad = 0.0; d_rem_code_phase_chips = 0.0; @@ -1394,15 +1395,17 @@ bool dll_pll_veml_tracking::cn0_and_tracking_lock_status(double coh_integration_ } } } - if (d_carrier_lock_fail_counter > d_trk_parameters.max_carrier_lock_fail || d_code_lock_fail_counter > d_trk_parameters.max_code_lock_fail) + if (d_force_loss_of_lock || d_carrier_lock_fail_counter > d_trk_parameters.max_carrier_lock_fail || d_code_lock_fail_counter > d_trk_parameters.max_code_lock_fail) { std::cout << "Loss of lock in channel " << d_channel << ", satellite " << Gnss_Satellite(d_systemName, d_acquisition_gnss_synchro->PRN) << " !\n"; LOG(INFO) << "Loss of lock in channel " << d_channel << ", satellite " << Gnss_Satellite(d_systemName, d_acquisition_gnss_synchro->PRN) << " (carrier_lock_fail_counter:" << d_carrier_lock_fail_counter - << " code_lock_fail_counter : " << d_code_lock_fail_counter << ")"; + << " code_lock_fail_counter : " << d_code_lock_fail_counter + << (d_force_loss_of_lock ? " forced" : "") << ")"; this->message_port_pub(pmt::mp("events"), pmt::from_long(3)); // 3 -> loss of lock d_carrier_lock_fail_counter = 0; d_code_lock_fail_counter = 0; + d_force_loss_of_lock = false; return false; } return true; @@ -2459,7 +2462,7 @@ int dll_pll_veml_tracking::general_work(int noutput_items __attribute__((unused) // if (d_trk_parameters.bit_synchronization_time_limit_s < (d_sample_counter - d_acq_sample_stamp) / static_cast(d_trk_parameters.fs_in)) if (d_trk_parameters.bit_synchronization_time_limit_s < tracking_elapsed_seconds(this->nitems_read(0))) { - d_carrier_lock_fail_counter = 300000; // force loss-of-lock condition + d_force_loss_of_lock = true; LOG(INFO) << d_systemName << " " << d_signal_pretty_name << " tracking synchronization time limit reached in channel " << d_channel << " for satellite " << Gnss_Satellite(d_systemName, d_acquisition_gnss_synchro->PRN) << '\n'; } diff --git a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.h b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.h index de5b46568..0efaf5a51 100644 --- a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.h +++ b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.h @@ -257,6 +257,7 @@ private: bool d_wait_for_bit_edge{false}; bool d_b1c_prelock_output_pending{false}; bool d_carrier_phase_discontinuity{true}; // pending report of a new carrier phase ambiguity + bool d_force_loss_of_lock{false}; // declare loss of lock at the next lock check, whatever the lock fail counters }; diff --git a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking_fpga.cc b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking_fpga.cc index 383525f4f..39a17d2f1 100644 --- a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking_fpga.cc +++ b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking_fpga.cc @@ -519,7 +519,7 @@ void dll_pll_veml_tracking_fpga::msg_handler_telemetry_to_trk(const pmt::pmt_t & { DLOG(INFO) << "Telemetry fault received in ch " << this->d_channel; gr::thread::scoped_lock lock(d_setlock); - d_carrier_lock_fail_counter = 200000; // force loss-of-lock condition + d_force_loss_of_lock = true; } } } @@ -685,15 +685,17 @@ bool dll_pll_veml_tracking_fpga::cn0_and_tracking_lock_status(double coh_integra } } } - if (d_carrier_lock_fail_counter > d_trk_parameters.max_carrier_lock_fail || d_code_lock_fail_counter > d_trk_parameters.max_code_lock_fail) + if (d_force_loss_of_lock || d_carrier_lock_fail_counter > d_trk_parameters.max_carrier_lock_fail || d_code_lock_fail_counter > d_trk_parameters.max_code_lock_fail) { std::cout << "Loss of lock in channel " << d_channel << ", satellite " << Gnss_Satellite(d_systemName, d_acquisition_gnss_synchro->PRN) << " !\n"; LOG(INFO) << "Loss of lock in channel " << d_channel << ", satellite " << Gnss_Satellite(d_systemName, d_acquisition_gnss_synchro->PRN) << " (carrier_lock_fail_counter:" << d_carrier_lock_fail_counter - << " code_lock_fail_counter : " << d_code_lock_fail_counter << ")"; + << " code_lock_fail_counter : " << d_code_lock_fail_counter + << (d_force_loss_of_lock ? " forced" : "") << ")"; this->message_port_pub(pmt::mp("events"), pmt::from_long(3)); // 3 -> loss of lock d_carrier_lock_fail_counter = 0; d_code_lock_fail_counter = 0; + d_force_loss_of_lock = false; d_multicorrelator_fpga->unlock_channel(); return false; } @@ -1439,6 +1441,7 @@ void dll_pll_veml_tracking_fpga::set_gnss_synchro(Gnss_Synchro *p_gnss_synchro) d_carrier_lock_fail_counter = 0; d_code_lock_fail_counter = 0; + d_force_loss_of_lock = false; d_rem_code_phase_samples = 0.0; d_rem_carr_phase_rad = 0.0; d_rem_code_phase_chips = 0.0; @@ -1638,7 +1641,7 @@ int dll_pll_veml_tracking_fpga::general_work(int noutput_items __attribute__((un // fail-safe: check if the secondary code or bit synchronization has not succeeded in a limited time period if (d_trk_parameters.bit_synchronization_time_limit_s < (d_sample_counter - d_acq_sample_stamp) / static_cast(d_trk_parameters.fs_in)) { - d_carrier_lock_fail_counter = 300000; // force loss-of-lock condition + d_force_loss_of_lock = true; LOG(INFO) << d_systemName << " " << d_signal_pretty_name << " tracking synchronization time limit reached in channel " << d_channel << " for satellite " << Gnss_Satellite(d_systemName, d_acquisition_gnss_synchro->PRN) << '\n'; } diff --git a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking_fpga.h b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking_fpga.h index a695d9072..87df902fd 100644 --- a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking_fpga.h +++ b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking_fpga.h @@ -247,6 +247,7 @@ private: bool d_Flag_PLL_180_deg_phase_locked; bool d_use_histogram_bit_sync; bool d_wait_for_bit_edge{false}; + bool d_force_loss_of_lock{false}; // declare loss of lock at the next lock check, whatever the lock fail counters }; diff --git a/src/algorithms/tracking/gnuradio_blocks/kf_tracking.cc b/src/algorithms/tracking/gnuradio_blocks/kf_tracking.cc index 329733bac..790bfa9a5 100644 --- a/src/algorithms/tracking/gnuradio_blocks/kf_tracking.cc +++ b/src/algorithms/tracking/gnuradio_blocks/kf_tracking.cc @@ -641,7 +641,7 @@ void kf_tracking::msg_handler_telemetry_to_trk(const pmt::pmt_t &msg) { DLOG(INFO) << "Telemetry fault received in ch " << this->d_channel; gr::thread::scoped_lock lock(d_setlock); - d_carrier_lock_fail_counter = 200000; // force loss-of-lock condition + d_force_loss_of_lock = true; } } } @@ -853,6 +853,7 @@ void kf_tracking::start_tracking() d_carrier_lock_fail_counter = 0; d_code_lock_fail_counter = 0; + d_force_loss_of_lock = false; d_rem_code_phase_samples = 0.0; d_rem_carr_phase_rad = 0.0; d_rem_code_phase_chips = 0.0; @@ -1113,15 +1114,17 @@ bool kf_tracking::cn0_and_tracking_lock_status(double coh_integration_time_s) } } } - if (d_carrier_lock_fail_counter > d_trk_parameters.max_carrier_lock_fail || d_code_lock_fail_counter > d_trk_parameters.max_code_lock_fail) + if (d_force_loss_of_lock || d_carrier_lock_fail_counter > d_trk_parameters.max_carrier_lock_fail || d_code_lock_fail_counter > d_trk_parameters.max_code_lock_fail) { std::cout << "Loss of lock in channel " << d_channel << "!\n"; LOG(INFO) << "Loss of lock in channel " << d_channel << " (carrier_lock_fail_counter:" << d_carrier_lock_fail_counter - << " code_lock_fail_counter : " << d_code_lock_fail_counter << ")"; + << " code_lock_fail_counter : " << d_code_lock_fail_counter + << (d_force_loss_of_lock ? " forced" : "") << ")"; this->message_port_pub(pmt::mp("events"), pmt::from_long(3)); // 3 -> loss of lock d_carrier_lock_fail_counter = 0; d_code_lock_fail_counter = 0; + d_force_loss_of_lock = false; return false; } return true; @@ -1823,7 +1826,7 @@ int kf_tracking::general_work(int noutput_items __attribute__((unused)), gr_vect // fail-safe: check if the secondary code or bit synchronization has not succeeded in a limited time period if (d_trk_parameters.bit_synchronization_time_limit_s < (d_sample_counter - d_acq_sample_stamp) / static_cast(d_trk_parameters.fs_in)) { - d_carrier_lock_fail_counter = 300000; // force loss-of-lock condition + d_force_loss_of_lock = true; LOG(INFO) << d_systemName << " " << d_signal_pretty_name << " tracking synchronization time limit reached in channel " << d_channel << " for satellite " << Gnss_Satellite(d_systemName, d_acquisition_gnss_synchro->PRN) << '\n'; } diff --git a/src/algorithms/tracking/gnuradio_blocks/kf_tracking.h b/src/algorithms/tracking/gnuradio_blocks/kf_tracking.h index 1320a3722..82f5d428f 100644 --- a/src/algorithms/tracking/gnuradio_blocks/kf_tracking.h +++ b/src/algorithms/tracking/gnuradio_blocks/kf_tracking.h @@ -231,6 +231,7 @@ private: bool d_acc_carrier_phase_initialized; bool d_carrier_phase_discontinuity{true}; // pending report of a new carrier phase ambiguity bool d_enable_extended_integration; + bool d_force_loss_of_lock{false}; // declare loss of lock at the next lock check, whatever the lock fail counters }; #endif // GNSS_SDR_KF_TRACKING_H diff --git a/tests/unit-tests/signal-processing-blocks/tracking/frequency_error_reduction_test.cc b/tests/unit-tests/signal-processing-blocks/tracking/frequency_error_reduction_test.cc index a1bb4a7ba..8c0e1a9b1 100644 --- a/tests/unit-tests/signal-processing-blocks/tracking/frequency_error_reduction_test.cc +++ b/tests/unit-tests/signal-processing-blocks/tracking/frequency_error_reduction_test.cc @@ -1,7 +1,8 @@ /*! * \file frequency_error_reduction_test.cc * \brief This file implements tests for the tracking frequency-error - * reduction mechanism and bit/secondary-code synchronization. + * reduction mechanism, bit/secondary-code synchronization, and the forced + * loss-of-lock fail-safes. * * ----------------------------------------------------------------------------- * @@ -23,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -281,6 +283,63 @@ protected: EXPECT_DOUBLE_EQ(0.0, tracking->d_carrier_phase_rate_step_rad); } + // A carrier lock fail limit of 1000000 is not reached within these tests, + // so only a forced loss of lock can drop the channel. It is also above the + // values (200000 and 300000) the fail-safes used to write into the carrier + // lock fail counter to force a loss of lock. + void make_tracking_with_high_lock_fail_limit() + { + Dll_Pll_Conf params; + params.fs_in = 2000000.0; + params.vector_length = 2000U; + params.f_error_step_num = 0; + params.f_error_dump_filename.clear(); + // The pull-in transitory freezes the lock fail counters and postpones + // bit synchronization. + params.pull_in_time_s = 10U; + params.bit_synchronization_time_limit_s = 1U; + params.max_carrier_lock_fail = 1000000; + synchro = Gnss_Synchro(); + synchro.PRN = 1; + synchro.System = params.system; + synchro.Signal[0] = params.signal[0]; + synchro.Signal[1] = params.signal[1]; + tracking = dll_pll_veml_make_tracking(params); + tracking->set_gnss_synchro(&synchro); + tracking->start_tracking(); + } + + void check_telemetry_fault() + { + make_tracking_with_high_lock_fail_limit(); + const int bad_telemetry = 1; + tracking->msg_handler_telemetry_to_trk(pmt::make_any(bad_telemetry)); + // The lock status is evaluated once the C/N0 estimation buffer is full. + for (int32_t i = 0; i < tracking->d_trk_parameters.cn0_samples; ++i) + { + ASSERT_TRUE(tracking->cn0_and_tracking_lock_status(0.001)); + } + EXPECT_FALSE(tracking->cn0_and_tracking_lock_status(0.001)); + // The forced loss of lock is declared only once. + EXPECT_TRUE(tracking->cn0_and_tracking_lock_status(0.001)); + } + + void check_synchronization_time_limit() + { + make_tracking_with_high_lock_fail_limit(); + auto top_block = gr::make_top_block("Synchronization time limit"); + auto source = gr::blocks::null_source::make(sizeof(gr_complex)); + // 3 s of signal: the 1 s synchronization time limit is exceeded after 2 s. + auto head = gr::blocks::head::make(sizeof(gr_complex), 3ULL * static_cast(tracking->d_trk_parameters.fs_in)); + auto sink = gr::blocks::null_sink::make(sizeof(Gnss_Synchro)); + top_block->connect(source, 0, head, 0); + top_block->connect(head, 0, tracking, 0); + top_block->connect(tracking, 0, sink, 0); + top_block->run(); + + EXPECT_EQ(0, tracking->d_state); // loss of lock declared + } + Gnss_Synchro synchro; dll_pll_veml_tracking_sptr tracking; }; @@ -332,3 +391,15 @@ TEST_F(DllPllTrackingFrequencyErrorTest, LongL2cScanRetainsFllPullIn) { run_long_scan(); } + + +TEST_F(DllPllTrackingFrequencyErrorTest, TelemetryFaultForcesLossOfLock) +{ + check_telemetry_fault(); +} + + +TEST_F(DllPllTrackingFrequencyErrorTest, SynchronizationTimeLimitForcesLossOfLock) +{ + check_synchronization_time_limit(); +} From a81888f2aed8d1c8a64ae7f5feeef6fec56a537c Mon Sep 17 00:00:00 2001 From: ObvMamut Date: Mon, 19 Oct 2026 19:40:48 +0200 Subject: [PATCH 02/11] Write the accumulated carrier phase as double in tracking dumps log_data() in dll_pll_veml_tracking and dll_pll_veml_tracking_fpga casts d_acc_carrier_phase_rad, a double, to float before writing it to the binary dump, and save_matfile() reads it back as a float. The accumulated phase grows by 2*pi times the Doppler shift every second (about 31400 rad/s at 5 kHz), so it reaches 1e6 rad after about 30 s of tracking at 5 kHz, or under 3 minutes at 1 kHz. The float spacing is 0.0625 rad at 1e6 rad, 0.25 rad at 3e6 rad and 1 rad at 1e7 rad. At 3e6 rad, for instance, the phase difference between two 1 ms epochs of the dump is only known to within +/-0.25 rad, about 40 Hz in frequency terms. The phase used by the receiver (Gnss_Synchro::Carrier_phase_rads) is a double and is not affected; only the dump is. Write the field as a double, and read it back as a double in save_matfile(), so that the .mat file also holds a double. This changes the dump record layout. The field keeps its position but grows from 4 to 8 bytes, so a record is now 112 bytes long in dll_pll_veml_tracking (it was 108) and 100 bytes long in dll_pll_veml_tracking_fpga (it was 96). The readers of this format are updated accordingly: Tracking_Dump_Reader, used by the unit tests, and dll_pll_veml_read_tracking_dump in utils/matlab and utils/python. Signed-off-by: ObvMamut --- .../gnuradio_blocks/dll_pll_veml_tracking.cc | 16 ++++++++-------- .../dll_pll_veml_tracking_fpga.cc | 16 ++++++++-------- .../libs/tracking_dump_reader.cc | 6 +++--- .../libs/tracking_dump_reader.h | 2 +- .../libs/dll_pll_veml_read_tracking_dump.m | 10 +++++----- .../lib/dll_pll_veml_read_tracking_dump.py | 2 +- 6 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.cc b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.cc index e5d43111a..c9dddb7ce 100644 --- a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.cc +++ b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.cc @@ -1909,9 +1909,9 @@ void dll_pll_veml_tracking::log_data() // PRN start sample stamp tmp_long_int = this->nitems_read(0) + static_cast(d_current_prn_length_samples); d_dump_file.write(reinterpret_cast(&tmp_long_int), sizeof(uint64_t)); - // accumulated carrier phase - tmp_float = static_cast(d_acc_carrier_phase_rad); - d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); + // accumulated carrier phase (double, since it grows without bound) + tmp_double = d_acc_carrier_phase_rad; + d_dump_file.write(reinterpret_cast(&tmp_double), sizeof(double)); // carrier and code frequency tmp_float = static_cast(d_carrier_doppler_hz); d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); @@ -1965,8 +1965,8 @@ int32_t dll_pll_veml_tracking::save_matfile() const { // READ DUMP FILE std::ifstream::pos_type size; - const int32_t number_of_double_vars = 1; - const int32_t number_of_float_vars = 19; + const int32_t number_of_double_vars = 2; + const int32_t number_of_float_vars = 18; const int32_t epoch_size_bytes = sizeof(uint64_t) + sizeof(double) * number_of_double_vars + sizeof(float) * number_of_float_vars + sizeof(uint32_t) + sizeof(uint64_t) + sizeof(int32_t); @@ -2007,7 +2007,7 @@ int32_t dll_pll_veml_tracking::save_matfile() const auto Prompt_I = std::vector(num_epoch); auto Prompt_Q = std::vector(num_epoch); auto PRN_start_sample_count = std::vector(num_epoch); - auto acc_carrier_phase_rad = std::vector(num_epoch); + auto acc_carrier_phase_rad = std::vector(num_epoch); auto carrier_doppler_hz = std::vector(num_epoch); auto carrier_doppler_rate_hz = std::vector(num_epoch); auto code_freq_chips = std::vector(num_epoch); @@ -2037,7 +2037,7 @@ int32_t dll_pll_veml_tracking::save_matfile() const dump_file.read(reinterpret_cast(&Prompt_I[i]), sizeof(float)); dump_file.read(reinterpret_cast(&Prompt_Q[i]), sizeof(float)); dump_file.read(reinterpret_cast(&PRN_start_sample_count[i]), sizeof(uint64_t)); - dump_file.read(reinterpret_cast(&acc_carrier_phase_rad[i]), sizeof(float)); + dump_file.read(reinterpret_cast(&acc_carrier_phase_rad[i]), sizeof(double)); dump_file.read(reinterpret_cast(&carrier_doppler_hz[i]), sizeof(float)); dump_file.read(reinterpret_cast(&carrier_doppler_rate_hz[i]), sizeof(float)); dump_file.read(reinterpret_cast(&code_freq_chips[i]), sizeof(float)); @@ -2080,7 +2080,7 @@ int32_t dll_pll_veml_tracking::save_matfile() const write_matlab_var<2, float>("Prompt_I", Prompt_I.data(), matfp, dims); write_matlab_var<2, float>("Prompt_Q", Prompt_Q.data(), matfp, dims); write_matlab_var<2, uint64_t>("PRN_start_sample_count", PRN_start_sample_count.data(), matfp, dims); - write_matlab_var<2, float>("acc_carrier_phase_rad", acc_carrier_phase_rad.data(), matfp, dims); + write_matlab_var<2, double>("acc_carrier_phase_rad", acc_carrier_phase_rad.data(), matfp, dims); write_matlab_var<2, float>("carrier_doppler_hz", carrier_doppler_hz.data(), matfp, dims); write_matlab_var<2, float>("carrier_doppler_rate_hz", carrier_doppler_rate_hz.data(), matfp, dims); write_matlab_var<2, float>("code_freq_chips", code_freq_chips.data(), matfp, dims); diff --git a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking_fpga.cc b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking_fpga.cc index 383525f4f..cf1f188e4 100644 --- a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking_fpga.cc +++ b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking_fpga.cc @@ -1135,9 +1135,9 @@ void dll_pll_veml_tracking_fpga::log_data() // PRN start sample stamp tmp_long_int = d_sample_counter_next; d_dump_file.write(reinterpret_cast(&tmp_long_int), sizeof(uint64_t)); - // accumulated carrier phase - tmp_float = static_cast(d_acc_carrier_phase_rad); - d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); + // accumulated carrier phase (double, since it grows without bound) + tmp_double = d_acc_carrier_phase_rad; + d_dump_file.write(reinterpret_cast(&tmp_double), sizeof(double)); // carrier and code frequency tmp_float = static_cast(d_carrier_doppler_hz); d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); @@ -1185,8 +1185,8 @@ int32_t dll_pll_veml_tracking_fpga::save_matfile() const { // READ DUMP FILE std::ifstream::pos_type size; - const int32_t number_of_double_vars = 1; - const int32_t number_of_float_vars = 19; + const int32_t number_of_double_vars = 2; + const int32_t number_of_float_vars = 18; const int32_t epoch_size_bytes = sizeof(uint64_t) + sizeof(double) * number_of_double_vars + sizeof(float) * number_of_float_vars + sizeof(uint32_t); std::ifstream dump_file; @@ -1226,7 +1226,7 @@ int32_t dll_pll_veml_tracking_fpga::save_matfile() const auto Prompt_I = std::vector(num_epoch); auto Prompt_Q = std::vector(num_epoch); auto PRN_start_sample_count = std::vector(num_epoch); - auto acc_carrier_phase_rad = std::vector(num_epoch); + auto acc_carrier_phase_rad = std::vector(num_epoch); auto carrier_doppler_hz = std::vector(num_epoch); auto carrier_doppler_rate_hz = std::vector(num_epoch); auto code_freq_chips = std::vector(num_epoch); @@ -1254,7 +1254,7 @@ int32_t dll_pll_veml_tracking_fpga::save_matfile() const dump_file.read(reinterpret_cast(&Prompt_I[i]), sizeof(float)); dump_file.read(reinterpret_cast(&Prompt_Q[i]), sizeof(float)); dump_file.read(reinterpret_cast(&PRN_start_sample_count[i]), sizeof(uint64_t)); - dump_file.read(reinterpret_cast(&acc_carrier_phase_rad[i]), sizeof(float)); + dump_file.read(reinterpret_cast(&acc_carrier_phase_rad[i]), sizeof(double)); dump_file.read(reinterpret_cast(&carrier_doppler_hz[i]), sizeof(float)); dump_file.read(reinterpret_cast(&carrier_doppler_rate_hz[i]), sizeof(float)); dump_file.read(reinterpret_cast(&code_freq_chips[i]), sizeof(float)); @@ -1295,7 +1295,7 @@ int32_t dll_pll_veml_tracking_fpga::save_matfile() const write_matlab_var<2, float>("Prompt_I", Prompt_I.data(), matfp, dims); write_matlab_var<2, float>("Prompt_Q", Prompt_Q.data(), matfp, dims); write_matlab_var<2, uint64_t>("PRN_start_sample_count", PRN_start_sample_count.data(), matfp, dims); - write_matlab_var<2, float>("acc_carrier_phase_rad", acc_carrier_phase_rad.data(), matfp, dims); + write_matlab_var<2, double>("acc_carrier_phase_rad", acc_carrier_phase_rad.data(), matfp, dims); write_matlab_var<2, float>("carrier_doppler_hz", carrier_doppler_hz.data(), matfp, dims); write_matlab_var<2, float>("carrier_doppler_rate_hz", carrier_doppler_rate_hz.data(), matfp, dims); write_matlab_var<2, float>("code_freq_chips", code_freq_chips.data(), matfp, dims); diff --git a/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.cc b/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.cc index 985aa596a..e9cf068cb 100644 --- a/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.cc +++ b/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.cc @@ -31,7 +31,7 @@ bool Tracking_Dump_Reader::read_binary_obs() d_dump_file.read(reinterpret_cast(&prompt_I), sizeof(float)); d_dump_file.read(reinterpret_cast(&prompt_Q), sizeof(float)); d_dump_file.read(reinterpret_cast(&PRN_start_sample_count), sizeof(uint64_t)); - d_dump_file.read(reinterpret_cast(&acc_carrier_phase_rad), sizeof(float)); + d_dump_file.read(reinterpret_cast(&acc_carrier_phase_rad), sizeof(double)); d_dump_file.read(reinterpret_cast(&carrier_doppler_hz), sizeof(float)); d_dump_file.read(reinterpret_cast(&carrier_doppler_rate_hz_s), sizeof(float)); d_dump_file.read(reinterpret_cast(&code_freq_chips), sizeof(float)); @@ -71,8 +71,8 @@ bool Tracking_Dump_Reader::restart() int64_t Tracking_Dump_Reader::num_epochs() { std::ifstream::pos_type size; - int number_of_double_vars = 1; - int number_of_float_vars = 19; + int number_of_double_vars = 2; + int number_of_float_vars = 18; int epoch_size_bytes = sizeof(uint64_t) + sizeof(double) * number_of_double_vars + sizeof(float) * number_of_float_vars + sizeof(unsigned int) + sizeof(uint64_t) + sizeof(int32_t); diff --git a/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.h b/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.h index 9fd69a624..860882888 100644 --- a/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.h +++ b/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.h @@ -45,7 +45,7 @@ public: uint64_t PRN_start_sample_count; // accumulated carrier phase - float acc_carrier_phase_rad; + double acc_carrier_phase_rad; // carrier and code frequency float carrier_doppler_hz; diff --git a/utils/matlab/libs/dll_pll_veml_read_tracking_dump.m b/utils/matlab/libs/dll_pll_veml_read_tracking_dump.m index 2b43a1408..93919dd6e 100644 --- a/utils/matlab/libs/dll_pll_veml_read_tracking_dump.m +++ b/utils/matlab/libs/dll_pll_veml_read_tracking_dump.m @@ -17,9 +17,9 @@ function [GNSS_tracking] = dll_pll_veml_read_tracking_dump (filename, count) m = nargchk (1,2,nargin); -num_float_vars = 19; +num_float_vars = 18; num_unsigned_long_int_vars = 1; -num_double_vars = 1; +num_double_vars = 2; num_unsigned_int_vars = 2; num_unsigned_int64_vars = 1; @@ -78,9 +78,9 @@ else v8 = fread (f, count, 'uint32', skip_bytes_each_read - unsigned_long_int_size_bytes); end bytes_shift = bytes_shift + unsigned_long_int_size_bytes; - fseek(f,bytes_shift,'bof'); % move to next float - v9 = fread (f, count, 'float', skip_bytes_each_read - float_size_bytes); - bytes_shift = bytes_shift + float_size_bytes; + fseek(f,bytes_shift,'bof'); % move to next double + v9 = fread (f, count, 'double', skip_bytes_each_read - double_size_bytes); + bytes_shift = bytes_shift + double_size_bytes; fseek(f,bytes_shift,'bof'); % move to next float v10 = fread (f, count, 'float', skip_bytes_each_read - float_size_bytes); bytes_shift = bytes_shift + float_size_bytes; diff --git a/utils/python/lib/dll_pll_veml_read_tracking_dump.py b/utils/python/lib/dll_pll_veml_read_tracking_dump.py index 675792d04..18b59db20 100644 --- a/utils/python/lib/dll_pll_veml_read_tracking_dump.py +++ b/utils/python/lib/dll_pll_veml_read_tracking_dump.py @@ -44,7 +44,7 @@ _RECORD_FORMAT = '<' + ( 'f' # prompt_I -> Prompt correlator, In-phase component. 'f' # prompt_Q -> Prompt correlator, Quadrature component. 'Q' # PRN_start_sample -> Sample counter from tracking start. - 'f' # acc_carrier_phase_rad -> Accumulated carrier phase, in rad. + 'd' # acc_carrier_phase_rad -> Accumulated carrier phase, in rad. 'f' # carrier_doppler_hz -> Doppler shift, in Hz. 'f' # carrier_doppler_rate_hz_s -> Doppler rate, in Hz/s. 'f' # code_freq_hz -> Code frequency, in chips/s. From 002b41804ed8fc584c8a40c99f8fcb76f5b192ab Mon Sep 17 00:00:00 2001 From: Carles Fernandez Date: Sun, 25 Oct 2026 13:37:34 +0100 Subject: [PATCH 03/11] The SUPL client now verifies the server certificate and DNS name or IP address --- docs/CHANGELOG.md | 9 + src/core/libs/gnss_sdr_supl_client.cc | 11 - src/core/libs/supl/supl.c | 509 +++++++++++++++----------- src/core/libs/supl/supl.h | 3 +- 4 files changed, 297 insertions(+), 235 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 567561d30..dac2da923 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -81,6 +81,15 @@ All notable changes to GNSS-SDR will be documented in this file. multiple of 24 bytes). Also, `seconds_to_skip` no longer lands in the middle of a frame when channels have bandwidth dividers that are not powers of two. +### Improvements in Reliability: + +- The SUPL client now verifies the server certificate and DNS name or IP address + with OpenSSL and GnuTLS. It rejects assistance data that exceeds the + fixed-size acquisition, almanac, or ephemeris arrays, including across + multiple responses, and discards partial assistance on failure. SUPL framing + and malformed RRLP payload handling have also been hardened. Reported by Harry + Burgess of Countersight. + ### Improvements in Usability: - Fixed the Monitor (`Monitor.enable_monitor=true`) for channels without a valid diff --git a/src/core/libs/gnss_sdr_supl_client.cc b/src/core/libs/gnss_sdr_supl_client.cc index 25fa353a4..2d0777a92 100644 --- a/src/core/libs/gnss_sdr_supl_client.cc +++ b/src/core/libs/gnss_sdr_supl_client.cc @@ -207,17 +207,6 @@ int Gnss_Sdr_Supl_Client::get_assistance(int i_mcc, int i_mns, int i_lac, int i_ if (err == 0) { read_supl_data(); - if (supl_ctx_free(&ctx)) - { - } // clean it up before leaving - } - else - { - /* - * If supl_get_assist() fails, the connection remains open - * and the memory/files are not released. - */ - supl_close(&ctx); } return err; } diff --git a/src/core/libs/supl/supl.c b/src/core/libs/supl/supl.c index c32866945..1eee06b8e 100644 --- a/src/core/libs/supl/supl.c +++ b/src/core/libs/supl/supl.c @@ -15,6 +15,7 @@ */ #include "supl.h" +#include #include #include #include @@ -55,18 +56,23 @@ int EXPORT supl_ulp_decode(supl_ulp_t *pdu) asn_codec_ctx_t ctx; asn_dec_rval_t rval; - ulp = calloc(1, sizeof(ULP_PDU_t)); - pdu->pdu = ulp; - - ctx.max_stack_size = 0; - rval = uper_decode_complete(&ctx, &asn_DEF_ULP_PDU, (void **)&ulp, pdu->buffer, pdu->size); - if (rval.code == RC_OK) + pdu->pdu = 0; + if (pdu->size < 2 || pdu->size > sizeof(pdu->buffer)) { + return E_SUPL_DECODE; + } + ulp = 0; + ctx.max_stack_size = 65536; + rval = uper_decode_complete(&ctx, &asn_DEF_ULP_PDU, (void **)&ulp, pdu->buffer, pdu->size); + if (rval.code == RC_OK && rval.consumed == pdu->size && + ulp->length == (long)pdu->size && + asn_check_constraints(&asn_DEF_ULP_PDU, ulp, 0, 0) == 0) + { + pdu->pdu = ulp; return 0; } - free(ulp); - pdu->pdu = 0; + ASN_STRUCT_FREE(asn_DEF_ULP_PDU, ulp); return E_SUPL_DECODE; } @@ -104,7 +110,8 @@ int EXPORT supl_ulp_encode(supl_ulp_t *pdu) void EXPORT supl_ulp_free(supl_ulp_t *pdu) { - asn_DEF_ULP_PDU.free_struct(&asn_DEF_ULP_PDU, pdu->pdu, 0); + ASN_STRUCT_FREE(asn_DEF_ULP_PDU, pdu->pdu); + pdu->pdu = 0; } @@ -120,14 +127,20 @@ int EXPORT supl_ulp_send(supl_ctx_t *ctx, supl_ulp_t *pdu) } #endif - err = SSL_write(ctx->ssl, pdu->buffer, pdu->size); - if (err <= 0) + size_t sent = 0; + if (pdu->size == 0 || pdu->size > sizeof(pdu->buffer)) { -#if SUPL_DEBUG - if (debug.debug) fprintf(debug.log, "Error: SSL_write error: %s\n", strerror(errno)); -#endif return E_SUPL_WRITE; } + while (sent < pdu->size) + { + err = SSL_write(ctx->ssl, pdu->buffer + sent, (int)(pdu->size - sent)); + if (err <= 0) + { + return E_SUPL_WRITE; + } + sent += err; + } #ifdef SUPL_DEBUG debug.sent += pdu->size; @@ -140,46 +153,31 @@ int EXPORT supl_ulp_send(supl_ctx_t *ctx, supl_ulp_t *pdu) int EXPORT supl_ulp_recv(supl_ctx_t *ctx, supl_ulp_t *pdu) { - int64_t err; - int64_t n; - asn_dec_rval_t rval; - ULP_PDU_t *length; + size_t received = 0; + size_t length = 2; - err = SSL_read(ctx->ssl, pdu->buffer, sizeof(pdu->buffer)); - if (err <= 0) + pdu->pdu = 0; + pdu->size = 0; + /* ULP starts with a 16-bit length, including the length field itself. + * Read exactly one frame, even when TLS splits or coalesces messages. */ + while (received < length) { -#ifdef SUPL_DEBUG - if (debug.debug) fprintf(debug.log, "Error: SSL_read error: %s\n", strerror(errno)); -#endif - return E_SUPL_READ; - } - n = err; - - length = calloc(1, sizeof(ULP_PDU_t)); - // decode the very first bytes of the ULP_PDU message, just enough to the get message length - rval = uper_decode_complete(0, &asn_DEF_ULP_PDU, (void **)&length, pdu->buffer, n < 6 ? n : 6); - if (rval.code == RC_WMORE) - { - // read the missing data - for (n = err; n < length->length; n += err) + int err = SSL_read(ctx->ssl, pdu->buffer + received, (int)(length - received)); + if (err <= 0) { -#ifdef SUPL_DEBUG - if (debug.debug) fprintf(debug.log, "SSL_read got %u bytes (total %lu)\n", n, length->length); -#endif - err = SSL_read(ctx->ssl, &pdu->buffer[n], sizeof(pdu->buffer) - n); - if (err <= 0) + return E_SUPL_READ; + } + received += err; + if (received == 2) + { + length = ((size_t)pdu->buffer[0] << 8) | pdu->buffer[1]; + if (length <= 2 || length > sizeof(pdu->buffer)) { -#ifdef SUPL_DEBUG - if (debug.debug) fprintf(debug.log, "Error: SSL_read (again) error: %s\n", strerror(errno)); -#endif - return E_SUPL_READ; + return E_SUPL_DECODE; } } } - - asn_DEF_ULP_PDU.free_struct(&asn_DEF_ULP_PDU, length, 0); - - pdu->size = n; + pdu->size = received; if (supl_ulp_decode(pdu)) { @@ -195,7 +193,7 @@ int EXPORT supl_ulp_recv(supl_ctx_t *ctx, supl_ulp_t *pdu) #endif #ifdef SUPL_DEBUG - debug.recv += err; + debug.recv += pdu->size; debug.in_msg++; #endif @@ -210,103 +208,135 @@ int EXPORT supl_decode_rrlp(supl_ulp_t *ulp_pdu, PDU_t **ret_rrlp) PDU_t *rrlp; ULP_PDU_t *ulp; + *ret_rrlp = 0; ulp = ulp_pdu->pdu; - - if (!(ulp->message.present == UlpMessage_PR_msSUPLPOS && - ulp->message.choice.msSUPLPOS.posPayLoad.present == PosPayLoad_PR_rrlpPayload)) + if (!ulp || ulp->message.present != UlpMessage_PR_msSUPLPOS || + ulp->message.choice.msSUPLPOS.posPayLoad.present != PosPayLoad_PR_rrlpPayload) { - return 0; + return E_SUPL_DECODE_RRLP; } rrlp_pdu = &ulp->message.choice.msSUPLPOS.posPayLoad.choice.rrlpPayload; - - rrlp = calloc(1, sizeof(PDU_t)); - rval = uper_decode_complete(0, &asn_DEF_PDU, (void **)&rrlp, rrlp_pdu->buf, rrlp_pdu->size); - switch (rval.code) + if (!rrlp_pdu->buf || rrlp_pdu->size <= 0) { - case RC_OK: -#ifdef SUPL_DEBUG - if (rval.consumed != rrlp_pdu->size) - { - if (debug.debug) fprintf(debug.log, "Warning: %lu bytes left over in RRLP decoding\n", rval.consumed); - } -#endif - - *ret_rrlp = rrlp; - return 0; - - case RC_WMORE: - asn_DEF_PDU.free_struct(&asn_DEF_PDU, rrlp, 0); - ret_rrlp = 0; - return E_SUPL_DECODE_RRLP; - - default: - asn_DEF_PDU.free_struct(&asn_DEF_PDU, rrlp, 0); - ret_rrlp = 0; return E_SUPL_DECODE_RRLP; } - - return E_SUPL_INTERNAL; + rrlp = 0; + rval = uper_decode_complete(0, &asn_DEF_PDU, (void **)&rrlp, rrlp_pdu->buf, rrlp_pdu->size); + if (rval.code == RC_OK && rval.consumed == (size_t)rrlp_pdu->size && + asn_check_constraints(&asn_DEF_PDU, rrlp, 0, 0) == 0) + { + *ret_rrlp = rrlp; + return 0; + } + ASN_STRUCT_FREE(asn_DEF_PDU, rrlp); + return E_SUPL_DECODE_RRLP; } int EXPORT supl_server_connect(supl_ctx_t *ctx, char *server) { - int err; - SSL_METHOD *meth; + unsigned char address[sizeof(struct in6_addr)]; + int numeric; - SSLeay_add_ssl_algorithms(); - // meth = TLSv1_client_method(); - meth = (SSL_METHOD *)SSLv23_client_method(); - SSL_load_error_strings(); - ctx->ssl_ctx = SSL_CTX_new(meth); - if (!ctx->ssl_ctx) + /* A peer name is mandatory, including for a caller-supplied socket. */ + if (!server || !server[0]) { return E_SUPL_CONNECT; } - + numeric = inet_pton(AF_INET, server, address) == 1 || + inet_pton(AF_INET6, server, address) == 1; + SSLeay_add_ssl_algorithms(); + SSL_load_error_strings(); + ctx->ssl_ctx = SSL_CTX_new((SSL_METHOD *)SSLv23_client_method()); + if (!ctx->ssl_ctx) + { + goto fail; + } +#if !USE_GNUTLS_FALLBACK + SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, 0); + if (SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) + { + goto fail; + } + SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | + SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1); +#endif ctx->ssl = SSL_new(ctx->ssl_ctx); if (!ctx->ssl) { - return E_SUPL_CONNECT; + goto fail; } - - if (server) +#if USE_GNUTLS_FALLBACK + /* The OpenSSL compatibility layer does not implement peer verification. + * Use the native GnuTLS credentials and verification API. */ + if (gnutls_certificate_set_x509_system_trust(ctx->ssl->gnutls_cred) < 0 || + gnutls_priority_set_direct(ctx->ssl->gnutls_state, + "NORMAL:-VERS-SSL3.0:-VERS-TLS1.0:-VERS-TLS1.1", 0) < 0 || + (!numeric && gnutls_server_name_set(ctx->ssl->gnutls_state, + GNUTLS_NAME_DNS, server, strlen(server)) < 0)) + { + goto fail; + } +#else +#if OPENSSL_VERSION_NUMBER >= 0x10002000L + if ((numeric && X509_VERIFY_PARAM_set1_ip_asc(SSL_get0_param(ctx->ssl), server) != 1) || + (!numeric && (X509_VERIFY_PARAM_set1_host(SSL_get0_param(ctx->ssl), server, 0) != 1 || + SSL_set_tlsext_host_name(ctx->ssl, server) != 1))) + { + goto fail; + } +#else + /* Older OpenSSL cannot authenticate the expected server identity. */ + goto fail; +#endif +#endif + if (ctx->fd < 0) { ctx->fd = server_connect(server); - if (ctx->fd == -1) - { - return E_SUPL_CONNECT; - } } - - SSL_set_fd(ctx->ssl, ctx->fd); - err = SSL_connect(ctx->ssl); - if (err == -1) + if (ctx->fd < 0 || SSL_set_fd(ctx->ssl, ctx->fd) != 1 || SSL_connect(ctx->ssl) != 1) { - return E_SUPL_CONNECT; + goto fail; + } +#if USE_GNUTLS_FALLBACK + { + unsigned int status = 0; + if (gnutls_certificate_verify_peers3(ctx->ssl->gnutls_state, server, &status) < 0 || status != 0) + { + goto fail; + } + } +#else + if (SSL_get_verify_result(ctx->ssl) != X509_V_OK) + { + goto fail; } - -#if 0 - { - X509 *s_cert = SSL_get_peer_certificate(ctx->ssl); - FILE *fp = fopen("/tmp/s_cert.pem", "w"); - if (fp) - PEM_write_X509(fp, s_cert); - fclose(fp); - X509_free(s_cert); - } #endif - return 0; + +fail: + supl_close(ctx); + return E_SUPL_CONNECT; } void EXPORT supl_close(supl_ctx_t *ctx) { - SSL_shutdown(ctx->ssl); - SSL_free(ctx->ssl); - SSL_CTX_free(ctx->ssl_ctx); - close(ctx->fd); + if (ctx->ssl) + { + SSL_free(ctx->ssl); + ctx->ssl = 0; + } + if (ctx->ssl_ctx) + { + SSL_CTX_free(ctx->ssl_ctx); + ctx->ssl_ctx = 0; + } + if (ctx->fd >= 0) + { + close(ctx->fd); + ctx->fd = -1; + } } @@ -328,22 +358,19 @@ static int server_connect(char *server) for (aip = ailist; aip; aip = aip->ai_next) { - if ((fd = socket(aip->ai_family, SOCK_STREAM, 0)) < 0) + fd = socket(aip->ai_family, SOCK_STREAM, 0); + if (fd < 0) { - err = errno; + continue; } - if (connect(fd, aip->ai_addr, aip->ai_addrlen) != 0) + if (connect(fd, aip->ai_addr, aip->ai_addrlen) == 0) { - freeaddrinfo(aip); - if (close(fd) != 0) - { - // avoid warning - } - return -1; + break; } - break; + close(fd); + fd = -1; } - freeaddrinfo(aip); + freeaddrinfo(ailist); return fd; } @@ -419,7 +446,13 @@ static int supl_response_harvest(supl_ctx_t *ctx, supl_ulp_t *pdu) ULP_PDU_t *ulp = pdu->pdu; void *buf; + free(ctx->slp_session_id.buf); ctx->slp_session_id.buf = 0; + ctx->slp_session_id.size = 0; + if (!ulp->sessionID.slpSessionID) + { + return 0; + } ret = uper_encode_to_new_buffer(&asn_DEF_SlpSessionID, 0, (void *)ulp->sessionID.slpSessionID, &buf); if (ret == -1) @@ -600,7 +633,7 @@ static int pdu_make_ulp_rrlp_ack(supl_ctx_t *ctx, supl_ulp_t *pdu, PDU_t *rrlp) rrlp_ack->component.present = RRLP_Component_PR_assistanceDataAck; ret = uper_encode_to_buffer(&asn_DEF_PDU, rrlp_ack, buffer, sizeof(buffer)); - asn_DEF_ULP_PDU.free_struct(&asn_DEF_PDU, rrlp_ack, 0); + ASN_STRUCT_FREE(asn_DEF_PDU, rrlp_ack); if (ret.encoded == -1) { return E_SUPL_ENCODE_RRLP; @@ -659,6 +692,10 @@ int EXPORT supl_collect_rrlp(supl_assist_t *assist, PDU_t *rrlp, struct timeval { ControlHeader_t *hdr; + if (!assist || !rrlp || !t) + { + return E_SUPL_DECODE_RRLP; + } if (rrlp->component.present != RRLP_Component_PR_assistanceData) { return 0; @@ -670,6 +707,66 @@ int EXPORT supl_collect_rrlp(supl_assist_t *assist, PDU_t *rrlp, struct timeval hdr = &rrlp->component.choice.assistanceData.gps_AssistData->controlHeader; + /* Validate the entire batch before modifying assistance. Counts accumulate + * across RRLP messages and must never exceed the destination arrays. */ + if (assist->cnt_acq < 0 || assist->cnt_acq > MAX_EPHEMERIS || + assist->cnt_alm < 0 || assist->cnt_alm > MAX_EPHEMERIS || + assist->cnt_eph < 0 || assist->cnt_eph > MAX_EPHEMERIS) + { + return E_SUPL_DECODE_RRLP; + } + if (hdr->acquisAssist) + { + int n; + int count = hdr->acquisAssist->acquisList.list.count; + if (count < 0 || count > MAX_EPHEMERIS - assist->cnt_acq || + (count > 0 && !hdr->acquisAssist->acquisList.list.array)) + { + return E_SUPL_DECODE_RRLP; + } + for (n = 0; n < count; n++) + { + if (!hdr->acquisAssist->acquisList.list.array[n]) + { + return E_SUPL_DECODE_RRLP; + } + } + } + if (hdr->almanac) + { + int n; + int count = hdr->almanac->almanacList.list.count; + if (count < 0 || count > MAX_EPHEMERIS - assist->cnt_alm || + (count > 0 && !hdr->almanac->almanacList.list.array)) + { + return E_SUPL_DECODE_RRLP; + } + for (n = 0; n < count; n++) + { + if (!hdr->almanac->almanacList.list.array[n]) + { + return E_SUPL_DECODE_RRLP; + } + } + } + if (hdr->navigationModel) + { + int n; + int count = hdr->navigationModel->navModelList.list.count; + if (count < 0 || count > MAX_EPHEMERIS - assist->cnt_eph || + (count > 0 && !hdr->navigationModel->navModelList.list.array)) + { + return E_SUPL_DECODE_RRLP; + } + for (n = 0; n < count; n++) + { + if (!hdr->navigationModel->navModelList.list.array[n]) + { + return E_SUPL_DECODE_RRLP; + } + } + } + if (hdr->referenceTime) { assist->set |= SUPL_RRLP_ASSIST_REFTIME; @@ -683,7 +780,7 @@ int EXPORT supl_collect_rrlp(supl_assist_t *assist, PDU_t *rrlp, struct timeval OCTET_STRING_t *loc; loc = &hdr->refLocation->threeDLocation; - if (loc->size == 14 && loc->buf[0] == 0x90) + if (loc->size == 14 && loc->buf && loc->buf[0] == 0x90) { double lat; double lon; @@ -885,6 +982,7 @@ int EXPORT supl_collect_rrlp(supl_assist_t *assist, PDU_t *rrlp, struct timeval int EXPORT supl_ctx_new(supl_ctx_t *ctx) { memset(ctx, 0, sizeof(supl_ctx_t)); + ctx->fd = -1; #ifdef SUPL_DEBUG memset(&debug, 0, sizeof(struct supl_debug_s)); #endif @@ -895,6 +993,7 @@ int EXPORT supl_ctx_new(supl_ctx_t *ctx) int EXPORT supl_ctx_free(supl_ctx_t *ctx) { + supl_close(ctx); if (ctx->slp_session_id.buf) { free(ctx->slp_session_id.buf); @@ -918,141 +1017,105 @@ static int supl_more_rrlp(PDU_t *rrlp) int EXPORT supl_get_assist(supl_ctx_t *ctx, char *server, supl_assist_t *assist) { - supl_ulp_t ulp; + supl_ulp_t ulp = {0}; + PDU_t *rrlp = 0; + int err; - // memcpy(ctx->p.msisdn, "\xde\xad\xbe\xef\xf0\x0b\xaa\x42", 8); + memset(assist, 0, sizeof(*assist)); memcpy(ctx->p.msisdn, "\xFF\xFF\x91\x94\x48\x45\x83\x98", 8); - - /* - ** connect to server - */ - - if (supl_server_connect(ctx, server) < 0) + err = supl_server_connect(ctx, server); + if (err < 0) { - return E_SUPL_CONNECT; + goto done; } - - /* - ** send SUPL_START - */ - if (pdu_make_ulp_start(ctx, &ulp) < 0) { - return E_SUPL_ENCODE_START; + ulp.pdu = 0; /* The encoder frees failed messages. */ + err = E_SUPL_ENCODE_START; + goto done; } - - (void)supl_ulp_send(ctx, &ulp); + err = supl_ulp_send(ctx, &ulp); supl_ulp_free(&ulp); - - /* - ** should receive SUPL_RESPONSE back - */ - - if (supl_ulp_recv(ctx, &ulp) < 0) + if (err < 0) { - return E_SUPL_RECV_RESPONSE; + goto done; } - - if (ulp.pdu->message.present != UlpMessage_PR_msSUPLRESPONSE) + err = supl_ulp_recv(ctx, &ulp); + if (err < 0) { - supl_ulp_free(&ulp); - return E_SUPL_SUPLRESPONSE; + goto done; + } + if (ulp.pdu->message.present != UlpMessage_PR_msSUPLRESPONSE || + supl_response_harvest(ctx, &ulp) < 0) + { + err = E_SUPL_SUPLRESPONSE; + goto done; } - - // get and copy slpSessionID if present - supl_response_harvest(ctx, &ulp); - supl_ulp_free(&ulp); - - /* - ** send SUPL_POS_INIT - */ - if (pdu_make_ulp_pos_init(ctx, &ulp) < 0) { - return E_SUPL_ENCODE_POSINIT; + ulp.pdu = 0; + err = E_SUPL_ENCODE_POSINIT; + goto done; + } + err = supl_ulp_send(ctx, &ulp); + supl_ulp_free(&ulp); + if (err < 0) + { + goto done; } - - (void)supl_ulp_send(ctx, &ulp); - - /* - ** should get SUPLPOS back - bounce back and forth until all messages have arrived - */ - - memset(assist, 0, sizeof(supl_assist_t)); - while (1) { struct timeval t; - PDU_t *rrlp; - - supl_ulp_free(&ulp); - - /* record packet recv time */ gettimeofday(&t, 0); - - if (supl_ulp_recv(ctx, &ulp) < 0) + err = supl_ulp_recv(ctx, &ulp); + if (err < 0) { - return E_SUPL_RECV_SUPLPOS; + goto done; } - if (ulp.pdu->message.present == UlpMessage_PR_msSUPLEND) { break; } - - if (ulp.pdu->message.present != UlpMessage_PR_msSUPLPOS) + err = supl_decode_rrlp(&ulp, &rrlp); + if (err < 0) { - supl_ulp_free(&ulp); - return E_SUPL_SUPLPOS; + goto done; } - - /* get the beef, the RRLP payload */ - - if (supl_decode_rrlp(&ulp, &rrlp) < 0) + supl_ulp_free(&ulp); + err = supl_collect_rrlp(assist, rrlp, &t); + if (err < 0) { - supl_ulp_free(&ulp); - return E_SUPL_DECODE_RRLP; + goto done; } - -#ifdef SUPL_DEBUG - if (debug.verbose_rrlp) - { - fprintf(debug.log, "Embedded RRLP message\n"); - xer_fprint(debug.log, &asn_DEF_PDU, rrlp); - } -#endif - - /* remember important stuff from it */ - - supl_collect_rrlp(assist, rrlp, &t); - if (!supl_more_rrlp(rrlp)) { - asn_DEF_ULP_PDU.free_struct(&asn_DEF_PDU, rrlp, 0); break; } - - /* More data coming in, send SUPLPOS + RRLP ACK */ - - if (pdu_make_ulp_rrlp_ack(ctx, &ulp, rrlp) < 0) + err = pdu_make_ulp_rrlp_ack(ctx, &ulp, rrlp); + if (err < 0) { - return E_SUPL_RRLP_ACK; + goto done; + } + ASN_STRUCT_FREE(asn_DEF_PDU, rrlp); + rrlp = 0; + err = supl_ulp_send(ctx, &ulp); + supl_ulp_free(&ulp); + if (err < 0) + { + goto done; } - - supl_ulp_send(ctx, &ulp); - asn_DEF_ULP_PDU.free_struct(&asn_DEF_PDU, rrlp, 0); } - + err = 0; +done: + ASN_STRUCT_FREE(asn_DEF_PDU, rrlp); supl_ulp_free(&ulp); - - /* - ** send SUPL_END (but who really cares) - */ - - supl_close(ctx); - - return 0; + supl_ctx_free(ctx); + if (err < 0) + { + memset(assist, 0, sizeof(*assist)); + } + return err; } diff --git a/src/core/libs/supl/supl.h b/src/core/libs/supl/supl.h index 8c9bef533..195de6ef8 100644 --- a/src/core/libs/supl/supl.h +++ b/src/core/libs/supl/supl.h @@ -235,7 +235,7 @@ typedef struct supl_ctx_s { supl_param_t p; - int fd; + int fd; /* -1 until connected; initialized by supl_ctx_new(). */ SSL *ssl; SSL_CTX *ssl_ctx; @@ -285,6 +285,7 @@ int supl_ulp_decode(supl_ulp_t *pdu); int supl_decode_rrlp(supl_ulp_t *pdu, PDU_t **rrlp); int supl_collect_rrlp(supl_assist_t *assist, PDU_t *rrlp, struct timeval *t); +/* server is required for certificate identity verification, even with an existing fd. */ int supl_server_connect(supl_ctx_t *ctx, char *server); void supl_close(supl_ctx_t *ctx); int supl_ulp_send(supl_ctx_t *ctx, supl_ulp_t *pdu); From 7d4f65d863e97d9979b32ca9e8233758d817e141 Mon Sep 17 00:00:00 2001 From: Carles Fernandez Date: Mon, 26 Oct 2026 08:21:51 +0100 Subject: [PATCH 04/11] Add a deterministic processing mode for recorded signals Add a deterministic processing mode for recorded signals Processing the same file twice was not repeatable, even with Acquisition_XX.blocking=true: the control thread started searches, assigned satellites and applied channel events at whatever sample each block had reached, and the PVT and observables applied each other's messages whenever they arrived. With GNSS-SDR.deterministic=true (default: false), events and messages carry the sample at which they happened, the control thread handles channel events in sample order, and their effects take place a fixed lookahead later (deterministic_lookahead_ms, default 100 ms). A gate at the Signal Conditioner output keeps the stream within that horizon, blocks take their stamped messages at the start of each work call, maintenance runs on signal time (deterministic_tick_ms), and the receiver stops once the whole input has reached the PVT. Dumps, RINEX, NMEA, KML, GPX and GeoJSON outputs are then bit-identical from run to run on the same machine (same FFTW wisdom and VOLK configuration), whatever the CPU load. Supported: all file sources (throttled or not, including LabSat, EVK1029 and ION), all acquisitions except assisted and FPGA, and the DLL/PLL VEML, KF and Gaussian trackers. Live front ends, HAS and NTRIP corrections, strict OSNMA, Galileo E6 with the TOW map, GNSS assistance and visibility-aware search are refused. --- docs/CHANGELOG.md | 76 ++++ .../PVT/gnuradio_blocks/rtklib_pvt_gs.cc | 89 ++++- .../PVT/gnuradio_blocks/rtklib_pvt_gs.h | 16 + .../adapters/pcps_acquisition_adapter.cc | 7 + .../adapters/pcps_acquisition_adapter.h | 6 + .../pcps_acquisition_adapter_custom.cc | 18 +- ...o_e5a_noncoherent_iq_acquisition_caf_cc.cc | 52 ++- ...eo_e5a_noncoherent_iq_acquisition_caf_cc.h | 12 + .../galileo_pcps_8ms_acquisition_cc.cc | 51 ++- .../galileo_pcps_8ms_acquisition_cc.h | 12 + .../gnuradio_blocks/pcps_acquisition.cc | 78 +++- .../gnuradio_blocks/pcps_acquisition.h | 9 + .../pcps_acquisition_fine_doppler_cc.cc | 52 ++- .../pcps_acquisition_fine_doppler_cc.h | 12 + .../pcps_cccwsr_acquisition_cc.cc | 51 ++- .../pcps_cccwsr_acquisition_cc.h | 12 + .../pcps_opencl_acquisition_cc.cc | 215 +++++++---- .../pcps_opencl_acquisition_cc.h | 32 +- .../pcps_quicksync_acquisition_cc.cc | 50 ++- .../pcps_quicksync_acquisition_cc.h | 12 + .../pcps_tong_acquisition_cc.cc | 51 ++- .../pcps_tong_acquisition_cc.h | 12 + .../acquisition/libs/CMakeLists.txt | 7 +- .../libs/deterministic_acquisition.cc | 190 ++++++++++ .../libs/deterministic_acquisition.h | 141 +++++++ src/algorithms/channel/adapters/channel.cc | 11 + src/algorithms/channel/libs/channel_fsm.cc | 7 +- .../channel/libs/channel_msg_receiver_cc.cc | 57 +-- .../channel/libs/channel_msg_receiver_cc.h | 7 + .../gnuradio_blocks/CMakeLists.txt | 2 +- .../gnuradio_blocks/hybrid_observables_gs.cc | 282 ++++++++++++-- .../gnuradio_blocks/hybrid_observables_gs.h | 23 ++ .../adapters/evk1029_signal_source.h | 1 + .../signal_source/adapters/file_source_base.h | 1 + .../adapters/gss6450_file_signal_source.h | 1 + .../adapters/labsat_signal_source.h | 1 + .../multichannel_file_signal_source.h | 1 + .../gnuradio_blocks/evk1029_source.cc | 17 +- .../signal_source/gnuradio_blocks/ion_gsms.cc | 15 + .../gnuradio_blocks/labsat23_source.cc | 31 +- .../signal_source/libs/gnss_sdr_valve.cc | 7 +- .../signal_source/libs/ion_gsms_chunk_data.cc | 292 +++++++------- .../signal_source/libs/ion_gsms_chunk_data.h | 81 ++-- .../libs/ion_gsms_chunk_unpacking_ctx.h | 11 + .../gnuradio_blocks/CMakeLists.txt | 1 + .../beidou_b1c_telemetry_decoder_gs.cc | 11 +- .../beidou_b2a_telemetry_decoder_gs.cc | 5 +- .../beidou_dnav_telemetry_decoder_gs.cc | 11 +- .../galileo_telemetry_decoder_gs.cc | 39 +- .../galileo_telemetry_decoder_gs.h | 2 +- .../glonass_gnav_telemetry_decoder_gs.cc | 9 +- .../gps_l1_ca_telemetry_decoder_gs.cc | 44 ++- .../gps_l1_ca_telemetry_decoder_gs.h | 2 +- .../gps_l2c_telemetry_decoder_gs.cc | 22 +- .../gps_l5_telemetry_decoder_gs.cc | 28 +- .../sbas_l1_telemetry_decoder_gs.cc | 5 +- .../gnuradio_blocks/telemetry_message_stamp.h | 94 +++++ .../gnuradio_blocks/dll_pll_veml_tracking.cc | 62 ++- .../gnuradio_blocks/dll_pll_veml_tracking.h | 5 + .../gps_l1_ca_gaussian_tracking_cc.cc | 45 ++- .../gps_l1_ca_gaussian_tracking_cc.h | 4 + .../tracking/gnuradio_blocks/kf_tracking.cc | 55 ++- .../tracking/gnuradio_blocks/kf_tracking.h | 4 + src/algorithms/tracking/libs/CMakeLists.txt | 10 + .../tracking/libs/deterministic_tracking.cc | 249 ++++++++++++ .../tracking/libs/deterministic_tracking.h | 117 ++++++ src/core/interfaces/signal_source_interface.h | 8 + src/core/libs/CMakeLists.txt | 10 + src/core/libs/channel_event.cc | 9 +- src/core/libs/channel_event.h | 14 +- src/core/libs/horizon_gate.cc | 111 ++++++ src/core/libs/horizon_gate.h | 66 ++++ src/core/receiver/control_thread.cc | 140 ++++++- src/core/receiver/control_thread.h | 8 + src/core/receiver/gnss_flowgraph.cc | 263 ++++++++++++- src/core/receiver/gnss_flowgraph.h | 19 + src/core/system_parameters/CMakeLists.txt | 2 + .../system_parameters/deterministic_clock.cc | 295 +++++++++++++++ .../system_parameters/deterministic_clock.h | 250 ++++++++++++ tests/system-tests/position_test.cc | 12 +- .../deterministic_observables_test.cc | 129 +++++++ .../sources/ion_gsms_chunk_data_test.cc | 34 ++ .../deterministic_telemetry_fault_test.cc | 358 ++++++++++++++++++ tests/unit_tests_core.cc | 2 + .../ieee-access18/L2-access18.conf | 2 +- 85 files changed, 4219 insertions(+), 448 deletions(-) create mode 100644 src/algorithms/acquisition/libs/deterministic_acquisition.cc create mode 100644 src/algorithms/acquisition/libs/deterministic_acquisition.h create mode 100644 src/algorithms/telemetry_decoder/gnuradio_blocks/telemetry_message_stamp.h create mode 100644 src/algorithms/tracking/libs/deterministic_tracking.cc create mode 100644 src/algorithms/tracking/libs/deterministic_tracking.h create mode 100644 src/core/libs/horizon_gate.cc create mode 100644 src/core/libs/horizon_gate.h create mode 100644 src/core/system_parameters/deterministic_clock.cc create mode 100644 src/core/system_parameters/deterministic_clock.h create mode 100644 tests/unit-tests/signal-processing-blocks/observables/deterministic_observables_test.cc create mode 100644 tests/unit-tests/signal-processing-blocks/telemetry_decoder/deterministic_telemetry_fault_test.cc diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 567561d30..159fdc623 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -69,6 +69,16 @@ All notable changes to GNSS-SDR will be documented in this file. built with `-DENABLE_CUDA=ON`, `band_cuda=true` computes that band's filter on an NVIDIA GPU, falling back to the CPU if no device is available or a GPU call fails. Contributed by @joebre. +- `ION_GSMS_Signal_Source` resolves the decoding parameters of each stream once + instead of for every chunk, which removes string comparisons and memory + allocations from the per-sample path, and decodes one-byte chunks through a + 256-entry lookup table. The decoded samples are unchanged. A four-band 2-bit + capture at 53 Msps now runs about 15 times faster, as fast as with + `NTLab_File_Signal_Source`. The source also asks the scheduler for room for at + least one whole chunk cycle. Before, when it was offered less (for instance, + one item for complex streams, or fewer than the 20 samples of a 5-byte IFEN + chunk), it produced nothing and GNU Radio polled it again only after 250 ms, + which could stall a file replay for seconds. ### Improvements in Interoperability: @@ -81,6 +91,72 @@ All notable changes to GNSS-SDR will be documented in this file. multiple of 24 bytes). Also, `seconds_to_skip` no longer lands in the middle of a frame when channels have bandwidth dividers that are not powers of two. +### Improvements in Reliability: + +- Fixed a heap buffer overflow in `Galileo_E1_PCPS_8ms_Ambiguous_Acquisition`. + The block always correlates with two local replicas that span two code + periods, but its coherent integration time defaulted to one code period (4 + ms), so every local code load read and wrote 4 ms of samples beyond the end of + its buffers. This corrupted the heap and randomly crashed the receiver at + startup, during processing, or at exit. The coherent integration time of this + implementation is now always 8 ms. +- Fixed `GPS_L1_CA_PCPS_OpenCl_Acquisition` with more than one dwell + (`Acquisition_1C.max_dwells` greater than 1, or + `Acquisition_1C.bit_transition_flag=true`). The block read its second and + later dwells from input ports that do not exist, which crashed the receiver + right after the first search started. Also fixed races between the block and + the worker thread that processes its dwells: a new search could start while + the previous one was still being processed, and a stopped search could still + report a result. + +### Improvements in Reproducibility: + +- Added a deterministic processing mode for recorded signals + (`GNSS-SDR.deterministic=true`, default: `false`). Processing the same file + twice was not repeatable, even with `Acquisition_XX.blocking=true`: the + control thread started acquisitions, assigned satellites and applied channel + events at whatever sample each block had reached, and the observables and PVT + blocks applied each other's messages (navigation data, receiver clock + corrections) whenever they arrived. Thread timing then changed the + satellite-to-channel assignment, the first sample of every search and pull-in, + the epoch of the first fix, and the end of the outputs. In this mode, events + and messages carry the sample at which they happened, the control thread + handles channel events in sample order, and every action they cause takes + effect at a sample that depends only on those stamps. Channel actions take + effect a fixed lookahead later (`GNSS-SDR.deterministic_lookahead_ms`, + default: 100 ms), and a gate at the output of the Signal Conditioner keeps the + stream from running further ahead. Maintenance tasks run every + `GNSS-SDR.deterministic_tick_ms` (default: 100 ms) of signal instead of every + 100 ms of wall-clock time, and the receiver stops only when the whole input + has gone through the PVT. Tracking, telemetry, observables and PVT dumps, and + RINEX, NMEA, KML, GPX and GeoJSON files, are then bit-identical from run to + run (except for the creation time written in the RINEX, KML and GPX headers), + whatever the CPU load, with `Acquisition_XX.blocking` set to either value, as + long as the machine, its FFTW wisdom (GNU Radio plans its FFTs with + `FFTW_MEASURE`) and its VOLK configuration do not change. The mode supports + all the acquisition implementations except the assisted and FPGA ones; the + DLL/PLL VEML, KF and Gaussian tracking implementations; and the signal sources + that read files, throttled or not (including LabSat, EVK1029 and ION GNSS SDR + metadata recordings). It refuses radio front ends and network or named-pipe + (`Fifo_Signal_Source`) inputs, whose samples could be lost while the stream is + held back, FPGA offloading, visibility-aware search, GNSS assistance, an + explicit `GNSS-SDR.assist_dual_frequency_acq=true`, + `GNSS-SDR.osnma_mode=strict`, Galileo HAS corrections + (`PVT.use_has_corrections=true`, the default with Galileo E6 channels) and + NTRIP corrections (`PVT.ntrip_client_enabled=true`), whose effects the PVT + applies when the messages arrive, Galileo E6 channels together with Galileo + E1, E5a or E5b channels, whose time of week reaches the E6 telemetry decoders + when it arrives, `Acquisition_XX.blocking_on_standby=true`, a lookahead that + is not positive, a control tick below 1 ms, and lookaheads that leave the + observables block no margin (220 ms with the default + `GNSS-SDR.observable_interval_ms`). Multiband configurations do not use + dual-frequency acquisition assistance in this mode, and the receiver does not + stop channels that track a satellite already tracked in another channel, since + both decisions depend on the live tracking status. With + `GNSS-SDR.tow_to_trk=true`, the DLL/PLL VEML tracking blocks do not compute + the TOW and week number, since the telemetry messages would reach them at a + timing-dependent sample. + ### Improvements in Usability: - Fixed the Monitor (`Monitor.enable_monitor=true`) for channels without a valid diff --git a/src/algorithms/PVT/gnuradio_blocks/rtklib_pvt_gs.cc b/src/algorithms/PVT/gnuradio_blocks/rtklib_pvt_gs.cc index 62a2f8684..643b097c7 100644 --- a/src/algorithms/PVT/gnuradio_blocks/rtklib_pvt_gs.cc +++ b/src/algorithms/PVT/gnuradio_blocks/rtklib_pvt_gs.cc @@ -91,6 +91,7 @@ #include // for ofstream #include // for put_time, setprecision #include // for operator<< +#include // for make_move_iterator #include // for locale #include // for ostringstream #include // for length_error @@ -315,6 +316,9 @@ rtklib_pvt_gs::rtklib_pvt_gs(uint32_t nchannels, // Send PVT status to gnss_flowgraph this->message_port_register_out(pmt::mp("status")); + // Telemetry data and PVT messages carry sample stamps (GNSS-SDR.deterministic=true) + d_deterministic = DeterministicClock::instance().enabled(); + // GPS Ephemeris data message port in this->message_port_register_in(pmt::mp("telemetry")); this->set_msg_handler(pmt::mp("telemetry"), @@ -1502,6 +1506,20 @@ rtklib_pvt_gs::~rtklib_pvt_gs() void rtklib_pvt_gs::msg_handler_telemetry(const pmt::pmt_t& msg) { + if (d_deterministic && pmt::is_pair(msg) && pmt::is_pair(pmt::car(msg))) + { + // ((sample stamp . channel) . message), from a telemetry decoder + const pmt::pmt_t key = pmt::car(msg); + const uint64_t stamp = pmt::is_uint64(pmt::car(key)) ? pmt::to_uint64(pmt::car(key)) : NO_SAMPLE_STAMP; + if (stamp == NO_SAMPLE_STAMP) + { + LOG(WARNING) << "Telemetry message without a sample stamp in deterministic processing"; + msg_handler_telemetry(pmt::cdr(msg)); + return; + } + d_det_telemetry.push_back(StampedTelemetry{stamp, pmt::to_long(pmt::cdr(key)), pmt::cdr(msg)}); + return; + } apply_pending_navigation_clear(); try { @@ -2899,9 +2917,54 @@ void rtklib_pvt_gs::report_solution_outage() } +void rtklib_pvt_gs::apply_deterministic_telemetry(uint64_t epoch_sample) +{ + // Due messages in stamp order, then channel order. The messages of a + // channel keep the order in which its decoder sent them. + const auto due_end = std::stable_partition(d_det_telemetry.begin(), d_det_telemetry.end(), + [epoch_sample](const StampedTelemetry& m) { return m.stamp <= epoch_sample; }); + if (due_end == d_det_telemetry.begin()) + { + return; + } + std::vector due(std::make_move_iterator(d_det_telemetry.begin()), std::make_move_iterator(due_end)); + d_det_telemetry.erase(d_det_telemetry.begin(), due_end); + std::stable_sort(due.begin(), due.end(), [](const StampedTelemetry& a, const StampedTelemetry& b) { + return a.stamp != b.stamp ? a.stamp < b.stamp : a.channel < b.channel; + }); + for (const auto& m : due) + { + msg_handler_telemetry(m.msg); + } +} + + +pmt::pmt_t rtklib_pvt_gs::stamp_observables_message(const pmt::pmt_t& msg) const +{ + if (!d_deterministic || d_det_epoch_sample == NO_SAMPLE_STAMP) + { + return msg; + } + // The observables block applies it at a fixed delay after this epoch + return pmt::cons(pmt::from_uint64(d_det_epoch_sample), msg); +} + + int rtklib_pvt_gs::work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items __attribute__((unused))) { + if (d_deterministic) + { + // GNU Radio dispatches messages only between calls: take the + // navigation messages queued since then, which may be due at + // the epochs of this call + const pmt::pmt_t port = pmt::mp("telemetry"); + pmt::pmt_t msg; + while ((msg = delete_head_nowait(port))) + { + msg_handler_telemetry(msg); + } + } apply_pending_navigation_clear(); bool latest_pvt_updated = false; // *************** time tags **************** @@ -2937,6 +3000,19 @@ int rtklib_pvt_gs::work(int noutput_items, gr_vector_const_void_star& input_item this->get_tags_in_range(sensor_tags, 0, this->nitems_read(0), this->nitems_read(0) + noutput_items, d_sensor_data_aggregator->SENSOR_DATA_TAG); d_sensor_data_aggregator->update(sensor_tags); + // Sample stamps of the epochs, set by the observables block + std::vector epoch_samples; + if (d_deterministic) + { + epoch_samples.assign(noutput_items, NO_SAMPLE_STAMP); + std::vector epoch_tags; + this->get_tags_in_range(epoch_tags, 0, this->nitems_read(0), this->nitems_read(0) + noutput_items, pmt::mp("deterministic_epoch")); + for (const auto& tag : epoch_tags) + { + epoch_samples[tag.offset - this->nitems_read(0)] = pmt::to_uint64(tag.value); + } + } + for (int32_t epoch = 0; epoch < noutput_items; epoch++) { bool flag_display_pvt = false; @@ -2948,6 +3024,15 @@ int rtklib_pvt_gs::work(int noutput_items, gr_vector_const_void_star& input_item bool flag_write_RINEX_obs_output = false; d_local_counter_ms += static_cast(d_observable_interval_ms); + if (d_deterministic) + { + d_det_epoch_sample = epoch_samples[epoch]; + if (d_det_epoch_sample != NO_SAMPLE_STAMP) + { + apply_deterministic_telemetry(d_det_epoch_sample); + } + } + d_gnss_observables_map.clear(); const auto** in = reinterpret_cast(&input_items[0]); // Get the input buffer pointer // ############ 1. READ PSEUDORANGES #### @@ -3238,7 +3323,7 @@ int rtklib_pvt_gs::work(int noutput_items, gr_vector_const_void_star& input_item // check if the message was just sent to not duplicate it while it is being applied if ((d_local_counter_ms - d_timestamp_rx_clock_offset_correction_msg_ms) > 1000) { - this->message_port_pub(pmt::mp("pvt_to_observables"), pmt::make_any(Rx_clock_offset_s)); + this->message_port_pub(pmt::mp("pvt_to_observables"), stamp_observables_message(pmt::make_any(Rx_clock_offset_s))); d_timestamp_rx_clock_offset_correction_msg_ms = d_local_counter_ms; LOG(INFO) << "PVT: Sent clock offset correction to observables: " << Rx_clock_offset_s << "[s]"; } @@ -3333,7 +3418,7 @@ int rtklib_pvt_gs::work(int noutput_items, gr_vector_const_void_star& input_item if (d_pvt_solver_errors_counter == 100) { int command = 1; - this->message_port_pub(pmt::mp("pvt_to_observables"), pmt::make_any(command)); + this->message_port_pub(pmt::mp("pvt_to_observables"), stamp_observables_message(pmt::make_any(command))); LOG(INFO) << "PVT: Number of consecutive position solver error reached, Sent reset to observables."; } } diff --git a/src/algorithms/PVT/gnuradio_blocks/rtklib_pvt_gs.h b/src/algorithms/PVT/gnuradio_blocks/rtklib_pvt_gs.h index d9dc12e25..cc896acba 100644 --- a/src/algorithms/PVT/gnuradio_blocks/rtklib_pvt_gs.h +++ b/src/algorithms/PVT/gnuradio_blocks/rtklib_pvt_gs.h @@ -17,6 +17,7 @@ #ifndef GNSS_SDR_RTKLIB_PVT_GS_H #define GNSS_SDR_RTKLIB_PVT_GS_H +#include "deterministic_clock.h" #include "gnss_block_interface.h" #include "gnss_sdr_make_unique.h" #include "gnss_synchro.h" @@ -190,6 +191,17 @@ private: void msg_handler_telemetry(const pmt::pmt_t& msg); + // GNSS-SDR.deterministic=true: telemetry data stamped with the sample of + // the symbol that carried it, applied at the first epoch past that sample + struct StampedTelemetry + { + uint64_t stamp; + int64_t channel; + pmt::pmt_t msg; + }; + void apply_deterministic_telemetry(uint64_t epoch_sample); + pmt::pmt_t stamp_observables_message(const pmt::pmt_t& msg) const; + void msg_handler_has_data(const pmt::pmt_t& msg); void msg_handler_osnma(const pmt::pmt_t& msg); @@ -410,6 +422,10 @@ private: const bool d_use_has_corrections; const bool d_use_unhealthy_sats; const bool d_osnma_strict; + + std::vector d_det_telemetry; + uint64_t d_det_epoch_sample{NO_SAMPLE_STAMP}; + bool d_deterministic{false}; }; diff --git a/src/algorithms/acquisition/adapters/pcps_acquisition_adapter.cc b/src/algorithms/acquisition/adapters/pcps_acquisition_adapter.cc index 72091ccf8..5cd366ae6 100644 --- a/src/algorithms/acquisition/adapters/pcps_acquisition_adapter.cc +++ b/src/algorithms/acquisition/adapters/pcps_acquisition_adapter.cc @@ -49,6 +49,7 @@ #include "qzss_signal_replica.h" #include "sbas_signal_replica.h" #include "signal_flag.h" +#include #if USE_GLOG_AND_GFLAGS #include @@ -404,6 +405,12 @@ void PcpsAcquisitionAdapter::set_resampler_latency(uint32_t latency_samples) } +unsigned int PcpsAcquisitionAdapter::resampler_decimation() const +{ + return acq_parameters_.use_automatic_resampler ? static_cast(std::lround(acq_parameters_.resampler_ratio)) : 1U; +} + + void PcpsAcquisitionAdapter::set_local_code() { volk_gnsssdr::vector> code(acq_parameters_.code_length); diff --git a/src/algorithms/acquisition/adapters/pcps_acquisition_adapter.h b/src/algorithms/acquisition/adapters/pcps_acquisition_adapter.h index 4d228c9c7..81542ab5a 100644 --- a/src/algorithms/acquisition/adapters/pcps_acquisition_adapter.h +++ b/src/algorithms/acquisition/adapters/pcps_acquisition_adapter.h @@ -128,6 +128,12 @@ public: */ void set_resampler_latency(uint32_t latency_samples) override; + /*! + * \brief Decimation of the stream that the acquisition expects to read: + * the resampler ratio with GNSS-SDR.use_acquisition_resampler=true, else 1 + */ + unsigned int resampler_decimation() const; + /*! * \brief Sets local code */ diff --git a/src/algorithms/acquisition/adapters/pcps_acquisition_adapter_custom.cc b/src/algorithms/acquisition/adapters/pcps_acquisition_adapter_custom.cc index 9652307f4..836a37095 100644 --- a/src/algorithms/acquisition/adapters/pcps_acquisition_adapter_custom.cc +++ b/src/algorithms/acquisition/adapters/pcps_acquisition_adapter_custom.cc @@ -181,6 +181,7 @@ Acq_Conf get_acq_conf( std::unique_ptr threshold_compute; boost::optional default_folding_factor; + boost::optional required_sampled_ms; uint32_t max_sampled_ms = std::numeric_limits::max(); if (implementation == "GPS_L1_CA_PCPS_QuickSync_Acquisition") @@ -209,6 +210,12 @@ Acq_Conf get_acq_conf( max_sampled_ms = 3; } } + else if (implementation == "Galileo_E1_PCPS_8ms_Ambiguous_Acquisition") + { + // The block correlates with two local replicas spanning two code + // periods (++ and +-), so its input must be exactly 8 ms long + required_sampled_ms = 2 * ms_per_code; + } if (default_folding_factor) { @@ -228,8 +235,8 @@ Acq_Conf get_acq_conf( } acq_parameters.ms_per_code = ms_per_code; - acq_parameters.sampled_ms = ms_per_code; // Set as default value - acq_parameters.dump_filename = default_dump_filename; // Set as default value + acq_parameters.sampled_ms = required_sampled_ms ? *required_sampled_ms : ms_per_code; // Set as default value + acq_parameters.dump_filename = default_dump_filename; // Set as default value acq_parameters.SetFromConfiguration(configuration, role, chip_rate, opt_freq); #if USE_GLOG_AND_GFLAGS @@ -259,6 +266,13 @@ Acq_Conf get_acq_conf( std::cout << "Too high coherent integration time. Changing to " << max_sampled_ms << "ms\n"; } + if (required_sampled_ms && acq_parameters.sampled_ms != *required_sampled_ms) + { + LOG(WARNING) << implementation << " requires " << role << ".coherent_integration_time_ms=" + << *required_sampled_ms << ". Changing to " << *required_sampled_ms << " ms"; + acq_parameters.sampled_ms = *required_sampled_ms; + } + acq_parameters.num_codes = acq_parameters.sampled_ms / ms_per_code; acq_parameters.code_length = static_cast(round(acq_parameters.fs_in / (chip_rate / code_length_chips))); acq_parameters.vector_length = acq_parameters.code_length * acq_parameters.num_codes; diff --git a/src/algorithms/acquisition/gnuradio_blocks/galileo_e5a_noncoherent_iq_acquisition_caf_cc.cc b/src/algorithms/acquisition/gnuradio_blocks/galileo_e5a_noncoherent_iq_acquisition_caf_cc.cc index f2b9eef45..b68b2e585 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/galileo_e5a_noncoherent_iq_acquisition_caf_cc.cc +++ b/src/algorithms/acquisition/gnuradio_blocks/galileo_e5a_noncoherent_iq_acquisition_caf_cc.cc @@ -82,6 +82,9 @@ galileo_e5a_noncoherentIQ_acquisition_caf_cc::galileo_e5a_noncoherentIQ_acquisit d_inbuffer(d_fft_size), d_magnitudeIA(d_fft_size) { + // A search needs its dwells beyond its first sample (GNSS-SDR.deterministic=true) + d_det.require_span(static_cast(d_fft_size) * (std::max(1U, d_acq_params.max_dwells) + 1)); + this->message_port_register_out(pmt::mp("events")); if (Zero_padding > 0) @@ -232,7 +235,24 @@ void galileo_e5a_noncoherentIQ_acquisition_caf_cc::set_local_code(std::complexmessage_port_pub(pmt::mp("events"), pmt::from_long(event)); }); + d_det.publish(d_sample_counter, d_active, d_channel); + } + return produced; +} + + +int galileo_e5a_noncoherentIQ_acquisition_caf_cc::process_input(int noutput_items __attribute__((unused)), gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @@ -264,6 +284,18 @@ int galileo_e5a_noncoherentIQ_acquisition_caf_cc::general_work(int noutput_items * 3 Positive acquisition * 4 Negative acquisition */ + if (d_det.enabled() && d_state == 0) + { + // GNSS-SDR.deterministic=true: the search starts at its stamped sample + int n_items = 0; + if (!d_det.ready_to_start(d_sample_counter, 0, 1, ninput_items[0], n_items, d_channel)) + { + d_sample_counter += static_cast(1) * static_cast(n_items); + consume_each(n_items); + return 0; + } + } + switch (d_state) { case 0: @@ -676,7 +708,14 @@ int galileo_e5a_noncoherentIQ_acquisition_caf_cc::general_work(int noutput_items d_state = 0; acquisition_message = 1; - this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + if (d_det.enabled()) + { + d_det.raise(acquisition_message); + } + else + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + } d_sample_counter += static_cast(ninput_items[0]); // sample counter consume_each(ninput_items[0]); LOG(INFO) << "Successful acquisition in channel " << d_channel @@ -713,7 +752,14 @@ int galileo_e5a_noncoherentIQ_acquisition_caf_cc::general_work(int noutput_items d_sample_counter += static_cast(ninput_items[0]); // sample counter consume_each(ninput_items[0]); acquisition_message = 2; - this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + if (d_det.enabled()) + { + d_det.raise(acquisition_message); + } + else + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + } break; } } diff --git a/src/algorithms/acquisition/gnuradio_blocks/galileo_e5a_noncoherent_iq_acquisition_caf_cc.h b/src/algorithms/acquisition/gnuradio_blocks/galileo_e5a_noncoherent_iq_acquisition_caf_cc.h index 536d8ebe6..a418d9cc4 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/galileo_e5a_noncoherent_iq_acquisition_caf_cc.h +++ b/src/algorithms/acquisition/gnuradio_blocks/galileo_e5a_noncoherent_iq_acquisition_caf_cc.h @@ -27,6 +27,7 @@ #include "acq_conf.h" #include "acquisition_impl_interface.h" #include "channel_fsm.h" +#include "deterministic_acquisition.h" #include "gnss_sdr_fft.h" #include "gnss_synchro.h" #include @@ -103,6 +104,13 @@ public: d_state = 0; } + if (active) + { + // GNSS-SDR.deterministic=true: a lookahead after the event that + // caused it. Before d_active, so that general_work() never sees + // an active search without its stamped start + d_det.activate(d_sample_counter, d_channel); + } d_active = active; } @@ -131,6 +139,9 @@ public: gr_vector_void_star& output_items) override; private: + int process_input(int noutput_items, gr_vector_int& ninput_items, + gr_vector_const_void_star& input_items, + gr_vector_void_star& output_items); friend galileo_e5a_noncoherentIQ_acquisition_caf_cc_sptr galileo_e5a_noncoherentIQ_make_acquisition_caf_cc( const Acq_Conf& conf, @@ -175,6 +186,7 @@ private: unsigned int d_code_phase; bool d_active; + DeterministicAcquisition d_det; // GNSS-SDR.deterministic=true const bool d_both_signal_components; std::weak_ptr d_channel_fsm; diff --git a/src/algorithms/acquisition/gnuradio_blocks/galileo_pcps_8ms_acquisition_cc.cc b/src/algorithms/acquisition/gnuradio_blocks/galileo_pcps_8ms_acquisition_cc.cc index 0788336bd..ecf45552c 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/galileo_pcps_8ms_acquisition_cc.cc +++ b/src/algorithms/acquisition/gnuradio_blocks/galileo_pcps_8ms_acquisition_cc.cc @@ -60,6 +60,9 @@ galileo_pcps_8ms_acquisition_cc::galileo_pcps_8ms_acquisition_cc(const Acq_Conf d_fft_code_B(d_fft_size, lv_cmake(0.0F, 0.0F)), d_magnitude(d_fft_size, 0.0F) { + // A search needs its dwells beyond its first sample (GNSS-SDR.deterministic=true) + d_det.require_span(static_cast(d_fft_size) * std::max(1U, d_acq_params.max_dwells)); + this->message_port_register_out(pmt::mp("events")); // Count the number of bins @@ -132,6 +135,23 @@ void galileo_pcps_8ms_acquisition_cc::set_local_code(std::complex *code) int galileo_pcps_8ms_acquisition_cc::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) +{ + d_det.begin_call(d_sample_counter); + const int produced = process_input(noutput_items, ninput_items, input_items, output_items); + if (d_det.enabled()) + { + // GNSS-SDR.deterministic=true: results reach the control queue + // before the progress passes their stamp + d_det.dispatch(d_channel, [this](int event) { this->message_port_pub(pmt::mp("events"), pmt::from_long(event)); }); + d_det.publish(d_sample_counter, d_active, d_channel); + } + return produced; +} + + +int galileo_pcps_8ms_acquisition_cc::process_input(int noutput_items, + gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items) { int32_t acquisition_message = -1; // 0=STOP_CHANNEL 1=ACQ_SUCCEES 2=ACQ_FAIL @@ -142,6 +162,18 @@ int galileo_pcps_8ms_acquisition_cc::general_work(int noutput_items, return 0; } + if (d_det.enabled() && d_state == 0) + { + // GNSS-SDR.deterministic=true: the search starts at its stamped sample + int n_items = 0; + if (!d_det.ready_to_start(d_sample_counter, 0, d_fft_size, ninput_items[0], n_items, d_channel)) + { + d_sample_counter += static_cast(d_fft_size) * static_cast(n_items); + consume_each(n_items); + return 0; + } + } + switch (d_state) { case 0: @@ -310,7 +342,14 @@ int galileo_pcps_8ms_acquisition_cc::general_work(int noutput_items, consume_each(ninput_items[0]); acquisition_message = 1; - this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + if (d_det.enabled()) + { + d_det.raise(acquisition_message); + } + else + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + } LOG(INFO) << "Successful acquisition in channel " << d_channel << " for satellite " << d_gnss_synchro->System << " " << d_gnss_synchro->PRN; @@ -347,8 +386,14 @@ int galileo_pcps_8ms_acquisition_cc::general_work(int noutput_items, consume_each(ninput_items[0]); acquisition_message = 2; - this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); - + if (d_det.enabled()) + { + d_det.raise(acquisition_message); + } + else + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + } break; } } diff --git a/src/algorithms/acquisition/gnuradio_blocks/galileo_pcps_8ms_acquisition_cc.h b/src/algorithms/acquisition/gnuradio_blocks/galileo_pcps_8ms_acquisition_cc.h index d9dba2465..4304a4384 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/galileo_pcps_8ms_acquisition_cc.h +++ b/src/algorithms/acquisition/gnuradio_blocks/galileo_pcps_8ms_acquisition_cc.h @@ -21,6 +21,7 @@ #include "acq_conf.h" #include "acquisition_impl_interface.h" #include "channel_fsm.h" +#include "deterministic_acquisition.h" #include "gnss_sdr_fft.h" #include "gnss_synchro.h" #include @@ -92,6 +93,13 @@ public: d_state = 0; } + if (active) + { + // GNSS-SDR.deterministic=true: a lookahead after the event that + // caused it. Before d_active, so that general_work() never sees + // an active search without its stamped start + d_det.activate(d_sample_counter, d_channel); + } d_active = active; } @@ -120,6 +128,9 @@ public: gr_vector_void_star& output_items) override; private: + int process_input(int noutput_items, gr_vector_int& ninput_items, + gr_vector_const_void_star& input_items, + gr_vector_void_star& output_items); friend galileo_pcps_8ms_acquisition_cc_sptr galileo_pcps_8ms_make_acquisition_cc(const Acq_Conf& conf); @@ -149,6 +160,7 @@ private: uint32_t d_code_phase; bool d_active; + DeterministicAcquisition d_det; // GNSS-SDR.deterministic=true std::weak_ptr d_channel_fsm; std::unique_ptr d_fft_if; diff --git a/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition.cc b/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition.cc index 9e187adc0..2da0c6783 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition.cc +++ b/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition.cc @@ -255,6 +255,15 @@ pcps_acquisition::pcps_acquisition(const Acq_Conf& conf_) // allocated when a search starts (see general_work()). set_history(d_data_buffer_size - d_samples_to_consume + 1); } + + // A search needs its window beyond its progress (GNSS-SDR.deterministic=true). + // Blocking searches publish progress at every dwell. With the acquisition + // resampler, sample counts are at the decimated rate, as in update_synchro(). + if (d_acq_parameters.use_automatic_resampler) + { + d_det.set_decimation(static_cast(std::lround(d_acq_parameters.resampler_ratio))); + } + d_det.require_span((d_data_buffer_size != 0 ? d_data_buffer_size : d_samples_to_consume) + 1); } @@ -355,6 +364,11 @@ void pcps_acquisition::set_active(bool active) { worker_cv.notify_one(); } + else + { + // GNSS-SDR.deterministic=true: a lookahead after the event that caused it + d_det.activate(d_sample_count, d_channel); + } } if (!active) @@ -524,6 +538,7 @@ void pcps_acquisition::send_positive_acquisition(const AcquisitionResult& result if (!d_channel_fsm.expired()) { // the channel FSM is set, so, notify it directly the positive acquisition to minimize delays + const DeterministicClock::Scope cause(d_det.clock_sample(result.sample_count)); d_channel_fsm.lock()->Event_valid_acquisition(); } else @@ -547,6 +562,13 @@ void pcps_acquisition::send_negative_acquisition(const AcquisitionResult& result { log_acquisition(result); + if (d_det.enabled()) + { + // Applied by dispatch_deterministic_events(), without the lock held + d_det.raise(DeterministicClock::ACQ_NEGATIVE, result.sample_count); + return; + } + // Declare negative acquisition using a message port // 0=STOP_CHANNEL 1=ACQ_SUCCEES 2=ACQ_FAIL this->message_port_pub(pmt::mp("events"), pmt::from_long(2)); @@ -1175,6 +1197,36 @@ void pcps_acquisition::acquisition_core(uint64_t sample_count) } +void pcps_acquisition::acquisition_worker(uint64_t sample_count) +{ + acquisition_core(sample_count); + dispatch_deterministic_events(); +} + + +bool pcps_acquisition::align_to_deterministic_start(int available_items) +{ + // The window starts at the oldest item of the input buffer + int n_consume = 0; + const int new_items = std::max(available_items - static_cast(history() - 1), 0); + if (d_det.ready_to_start(d_sample_count, history() - 1, 1, new_items, n_consume, d_channel)) + { + return false; + } + d_sample_count += static_cast(n_consume); + consume_each(n_consume); + // The search starts at a later call, with its first sample in front + return true; +} + + +void pcps_acquisition::dispatch_deterministic_events() +{ + // A repeated search restarts this block, which takes the lock + d_det.dispatch(d_channel, [this](int event) { this->message_port_pub(pmt::mp("events"), pmt::from_long(event)); }); +} + + float pcps_acquisition::get_threshold() const { return d_step_two ? d_threshold_step_two : d_threshold_active; @@ -1247,7 +1299,23 @@ void pcps_acquisition::wait_if_active() } -int pcps_acquisition::general_work(int noutput_items __attribute__((unused)), +int pcps_acquisition::general_work(int noutput_items, + gr_vector_int& ninput_items, + gr_vector_const_void_star& input_items, + gr_vector_void_star& output_items) +{ + const int produced = process_input(noutput_items, ninput_items, input_items, output_items); + if (d_det.enabled()) + { + dispatch_deterministic_events(); + gr::thread::scoped_lock lock(d_setlock); + d_det.publish(d_sample_count, d_active, d_channel); + } + return produced; +} + + +int pcps_acquisition::process_input(int noutput_items __attribute__((unused)), gr_vector_int& ninput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items) @@ -1277,6 +1345,11 @@ int pcps_acquisition::general_work(int noutput_items __attribute__((unused)), return 0; } + if (d_det.enabled() && d_state == 0 && align_to_deterministic_start(ninput_items[0])) + { + return 0; + } + // New non-coherent integration started if (d_state == 0) { @@ -1343,6 +1416,7 @@ int pcps_acquisition::general_work(int noutput_items __attribute__((unused)), // stamp is a dwell boundary and never ahead of the consumed samples. const uint64_t window_start = d_sample_count + input_offset - (history() - 1); window_stamp = window_start + (input_offset ? d_samples_to_consume : buffer_size); + d_det.begin_window(window_start); // Consume the dwell that completes the window (all new samples while the // history is not full yet); later samples are consumed while the worker runs. auto n_consume = input_offset ? new_samples : d_samples_to_consume; @@ -1421,7 +1495,7 @@ int pcps_acquisition::general_work(int noutput_items __attribute__((unused)), // set_active(false) may have dropped this search while we waited if (d_active && d_state == 3) { - d_worker = std::make_unique(&pcps_acquisition::acquisition_core, this, window_stamp); + d_worker = std::make_unique(&pcps_acquisition::acquisition_worker, this, window_stamp); if (d_buffer_sample_count >= d_data_buffer_size) { d_worker_active = true; diff --git a/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition.h b/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition.h index 6bc9a43ce..89710e836 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition.h +++ b/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition.h @@ -45,6 +45,7 @@ #include "acq_conf.h" #include "channel_fsm.h" +#include "deterministic_acquisition.h" #include "gnss_sdr_fft.h" #if CUDA_GPU_ACCEL #include "cuda_pcps_engine.h" @@ -227,6 +228,12 @@ private: void refine_doppler(AcquisitionResult& result); void handle_integration_done(const AcquisitionResult& result); void acquisition_core(uint64_t sample_count); + void acquisition_worker(uint64_t sample_count); + int process_input(int noutput_items, gr_vector_int& ninput_items, + gr_vector_const_void_star& input_items, gr_vector_void_star& output_items); + // GNSS-SDR.deterministic=true: start a search exactly at its stamped sample + bool align_to_deterministic_start(int available_items); + void dispatch_deterministic_events(); void log_acquisition(const AcquisitionResult& result) const; void send_negative_acquisition(const AcquisitionResult& result); void send_positive_acquisition(const AcquisitionResult& result); @@ -311,6 +318,8 @@ private: bool d_step_two; bool d_active; bool d_worker_active; + // GNSS-SDR.deterministic=true + DeterministicAcquisition d_det; // Only access these in acquisition_core and functions strictly called from acquisition_core uint32_t d_num_noncoherent_integrations_counter; diff --git a/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition_fine_doppler_cc.cc b/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition_fine_doppler_cc.cc index 6636b07c7..dedf90530 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition_fine_doppler_cc.cc +++ b/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition_fine_doppler_cc.cc @@ -78,6 +78,9 @@ pcps_acquisition_fine_doppler_cc::pcps_acquisition_fine_doppler_cc(const Acq_Con d_fine_doppler_magnitude(d_fine_doppler_fft_size), d_fine_doppler_freq_bins(d_fine_doppler_fft_size) { + // A search needs its dwells beyond its first sample (GNSS-SDR.deterministic=true) + d_det.require_span(static_cast(d_fft_size) * std::max(1U, d_acq_params.max_dwells) + 10 * static_cast(d_acq_params.samples_per_ms)); + this->message_port_register_out(pmt::mp("events")); update_carrier_wipeoff(); @@ -393,7 +396,24 @@ bool pcps_acquisition_fine_doppler_cc::start() } -int pcps_acquisition_fine_doppler_cc::general_work(int noutput_items __attribute__((unused)), +int pcps_acquisition_fine_doppler_cc::general_work(int noutput_items, + gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items) +{ + d_det.begin_call(d_sample_counter); + const int produced = process_input(noutput_items, ninput_items, input_items, output_items); + if (d_det.enabled()) + { + // GNSS-SDR.deterministic=true: results reach the control queue + // before the progress passes their stamp + d_det.dispatch(d_channel, [this](int event) { this->message_port_pub(pmt::mp("events"), pmt::from_long(event)); }); + d_det.publish(d_sample_counter, d_active, d_channel); + } + return produced; +} + + +int pcps_acquisition_fine_doppler_cc::process_input(int noutput_items __attribute__((unused)), gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @@ -422,6 +442,18 @@ int pcps_acquisition_fine_doppler_cc::general_work(int noutput_items __attribute return 0; } + if (d_det.enabled() && d_state == 0) + { + // GNSS-SDR.deterministic=true: the search starts at its stamped sample + int n_items = 0; + if (!d_det.ready_to_start(d_sample_counter, 0, 1, ninput_items[0], n_items, d_channel)) + { + d_sample_counter += static_cast(1) * static_cast(n_items); + consume_each(n_items); + return 0; + } + } + switch (d_state) { case 0: // S0. StandBy @@ -499,7 +531,14 @@ int pcps_acquisition_fine_doppler_cc::general_work(int noutput_items __attribute dump_results(d_fft_size); } // Send message to channel port //0=STOP_CHANNEL 1=ACQ_SUCCEES 2=ACQ_FAIL - this->message_port_pub(pmt::mp("events"), pmt::from_long(1)); + if (d_det.enabled()) + { + d_det.raise(1); + } + else + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(1)); + } LOG(INFO) << "Successful acquisition in channel " << d_channel << " for satellite " << d_gnss_synchro->System << " " << d_gnss_synchro->PRN; d_state = 0; @@ -534,7 +573,14 @@ int pcps_acquisition_fine_doppler_cc::general_work(int noutput_items __attribute dump_results(d_fft_size); } // Send message to channel port //0=STOP_CHANNEL 1=ACQ_SUCCEES 2=ACQ_FAIL - this->message_port_pub(pmt::mp("events"), pmt::from_long(2)); + if (d_det.enabled()) + { + d_det.raise(2); + } + else + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(2)); + } d_state = 0; if (!d_acq_params.blocking_on_standby) { diff --git a/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition_fine_doppler_cc.h b/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition_fine_doppler_cc.h index 09c26c004..61b77ce89 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition_fine_doppler_cc.h +++ b/src/algorithms/acquisition/gnuradio_blocks/pcps_acquisition_fine_doppler_cc.h @@ -42,6 +42,7 @@ #include "acq_conf.h" #include "channel_fsm.h" +#include "deterministic_acquisition.h" #include "gnss_sdr_fft.h" #include "gnss_synchro.h" #include @@ -115,6 +116,13 @@ public: d_state = 0; } + if (active) + { + // GNSS-SDR.deterministic=true: a lookahead after the event that + // caused it. Before d_active, so that general_work() never sees + // an active search without its stamped start + d_det.activate(d_sample_counter, d_channel); + } d_active = active; } @@ -144,6 +152,9 @@ public: gr_vector_void_star& output_items) override; private: + int process_input(int noutput_items, gr_vector_int& ninput_items, + gr_vector_const_void_star& input_items, + gr_vector_void_star& output_items); /*! * \brief Obtains the next power of 2 greater or equal to the input parameter * \param n - Integer value to obtain the next power of 2. @@ -195,6 +206,7 @@ private: unsigned int d_dump_channel; bool d_active; + DeterministicAcquisition d_det; // GNSS-SDR.deterministic=true bool d_dump; std::weak_ptr d_channel_fsm; diff --git a/src/algorithms/acquisition/gnuradio_blocks/pcps_cccwsr_acquisition_cc.cc b/src/algorithms/acquisition/gnuradio_blocks/pcps_cccwsr_acquisition_cc.cc index fda2896ca..3ff5dbc96 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/pcps_cccwsr_acquisition_cc.cc +++ b/src/algorithms/acquisition/gnuradio_blocks/pcps_cccwsr_acquisition_cc.cc @@ -73,6 +73,9 @@ pcps_cccwsr_acquisition_cc::pcps_cccwsr_acquisition_cc(const Acq_Conf &conf) d_correlation_minus(d_fft_size), d_magnitude(d_fft_size) { + // A search needs its dwells beyond its first sample (GNSS-SDR.deterministic=true) + d_det.require_span(static_cast(d_fft_size) * std::max(1U, d_acq_params.max_dwells)); + this->message_port_register_out(pmt::mp("events")); // Count the number of bins @@ -137,6 +140,23 @@ void pcps_cccwsr_acquisition_cc::set_local_code(std::complex *code_data, int pcps_cccwsr_acquisition_cc::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) +{ + d_det.begin_call(d_sample_counter); + const int produced = process_input(noutput_items, ninput_items, input_items, output_items); + if (d_det.enabled()) + { + // GNSS-SDR.deterministic=true: results reach the control queue + // before the progress passes their stamp + d_det.dispatch(d_channel, [this](int event) { this->message_port_pub(pmt::mp("events"), pmt::from_long(event)); }); + d_det.publish(d_sample_counter, d_active, d_channel); + } + return produced; +} + + +int pcps_cccwsr_acquisition_cc::process_input(int noutput_items, + gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items) { int32_t acquisition_message = -1; // 0=STOP_CHANNEL 1=ACQ_SUCCEES 2=ACQ_FAIL @@ -147,6 +167,18 @@ int pcps_cccwsr_acquisition_cc::general_work(int noutput_items, return 0; } + if (d_det.enabled() && d_state == 0) + { + // GNSS-SDR.deterministic=true: the search starts at its stamped sample + int n_items = 0; + if (!d_det.ready_to_start(d_sample_counter, 0, d_fft_size, ninput_items[0], n_items, d_channel)) + { + d_sample_counter += static_cast(d_fft_size) * static_cast(n_items); + consume_each(n_items); + return 0; + } + } + switch (d_state) { case 0: @@ -326,7 +358,14 @@ int pcps_cccwsr_acquisition_cc::general_work(int noutput_items, consume_each(ninput_items[0]); acquisition_message = 1; - this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + if (d_det.enabled()) + { + d_det.raise(acquisition_message); + } + else + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + } LOG(INFO) << "Successful acquisition in channel " << d_channel << " for satellite " << d_gnss_synchro->System << " " << d_gnss_synchro->PRN; @@ -363,8 +402,14 @@ int pcps_cccwsr_acquisition_cc::general_work(int noutput_items, consume_each(ninput_items[0]); acquisition_message = 2; - this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); - + if (d_det.enabled()) + { + d_det.raise(acquisition_message); + } + else + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + } break; } } diff --git a/src/algorithms/acquisition/gnuradio_blocks/pcps_cccwsr_acquisition_cc.h b/src/algorithms/acquisition/gnuradio_blocks/pcps_cccwsr_acquisition_cc.h index 23ba6accd..274af1629 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/pcps_cccwsr_acquisition_cc.h +++ b/src/algorithms/acquisition/gnuradio_blocks/pcps_cccwsr_acquisition_cc.h @@ -26,6 +26,7 @@ #include "acq_conf.h" #include "acquisition_impl_interface.h" #include "channel_fsm.h" +#include "deterministic_acquisition.h" #include "gnss_sdr_fft.h" #include "gnss_synchro.h" #include @@ -97,6 +98,13 @@ public: d_state = 0; } + if (active) + { + // GNSS-SDR.deterministic=true: a lookahead after the event that + // caused it. Before d_active, so that general_work() never sees + // an active search without its stamped start + d_det.activate(d_sample_counter, d_channel); + } d_active = active; } @@ -125,6 +133,9 @@ public: gr_vector_void_star& output_items) override; private: + int process_input(int noutput_items, gr_vector_int& ninput_items, + gr_vector_const_void_star& input_items, + gr_vector_void_star& output_items); friend pcps_cccwsr_acquisition_cc_sptr pcps_cccwsr_make_acquisition_cc(const Acq_Conf& conf); @@ -154,6 +165,7 @@ private: uint32_t d_channel; bool d_active; + DeterministicAcquisition d_det; // GNSS-SDR.deterministic=true std::weak_ptr d_channel_fsm; diff --git a/src/algorithms/acquisition/gnuradio_blocks/pcps_opencl_acquisition_cc.cc b/src/algorithms/acquisition/gnuradio_blocks/pcps_opencl_acquisition_cc.cc index cde29a9bb..b462fcc23 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/pcps_opencl_acquisition_cc.cc +++ b/src/algorithms/acquisition/gnuradio_blocks/pcps_opencl_acquisition_cc.cc @@ -118,6 +118,11 @@ pcps_opencl_acquisition_cc::pcps_opencl_acquisition_cc(const Acq_Conf &conf, uin d_fft_codes(d_fft_size_pow2), d_zero_vector(d_fft_size_pow2 - d_fft_size, 0.0) { + // A search needs its dwells beyond its first sample (GNSS-SDR.deterministic=true) + d_det.require_span(static_cast(d_fft_size) * std::max(1U, d_max_dwells)); + // Filled while an acquisition core reads it: never reallocated + d_sample_counter_buffer.reserve(d_max_dwells); + this->message_port_register_out(pmt::mp("events")); d_opencl = init_opencl_environment("math_kernel.cl"); @@ -255,7 +260,7 @@ int pcps_opencl_acquisition_cc::init_opencl_environment(const std::string &kerne cl::Program::Sources sources; - sources.push_back({kernel_code.c_str(), kernel_code.length()}); + sources.emplace_back(kernel_code.c_str(), kernel_code.length()); cl::Program program(context, sources); if (program.build(device) != CL_SUCCESS) @@ -432,33 +437,7 @@ void pcps_opencl_acquisition_cc::acquisition_core_volk() } } - if (!d_acq_params.bit_transition_flag) - { - if (d_test_statistics > d_acq_params.threshold) - { - d_state = 2; // Positive acquisition - } - else if (d_well_count == d_max_dwells) - { - d_state = 3; // Negative acquisition - } - } - else - { - if (d_well_count == d_max_dwells) // d_max_dwells = 2 - { - if (d_test_statistics > d_acq_params.threshold) - { - d_state = 2; // Positive acquisition - } - else - { - d_state = 3; // Negative acquisition - } - } - } - - d_core_working = false; + conclude_dwell(samplestamp); } @@ -599,46 +578,134 @@ void pcps_opencl_acquisition_cc::acquisition_core_opencl() // end = tv.tv_sec *1e6 + tv.tv_usec; // std::cout << "Acq time = " << (end-begin) << " us\n"; + conclude_dwell(samplestamp); +} + + +void pcps_opencl_acquisition_cc::conclude_dwell(uint64_t samplestamp) +{ + int result = 1; // keep searching if (!d_acq_params.bit_transition_flag) { if (d_test_statistics > d_acq_params.threshold) { - d_state = 2; // Positive acquisition + result = 2; // Positive acquisition } else if (d_well_count == d_max_dwells) { - d_state = 3; // Negative acquisition + result = 3; // Negative acquisition } } else { if (d_well_count == d_max_dwells) // d_max_dwells = 2 { - if (d_test_statistics > d_acq_params.threshold) - { - d_state = 2; // Positive acquisition - } - else - { - d_state = 3; // Negative acquisition - } + result = d_test_statistics > d_acq_params.threshold ? 2 : 3; // Positive or negative acquisition } } + bool concluded = false; + if (result != 1) + { + std::lock_guard lock(d_state_mutex); + if (d_state == 1) // not stopped meanwhile + { + if (d_det.enabled()) + { + // GNSS-SDR.deterministic=true: stamped with the end of the dwell that decided it + d_det.raise(result == 2 ? DeterministicClock::ACQ_POSITIVE : DeterministicClock::ACQ_NEGATIVE, samplestamp); + } + d_state = result; + d_active = false; + concluded = true; + } + } + if (concluded && d_det.enabled()) + { + // Released here: the stream may be held back until the result is + // out, so general_work() may not run again before + d_det.dispatch(d_channel, [this](int event) { this->message_port_pub(pmt::mp("events"), pmt::from_long(event)); }); + std::lock_guard lock(d_state_mutex); + d_det.publish(d_sample_counter, d_active, d_channel); + } +} + + +void pcps_opencl_acquisition_cc::run_acquisition_cores() +{ + // Processes the buffered dwells in order, until a decision or until it + // runs out of them (then general_work() starts it again for the next one) + do + { + if (d_opencl == 0) + { // Use OpenCL implementation + acquisition_core_opencl(); + } + else + { // Use Volk implementation + acquisition_core_volk(); + } + } + while (next_dwell_ready()); +} + + +bool pcps_opencl_acquisition_cc::next_dwell_ready() +{ + std::lock_guard lock(d_state_mutex); + if (d_state == 1 && d_well_count < d_in_dwell_count) + { + return true; + } d_core_working = false; + return false; } int pcps_opencl_acquisition_cc::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) +{ + const int produced = process_input(noutput_items, ninput_items, input_items, output_items); + if (d_det.enabled()) + { + // GNSS-SDR.deterministic=true: results reach the control queue + // before the progress passes their stamp + d_det.dispatch(d_channel, [this](int event) { this->message_port_pub(pmt::mp("events"), pmt::from_long(event)); }); + std::lock_guard lock(d_state_mutex); + d_det.publish(d_sample_counter, d_active, d_channel); + } + return produced; +} + + +int pcps_opencl_acquisition_cc::process_input(int noutput_items, + gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items) { int acquisition_message = -1; // 0=STOP_CHANNEL 1=ACQ_SUCCEES 2=ACQ_FAIL - switch (d_state) + + if (d_det.enabled() && d_state == 1 && d_in_dwell_count == 0) + { + // GNSS-SDR.deterministic=true: the first dwell starts at its stamped sample + int n_items = 0; + if (!d_det.ready_to_start(d_sample_counter, 0, d_fft_size, ninput_items[0], n_items, d_channel)) + { + d_sample_counter += static_cast(d_fft_size) * static_cast(n_items); + consume_each(n_items); + return 0; + } + } + + // GNSS-SDR.deterministic=true: a requested search keeps the input for its + // first dwell, which starts at its stamped sample + bool keep_input = false; + switch (d_state.load()) // C++11 cannot switch on std::atomic { case 0: { - if (d_active) + // A new search waits for the core of the previous one + if (d_active && !d_core_working) { // restart acquisition variables d_gnss_synchro->Acq_delay_samples = 0.0; @@ -654,8 +721,11 @@ int pcps_opencl_acquisition_cc::general_work(int noutput_items, d_state = 1; } - - d_sample_counter += static_cast(d_fft_size) * ninput_items[0]; // sample counter + keep_input = d_det.enabled() && d_active; + if (!keep_input) + { + d_sample_counter += static_cast(d_fft_size) * ninput_items[0]; // sample counter + } break; } @@ -670,10 +740,11 @@ int pcps_opencl_acquisition_cc::general_work(int noutput_items, uint32_t num_dwells = std::min(static_cast(d_max_dwells - d_in_dwell_count), ninput_items[0]); for (uint32_t i = 0; i < num_dwells; i++) { - const auto *in = reinterpret_cast(input_items[i]); - std::copy(in, in + d_fft_size, d_in_buffer[d_in_dwell_count++].data()); + const auto *in = reinterpret_cast(input_items[0]) + static_cast(i) * d_fft_size; + std::copy(in, in + d_fft_size, d_in_buffer[d_in_dwell_count].data()); d_sample_counter += static_cast(d_fft_size); d_sample_counter_buffer.push_back(d_sample_counter); + d_in_dwell_count++; // complete: an acquisition core may process it } if (ninput_items[0] > static_cast(num_dwells)) @@ -697,18 +768,15 @@ int pcps_opencl_acquisition_cc::general_work(int noutput_items, // moment by the external thread (may have changed since checked in the switch()). // If the external thread has already declared positive (d_state=2) or negative // (d_state=3) acquisition, we don't have to process next block!! - if ((d_well_count < d_in_dwell_count) && !d_core_working && d_state == 1) - { - d_core_working = true; - if (d_opencl == 0) - { // Use OpenCL implementation - boost::thread(&pcps_opencl_acquisition_cc::acquisition_core_opencl, this); - } - else - { // Use Volk implementation - boost::thread(&pcps_opencl_acquisition_cc::acquisition_core_volk, this); - } - } + { + // A running core checks for the next dwell under the same lock + std::lock_guard lock(d_state_mutex); + if (!d_core_working && (d_well_count < d_in_dwell_count) && d_state == 1) + { + d_core_working = true; + boost::thread(&pcps_opencl_acquisition_cc::run_acquisition_cores, this); + } + } break; } @@ -726,13 +794,20 @@ int pcps_opencl_acquisition_cc::general_work(int noutput_items, DLOG(INFO) << "magnitude " << d_mag; DLOG(INFO) << "input signal power " << d_input_power; - d_active = false; - d_state = 0; + d_state = 0; // the acquisition core has set d_active = false - d_sample_counter += static_cast(d_fft_size) * ninput_items[0]; // sample counter + // A new search may already be requested (e.g., the channel repeats a failed one) + keep_input = d_det.enabled() && d_active; + if (!keep_input) + { + d_sample_counter += static_cast(d_fft_size) * ninput_items[0]; // sample counter + } acquisition_message = 1; - this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + if (!d_det.enabled()) // else raised by the acquisition core + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + } LOG(INFO) << "Successful acquisition in channel " << d_channel << " for satellite " << d_gnss_synchro->System << " " << d_gnss_synchro->PRN; @@ -762,19 +837,29 @@ int pcps_opencl_acquisition_cc::general_work(int noutput_items, DLOG(INFO) << "magnitude " << d_mag; DLOG(INFO) << "input signal power " << d_input_power; - d_active = false; - d_state = 0; + d_state = 0; // the acquisition core has set d_active = false - d_sample_counter += static_cast(d_fft_size) * ninput_items[0]; // sample counter + // A new search may already be requested (e.g., the channel repeats a failed one) + keep_input = d_det.enabled() && d_active; + if (!keep_input) + { + d_sample_counter += static_cast(d_fft_size) * ninput_items[0]; // sample counter + } acquisition_message = 2; - this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + if (!d_det.enabled()) // else raised by the acquisition core + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + } break; } } - consume_each(ninput_items[0]); + if (!keep_input) + { + consume_each(ninput_items[0]); + } return noutput_items; } diff --git a/src/algorithms/acquisition/gnuradio_blocks/pcps_opencl_acquisition_cc.h b/src/algorithms/acquisition/gnuradio_blocks/pcps_opencl_acquisition_cc.h index 186e2b548..ca14c2e3b 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/pcps_opencl_acquisition_cc.h +++ b/src/algorithms/acquisition/gnuradio_blocks/pcps_opencl_acquisition_cc.h @@ -41,6 +41,7 @@ #include "acq_conf.h" #include "acquisition_impl_interface.h" #include "channel_fsm.h" +#include "deterministic_acquisition.h" #include "gnss_block_interface.h" #include "gnss_sdr_fft.h" #include "gnss_synchro.h" @@ -48,9 +49,11 @@ #include #include #include "opencl/cl.hpp" +#include #include #include #include // for weak_ptr +#include #include #include @@ -111,11 +114,19 @@ public: */ inline void set_active(bool active) override { + std::lock_guard lock(d_state_mutex); if (!active) { d_state = 0; } + if (active) + { + // GNSS-SDR.deterministic=true: a lookahead after the event that + // caused it. Before d_active, so that general_work() never sees + // an active search without its stamped start + d_det.activate(d_sample_counter, d_channel); + } d_active = active; } @@ -163,6 +174,13 @@ private: explicit pcps_opencl_acquisition_cc(const Acq_Conf& conf, uint32_t max_dwells); + int process_input(int noutput_items, gr_vector_int& ninput_items, + gr_vector_const_void_star& input_items, + gr_vector_void_star& output_items); + void conclude_dwell(uint64_t samplestamp); + void run_acquisition_cores(); + bool next_dwell_ready(); + void calculate_magnitudes(gr_complex* fft_begin, int doppler_shift, int doppler_offset); int init_opencl_environment(const std::string& kernel_filename); @@ -188,7 +206,7 @@ private: Gnss_Synchro* d_gnss_synchro; - uint64_t d_sample_counter; + std::atomic d_sample_counter; // also read by the acquisition cores int* d_max_doppler_indexs; @@ -196,20 +214,22 @@ private: float d_input_power; float d_test_statistics; - int d_state; + std::atomic d_state; // set by the acquisition cores int d_opencl; uint32_t d_max_dwells; - uint32_t d_well_count; + std::atomic d_well_count; // dwells processed by the acquisition cores const uint32_t d_fft_size; uint32_t d_fft_size_pow2; uint32_t d_num_doppler_bins; uint32_t d_code_phase; uint32_t d_channel; - uint32_t d_in_dwell_count; + std::atomic d_in_dwell_count; // dwells in d_in_buffer - bool d_active; - bool d_core_working; + std::atomic d_active; + std::atomic d_core_working; + std::mutex d_state_mutex; // a result and a deactivation do not cross + DeterministicAcquisition d_det; // GNSS-SDR.deterministic=true std::weak_ptr d_channel_fsm; diff --git a/src/algorithms/acquisition/gnuradio_blocks/pcps_quicksync_acquisition_cc.cc b/src/algorithms/acquisition/gnuradio_blocks/pcps_quicksync_acquisition_cc.cc index e100ffa3e..f78dbf4bd 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/pcps_quicksync_acquisition_cc.cc +++ b/src/algorithms/acquisition/gnuradio_blocks/pcps_quicksync_acquisition_cc.cc @@ -75,6 +75,9 @@ pcps_quicksync_acquisition_cc::pcps_quicksync_acquisition_cc(const Acq_Conf& con d_magnitude_folded(d_fft_size), d_possible_delay(d_folding_factor) { + // A search needs its dwells beyond its first sample (GNSS-SDR.deterministic=true) + d_det.require_span(static_cast(d_vector_length) * std::max(1U, d_max_dwells)); + // Each call to general_work() processes d_samples_per_code * d_folding_factor // samples from a single input item, so the item must be at least that long if (static_cast(d_vector_length) < static_cast(d_samples_per_code) * static_cast(d_folding_factor)) @@ -155,6 +158,23 @@ void pcps_quicksync_acquisition_cc::set_local_code(std::complex* code) int pcps_quicksync_acquisition_cc::general_work(int noutput_items, gr_vector_int& ninput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items) +{ + d_det.begin_call(d_sample_counter); + const int produced = process_input(noutput_items, ninput_items, input_items, output_items); + if (d_det.enabled()) + { + // GNSS-SDR.deterministic=true: results reach the control queue + // before the progress passes their stamp + d_det.dispatch(d_channel, [this](int event) { this->message_port_pub(pmt::mp("events"), pmt::from_long(event)); }); + d_det.publish(d_sample_counter, d_active, d_channel); + } + return produced; +} + + +int pcps_quicksync_acquisition_cc::process_input(int noutput_items, + gr_vector_int& ninput_items, gr_vector_const_void_star& input_items, + gr_vector_void_star& output_items) { /* * By J.Arribas, L.Esteve and M.Molina @@ -176,6 +196,18 @@ int pcps_quicksync_acquisition_cc::general_work(int noutput_items, return 0; } + if (d_det.enabled() && d_state == 0) + { + // GNSS-SDR.deterministic=true: the search starts at its stamped sample + int n_items = 0; + if (!d_det.ready_to_start(d_sample_counter, 0, d_vector_length, ninput_items[0], n_items, d_channel)) + { + d_sample_counter += static_cast(d_vector_length) * static_cast(n_items); + consume_each(n_items); + return 0; + } + } + switch (d_state) { case 0: @@ -417,7 +449,14 @@ int pcps_quicksync_acquisition_cc::general_work(int noutput_items, consume_each(ninput_items[0]); acquisition_message = 1; - this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + if (d_det.enabled()) + { + d_det.raise(acquisition_message); + } + else + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + } LOG(INFO) << "Successful acquisition in channel " << d_channel << " for satellite " << d_gnss_synchro->System << " " << d_gnss_synchro->PRN; // DLOG(INFO) << "END CASE 2"; @@ -462,7 +501,14 @@ int pcps_quicksync_acquisition_cc::general_work(int noutput_items, consume_each(ninput_items[0]); acquisition_message = 2; - this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + if (d_det.enabled()) + { + d_det.raise(acquisition_message); + } + else + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + } // DLOG(INFO) << "END CASE 3"; break; } diff --git a/src/algorithms/acquisition/gnuradio_blocks/pcps_quicksync_acquisition_cc.h b/src/algorithms/acquisition/gnuradio_blocks/pcps_quicksync_acquisition_cc.h index 32b54a9c8..609a64d73 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/pcps_quicksync_acquisition_cc.h +++ b/src/algorithms/acquisition/gnuradio_blocks/pcps_quicksync_acquisition_cc.h @@ -40,6 +40,7 @@ #include "acq_conf.h" #include "acquisition_impl_interface.h" #include "channel_fsm.h" +#include "deterministic_acquisition.h" #include "gnss_sdr_fft.h" #include "gnss_synchro.h" #include @@ -114,6 +115,13 @@ public: d_state = 0; } + if (active) + { + // GNSS-SDR.deterministic=true: a lookahead after the event that + // caused it. Before d_active, so that general_work() never sees + // an active search without its stamped start + d_det.activate(d_sample_counter, d_channel); + } d_active = active; } @@ -142,6 +150,9 @@ public: gr_vector_void_star& output_items) override; private: + int process_input(int noutput_items, gr_vector_int& ninput_items, + gr_vector_const_void_star& input_items, + gr_vector_void_star& output_items); friend pcps_quicksync_acquisition_cc_sptr pcps_quicksync_make_acquisition_cc(const Acq_Conf& conf, uint32_t folding_factor, uint32_t max_dwells); @@ -174,6 +185,7 @@ private: uint32_t d_code_phase; bool d_active; + DeterministicAcquisition d_det; // GNSS-SDR.deterministic=true std::weak_ptr d_channel_fsm; diff --git a/src/algorithms/acquisition/gnuradio_blocks/pcps_tong_acquisition_cc.cc b/src/algorithms/acquisition/gnuradio_blocks/pcps_tong_acquisition_cc.cc index 2a5f982f3..40d0baf79 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/pcps_tong_acquisition_cc.cc +++ b/src/algorithms/acquisition/gnuradio_blocks/pcps_tong_acquisition_cc.cc @@ -92,6 +92,9 @@ pcps_tong_acquisition_cc::pcps_tong_acquisition_cc( d_fft_codes(d_fft_size), d_magnitude(d_fft_size) { + // A search needs its dwells beyond its first sample (GNSS-SDR.deterministic=true) + d_det.require_span(static_cast(d_fft_size) * std::max(1U, d_tong_max_dwells)); + this->message_port_register_out(pmt::mp("events")); // Count the number of bins @@ -147,6 +150,23 @@ void pcps_tong_acquisition_cc::set_local_code(std::complex *code) int pcps_tong_acquisition_cc::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) +{ + d_det.begin_call(d_sample_counter); + const int produced = process_input(noutput_items, ninput_items, input_items, output_items); + if (d_det.enabled()) + { + // GNSS-SDR.deterministic=true: results reach the control queue + // before the progress passes their stamp + d_det.dispatch(d_channel, [this](int event) { this->message_port_pub(pmt::mp("events"), pmt::from_long(event)); }); + d_det.publish(d_sample_counter, d_active, d_channel); + } + return produced; +} + + +int pcps_tong_acquisition_cc::process_input(int noutput_items, + gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items) { int32_t acquisition_message = -1; // 0=STOP_CHANNEL 1=ACQ_SUCCEES 2=ACQ_FAIL @@ -157,6 +177,18 @@ int pcps_tong_acquisition_cc::general_work(int noutput_items, return 0; } + if (d_det.enabled() && d_state == 0) + { + // GNSS-SDR.deterministic=true: the search starts at its stamped sample + int n_items = 0; + if (!d_det.ready_to_start(d_sample_counter, 0, d_fft_size, ninput_items[0], n_items, d_channel)) + { + d_sample_counter += static_cast(d_fft_size) * static_cast(n_items); + consume_each(n_items); + return 0; + } + } + switch (d_state) { case 0: @@ -322,7 +354,14 @@ int pcps_tong_acquisition_cc::general_work(int noutput_items, consume_each(ninput_items[0]); acquisition_message = 1; - this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + if (d_det.enabled()) + { + d_det.raise(acquisition_message); + } + else + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + } LOG(INFO) << "Successful acquisition in channel " << d_channel << " for satellite " << d_gnss_synchro->System << " " << d_gnss_synchro->PRN; @@ -359,8 +398,14 @@ int pcps_tong_acquisition_cc::general_work(int noutput_items, consume_each(ninput_items[0]); acquisition_message = 2; - this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); - + if (d_det.enabled()) + { + d_det.raise(acquisition_message); + } + else + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(acquisition_message)); + } break; } } diff --git a/src/algorithms/acquisition/gnuradio_blocks/pcps_tong_acquisition_cc.h b/src/algorithms/acquisition/gnuradio_blocks/pcps_tong_acquisition_cc.h index ff395917c..eab0a089e 100644 --- a/src/algorithms/acquisition/gnuradio_blocks/pcps_tong_acquisition_cc.h +++ b/src/algorithms/acquisition/gnuradio_blocks/pcps_tong_acquisition_cc.h @@ -40,6 +40,7 @@ #include "acq_conf.h" #include "acquisition_impl_interface.h" #include "channel_fsm.h" +#include "deterministic_acquisition.h" #include "gnss_sdr_fft.h" #include "gnss_synchro.h" #include @@ -114,6 +115,13 @@ public: d_state = 0; } + if (active) + { + // GNSS-SDR.deterministic=true: a lookahead after the event that + // caused it. Before d_active, so that general_work() never sees + // an active search without its stamped start + d_det.activate(d_sample_counter, d_channel); + } d_active = active; } @@ -142,6 +150,9 @@ public: gr_vector_void_star& output_items) override; private: + int process_input(int noutput_items, gr_vector_int& ninput_items, + gr_vector_const_void_star& input_items, + gr_vector_void_star& output_items); friend pcps_tong_acquisition_cc_sptr pcps_tong_make_acquisition_cc( const Acq_Conf& conf, @@ -181,6 +192,7 @@ private: uint32_t d_code_phase; bool d_active; + DeterministicAcquisition d_det; // GNSS-SDR.deterministic=true std::weak_ptr d_channel_fsm; std::unique_ptr d_fft_if; diff --git a/src/algorithms/acquisition/libs/CMakeLists.txt b/src/algorithms/acquisition/libs/CMakeLists.txt index 45b09f80a..5d1c4811d 100644 --- a/src/algorithms/acquisition/libs/CMakeLists.txt +++ b/src/algorithms/acquisition/libs/CMakeLists.txt @@ -5,8 +5,8 @@ # SPDX-License-Identifier: BSD-3-Clause -set(ACQUISITION_LIB_HEADERS acq_conf.h) -set(ACQUISITION_LIB_SOURCES acq_conf.cc) +set(ACQUISITION_LIB_HEADERS acq_conf.h deterministic_acquisition.h) +set(ACQUISITION_LIB_SOURCES acq_conf.cc deterministic_acquisition.cc) if(ENABLE_FPGA) set(ACQUISITION_LIB_SOURCES ${ACQUISITION_LIB_SOURCES} acq_conf_fpga.cc) @@ -40,11 +40,12 @@ else() endif() target_link_libraries(acquisition_libs + PUBLIC + core_system_parameters INTERFACE Gnuradio::runtime PRIVATE algorithms_libs - core_system_parameters ) if(ENABLE_GLOG_AND_GFLAGS) diff --git a/src/algorithms/acquisition/libs/deterministic_acquisition.cc b/src/algorithms/acquisition/libs/deterministic_acquisition.cc new file mode 100644 index 000000000..111316d49 --- /dev/null +++ b/src/algorithms/acquisition/libs/deterministic_acquisition.cc @@ -0,0 +1,190 @@ +/*! + * \file deterministic_acquisition.cc + * \brief Bookkeeping of an acquisition block in deterministic processing + * \author Carles Fernandez Prades, 2026 cfernandez(at)cttc.es + * + * ----------------------------------------------------------------------------- + * + * GNSS-SDR is a Global Navigation Satellite System software-defined receiver. + * This file is part of GNSS-SDR. + * + * Copyright (C) 2010-2026 (see AUTHORS file for a list of contributors) + * SPDX-License-Identifier: GPL-3.0-or-later + * + * ----------------------------------------------------------------------------- + */ + +#include "deterministic_acquisition.h" +#include + +#if USE_GLOG_AND_GFLAGS +#include +#else +#include +#endif + + +DeterministicAcquisition::DeterministicAcquisition() +{ + auto& clock = DeterministicClock::instance(); + if (clock.enabled()) + { + d_producer = clock.register_producer(DeterministicProducer::Kind::Acquisition); + } +} + + +void DeterministicAcquisition::require_span(uint64_t samples) const +{ + if (d_producer) + { + DeterministicClock::instance().require_span(clock_sample(samples)); + } +} + + +void DeterministicAcquisition::activate(uint64_t consumed, uint32_t channel) +{ + if (!d_producer) + { + return; + } + const uint64_t cause = DeterministicClock::scope_stamp(); + if (cause == NO_SAMPLE_STAMP && consumed > 0) + { + LOG(WARNING) << "Deterministic acquisition started without a stamped cause in channel " << channel; + } + std::lock_guard lock(d_mutex); + if (cause == NO_SAMPLE_STAMP) + { + d_start = consumed; + } + else + { + // First input sample at or after the effective stream sample + d_start = (DeterministicClock::instance().effective_sample(cause) + d_decimation - 1) / d_decimation; + } + d_floor = std::max(d_floor, d_start); +} + + +bool DeterministicAcquisition::ready_to_start(uint64_t consumed, uint64_t window_offset, uint64_t samples_per_item, int available_items, int& items, uint32_t channel) +{ + items = 0; + if (!d_producer) + { + return true; + } + std::lock_guard lock(d_mutex); + if (d_start != NO_SAMPLE_STAMP && d_start > 0) + { + // A search started at the stream start keeps the window it has + const uint64_t target = d_start + window_offset; + if (consumed < target) + { + const uint64_t needed = (target - consumed + samples_per_item - 1) / samples_per_item; + items = static_cast(std::min(needed, static_cast(std::max(available_items, 0)))); + return false; + } + if (consumed >= target + samples_per_item) + { + LOG(ERROR) << "Deterministic acquisition in channel " << channel << " started " << consumed - target + << " samples after its stamped start " << d_start; + } + } + d_start = NO_SAMPLE_STAMP; + d_floor = std::max(d_floor, consumed >= window_offset ? consumed - window_offset : 0); + return true; +} + + +void DeterministicAcquisition::begin_window(uint64_t sample) +{ + if (!d_producer) + { + return; + } + std::lock_guard lock(d_mutex); + d_floor = std::max(d_floor, sample); +} + + +void DeterministicAcquisition::raise(int event, uint64_t stamp) +{ + std::lock_guard lock(d_mutex); + d_event = event; + d_stamp = stamp; +} + + +void DeterministicAcquisition::begin_call(uint64_t consumed) +{ + if (!d_producer) + { + return; + } + std::lock_guard lock(d_mutex); + d_call_start = consumed; +} + + +void DeterministicAcquisition::raise(int event) +{ + std::lock_guard lock(d_mutex); + d_event = event; + d_stamp = d_call_start; +} + + +void DeterministicAcquisition::dispatch(uint32_t channel, const std::function& fallback) +{ + if (!d_producer) + { + return; + } + uint64_t stamp = NO_SAMPLE_STAMP; + int event = 0; + { + std::lock_guard lock(d_mutex); + if (d_claimed || d_stamp == NO_SAMPLE_STAMP) + { + return; + } + d_claimed = true; + stamp = d_stamp; + event = d_event; + } + if (!DeterministicClock::instance().emit_channel_event(static_cast(channel), event, clock_sample(stamp))) + { + fallback(event); + } + std::lock_guard lock(d_mutex); + if (d_stamp == stamp) + { + d_stamp = NO_SAMPLE_STAMP; + } + d_claimed = false; +} + + +void DeterministicAcquisition::publish(uint64_t consumed, bool searching, uint32_t channel) +{ + if (!d_producer) + { + return; + } + std::lock_guard lock(d_mutex); + uint64_t progress = consumed; + if (searching || d_stamp != NO_SAMPLE_STAMP || d_start != NO_SAMPLE_STAMP) + { + progress = std::min(progress, d_floor); + } + if (progress < d_published) + { + LOG(WARNING) << "Deterministic progress of the acquisition in channel " << channel + << " moved back from " << d_published << " to " << progress; + return; + } + d_published = progress; + d_producer->set_progress(clock_sample(progress)); +} diff --git a/src/algorithms/acquisition/libs/deterministic_acquisition.h b/src/algorithms/acquisition/libs/deterministic_acquisition.h new file mode 100644 index 000000000..f156ba799 --- /dev/null +++ b/src/algorithms/acquisition/libs/deterministic_acquisition.h @@ -0,0 +1,141 @@ +/*! + * \file deterministic_acquisition.h + * \brief Bookkeeping of an acquisition block in deterministic processing + * \author Carles Fernandez Prades, 2026 cfernandez(at)cttc.es + * + * With GNSS-SDR.deterministic=true (see DeterministicClock), an acquisition + * block starts each search at a stamped sample, publishes its progress, and + * raises its results in its own thread, so that they reach the control queue + * before its progress passes their stamp. + * + * ----------------------------------------------------------------------------- + * + * GNSS-SDR is a Global Navigation Satellite System software-defined receiver. + * This file is part of GNSS-SDR. + * + * Copyright (C) 2010-2026 (see AUTHORS file for a list of contributors) + * SPDX-License-Identifier: GPL-3.0-or-later + * + * ----------------------------------------------------------------------------- + */ + +#ifndef GNSS_SDR_DETERMINISTIC_ACQUISITION_H +#define GNSS_SDR_DETERMINISTIC_ACQUISITION_H + +#include "deterministic_clock.h" +#include +#include +#include +#include + +/** \addtogroup Acquisition + * \{ */ +/** \addtogroup acquisition_libs acquisition_libs + * \{ */ + + +/*! + * \brief Deterministic-processing state of an acquisition block. It does + * nothing unless GNSS-SDR.deterministic=true. + */ +class DeterministicAcquisition +{ +public: + //! Registers the block as a producer of channel events, if enabled + DeterministicAcquisition(); + + bool enabled() const { return static_cast(d_producer); } + + /*! + * \brief Declares that the block reads the stream decimated by \p factor + * (GNSS-SDR.use_acquisition_resampler=true). The samples passed to this + * class are then input samples of the block, and they are converted to + * samples of the clock, which counts the stream before decimation. The + * decimator reads \p factor stream samples per output and does not look + * ahead (its history is zero-filled), so input sample n is stream sample + * n * factor. Call before require_span(). + */ + void set_decimation(uint64_t factor) { d_decimation = factor > 0 ? factor : 1; } + + //! Stream sample of the clock at input sample \p sample of the block + uint64_t clock_sample(uint64_t sample) const { return sample * d_decimation; } + + /*! + * \brief Declares the input that a search needs beyond the first sample + * of its window, so that the lookahead covers it. + */ + void require_span(uint64_t samples) const; + + /*! + * \brief Call when the search is activated. It starts one lookahead after + * the event that the calling thread is handling, or at \p consumed + * outside an event (e.g., at connection time). + */ + void activate(uint64_t consumed, uint32_t channel); + + /*! + * \brief Whether the first window of a new search can start now, at the + * first item boundary at or after its stamped sample. If not, \p items is + * the number of input items to consume first (possibly 0, if none is + * available yet). + * \param consumed Samples consumed so far. + * \param window_offset Samples between the start of the window and the + * consumed count (history - 1 for stream inputs). + * \param samples_per_item Samples per input item (vector length). + * \param available_items New input items available in this call. + * \param[out] items Input items to consume before the window can start. + * \param channel For logging only. + */ + bool ready_to_start(uint64_t consumed, uint64_t window_offset, uint64_t samples_per_item, int available_items, int& items, uint32_t channel); + + //! The current window starts at \p sample: no later result has a lower stamp + void begin_window(uint64_t sample); + + /*! + * \brief Defers a result (DeterministicClock::ACQ_POSITIVE or + * ACQ_NEGATIVE), which may be raised with the block lock held, to + * dispatch(). + */ + void raise(int event, uint64_t stamp); + + /*! + * \brief Records the consumed count when a call to general_work() begins, + * for blocks that decide a result in a call after the one that consumed + * its last window: it is then the end of that window. + */ + void begin_call(uint64_t consumed); + + //! Defers a result stamped with the count recorded by begin_call() + void raise(int event); + + /*! + * \brief Applies the deferred result, if any, in the calling thread. + * Call it without the block lock: a repeated search restarts the block. + * Calls \p fallback (which should publish the event) if the channel has + * no event sink. + */ + void dispatch(uint32_t channel, const std::function& fallback); + + /*! + * \brief Publishes the progress: \p consumed, or the start of the current + * window while a search, or a result, is pending. + */ + void publish(uint64_t consumed, bool searching, uint32_t channel); + +private: + std::shared_ptr d_producer; + std::mutex d_mutex; + uint64_t d_decimation{1}; // stream samples per input sample + uint64_t d_start{NO_SAMPLE_STAMP}; // first sample of the next search + uint64_t d_floor{0}; // no result of the current search can have a lower stamp + uint64_t d_stamp{NO_SAMPLE_STAMP}; // deferred result + uint64_t d_published{0}; + uint64_t d_call_start{0}; + int d_event{0}; + bool d_claimed{false}; // a thread is dispatching the deferred result +}; + + +/** \} */ +/** \} */ +#endif // GNSS_SDR_DETERMINISTIC_ACQUISITION_H diff --git a/src/algorithms/channel/adapters/channel.cc b/src/algorithms/channel/adapters/channel.cc index 373a60eee..f5db339b4 100644 --- a/src/algorithms/channel/adapters/channel.cc +++ b/src/algorithms/channel/adapters/channel.cc @@ -19,6 +19,7 @@ #include "acquisition_interface.h" #include "channel_fsm.h" #include "configuration_interface.h" +#include "deterministic_clock.h" #include "telemetry_decoder_interface.h" #include "tracking_interface.h" #include // for std::invalid_argument @@ -82,6 +83,16 @@ Channel::Channel(const ConfigurationInterface* configuration, gnss_signal_ = Gnss_Signal(signal_str); channel_msg_rx_ = channel_msg_receiver_make_cc(channel_fsm_, repeat_); + + auto& deterministic_clock = DeterministicClock::instance(); + if (deterministic_clock.enabled() && !flag_enable_fpga_) + { + // Events are applied in the thread that raises them, before the + // producer moves past their sample stamp + const auto msg_rx = channel_msg_rx_; + deterministic_clock.set_channel_event_sink(static_cast(channel_), + [msg_rx](int event) { msg_rx->dispatch_event(event); }); + } } diff --git a/src/algorithms/channel/libs/channel_fsm.cc b/src/algorithms/channel/libs/channel_fsm.cc index 868ef8a7b..64a4578c6 100644 --- a/src/algorithms/channel/libs/channel_fsm.cc +++ b/src/algorithms/channel/libs/channel_fsm.cc @@ -18,6 +18,7 @@ #include "channel_fsm.h" #include "channel_event.h" +#include "deterministic_clock.h" #include #if USE_GLOG_AND_GFLAGS @@ -212,17 +213,17 @@ void ChannelFsm::start_acquisition() void ChannelFsm::start_tracking() { trk_->start_tracking(); - queue_->push(pmt::make_any(channel_event_make(channel_, 1))); + queue_->push(pmt::make_any(channel_event_make(channel_, 1, DeterministicClock::scope_stamp()))); } void ChannelFsm::request_satellite() { - queue_->push(pmt::make_any(channel_event_make(channel_, 0))); + queue_->push(pmt::make_any(channel_event_make(channel_, 0, DeterministicClock::scope_stamp()))); } void ChannelFsm::notify_stop_tracking() { - queue_->push(pmt::make_any(channel_event_make(channel_, 2))); + queue_->push(pmt::make_any(channel_event_make(channel_, 2, DeterministicClock::scope_stamp()))); } diff --git a/src/algorithms/channel/libs/channel_msg_receiver_cc.cc b/src/algorithms/channel/libs/channel_msg_receiver_cc.cc index 26844cbfd..faa23d71c 100644 --- a/src/algorithms/channel/libs/channel_msg_receiver_cc.cc +++ b/src/algorithms/channel/libs/channel_msg_receiver_cc.cc @@ -68,39 +68,44 @@ channel_msg_receiver_cc::channel_msg_receiver_cc(std::shared_ptr cha void channel_msg_receiver_cc::msg_handler_channel_events(const pmt::pmt_t& msg) { - bool result = false; try { - const int64_t message = pmt::to_long(msg); - switch (message) - { - case 1: // positive acquisition - // Now the acquisition block can optionally trigger the event valid acquisition internally, - // in order to reduce acquisition to tracking delay. - result = d_channel_fsm->Event_valid_acquisition(); - break; - case 2: // negative acquisition - if (d_repeat == true) - { - result = d_channel_fsm->Event_failed_acquisition_repeat(); - } - else - { - result = d_channel_fsm->Event_failed_acquisition_no_repeat(); - } - break; - case 3: // tracking loss of lock event - result = d_channel_fsm->Event_failed_tracking_standby(); - break; - default: - LOG(WARNING) << "Default case, invalid message."; - break; - } + dispatch_event(pmt::to_long(msg)); } catch (const wht::bad_any_cast& e) { LOG(WARNING) << "msg_handler_channel_events Bad any cast: " << e.what(); } +} + + +void channel_msg_receiver_cc::dispatch_event(int64_t event) +{ + bool result = false; + switch (event) + { + case 1: // positive acquisition + // Now the acquisition block can optionally trigger the event valid acquisition internally, + // in order to reduce acquisition to tracking delay. + result = d_channel_fsm->Event_valid_acquisition(); + break; + case 2: // negative acquisition + if (d_repeat == true) + { + result = d_channel_fsm->Event_failed_acquisition_repeat(); + } + else + { + result = d_channel_fsm->Event_failed_acquisition_no_repeat(); + } + break; + case 3: // tracking loss of lock event + result = d_channel_fsm->Event_failed_tracking_standby(); + break; + default: + LOG(WARNING) << "Default case, invalid message."; + break; + } if (!result) { LOG(WARNING) << "msg_handler_channel_events invalid event"; diff --git a/src/algorithms/channel/libs/channel_msg_receiver_cc.h b/src/algorithms/channel/libs/channel_msg_receiver_cc.h index d5abdf0ae..f94d60014 100644 --- a/src/algorithms/channel/libs/channel_msg_receiver_cc.h +++ b/src/algorithms/channel/libs/channel_msg_receiver_cc.h @@ -20,6 +20,7 @@ #include "channel_fsm.h" #include #include +#include #include /** \addtogroup Channel @@ -42,6 +43,12 @@ class channel_msg_receiver_cc : public gr::block public: ~channel_msg_receiver_cc() = default; //!< Default destructor + /*! + * \brief Applies a channel event (1: positive acquisition, 2: negative + * acquisition, 3: loss of lock) to the channel FSM in the calling thread. + */ + void dispatch_event(int64_t event); + private: friend channel_msg_receiver_cc_sptr channel_msg_receiver_make_cc(std::shared_ptr channel_fsm, bool repeat); channel_msg_receiver_cc(std::shared_ptr channel_fsm, bool repeat); diff --git a/src/algorithms/observables/gnuradio_blocks/CMakeLists.txt b/src/algorithms/observables/gnuradio_blocks/CMakeLists.txt index a8964f90c..95cd3a34e 100644 --- a/src/algorithms/observables/gnuradio_blocks/CMakeLists.txt +++ b/src/algorithms/observables/gnuradio_blocks/CMakeLists.txt @@ -27,10 +27,10 @@ target_link_libraries(obs_gr_blocks PUBLIC Boost::headers Gnuradio::blocks + core_system_parameters observables_libs PRIVATE algorithms_libs - core_system_parameters Matio::matio Gnuradio::pmt ) diff --git a/src/algorithms/observables/gnuradio_blocks/hybrid_observables_gs.cc b/src/algorithms/observables/gnuradio_blocks/hybrid_observables_gs.cc index c06cb1ac4..5ece81db7 100644 --- a/src/algorithms/observables/gnuradio_blocks/hybrid_observables_gs.cc +++ b/src/algorithms/observables/gnuradio_blocks/hybrid_observables_gs.cc @@ -122,6 +122,21 @@ hybrid_observables_gs::hybrid_observables_gs(const Obs_Conf &conf_) set_tag_propagation_policy(TPP_DONT); // no tag propagation, the time tag will be adjusted and regenerated in work() + auto &deterministic_clock = DeterministicClock::instance(); + if (deterministic_clock.enabled()) + { + const double fs = deterministic_clock.sampling_rate(); + const auto age_ms = observables_clock_delay_ms(d_T_rx_step_ms); + d_det_margin_samples = static_cast(std::ceil(DETERMINISTIC_OBSERVABLES_MARGIN_MS * fs / 1000.0)); + // Channels are constructed later and may increase the lookahead. + // Cache only the epoch age; use the final lookahead at run time. + d_det_epoch_age_samples = static_cast(std::ceil(age_ms * fs / 1000.0)); + d_det_pending_trk = std::vector>(d_nchannels_out); + d_det_producer = deterministic_clock.register_producer(DeterministicProducer::Kind::Observables); + d_det_producer->set_progress(NO_SAMPLE_STAMP); + d_det_producer->set_bound([this]() { return deterministic_downstream_bound(); }); + } + // ############# ENABLE DATA FILE LOG ################# if (d_dump) { @@ -171,6 +186,10 @@ hybrid_observables_gs::hybrid_observables_gs(const Obs_Conf &conf_) hybrid_observables_gs::~hybrid_observables_gs() noexcept { + if (d_det_producer) + { + d_det_producer->set_bound(nullptr); + } DLOG(INFO) << "Observables block destructor called."; if (d_dump_file.is_open()) { @@ -241,6 +260,18 @@ hybrid_observables_gs::~hybrid_observables_gs() noexcept void hybrid_observables_gs::msg_handler_pvt_to_observables(const pmt::pmt_t &msg) { gr::thread::scoped_lock lock(d_setlock); // require mutex with work function called by the scheduler + if (d_det_producer && pmt::is_pair(msg) && pmt::is_uint64(pmt::car(msg))) + { + // Stamped with the sample of the PVT epoch that sent it + d_det_pvt_messages.emplace_back(pmt::to_uint64(pmt::car(msg)) + deterministic_pvt_delay_samples(), pmt::cdr(msg)); + return; + } + apply_pvt_message(msg); +} + + +void hybrid_observables_gs::apply_pvt_message(const pmt::pmt_t &msg) +{ try { if (pmt::any_ref(msg).type().hash_code() == d_double_type_hash_code) @@ -546,6 +577,11 @@ bool hybrid_observables_gs::interp_trk_obs(Gnss_Synchro &interpolated_obs, uint3 void hybrid_observables_gs::forecast(int noutput_items __attribute__((unused)), gr_vector_int &ninput_items_required) { + if (d_det_producer) + { + deterministic_forecast(ninput_items_required); + return; + } for (int32_t n = 0; n < static_cast(d_nchannels_in) - 1; n++) { ninput_items_required[n] = 0; @@ -1206,6 +1242,184 @@ void hybrid_observables_gs::propagate_sensor_data(const std::vectorsize(n) > 0) + { + // Check if the last Gnss_Synchro comes from the same satellite as the previous ones + if (d_gnss_synchro_history->front(n).PRN != trk.PRN) + { + d_gnss_synchro_history->clear(n); + d_channel_has_previous_observation[n] = false; + // LOG(INFO) << "Channel " << d_gnss_synchro_history->front(n).Channel_ID << " changed satellite to PRN " << trk.PRN; + } + } + d_gnss_synchro_history->push_back(n, trk); + d_gnss_synchro_history->back(n).RX_time = compute_T_rx_s(trk); + } +} + + +void hybrid_observables_gs::prepare_deterministic_epoch(uint64_t rx_clock) +{ + // PVT messages, in the order the PVT sent them + while (!d_det_pvt_messages.empty() && d_det_pvt_messages.front().first <= rx_clock) + { + apply_pvt_message(d_det_pvt_messages.front().second); + d_det_pvt_messages.pop_front(); + } + // Channel data up to just after the epoch, so that the interpolation has + // its samples and history changes take effect at the same epoch every run + const uint64_t limit = rx_clock + d_det_margin_samples; + for (uint32_t n = 0; n < d_nchannels_out; n++) + { + auto &pending = d_det_pending_trk[n]; + while (!pending.empty() && pending.front().Tracking_sample_counter <= limit) + { + add_trk_obs(n, pending.front()); + pending.pop_front(); + } + } +} + + +uint64_t hybrid_observables_gs::deterministic_pvt_delay_samples() const +{ + // The PVT reads an epoch one epoch age after its clock sample. Leave a + // lookahead for the stream and another for scheduling and horizon rounding. + return d_det_epoch_age_samples + 2 * DeterministicClock::instance().lookahead(); +} + + +void hybrid_observables_gs::finish_deterministic_epoch(bool produced) +{ + const uint64_t rx_clock = d_Rx_clock_buffer.empty() ? 0 : d_Rx_clock_buffer.front(); + if (produced) + { + // The PVT applies telemetry data and stamps its messages by epoch sample. + add_item_tag(0, this->nitems_written(0), pmt::mp("deterministic_epoch"), pmt::from_uint64(rx_clock)); + } + std::lock_guard lock(d_det_stamps_mutex); + if (produced) + { + d_det_output_stamps.emplace_back(this->nitems_written(0), rx_clock); + } + if (d_Rx_clock_buffer.size() == d_Rx_clock_buffer.capacity()) + { + // Publish the PVT's pending stamp before advancing the next epoch, + // also advancing when an epoch produces no valid observations. + d_det_next_epoch = d_Rx_clock_buffer[1]; + } +} + + +uint64_t hybrid_observables_gs::deterministic_downstream_bound() +{ + const auto state = detail(); + if (!state || state->noutputs() < 1) + { + return NO_SAMPLE_STAMP; + } + const auto output = state->output(0); + if (!output) + { + return NO_SAMPLE_STAMP; + } + uint64_t consumed = NO_SAMPLE_STAMP; + { + gr::thread::scoped_lock lock(*output->mutex()); + for (size_t r = 0; r < output->nreaders(); r++) + { + consumed = std::min(consumed, output->reader(r)->nitems_read()); + } + } + // The oldest epoch that the PVT has not finished, or the next one to + // compute if this block lags behind: a message that the PVT sends for it + // takes effect one delay later, so the stream may run up to there + uint64_t epoch; + { + std::lock_guard lock(d_det_stamps_mutex); + epoch = d_det_next_epoch; + while (!d_det_output_stamps.empty() && d_det_output_stamps.front().first < consumed) + { + d_det_output_stamps.pop_front(); + } + if (!d_det_output_stamps.empty()) + { + epoch = std::min(epoch, d_det_output_stamps.front().second); + } + } + const uint64_t lookahead = DeterministicClock::instance().lookahead(); + const uint64_t reach = epoch + deterministic_pvt_delay_samples(); + return reach > lookahead ? reach - lookahead : 0; +} + + +void hybrid_observables_gs::deterministic_forecast(gr_vector_int &ninput_items_required) +{ + for (uint32_t n = 0; n < d_nchannels_out; n++) + { + ninput_items_required[n] = 0; + } + ninput_items_required[d_nchannels_in - 1] = 1; + const auto state = detail(); + if (!state) + { + return; + } + int32_t waiting_channel = -1; + for (uint32_t n = 0; n < d_nchannels_out; n++) + { + const auto input = state->input(n); + gr::thread::scoped_lock lock(*input->mutex()); + if (input->items_available() > 0) + { + // Drain channel backlogs even when the clock is stalled + ninput_items_required[d_nchannels_in - 1] = 0; + return; + } + if (waiting_channel < 0 && !input->done()) + { + waiting_channel = static_cast(n); + } + } + const auto clock = state->input(d_nchannels_in - 1); + bool clock_finished = false; + { + gr::thread::scoped_lock lock(*clock->mutex()); + clock_finished = clock->done() && clock->items_available() == 0; + } + if (clock_finished && waiting_channel >= 0) + { + // Wait for the channels that are still running instead of ending + // here, so that they process their whole input + ninput_items_required[d_nchannels_in - 1] = 0; + ninput_items_required[waiting_channel] = 1; + } +} + + int hybrid_observables_gs::general_work(int noutput_items __attribute__((unused)), gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) @@ -1213,11 +1427,28 @@ int hybrid_observables_gs::general_work(int noutput_items __attribute__((unused) const auto **in = reinterpret_cast(&input_items[0]); auto **out = reinterpret_cast(&output_items[0]); + if (d_det_producer) + { + // GNU Radio dispatches messages only between calls: take the PVT + // messages queued since then, which may be due at this epoch + const pmt::pmt_t port = pmt::mp("pvt_to_observables"); + pmt::pmt_t msg; + while ((msg = delete_head_nowait(port))) + { + msg_handler_pvt_to_observables(msg); + } + } + // Push receiver clock into history buffer (connected to the last of the input channels) // The clock buffer gives time to the channels to compute the tracking observables if (ninput_items[d_nchannels_in - 1] > 0) { d_Rx_clock_buffer.push_back(in[d_nchannels_in - 1][0].Tracking_sample_counter); + if (d_det_producer) + { + // The next epoch to compute, until this call computes it + d_det_next_epoch = d_Rx_clock_buffer.front(); + } std::vector tags_vec; // Propagate sensor data tags @@ -1285,39 +1516,14 @@ int hybrid_observables_gs::general_work(int noutput_items __attribute__((unused) // ************ end time tags ************** for (int32_t m = 0; m < ninput_items[n]; m++) { - // Keep the latest tracking data so that channels without a valid - // time reference can be reported through the Monitor and to the - // flowgraph channel status (secondary-frequency acquisition assistance) - d_last_trk_data[n] = in[n][m]; - // Latch a restarted carrier phase accumulator reported by the - // tracking block: it is flagged on a single sample, which may - // not be the one the observation is interpolated from - if (!in[n][m].Flag_carrier_phase_continuous) + if (d_det_producer) { - d_channel_phase_discontinuity_pending[n] = true; + // taken into account when its epoch is computed + d_det_pending_trk[n].push_back(in[n][m]); } - // Push the valid tracking Gnss_Synchros to their corresponding deque - if (in[n][m].Flag_valid_word) + else { - if (std::string(in[n][m].Signal, 2) == std::string("E6")) - { - if (d_conf.enable_E6 == false) - { - continue; - } - } - if (d_gnss_synchro_history->size(n) > 0) - { - // Check if the last Gnss_Synchro comes from the same satellite as the previous ones - if (d_gnss_synchro_history->front(n).PRN != in[n][m].PRN) - { - d_gnss_synchro_history->clear(n); - d_channel_has_previous_observation[n] = false; - // LOG(INFO) << "Channel " << d_gnss_synchro_history->front(n).Channel_ID << " changed satellite to PRN " << in[n][m].PRN; - } - } - d_gnss_synchro_history->push_back(n, in[n][m]); - d_gnss_synchro_history->back(n).RX_time = compute_T_rx_s(in[n][m]); + add_trk_obs(n, in[n][m]); } } consume(n, ninput_items[n]); @@ -1330,6 +1536,10 @@ int hybrid_observables_gs::general_work(int noutput_items __attribute__((unused) if (d_Rx_clock_buffer.size() == d_Rx_clock_buffer.capacity()) { + if (d_det_producer) + { + prepare_deterministic_epoch(d_Rx_clock_buffer.front()); + } std::vector epoch_data(d_nchannels_out); int32_t n_valid = 0; int32_t n_trk_only = 0; @@ -1469,6 +1679,10 @@ int hybrid_observables_gs::general_work(int noutput_items __attribute__((unused) { // LOG(INFO) << "OBS: diff time: " << out[0][0].RX_time * 1000.0 - old_time_debug; // old_time_debug = out[0][0].RX_time * 1000.0; + if (d_det_producer) + { + finish_deterministic_epoch(true); + } return 1; } } @@ -1479,7 +1693,15 @@ int hybrid_observables_gs::general_work(int noutput_items __attribute__((unused) { out[n][0] = empty_gs; } + if (d_det_producer) + { + finish_deterministic_epoch(true); + } return 1; } + if (d_det_producer) + { + finish_deterministic_epoch(false); + } return 0; } diff --git a/src/algorithms/observables/gnuradio_blocks/hybrid_observables_gs.h b/src/algorithms/observables/gnuradio_blocks/hybrid_observables_gs.h index 43afb216a..9e9f81805 100644 --- a/src/algorithms/observables/gnuradio_blocks/hybrid_observables_gs.h +++ b/src/algorithms/observables/gnuradio_blocks/hybrid_observables_gs.h @@ -20,16 +20,20 @@ #ifndef GNSS_SDR_HYBRID_OBSERVABLES_GS_H #define GNSS_SDR_HYBRID_OBSERVABLES_GS_H +#include "deterministic_clock.h" #include "gnss_block_interface.h" #include "gnss_time.h" // for timetags produced by Tracking #include "obs_conf.h" #include // for boost::circular_buffer #include // for block #include // for gr_vector_int +#include // for std::atomic #include // for size_t #include // for int32_t +#include // for std::deque #include // for std::ofstream #include // for std::shared, std:unique_ptr +#include // for std::mutex #include // for std::queue #include // for std::string #include // for typeid @@ -192,6 +196,15 @@ private: bool& is_unique); void msg_handler_pvt_to_observables(const pmt::pmt_t& msg); + void apply_pvt_message(const pmt::pmt_t& msg); + void add_trk_obs(uint32_t n, const Gnss_Synchro& trk); + // GNSS-SDR.deterministic=true: channel data and PVT messages take effect + // at the epoch given by their sample stamps, not when they arrive + void prepare_deterministic_epoch(uint64_t rx_clock); + void finish_deterministic_epoch(bool produced); + uint64_t deterministic_pvt_delay_samples() const; + uint64_t deterministic_downstream_bound(); + void deterministic_forecast(gr_vector_int& ninput_items_required); double compute_T_rx_s(const Gnss_Synchro& a) const; bool interp_trk_obs(Gnss_Synchro& interpolated_obs, uint32_t ch, uint64_t rx_clock) const; bool has_fresh_trk_data(uint32_t ch, uint64_t rx_clock) const; @@ -254,6 +267,16 @@ private: bool d_always_output_gs; bool d_dump; bool d_dump_mat; + + // GNSS-SDR.deterministic=true only (null producer otherwise) + std::shared_ptr d_det_producer; + std::vector> d_det_pending_trk; // channel data not taken into account yet + std::deque> d_det_pvt_messages; // (effective sample, message) + std::deque> d_det_output_stamps; // (output item, epoch sample) not read by the PVT yet + std::mutex d_det_stamps_mutex; + std::atomic d_det_next_epoch{0}; // sample of the next epoch to compute + uint64_t d_det_margin_samples{0}; // channel data beyond an epoch taken into account before computing it + uint64_t d_det_epoch_age_samples{0}; // age of the receiver clock sample when its epoch is computed }; /** \} */ diff --git a/src/algorithms/signal_source/adapters/evk1029_signal_source.h b/src/algorithms/signal_source/adapters/evk1029_signal_source.h index a8c362a6e..f0d01464e 100644 --- a/src/algorithms/signal_source/adapters/evk1029_signal_source.h +++ b/src/algorithms/signal_source/adapters/evk1029_signal_source.h @@ -85,6 +85,7 @@ public: void disconnect(gr::top_block_sptr top_block) override; gr::basic_block_sptr get_right_block() override; bool is_real_time() const override { return enable_throttle_control_; } + bool can_wait() const override { return true; } // a throttle waits too private: Evk1029Source_sptr evk1029_source_; diff --git a/src/algorithms/signal_source/adapters/file_source_base.h b/src/algorithms/signal_source/adapters/file_source_base.h index 5c9be0d57..b27d0e76b 100644 --- a/src/algorithms/signal_source/adapters/file_source_base.h +++ b/src/algorithms/signal_source/adapters/file_source_base.h @@ -89,6 +89,7 @@ public: //! Whether the replay is paced at the sampling frequency bool is_real_time() const override { return enable_throttle_control_; } + bool can_wait() const override { return true; } // a throttle waits too //! The sampling frequency of the source file int64_t sampling_frequency() const; diff --git a/src/algorithms/signal_source/adapters/gss6450_file_signal_source.h b/src/algorithms/signal_source/adapters/gss6450_file_signal_source.h index fb32be846..c3eadce68 100644 --- a/src/algorithms/signal_source/adapters/gss6450_file_signal_source.h +++ b/src/algorithms/signal_source/adapters/gss6450_file_signal_source.h @@ -67,6 +67,7 @@ public: gr::basic_block_sptr get_right_block() override; size_t getRfChannels() const override; bool is_real_time() const override { return enable_throttle_control_; } + bool can_wait() const override { return true; } // a throttle waits too inline std::string filename() const { diff --git a/src/algorithms/signal_source/adapters/labsat_signal_source.h b/src/algorithms/signal_source/adapters/labsat_signal_source.h index 90fcf3487..0da5b25e2 100644 --- a/src/algorithms/signal_source/adapters/labsat_signal_source.h +++ b/src/algorithms/signal_source/adapters/labsat_signal_source.h @@ -57,6 +57,7 @@ public: size_t getRfChannels() const override; bool is_real_time() const override { return enable_throttle_control_; } + bool can_wait() const override { return true; } // a throttle waits too void connect(gr::top_block_sptr top_block) override; void disconnect(gr::top_block_sptr top_block) override; gr::basic_block_sptr get_left_block() override; diff --git a/src/algorithms/signal_source/adapters/multichannel_file_signal_source.h b/src/algorithms/signal_source/adapters/multichannel_file_signal_source.h index f8b9c8566..0a9d2ae3d 100644 --- a/src/algorithms/signal_source/adapters/multichannel_file_signal_source.h +++ b/src/algorithms/signal_source/adapters/multichannel_file_signal_source.h @@ -65,6 +65,7 @@ public: gr::basic_block_sptr get_left_block() override; gr::basic_block_sptr get_right_block() override; bool is_real_time() const override { return enable_throttle_control_; } + bool can_wait() const override { return true; } // a throttle waits too inline std::string filename() const { diff --git a/src/algorithms/signal_source/gnuradio_blocks/evk1029_source.cc b/src/algorithms/signal_source/gnuradio_blocks/evk1029_source.cc index 977de7adb..1396f88c3 100644 --- a/src/algorithms/signal_source/gnuradio_blocks/evk1029_source.cc +++ b/src/algorithms/signal_source/gnuradio_blocks/evk1029_source.cc @@ -16,6 +16,7 @@ #include "evk1029_source.h" #include "command_event.h" +#include "deterministic_clock.h" #include "gnss_sdr_make_unique.h" // for std::make_unique in C++11 #include #include @@ -72,7 +73,7 @@ std::size_t max_history(const std::vector& bands) std::size_t m = 0; for (const auto& b : bands) { - m = std::max(m, b.taps.size() > 0 ? b.taps.size() - 1 : 0); + m = std::max(m, !b.taps.empty() ? b.taps.size() - 1 : 0); } return m; } @@ -156,7 +157,7 @@ Evk1029Source::Evk1029Source(const std::string& filename, Concurrent_Queue(2.0 * GR_M_PI * band.center_freq / sampling_frequency); + const auto fwT0 = static_cast(2.0 * GR_M_PI * band.center_freq / sampling_frequency); for (std::size_t i = 0; i < band.taps.size(); i++) { b.composite_fir[i] = band.taps[i] * std::exp(gr_complex(0, static_cast(i) * fwT0)); @@ -471,7 +472,11 @@ int Evk1029Source::work(int noutput_items, if (eof && produced == 0) { std::cout << "EVK1029_Source: EOF\n"; - queue_->push(pmt::make_any(command_event_make(200, 0))); + if (!DeterministicClock::instance().enabled()) + { + // otherwise the receiver stops once the samples have gone through the flowgraph + queue_->push(pmt::make_any(command_event_make(200, 0))); + } return this->WORK_DONE; } @@ -557,7 +562,11 @@ int Evk1029Source::work(int noutput_items, if (eof_) { std::cout << "EVK1029_Source: EOF\n"; - queue_->push(pmt::make_any(command_event_make(200, 0))); + if (!DeterministicClock::instance().enabled()) + { + // otherwise the receiver stops once the samples have gone through the flowgraph + queue_->push(pmt::make_any(command_event_make(200, 0))); + } return this->WORK_DONE; } return 0; diff --git a/src/algorithms/signal_source/gnuradio_blocks/ion_gsms.cc b/src/algorithms/signal_source/gnuradio_blocks/ion_gsms.cc index c970fbc1a..33329fd19 100644 --- a/src/algorithms/signal_source/gnuradio_blocks/ion_gsms.cc +++ b/src/algorithms/signal_source/gnuradio_blocks/ion_gsms.cc @@ -21,6 +21,7 @@ #include #include #include +#include #include #if USE_GLOG_AND_GFLAGS @@ -137,6 +138,20 @@ IONGSMSFileSource::IONGSMSFileSource( } } + // work() decodes whole chunk cycles only. Without an output multiple, the + // scheduler can offer less room than one cycle; a source that then + // produces nothing is polled again only after a 250 ms timeout. Room for + // the largest cycle is sufficient: work() leaves any unused space for + // the next call, so no common multiple of the segment sizes is needed. + if (maximum_item_rate_ > static_cast(std::numeric_limits::max())) + { + throw std::runtime_error("ION_GSMS_Signal_Source chunk cycle exceeds GNU Radio's output item limit"); + } + if (maximum_item_rate_ > 1) + { + set_output_multiple(static_cast(maximum_item_rate_)); + } + current_segment_index_ = 0; advance_to_next_segment(); } diff --git a/src/algorithms/signal_source/gnuradio_blocks/labsat23_source.cc b/src/algorithms/signal_source/gnuradio_blocks/labsat23_source.cc index c8699ecee..f017b6501 100644 --- a/src/algorithms/signal_source/gnuradio_blocks/labsat23_source.cc +++ b/src/algorithms/signal_source/gnuradio_blocks/labsat23_source.cc @@ -21,6 +21,7 @@ #include "labsat23_source.h" #include "INIReader.h" #include "command_event.h" +#include "deterministic_clock.h" #include "gnss_sdr_filesystem.h" #include "gnss_sdr_make_unique.h" // for std::make_unique in C++11 #include @@ -36,6 +37,20 @@ #include #endif +namespace +{ +// At the end of the file. With GNSS-SDR.deterministic=true, the receiver +// stops once the samples have gone through the flowgraph instead. +void request_receiver_stop(Concurrent_Queue *queue) +{ + if (!DeterministicClock::instance().enabled()) + { + queue->push(pmt::make_any(command_event_make(200, 0))); + } +} +} // namespace + + labsat23_source_sptr labsat23_make_source_sptr( const char *signal_file_basename, const std::vector &channel_selector, @@ -1255,7 +1270,7 @@ int labsat23_source::parse_ls23_data(int noutput_items, std::vectorpush(pmt::make_any(command_event_make(200, 0))); + request_receiver_stop(d_queue); return -1; } else @@ -1310,7 +1325,7 @@ int labsat23_source::parse_ls23_data(int noutput_items, std::vectorpush(pmt::make_any(command_event_make(200, 0))); + request_receiver_stop(d_queue); return -1; } else @@ -1359,7 +1374,7 @@ int labsat23_source::parse_ls23_data(int noutput_items, std::vectorpush(pmt::make_any(command_event_make(200, 0))); + request_receiver_stop(d_queue); return -1; } else @@ -1405,7 +1420,7 @@ int labsat23_source::parse_ls23_data(int noutput_items, std::vectorpush(pmt::make_any(command_event_make(200, 0))); + request_receiver_stop(d_queue); return -1; } else @@ -1446,7 +1461,7 @@ int labsat23_source::parse_ls3w_data(int noutput_items, std::vectorpush(pmt::make_any(command_event_make(200, 0))); + request_receiver_stop(d_queue); return -1; } } @@ -1455,7 +1470,7 @@ int labsat23_source::parse_ls3w_data(int noutput_items, std::vectorpush(pmt::make_any(command_event_make(200, 0))); + request_receiver_stop(d_queue); return -1; } } @@ -1489,7 +1504,7 @@ int labsat23_source::parse_ls4_data(int noutput_items, std::vector if (!read_ls4_data()) { std::cout << "End of file reached, LabSat source stop.\n"; - d_queue->push(pmt::make_any(command_event_make(200, 0))); + request_receiver_stop(d_queue); return -1; } @@ -1520,7 +1535,7 @@ int labsat23_source::parse_ls4_data(int noutput_items, std::vector else { std::cout << "End of file reached, LabSat source stop.\n"; - d_queue->push(pmt::make_any(command_event_make(200, 0))); + request_receiver_stop(d_queue); return -1; } } diff --git a/src/algorithms/signal_source/libs/gnss_sdr_valve.cc b/src/algorithms/signal_source/libs/gnss_sdr_valve.cc index 17e6c0184..f03dff039 100644 --- a/src/algorithms/signal_source/libs/gnss_sdr_valve.cc +++ b/src/algorithms/signal_source/libs/gnss_sdr_valve.cc @@ -19,6 +19,7 @@ #include "gnss_sdr_valve.h" #include "command_event.h" +#include "deterministic_clock.h" #include // for io_signature #include // for min #include // for memcpy @@ -88,7 +89,11 @@ int Gnss_Sdr_Valve::work(int noutput_items, if (d_ncopied_items >= d_nitems) { LOG(INFO) << "Stopping receiver, " << d_ncopied_items << " samples processed"; - d_queue->push(pmt::make_any(command_event_make(200, 0))); + if (!DeterministicClock::instance().enabled()) + { + d_queue->push(pmt::make_any(command_event_make(200, 0))); + } + // else the receiver stops once the samples have gone through the flowgraph if (d_stop_flowgraph) { return -1; // Done! diff --git a/src/algorithms/signal_source/libs/ion_gsms_chunk_data.cc b/src/algorithms/signal_source/libs/ion_gsms_chunk_data.cc index 8dd66421f..6fd213d54 100644 --- a/src/algorithms/signal_source/libs/ion_gsms_chunk_data.cc +++ b/src/algorithms/signal_source/libs/ion_gsms_chunk_data.cc @@ -17,7 +17,6 @@ #include "ion_gsms_chunk_data.h" #include -#include #include #include #include @@ -29,10 +28,51 @@ #endif +IONGSMSChunkData::stream_metadata_t::stream_metadata_t( + const GnssMetadata::Lump& lump, + const GnssMetadata::IonStream& stream, + GnssMetadata::StreamEncoding stream_encoding_, + int output_index_, + std::size_t output_item_offset_, + std::size_t output_item_size_) + : stream_encoding(stream_encoding_), + format(stream.Format()), + alignment(stream.Alignment()), + output_index(output_index_), + output_item_offset(output_item_offset_), + output_item_size(output_item_size_), + packed_bits(stream.Packedbits()) +{ + if (output_index == -1) + { + // Skipped streams only need their packed size + return; + } + + padding_bits = stream_padding_bits(stream); + if (padding_bits > 0 && alignment == GnssMetadata::IonStream::Undefined) + { + throw std::runtime_error("ION_GSMS_Signal_Source stream has packed padding bits but no alignment metadata"); + } + if (stream.Quantization() == 0 || stream.Quantization() > 64) + { + throw std::runtime_error("ION_GSMS_Signal_Source unsupported sample quantization"); + } + rate_factor = stream.RateFactor(); + sample_bitsize = static_cast(stream.Quantization()); + output_item_bits = stream_output_item_bits(stream); + is_complex = stream_is_complex(format); + reversed = samples_are_reversed(stream.Shift(), lump.Shift()); +} + + IONGSMSChunkData::IONGSMSChunkData(const GnssMetadata::Chunk& chunk, const std::vector& stream_ids, std::size_t output_stream_offset) : chunk_(chunk), sizeword_(chunk_.SizeWord()), countwords_(chunk_.CountWords()), + head_padding_(chunk_.Padding() == GnssMetadata::Chunk::Head), + read_lsb_first_(chunk_.Shift() == GnssMetadata::Chunk::Right), + swap_endianness_(source_endianness_is_different(chunk_.Endian())), output_stream_offset_(output_stream_offset) { // Instantiate the Allocator functor @@ -109,6 +149,63 @@ IONGSMSChunkData::IONGSMSChunkData(const GnssMetadata::Chunk& chunk, const std:: } padding_bitsize_ = total_bitsize - pattern_bitsize; + + build_byte_lut(); +} + + +void IONGSMSChunkData::build_byte_lut() +{ + if (sizeword_ * countwords_ != 1 || output_stream_indices_.empty()) + { + return; + } + + byte_lut_output_offset_.assign(output_stream_count_, 0); + byte_lut_row_size_ = 0; + for (std::size_t i = 0; i < output_stream_count_; ++i) + { + if (output_stream_item_rate_[i] > 0 && output_stream_item_size_[i] != sizeof(int8_t)) + { + byte_lut_output_offset_.clear(); + byte_lut_row_size_ = 0; + return; + } + byte_lut_output_offset_[i] = byte_lut_row_size_; + byte_lut_row_size_ += output_stream_item_rate_[i]; + } + + // Run the generic decoder once for every possible chunk value + byte_lut_.assign(256 * byte_lut_row_size_, 0); + gr_vector_void_star outputs(output_stream_offset_ + output_stream_count_, nullptr); + std::vector output_items(outputs.size(), 0); + auto* chunk_byte = static_cast(buffer_); + for (std::size_t value = 0; value < 256; ++value) + { + *chunk_byte = static_cast(value); + for (std::size_t i = 0; i < output_stream_count_; ++i) + { + // An output without items in this chunk may point one past the end + outputs[output_stream_offset_ + i] = byte_lut_.data() + value * byte_lut_row_size_ + byte_lut_output_offset_[i]; + } + unpack_words(outputs, output_items); + } +} + + +void IONGSMSChunkData::write_from_byte_lut(gr_vector_void_star& outputs, std::vector& output_items) const +{ + const int8_t* row = byte_lut_.data() + static_cast(buffer_)[0] * byte_lut_row_size_; + for (int output_index : output_stream_indices_) + { + const auto relative_output_index = static_cast(output_index) - output_stream_offset_; + const auto item_count = output_stream_item_rate_[relative_output_index]; + const int8_t* items = row + byte_lut_output_offset_[relative_output_index]; + auto* out = static_cast(outputs[output_index]); + std::copy(items, items + item_count, out); + outputs[output_index] = out + item_count; + output_items[output_index] += static_cast(item_count); + } } @@ -167,7 +264,6 @@ bool IONGSMSChunkData::source_endianness_is_different(const GnssMetadata::Chunk: std::size_t IONGSMSChunkData::read_from_buffer(uint8_t* buffer, std::size_t offset) { - memset(buffer_, 0, sizeword_ * countwords_); memcpy(buffer_, &buffer[offset], sizeword_ * countwords_); return sizeword_ * countwords_; } @@ -175,6 +271,12 @@ std::size_t IONGSMSChunkData::read_from_buffer(uint8_t* buffer, std::size_t offs void IONGSMSChunkData::write_to_output(gr_vector_void_star& outputs, std::vector& output_items) { + if (!byte_lut_.empty()) + { + write_from_byte_lut(outputs, output_items); + return; + } + switch (sizeword_) { case 1: @@ -218,7 +320,7 @@ template void IONGSMSChunkData::unpack_words(gr_vector_void_star& outputs, std::vector& output_items) { WT* data = static_cast(buffer_); - if (source_endianness_is_different(chunk_.Endian())) + if (swap_endianness_) { for (std::size_t i = 0; i < countwords_; ++i) { @@ -226,37 +328,36 @@ void IONGSMSChunkData::unpack_words(gr_vector_void_star& outputs, std::vector ctx{data, countwords_, chunk_.Shift() == GnssMetadata::Chunk::Right}; + IONGSMSChunkUnpackingCtx ctx{data, countwords_, read_lsb_first_}; // Head padding - if (padding_bitsize_ > 0 && chunk_.Padding() == GnssMetadata::Chunk::Head) + if (padding_bitsize_ > 0 && head_padding_) { ctx.shift_padding(padding_bitsize_); } - const auto initial_output_items = output_items; - // Samples - for (const auto& [lump, stream, encoding, output_index, output_item_offset, output_item_size] : streams_) + for (const auto& stream : streams_) { - if (output_index == -1) + if (stream.output_index == -1) { // skip stream - ctx.shift_padding(stream.Packedbits()); + ctx.shift_padding(stream.packed_bits); } else { - void* output = static_cast(outputs[output_index]) + - output_item_offset * output_item_size; - output_items[output_index] += write_stream_samples(ctx, lump, stream, encoding, &output); + void* output = static_cast(outputs[stream.output_index]) + + stream.output_item_offset * stream.output_item_size; + output_items[stream.output_index] += write_stream_samples(ctx, stream, &output); } } + // Each chunk writes exactly output_stream_item_rate_ items to each of its outputs for (int output_index : output_stream_indices_) { const auto relative_output_index = static_cast(output_index) - output_stream_offset_; - const auto items_written = output_items[output_index] - initial_output_items[output_index]; - outputs[output_index] = static_cast(outputs[output_index]) + items_written * output_stream_item_size_[relative_output_index]; + outputs[output_index] = static_cast(outputs[output_index]) + + output_stream_item_rate_[relative_output_index] * output_stream_item_size_[relative_output_index]; } } @@ -264,51 +365,42 @@ void IONGSMSChunkData::unpack_words(gr_vector_void_star& outputs, std::vector std::size_t IONGSMSChunkData::write_stream_samples( IONGSMSChunkUnpackingCtx& ctx, - const GnssMetadata::Lump& lump, - const GnssMetadata::IonStream& stream, - const GnssMetadata::StreamEncoding stream_encoding, + const stream_metadata_t& stream, void** out) { - const std::size_t padding_bits = stream_padding_bits(stream); - if (padding_bits > 0 && stream.Alignment() == GnssMetadata::IonStream::Undefined) + if (stream.padding_bits > 0 && stream.alignment == GnssMetadata::IonStream::Right) { - throw std::runtime_error("ION_GSMS_Signal_Source stream has packed padding bits but no alignment metadata"); - } - - if (padding_bits > 0 && stream.Alignment() == GnssMetadata::IonStream::Right) - { - ctx.shift_padding(padding_bits); + ctx.shift_padding(stream.padding_bits); } std::size_t items_written = 0; - if (stream_encoding == GnssMetadata::StreamEncodings::FP) + if (stream.stream_encoding == GnssMetadata::StreamEncodings::FP) { - items_written = write_fp32_samples(ctx, lump.Shift(), stream, out); + items_written = write_fp32_samples(ctx, stream, out); } else { - const auto sample_bitsize = stream_output_item_bits(stream); - if (sample_bitsize <= 8) + if (stream.output_item_bits <= 8) { - items_written = write_n_samples(ctx, lump.Shift(), stream, stream_encoding, reinterpret_cast(out)); + items_written = write_n_samples(ctx, stream, reinterpret_cast(out)); } - else if (sample_bitsize <= 16) + else if (stream.output_item_bits <= 16) { - items_written = write_n_samples(ctx, lump.Shift(), stream, stream_encoding, reinterpret_cast(out)); + items_written = write_n_samples(ctx, stream, reinterpret_cast(out)); } - else if (sample_bitsize <= 32) + else if (stream.output_item_bits <= 32) { - items_written = write_n_samples(ctx, lump.Shift(), stream, stream_encoding, reinterpret_cast(out)); + items_written = write_n_samples(ctx, stream, reinterpret_cast(out)); } - else if (sample_bitsize <= 64) + else if (stream.output_item_bits <= 64) { - items_written = write_n_samples(ctx, lump.Shift(), stream, stream_encoding, reinterpret_cast(out)); + items_written = write_n_samples(ctx, stream, reinterpret_cast(out)); } } - if (padding_bits > 0 && stream.Alignment() == GnssMetadata::IonStream::Left) + if (stream.padding_bits > 0 && stream.alignment == GnssMetadata::IonStream::Left) { - ctx.shift_padding(padding_bits); + ctx.shift_padding(stream.padding_bits); } return items_written; @@ -318,29 +410,26 @@ std::size_t IONGSMSChunkData::write_stream_samples( template std::size_t IONGSMSChunkData::write_n_samples( IONGSMSChunkUnpackingCtx& ctx, - GnssMetadata::Lump::LumpShift lump_shift, - const GnssMetadata::IonStream& stream, - GnssMetadata::StreamEncoding stream_encoding, + const stream_metadata_t& stream, OT** out) { - const auto sample_bitsize = static_cast(stream.Quantization()); - const auto items_per_sample = stream_is_complex(stream.Format()) ? 2U : 1U; - std::vector> samples; - samples.reserve(stream.RateFactor()); + const std::size_t sample_count = stream.rate_factor; + const std::size_t items_per_sample = stream.is_complex ? 2U : 1U; + auto* sample_out = static_cast(*out); - for (std::size_t i = 0; i < stream.RateFactor(); ++i) + // Samples are read in packing order and written straight to their chronological position + for (std::size_t i = 0; i < sample_count; ++i) { - std::array sample{}; - const auto first = decode_sample(sample_bitsize, ctx.read_bits(sample_bitsize), stream_encoding); - if (!stream_is_complex(stream.Format())) + OT* sample = sample_out + (stream.reversed ? sample_count - 1 - i : i) * items_per_sample; + const auto first = decode_sample(stream.sample_bitsize, ctx.read_bits(stream.sample_bitsize), stream.stream_encoding); + if (!stream.is_complex) { - sample[0] = (stream.Format() == GnssMetadata::IonStream::IFn) ? static_cast(-first) : first; - samples.push_back(sample); + sample[0] = (stream.format == GnssMetadata::IonStream::IFn) ? static_cast(-first) : first; continue; } - const auto second = decode_sample(sample_bitsize, ctx.read_bits(sample_bitsize), stream_encoding); - switch (stream.Format()) + const auto second = decode_sample(stream.sample_bitsize, ctx.read_bits(stream.sample_bitsize), stream.stream_encoding); + switch (stream.format) { case GnssMetadata::IonStream::IQ: case GnssMetadata::IonStream::Int8IQ: @@ -379,111 +468,52 @@ std::size_t IONGSMSChunkData::write_n_samples( default: throw std::runtime_error("ION_GSMS_Signal_Source unsupported complex stream format"); } - samples.push_back(sample); } - const bool reverse_samples = samples_are_reversed(stream.Shift(), lump_shift); - auto* sample_out = static_cast(*out); - if (reverse_samples) - { - for (auto it = samples.rbegin(); it != samples.rend(); ++it) - { - for (std::size_t i = 0; i < items_per_sample; ++i) - { - *sample_out++ = (*it)[i]; - } - } - } - else - { - for (const auto& sample : samples) - { - for (std::size_t i = 0; i < items_per_sample; ++i) - { - *sample_out++ = sample[i]; - } - } - } - - *out = sample_out; - return samples.size() * items_per_sample; + *out = sample_out + sample_count * items_per_sample; + return sample_count * items_per_sample; } template std::size_t IONGSMSChunkData::write_fp32_samples( IONGSMSChunkUnpackingCtx& ctx, - const GnssMetadata::Lump::LumpShift lump_shift, - const GnssMetadata::IonStream& stream, + const stream_metadata_t& stream, void** out) { - if (stream.Quantization() != 32) + if (stream.sample_bitsize != 32) { throw std::runtime_error("ION_GSMS_Signal_Source only supports FP32 stream encoding"); } - const bool reverse_samples = samples_are_reversed(stream.Shift(), lump_shift); - if (!stream_is_complex(stream.Format())) + const std::size_t sample_count = stream.rate_factor; + if (!stream.is_complex) { - std::vector samples; - samples.reserve(stream.RateFactor()); - for (std::size_t i = 0; i < stream.RateFactor(); ++i) + auto* sample_out = static_cast(*out); + for (std::size_t i = 0; i < sample_count; ++i) { auto sample = read_fp32_sample(ctx); - if (stream.Format() == GnssMetadata::IonStream::IFn) + if (stream.format == GnssMetadata::IonStream::IFn) { sample = -sample; } - samples.push_back(sample); + sample_out[stream.reversed ? sample_count - 1 - i : i] = sample; } - auto* sample_out = static_cast(*out); - if (reverse_samples) - { - for (auto it = samples.rbegin(); it != samples.rend(); ++it) - { - *sample_out++ = *it; - } - } - else - { - for (const auto sample : samples) - { - *sample_out++ = sample; - } - } - - *out = sample_out; - return samples.size(); - } - - std::vector samples; - samples.reserve(stream.RateFactor()); - for (std::size_t i = 0; i < stream.RateFactor(); ++i) - { - const auto first = read_fp32_sample(ctx); - const auto second = read_fp32_sample(ctx); - samples.push_back(complex_sample_from_format(stream.Format(), first, second)); + *out = sample_out + sample_count; + return sample_count; } auto* sample_out = static_cast(*out); - if (reverse_samples) + for (std::size_t i = 0; i < sample_count; ++i) { - for (auto it = samples.rbegin(); it != samples.rend(); ++it) - { - *sample_out++ = *it; - } - } - else - { - for (const auto& sample : samples) - { - *sample_out++ = sample; - } + const auto first = read_fp32_sample(ctx); + const auto second = read_fp32_sample(ctx); + sample_out[stream.reversed ? sample_count - 1 - i : i] = complex_sample_from_format(stream.format, first, second); } - *out = sample_out; - return samples.size(); + *out = sample_out + sample_count; + return sample_count; } diff --git a/src/algorithms/signal_source/libs/ion_gsms_chunk_data.h b/src/algorithms/signal_source/libs/ion_gsms_chunk_data.h index 695bac9a9..03d020898 100644 --- a/src/algorithms/signal_source/libs/ion_gsms_chunk_data.h +++ b/src/algorithms/signal_source/libs/ion_gsms_chunk_data.h @@ -136,30 +136,55 @@ public: static std::size_t stream_output_item_rate(const GnssMetadata::IonStream& stream); private: + // Decoding parameters of one stream, resolved once at construction so that + // the per-chunk path neither queries the metadata objects nor allocates. + struct stream_metadata_t + { + GnssMetadata::StreamEncoding stream_encoding; + GnssMetadata::IonStream::SampleFormat format; + GnssMetadata::IonStream::StreamAlignment alignment; + int output_index = -1; + std::size_t output_item_offset = 0; + std::size_t output_item_size = 0; + std::size_t packed_bits = 0; + std::size_t padding_bits = 0; + std::size_t rate_factor = 0; + uint8_t sample_bitsize = 0; + uint8_t output_item_bits = 0; + bool is_complex = false; + bool reversed = false; + + stream_metadata_t( + const GnssMetadata::Lump& lump, + const GnssMetadata::IonStream& stream, + GnssMetadata::StreamEncoding stream_encoding_, + int output_index_ = -1, + std::size_t output_item_offset_ = 0, + std::size_t output_item_size_ = 0); + }; + template void unpack_words(gr_vector_void_star& outputs, std::vector& output_items); + void build_byte_lut(); + void write_from_byte_lut(gr_vector_void_star& outputs, std::vector& output_items) const; + template - std::size_t write_stream_samples( + static std::size_t write_stream_samples( IONGSMSChunkUnpackingCtx& ctx, - const GnssMetadata::Lump& lump, - const GnssMetadata::IonStream& stream, - GnssMetadata::StreamEncoding stream_encoding, + const stream_metadata_t& stream, void** out); template - std::size_t write_n_samples( + static std::size_t write_n_samples( IONGSMSChunkUnpackingCtx& ctx, - GnssMetadata::Lump::LumpShift lump_shift, - const GnssMetadata::IonStream& stream, - GnssMetadata::StreamEncoding stream_encoding, + const stream_metadata_t& stream, OT** out); template - std::size_t write_fp32_samples( + static std::size_t write_fp32_samples( IONGSMSChunkUnpackingCtx& ctx, - GnssMetadata::Lump::LumpShift lump_shift, - const GnssMetadata::IonStream& stream, + const stream_metadata_t& stream, void** out); template @@ -184,38 +209,22 @@ private: std::size_t sizeword_; std::size_t countwords_; std::size_t padding_bitsize_; + bool head_padding_; + bool read_lsb_first_; + bool swap_endianness_; std::size_t output_stream_offset_; std::size_t output_stream_count_; std::vector output_stream_item_size_; std::vector output_stream_item_rate_; - - struct stream_metadata_t - { - const GnssMetadata::Lump& lump; - const GnssMetadata::IonStream& stream; - GnssMetadata::StreamEncoding stream_encoding; - int output_index = -1; - std::size_t output_item_offset = 0; - std::size_t output_item_size = 0; - - stream_metadata_t( - const GnssMetadata::Lump& lump_, - const GnssMetadata::IonStream& stream_, - GnssMetadata::StreamEncoding stream_encoding_, - int output_index_ = -1, - std::size_t output_item_offset_ = 0, - std::size_t output_item_size_ = 0) : lump(lump_), - stream(stream_), - stream_encoding(stream_encoding_), - output_index(output_index_), - output_item_offset(output_item_offset_), - output_item_size(output_item_size_) - { - } - }; std::vector streams_; std::vector output_stream_indices_; + // One-byte chunks with 8-bit outputs are decoded once for each of their + // 256 values; a row holds the items of all outputs, concatenated. + std::vector byte_lut_; + std::vector byte_lut_output_offset_; + std::size_t byte_lut_row_size_ = 0; + void* buffer_ = nullptr; }; diff --git a/src/algorithms/signal_source/libs/ion_gsms_chunk_unpacking_ctx.h b/src/algorithms/signal_source/libs/ion_gsms_chunk_unpacking_ctx.h index c4bd0c890..376d72d54 100644 --- a/src/algorithms/signal_source/libs/ion_gsms_chunk_unpacking_ctx.h +++ b/src/algorithms/signal_source/libs/ion_gsms_chunk_unpacking_ctx.h @@ -54,6 +54,17 @@ struct IONGSMSChunkUnpackingCtx uint64_t read_bits(std::size_t bit_count) { + // Fast path: the field lies within a single word + const std::size_t first_word_index = bit_offset_ / word_bitsize_; + const std::size_t first_bit_index = bit_offset_ % word_bitsize_; + if (bit_count > 0 && first_bit_index + bit_count <= word_bitsize_ && first_word_index < word_count_) + { + const std::size_t shift = read_lsb_first_ ? first_bit_index : word_bitsize_ - first_bit_index - bit_count; + const uint64_t mask = bit_count >= 64 ? ~uint64_t{0} : (uint64_t{1} << bit_count) - 1U; + bit_offset_ += bit_count; + return (static_cast(data_[first_word_index]) >> shift) & mask; + } + uint64_t value = 0; for (std::size_t bit = 0; bit < bit_count; ++bit) { diff --git a/src/algorithms/telemetry_decoder/gnuradio_blocks/CMakeLists.txt b/src/algorithms/telemetry_decoder/gnuradio_blocks/CMakeLists.txt index 505c6a638..0ec5d510b 100644 --- a/src/algorithms/telemetry_decoder/gnuradio_blocks/CMakeLists.txt +++ b/src/algorithms/telemetry_decoder/gnuradio_blocks/CMakeLists.txt @@ -29,6 +29,7 @@ set(TELEMETRY_DECODER_GR_BLOCKS_HEADERS beidou_dnav_telemetry_decoder_gs.h beidou_b1c_telemetry_decoder_gs.h beidou_b2a_telemetry_decoder_gs.h + telemetry_message_stamp.h ) list(SORT TELEMETRY_DECODER_GR_BLOCKS_HEADERS) diff --git a/src/algorithms/telemetry_decoder/gnuradio_blocks/beidou_b1c_telemetry_decoder_gs.cc b/src/algorithms/telemetry_decoder/gnuradio_blocks/beidou_b1c_telemetry_decoder_gs.cc index ecfdb727b..7aa406737 100644 --- a/src/algorithms/telemetry_decoder/gnuradio_blocks/beidou_b1c_telemetry_decoder_gs.cc +++ b/src/algorithms/telemetry_decoder/gnuradio_blocks/beidou_b1c_telemetry_decoder_gs.cc @@ -26,6 +26,7 @@ #include "dump_logger_helper.h" #include "gnss_sdr_make_unique.h" #include "gnss_synchro.h" +#include "telemetry_message_stamp.h" #include "tlm_crc_stats.h" #include "tlm_utils.h" #include "tow_to_trk.h" @@ -328,7 +329,7 @@ void beidou_b1c_telemetry_decoder_gs::publish_navigation(double cn0_db_hz) { auto eph = std::make_shared(d_nav.get_ephemeris()); eph->PRN = d_satellite.get_PRN(); - message_port_pub(pmt::mp("telemetry"), pmt::make_any(eph)); + message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(eph), d_channel)); #if __cplusplus == 201103L const int default_precision = std::cout.precision(); #else @@ -345,7 +346,7 @@ void beidou_b1c_telemetry_decoder_gs::publish_navigation(double cn0_db_hz) { auto iono = std::make_shared(d_nav.get_iono()); iono->valid = true; - message_port_pub(pmt::mp("telemetry"), pmt::make_any(iono)); + message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(iono), d_channel)); DLOG(INFO) << "New BeiDou B-CNAV1 iono model from PRN " << d_satellite.get_PRN() << " in channel " << d_channel; } @@ -353,7 +354,7 @@ void beidou_b1c_telemetry_decoder_gs::publish_navigation(double cn0_db_hz) { auto utc = std::make_shared(d_nav.get_utc_model()); utc->valid = true; - message_port_pub(pmt::mp("telemetry"), pmt::make_any(utc)); + message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(utc), d_channel)); DLOG(INFO) << "New BeiDou B-CNAV1 UTC model from PRN " << d_satellite.get_PRN() << " in channel " << d_channel; } @@ -362,7 +363,7 @@ void beidou_b1c_telemetry_decoder_gs::publish_navigation(double cn0_db_hz) Beidou_Cnav1_PageData_Message page_msg{}; page_msg.PRN = d_satellite.get_PRN(); page_msg.page_data = d_nav.get_page_data(); - message_port_pub(pmt::mp("telemetry"), pmt::make_any(std::make_shared(page_msg))); + message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(std::make_shared(page_msg)), d_channel)); DLOG(INFO) << "New BeiDou B-CNAV1 page data from PRN " << d_satellite.get_PRN() << " in channel " << d_channel << " PageID=" << d_nav.get_page_data().common.page_id; @@ -397,6 +398,8 @@ int beidou_b1c_telemetry_decoder_gs::general_work( const int32_t hist = BEIDOU_CNAV1_FRAME_SYMBOLS; const Gnss_Synchro* frame_window = in; Gnss_Synchro current_symbol = in[hist - 1]; + // Navigation data sent to the PVT is stamped with this symbol + const TelemetryWorkScope symbol_stamp(this, current_symbol.Tracking_sample_counter); current_symbol.PRN = d_satellite.get_PRN(); d_sample_counter++; diff --git a/src/algorithms/telemetry_decoder/gnuradio_blocks/beidou_b2a_telemetry_decoder_gs.cc b/src/algorithms/telemetry_decoder/gnuradio_blocks/beidou_b2a_telemetry_decoder_gs.cc index 202336976..ba4da9856 100644 --- a/src/algorithms/telemetry_decoder/gnuradio_blocks/beidou_b2a_telemetry_decoder_gs.cc +++ b/src/algorithms/telemetry_decoder/gnuradio_blocks/beidou_b2a_telemetry_decoder_gs.cc @@ -21,6 +21,7 @@ #include "display.h" #include "gnss_satellite.h" #include "gnss_synchro.h" +#include "telemetry_message_stamp.h" #include "tlm_crc_stats.h" #include "tlm_utils.h" #include "tow_to_trk.h" @@ -134,7 +135,7 @@ void beidou_b2a_telemetry_decoder_gs::publish_navigation(double cn0_db_hz) { auto eph = std::make_shared(d_nav.get_ephemeris()); eph->PRN = d_satellite.get_PRN(); - message_port_pub(pmt::mp("telemetry"), pmt::make_any(eph)); + message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(eph), d_channel)); #if __cplusplus == 201103L const int default_precision = std::cout.precision(); #else @@ -214,6 +215,8 @@ int beidou_b2a_telemetry_decoder_gs::general_work( const auto* in = reinterpret_cast(input_items[0]); auto* out = reinterpret_cast(output_items[0]); Gnss_Synchro current = in[0]; + // Navigation data sent to the PVT is stamped with this symbol + const TelemetryWorkScope symbol_stamp(this, current.Tracking_sample_counter); current.PRN = d_satellite.get_PRN(); current.Flag_valid_word = false; bool frame_decoded = false; diff --git a/src/algorithms/telemetry_decoder/gnuradio_blocks/beidou_dnav_telemetry_decoder_gs.cc b/src/algorithms/telemetry_decoder/gnuradio_blocks/beidou_dnav_telemetry_decoder_gs.cc index 2a5f9b699..fdd958f50 100644 --- a/src/algorithms/telemetry_decoder/gnuradio_blocks/beidou_dnav_telemetry_decoder_gs.cc +++ b/src/algorithms/telemetry_decoder/gnuradio_blocks/beidou_dnav_telemetry_decoder_gs.cc @@ -29,6 +29,7 @@ #include "dump_logger_helper.h" #include "gnss_sdr_make_unique.h" // for std::make_unique in C++11 #include "gnss_synchro.h" +#include "telemetry_message_stamp.h" #include "tlm_conf.h" #include "tlm_crc_stats.h" #include "tlm_utils.h" @@ -289,7 +290,7 @@ void beidou_dnav_telemetry_decoder_gs::decode_subframe(float *frame_symbols, dou { // get object for this SV (mandatory) const std::shared_ptr tmp_obj = std::make_shared(d_nav.get_ephemeris()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); LOG(INFO) << "BEIDOU DNAV Ephemeris have been received in channel" << d_channel << " from satellite " << d_satellite << " with CN0=" << cn0 << " dB-Hz"; const auto default_precision = std::cout.precision(); std::cout << text_color << "New BEIDOU B" << d_band << "I DNAV message received in channel " << d_channel @@ -301,7 +302,7 @@ void beidou_dnav_telemetry_decoder_gs::decode_subframe(float *frame_symbols, dou { // get object for this SV (mandatory) const std::shared_ptr tmp_obj = std::make_shared(d_nav.get_utc_model()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); LOG(INFO) << "BEIDOU DNAV UTC Model data have been received in channel" << d_channel << " from satellite " << d_satellite << " with CN0=" << cn0 << " dB-Hz"; const auto default_precision = std::cout.precision(); std::cout << text_color << "New BEIDOU B" << d_band << "I DNAV utc model message received in channel " @@ -314,7 +315,7 @@ void beidou_dnav_telemetry_decoder_gs::decode_subframe(float *frame_symbols, dou { // get object for this SV (mandatory) const std::shared_ptr tmp_obj = std::make_shared(d_nav.get_iono()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); LOG(INFO) << "BEIDOU DNAV Iono data have been received in channel" << d_channel << " from satellite " << d_satellite << " with CN0=" << cn0 << " dB-Hz"; const auto default_precision = std::cout.precision(); std::cout << text_color << "New BEIDOU B" << d_band << "I DNAV Iono message received in channel " << d_channel @@ -325,7 +326,7 @@ void beidou_dnav_telemetry_decoder_gs::decode_subframe(float *frame_symbols, dou if (d_nav.have_new_almanac() == true) { const std::shared_ptr tmp_obj = std::make_shared(d_nav.get_almanac()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); LOG(INFO) << "BEIDOU DNAV Almanac data have been received in channel" << d_channel << " from satellite " << d_satellite << " with CN0=" << cn0 << " dB-Hz"; const auto default_precision = std::cout.precision(); std::cout << text_color << "New BEIDOU B" << d_band << "I DNAV almanac received in channel " << d_channel @@ -431,6 +432,8 @@ int beidou_dnav_telemetry_decoder_gs::general_work(int noutput_items __attribute Gnss_Synchro current_symbol{}; // structure to save the synchronization information and send the output object to the next block // 1. Copy the current tracking output current_symbol = in[0][0]; + // Navigation data sent to the PVT is stamped with this symbol + const TelemetryWorkScope symbol_stamp(this, current_symbol.Tracking_sample_counter); d_symbol_history.push_back(current_symbol.Prompt_I); // add new symbol to the symbol queue d_sample_counter++; // count for the processed samples consume_each(1); diff --git a/src/algorithms/telemetry_decoder/gnuradio_blocks/galileo_telemetry_decoder_gs.cc b/src/algorithms/telemetry_decoder/gnuradio_blocks/galileo_telemetry_decoder_gs.cc index 3d69945a4..5f97f8839 100644 --- a/src/algorithms/telemetry_decoder/gnuradio_blocks/galileo_telemetry_decoder_gs.cc +++ b/src/algorithms/telemetry_decoder/gnuradio_blocks/galileo_telemetry_decoder_gs.cc @@ -22,7 +22,8 @@ #include "Galileo_E1.h" // for GALILEO_E1_CODE_PERIOD_MS #include "Galileo_E5a.h" // for GALILEO_E5A_CODE_PERIOD_MS #include "Galileo_E6.h" // for GALILEO_E6_CODE_PERIOD_MS -#include "display.h" // for colours in terminal: TEXT_BLUE, TEXT_RESET, ... +#include "deterministic_clock.h" +#include "display.h" // for colours in terminal: TEXT_BLUE, TEXT_RESET, ... #include "dump_logger_helper.h" #include "galileo_almanac_helper.h" // for Galileo_Almanac_Helper #include "galileo_ephemeris.h" // for Galileo_Ephemeris @@ -34,6 +35,7 @@ #include "gnss_sdr_make_unique.h" // for std::make_unique in C++11 #include "gnss_synchro.h" // for Gnss_Synchro #include "osnma_data.h" // for osnma::galileo_week_tow_with_offset +#include "telemetry_message_stamp.h" #include "tlm_conf.h" #include "tlm_crc_stats.h" // for Tlm_CRC_Stats #include "tlm_utils.h" // for save_tlm_matfile, tlm_remove_file @@ -473,8 +475,7 @@ void galileo_telemetry_decoder_gs::publish_pending_reduced_ced() reduced_ced.WN = reduced_ced_week; reduced_ced.TOTRedCED = galileo_tow::add_ms(d_TOW_at_current_symbol_ms, tow_delta_ms) / 1000U; const auto tmp_obj = std::make_shared(reduced_ced); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); - + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); const auto default_precision = std::cout.precision(); std::cout << "New Galileo E1 I/NAV reduced CED message received in channel " << d_channel << " from satellite " << d_satellite << " with CN0=" @@ -653,7 +654,7 @@ void galileo_telemetry_decoder_gs::decode_INAV_word(float *page_part_symbols, in << std::setprecision(2) << cn0 << std::setprecision(default_precision) << " dB-Hz" << TEXT_RESET << std::endl; } - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); d_first_eph_sent = true; // do not send reduced CED anymore, since we have the full ephemeris set d_pending_reduced_ced = false; } @@ -662,7 +663,7 @@ void galileo_telemetry_decoder_gs::decode_INAV_word(float *page_part_symbols, in { // get object for this SV (mandatory) const std::shared_ptr tmp_obj = std::make_shared(d_inav_nav.get_iono()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); if (d_band == '1') { const auto default_precision = std::cout.precision(); @@ -686,7 +687,7 @@ void galileo_telemetry_decoder_gs::decode_INAV_word(float *page_part_symbols, in // get object for this SV (mandatory) const std::shared_ptr tmp_obj = std::make_shared(d_inav_nav.get_utc_model()); LOG(INFO) << "Galileo leap second Delta_tLS=" << tmp_obj->Delta_tLS; - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); if (d_band == '1') { const auto default_precision = std::cout.precision(); @@ -717,7 +718,7 @@ void galileo_telemetry_decoder_gs::decode_INAV_word(float *page_part_symbols, in if (d_inav_nav.have_new_almanac() == true) // flag_almanac_4 tells if W10 available. { const std::shared_ptr tmp_obj = std::make_shared(d_inav_nav.get_almanac()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); // debug if (d_band == '1') { @@ -802,7 +803,7 @@ void galileo_telemetry_decoder_gs::decode_FNAV_word(float *page_symbols, int32_t if (d_fnav_nav.have_new_ephemeris() == true) { const std::shared_ptr tmp_obj = std::make_shared(d_fnav_nav.get_ephemeris()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); const auto default_precision = std::cout.precision(); std::cout << TEXT_MAGENTA << "New Galileo E5a F/NAV message received in channel " << d_channel << ": ephemeris from satellite " << d_satellite << " with CN0=" @@ -813,7 +814,7 @@ void galileo_telemetry_decoder_gs::decode_FNAV_word(float *page_symbols, int32_t if (d_fnav_nav.have_new_iono_and_GST() == true) { const std::shared_ptr tmp_obj = std::make_shared(d_fnav_nav.get_iono()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); const auto default_precision = std::cout.precision(); std::cout << TEXT_MAGENTA << "New Galileo E5a F/NAV message received in channel " << d_channel << ": iono/GST model parameters from satellite " << d_satellite @@ -825,7 +826,7 @@ void galileo_telemetry_decoder_gs::decode_FNAV_word(float *page_symbols, int32_t { const std::shared_ptr tmp_obj = std::make_shared(d_fnav_nav.get_utc_model()); LOG(INFO) << "Galileo leap second Delta_tLS=" << tmp_obj->Delta_tLS; - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); const auto default_precision = std::cout.precision(); std::cout << TEXT_MAGENTA << "New Galileo E5a F/NAV message received in channel " << d_channel << ": UTC model parameters from satellite " << d_satellite @@ -986,15 +987,23 @@ void galileo_telemetry_decoder_gs::set_channel(int32_t channel) } -void galileo_telemetry_decoder_gs::check_tlm_separation() +void galileo_telemetry_decoder_gs::check_tlm_separation(uint64_t sample_stamp) { if (d_sent_tlm_failed_msg == false) { if ((d_symbol_counter - d_last_valid_preamble) > d_max_symbols_without_valid_frame) { - const int message = 1; // bad telemetry DLOG(INFO) << "Wrong tlm sync in sat " << this->d_satellite; - this->message_port_pub(pmt::mp("telemetry_to_trk"), pmt::make_any(message)); + const int message = 1; // bad telemetry + if (DeterministicClock::instance().enabled()) + { + // Record before releasing progress; tracking reads this in its work call + DeterministicClock::instance().report_telemetry_fault(d_channel, sample_stamp); + } + else + { + this->message_port_pub(pmt::mp("telemetry_to_trk"), pmt::make_any(message)); + } d_sent_tlm_failed_msg = true; } } @@ -1014,6 +1023,8 @@ int galileo_telemetry_decoder_gs::general_work(int noutput_items __attribute__(( Gnss_Synchro current_symbol{}; // structure to save the synchronization information and send the output object to the next block // 1. Copy the current tracking output current_symbol = in[0][0]; + // Navigation data sent to the PVT is stamped with this symbol + const TelemetryWorkScope symbol_stamp(this, current_symbol.Tracking_sample_counter); d_band = current_symbol.Signal[0]; // add new symbol to the symbol queue @@ -1068,7 +1079,7 @@ int galileo_telemetry_decoder_gs::general_work(int noutput_items __attribute__(( d_flag_preamble = false; // check if there is a problem with the telemetry of the current satellite - check_tlm_separation(); + check_tlm_separation(current_symbol.Tracking_sample_counter); // ******* frame sync ****************** int32_t corr_value = 0; diff --git a/src/algorithms/telemetry_decoder/gnuradio_blocks/galileo_telemetry_decoder_gs.h b/src/algorithms/telemetry_decoder/gnuradio_blocks/galileo_telemetry_decoder_gs.h index c58bb5f14..fbf811634 100644 --- a/src/algorithms/telemetry_decoder/gnuradio_blocks/galileo_telemetry_decoder_gs.h +++ b/src/algorithms/telemetry_decoder/gnuradio_blocks/galileo_telemetry_decoder_gs.h @@ -73,7 +73,7 @@ private: // Callers must hold d_setlock while resetting or checking decoder state. void reset_decoder_state(); - void check_tlm_separation(); + void check_tlm_separation(uint64_t sample_stamp); void msg_handler_read_galileo_tow_map(const pmt::pmt_t &msg); void clear_galileo_tow_map_entry(); diff --git a/src/algorithms/telemetry_decoder/gnuradio_blocks/glonass_gnav_telemetry_decoder_gs.cc b/src/algorithms/telemetry_decoder/gnuradio_blocks/glonass_gnav_telemetry_decoder_gs.cc index 86073b21a..fe7dcd163 100644 --- a/src/algorithms/telemetry_decoder/gnuradio_blocks/glonass_gnav_telemetry_decoder_gs.cc +++ b/src/algorithms/telemetry_decoder/gnuradio_blocks/glonass_gnav_telemetry_decoder_gs.cc @@ -25,6 +25,7 @@ #include "glonass_gnav_ephemeris.h" #include "glonass_gnav_utc_model.h" #include "gnss_sdr_make_unique.h" // for std::make_unique in C++11 +#include "telemetry_message_stamp.h" #include "tlm_conf.h" #include "tlm_crc_stats.h" #include "tlm_utils.h" @@ -169,7 +170,7 @@ void glonass_gnav_telemetry_decoder_gs::decode_string(const double *frame_symbol // get object for this SV (mandatory) d_nav.set_rf_link(d_satellite.get_rf_link()); const std::shared_ptr tmp_obj = std::make_shared(d_nav.get_ephemeris()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); LOG(INFO) << "GLONASS GNAV Ephemeris have been received in channel" << d_channel << " from satellite " << d_satellite; const auto default_precision = std::cout.precision(); std::cout << text_color << "New GLONASS L" << d_band << " GNAV message received in channel " << d_channel @@ -181,7 +182,7 @@ void glonass_gnav_telemetry_decoder_gs::decode_string(const double *frame_symbol { // get object for this SV (mandatory) const std::shared_ptr tmp_obj = std::make_shared(d_nav.get_utc_model()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); LOG(INFO) << "GLONASS GNAV UTC Model data have been received in channel" << d_channel << " from satellite " << d_satellite; const auto default_precision = std::cout.precision(); std::cout << text_color << "New GLONASS L" << d_band << " GNAV message received in channel " << d_channel @@ -194,7 +195,7 @@ void glonass_gnav_telemetry_decoder_gs::decode_string(const double *frame_symbol const uint32_t slot_nbr = d_nav.get_alm_satellite_slot_number(); const std::shared_ptr tmp_obj = std::make_shared(d_nav.get_almanac(slot_nbr)); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); LOG(INFO) << "GLONASS GNAV Almanac data have been received in channel" << d_channel << " in slot number " << slot_nbr; const auto default_precision = std::cout.precision(); std::cout << text_color << "New GLONASS L" << d_band << " GNAV almanac received in channel " << d_channel @@ -266,6 +267,8 @@ int glonass_gnav_telemetry_decoder_gs::general_work(int noutput_items __attribut // 1. Copy the current tracking output current_symbol = in[0][0]; + // Navigation data sent to the PVT is stamped with this symbol + const TelemetryWorkScope symbol_stamp(this, current_symbol.Tracking_sample_counter); d_symbol_history.push_back(current_symbol); // add new symbol to the symbol queue d_sample_counter++; // count for the processed samples consume_each(1); diff --git a/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l1_ca_telemetry_decoder_gs.cc b/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l1_ca_telemetry_decoder_gs.cc index 023a3ffad..a71c22bd8 100644 --- a/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l1_ca_telemetry_decoder_gs.cc +++ b/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l1_ca_telemetry_decoder_gs.cc @@ -20,6 +20,7 @@ */ #include "gps_l1_ca_telemetry_decoder_gs.h" +#include "deterministic_clock.h" #include "dump_logger_helper.h" #include "gnss_sdr_make_unique.h" // for std::make_unique in C++11 #include "gnss_synchro.h" @@ -29,6 +30,7 @@ #include "gps_utc_model.h" // for Gps_Utc_Model #include "qzss_iono.h" // for Qzss_Iono #include "qzss_utc_model.h" // for Qzss_Utc_Model +#include "telemetry_message_stamp.h" #include "tlm_conf.h" #include "tlm_crc_stats.h" #include "tlm_utils.h" @@ -397,7 +399,7 @@ bool gps_l1_ca_telemetry_decoder_gs::decode_subframe(double cn0, bool flag_inver { // get ephemeris object for this SV (mandatory) const std::shared_ptr tmp_obj = std::make_shared(d_nav->get_ephemeris()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } break; case 2: @@ -405,7 +407,7 @@ bool gps_l1_ca_telemetry_decoder_gs::decode_subframe(double cn0, bool flag_inver { // get ephemeris object for this SV (mandatory) const std::shared_ptr tmp_obj = std::make_shared(d_nav->get_ephemeris()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } break; case 3: // we have a new set of ephemeris data for the current SV @@ -413,7 +415,7 @@ bool gps_l1_ca_telemetry_decoder_gs::decode_subframe(double cn0, bool flag_inver { // get ephemeris object for this SV (mandatory) const std::shared_ptr tmp_obj = std::make_shared(d_nav->get_ephemeris()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } break; case 4: // Possible IONOSPHERE and UTC model update (page 18) @@ -424,12 +426,12 @@ bool gps_l1_ca_telemetry_decoder_gs::decode_subframe(double cn0, bool flag_inver // QZSS broadcasts its own Klobuchar coefficients; keep them // separate from the GPS ones const std::shared_ptr tmp_obj = std::make_shared(d_nav->get_iono()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } else { const std::shared_ptr tmp_obj = std::make_shared(d_nav->get_iono()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } } if (d_nav->get_flag_utc_model_valid() == true) @@ -438,18 +440,18 @@ bool gps_l1_ca_telemetry_decoder_gs::decode_subframe(double cn0, bool flag_inver { // The QZSS UTC offset refers to UTC(NICT), not to UTC(USNO) const std::shared_ptr tmp_obj = std::make_shared(d_nav->get_utc_model()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } else { const std::shared_ptr tmp_obj = std::make_shared(d_nav->get_utc_model()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } } if (d_nav->almanac_validation() == true) { const std::shared_ptr tmp_obj = std::make_shared(d_nav->get_almanac()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } break; case 5: @@ -460,12 +462,12 @@ bool gps_l1_ca_telemetry_decoder_gs::decode_subframe(double cn0, bool flag_inver // QZSS broadcasts its own Klobuchar coefficients; keep them // separate from the GPS ones const std::shared_ptr tmp_obj = std::make_shared(d_nav->get_iono()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } else { const std::shared_ptr tmp_obj = std::make_shared(d_nav->get_iono()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } } if (d_nav->get_flag_utc_model_valid() == true) @@ -474,18 +476,18 @@ bool gps_l1_ca_telemetry_decoder_gs::decode_subframe(double cn0, bool flag_inver { // The QZSS UTC offset refers to UTC(NICT), not to UTC(USNO) const std::shared_ptr tmp_obj = std::make_shared(d_nav->get_utc_model()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } else { const std::shared_ptr tmp_obj = std::make_shared(d_nav->get_utc_model()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } } if (d_nav->almanac_validation() == true) { const std::shared_ptr tmp_obj = std::make_shared(d_nav->get_almanac()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } break; default: @@ -555,7 +557,7 @@ void gps_l1_ca_telemetry_decoder_gs::reset() } -void gps_l1_ca_telemetry_decoder_gs::check_tlm_separation() +void gps_l1_ca_telemetry_decoder_gs::check_tlm_separation(uint64_t sample_stamp) { gr::thread::scoped_lock lock(d_setlock); if (d_stat < 2 && d_sent_tlm_failed_msg == false) @@ -563,7 +565,15 @@ void gps_l1_ca_telemetry_decoder_gs::check_tlm_separation() if ((d_sample_counter - d_last_valid_preamble) > d_max_symbols_without_valid_frame) { const int message = 1; // bad telemetry - this->message_port_pub(pmt::mp("telemetry_to_trk"), pmt::make_any(message)); + if (DeterministicClock::instance().enabled()) + { + // Record before releasing progress; tracking reads this in its work call + DeterministicClock::instance().report_telemetry_fault(d_channel, sample_stamp); + } + else + { + this->message_port_pub(pmt::mp("telemetry_to_trk"), pmt::make_any(message)); + } d_sent_tlm_failed_msg = true; } } @@ -693,6 +703,8 @@ int gps_l1_ca_telemetry_decoder_gs::general_work(int noutput_items __attribute__ Gnss_Synchro current_symbol{}; // 1. Copy the current tracking output current_symbol = in[0][0]; + // Navigation data sent to the PVT is stamped with this symbol + const TelemetryWorkScope symbol_stamp(this, current_symbol.Tracking_sample_counter); if (d_symbol_history.empty()) { // Tracking synchronizes the tlm bit boundaries by acquiring the preamble @@ -719,7 +731,7 @@ int gps_l1_ca_telemetry_decoder_gs::general_work(int noutput_items __attribute__ d_flag_preamble = false; // check if there is a problem with the telemetry of the current satellite - check_tlm_separation(); + check_tlm_separation(current_symbol.Tracking_sample_counter); // frame sync frame_synchronization(current_symbol); diff --git a/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l1_ca_telemetry_decoder_gs.h b/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l1_ca_telemetry_decoder_gs.h index 148d29ecd..75083cdd8 100644 --- a/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l1_ca_telemetry_decoder_gs.h +++ b/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l1_ca_telemetry_decoder_gs.h @@ -71,7 +71,7 @@ private: gps_l1_ca_telemetry_decoder_gs(const Tlm_Conf &conf, L1LnavSystem system); - void check_tlm_separation(); + void check_tlm_separation(uint64_t sample_stamp); void frame_synchronization(const Gnss_Synchro ¤t_gs); bool is_PLL_180_deg_phase_locked(); bool gps_word_parityCheck(uint32_t gpsword); diff --git a/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l2c_telemetry_decoder_gs.cc b/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l2c_telemetry_decoder_gs.cc index 6a4536e2f..7e076bf3f 100644 --- a/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l2c_telemetry_decoder_gs.cc +++ b/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l2c_telemetry_decoder_gs.cc @@ -17,6 +17,7 @@ #include "gps_l2c_telemetry_decoder_gs.h" #include "GPS_L2C.h" // for GPS_L2_CNAV_DATA_PAGE_BITS, GPS_L... +#include "deterministic_clock.h" #include "display.h" #include "dump_logger_helper.h" #include "gnss_sdr_make_unique.h" // for std::make_unique in C++11 @@ -25,6 +26,7 @@ #include "gps_cnav_ephemeris.h" // for Gps_CNAV_Ephemeris #include "gps_cnav_iono.h" // for Gps_CNAV_Iono #include "gps_cnav_utc_model.h" // for Gps_CNAV_Utc_Model +#include "telemetry_message_stamp.h" #include "tlm_conf.h" #include "tlm_crc_stats.h" #include "tlm_utils.h" @@ -141,6 +143,8 @@ int gps_l2c_telemetry_decoder_gs::general_work(int noutput_items __attribute__(( // get pointers on in- and output gnss-synchro objects auto *out = reinterpret_cast(output_items[0]); // Get the output buffer pointer const auto *in = reinterpret_cast(input_items[0]); // Get the input buffer pointer + // Navigation data sent to the PVT is stamped with this symbol + const TelemetryWorkScope symbol_stamp(this, in[0].Tracking_sample_counter); bool flag_new_cnav_frame = false; cnav_msg_t msg; @@ -166,7 +170,15 @@ int gps_l2c_telemetry_decoder_gs::general_work(int noutput_items __attribute__(( if ((d_sample_counter - d_last_valid_preamble) > d_max_symbols_without_valid_frame) { const int message = 1; // bad telemetry - this->message_port_pub(pmt::mp("telemetry_to_trk"), pmt::make_any(message)); + if (DeterministicClock::instance().enabled()) + { + // Record before releasing progress; tracking reads this in its work call + DeterministicClock::instance().report_telemetry_fault(d_channel, in[0].Tracking_sample_counter); + } + else + { + this->message_port_pub(pmt::mp("telemetry_to_trk"), pmt::make_any(message)); + } d_sent_tlm_failed_msg = true; } } @@ -208,7 +220,7 @@ int gps_l2c_telemetry_decoder_gs::general_work(int noutput_items __attribute__(( { // get ephemeris object for this SV const std::shared_ptr tmp_obj = std::make_shared(d_CNAV_Message.get_ephemeris()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); const auto default_precision = std::cout.precision(); std::cout << TEXT_BLUE << "New GPS CNAV message received in channel " << d_channel << ": ephemeris from satellite " << d_satellite @@ -218,7 +230,7 @@ int gps_l2c_telemetry_decoder_gs::general_work(int noutput_items __attribute__(( if (d_CNAV_Message.have_new_eop() == true) { const std::shared_ptr tmp_obj = std::make_shared(d_CNAV_Message.get_eop()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); const auto default_precision = std::cout.precision(); std::cout << TEXT_BLUE << "New GPS CNAV message received in channel " << d_channel << ": Earth orientation parameters from satellite " << d_satellite @@ -228,7 +240,7 @@ int gps_l2c_telemetry_decoder_gs::general_work(int noutput_items __attribute__(( if (d_CNAV_Message.have_new_iono() == true) { const std::shared_ptr tmp_obj = std::make_shared(d_CNAV_Message.get_iono()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); const auto default_precision = std::cout.precision(); std::cout << TEXT_BLUE << "New GPS CNAV message received in channel " << d_channel << ": iono model parameters from satellite " << d_satellite @@ -239,7 +251,7 @@ int gps_l2c_telemetry_decoder_gs::general_work(int noutput_items __attribute__(( if (d_CNAV_Message.have_new_utc_model() == true) { const std::shared_ptr tmp_obj = std::make_shared(d_CNAV_Message.get_utc_model()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); const auto default_precision = std::cout.precision(); std::cout << TEXT_BLUE << "New GPS CNAV message received in channel " << d_channel << ": UTC model parameters from satellite " << d_satellite diff --git a/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l5_telemetry_decoder_gs.cc b/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l5_telemetry_decoder_gs.cc index ff6be7dd8..579cc1d63 100644 --- a/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l5_telemetry_decoder_gs.cc +++ b/src/algorithms/telemetry_decoder/gnuradio_blocks/gps_l5_telemetry_decoder_gs.cc @@ -18,6 +18,7 @@ #include "gps_l5_telemetry_decoder_gs.h" #include "GPS_L5.h" +#include "deterministic_clock.h" #include "display.h" #include "dump_logger_helper.h" #include "gnss_sdr_make_unique.h" // for std::make_unique in C++11 @@ -29,6 +30,7 @@ #include "qzss_cnav_eop.h" // for Qzss_CNAV_Eop #include "qzss_cnav_iono.h" // for Qzss_CNAV_Iono #include "qzss_cnav_utc_model.h" // for Qzss_CNAV_Utc_Model +#include "telemetry_message_stamp.h" #include "tlm_conf.h" #include "tlm_crc_stats.h" #include "tlm_utils.h" @@ -167,6 +169,8 @@ int gps_l5_telemetry_decoder_gs::general_work(int noutput_items __attribute__((u Gnss_Synchro current_synchro_data{}; // structure to save the synchronization information and send the output object to the next block // 1. Copy the current tracking output current_synchro_data = in[0]; + // Navigation data sent to the PVT is stamped with this symbol + const TelemetryWorkScope symbol_stamp(this, current_synchro_data.Tracking_sample_counter); consume_each(1); // one by one // check if there is a problem with the telemetry of the current satellite @@ -176,7 +180,15 @@ int gps_l5_telemetry_decoder_gs::general_work(int noutput_items __attribute__((u if ((d_sample_counter - d_last_valid_preamble) > d_max_symbols_without_valid_frame) { const int message = 1; // bad telemetry - this->message_port_pub(pmt::mp("telemetry_to_trk"), pmt::make_any(message)); + if (DeterministicClock::instance().enabled()) + { + // Record before releasing progress; tracking reads this in its work call + DeterministicClock::instance().report_telemetry_fault(d_channel, current_synchro_data.Tracking_sample_counter); + } + else + { + this->message_port_pub(pmt::mp("telemetry_to_trk"), pmt::make_any(message)); + } d_sent_tlm_failed_msg = true; } } @@ -224,7 +236,7 @@ int gps_l5_telemetry_decoder_gs::general_work(int noutput_items __attribute__((u { // get ephemeris object for this SV const std::shared_ptr tmp_obj = std::make_shared(d_CNAV_Message->get_ephemeris()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); const auto default_precision = std::cout.precision(); std::cout << TEXT_MAGENTA << "New " << ((d_system == CnavSystem::GPS) ? "GPS" : "QZSS") << " L5 CNAV message received in channel " << d_channel @@ -237,12 +249,12 @@ int gps_l5_telemetry_decoder_gs::general_work(int noutput_items __attribute__((u if (d_system == CnavSystem::QZSS) { const std::shared_ptr tmp_obj = std::make_shared(d_CNAV_Message->get_eop()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } else { const std::shared_ptr tmp_obj = std::make_shared(d_CNAV_Message->get_eop()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } const auto default_precision = std::cout.precision(); std::cout << TEXT_MAGENTA << "New " << ((d_system == CnavSystem::GPS) ? "GPS" : "QZSS") @@ -258,12 +270,12 @@ int gps_l5_telemetry_decoder_gs::general_work(int noutput_items __attribute__((u // QZSS broadcasts its own Klobuchar coefficients (the Wide Area // set in Message Type 30); keep them separate from the GPS ones const std::shared_ptr tmp_obj = std::make_shared(d_CNAV_Message->get_iono()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } else { const std::shared_ptr tmp_obj = std::make_shared(d_CNAV_Message->get_iono()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } const auto default_precision = std::cout.precision(); std::cout << TEXT_MAGENTA << "New " << ((d_system == CnavSystem::GPS) ? "GPS" : "QZSS") @@ -279,12 +291,12 @@ int gps_l5_telemetry_decoder_gs::general_work(int noutput_items __attribute__((u { // The QZSS UTC offset refers to UTC(NICT), not to UTC(USNO) const std::shared_ptr tmp_obj = std::make_shared(d_CNAV_Message->get_utc_model()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } else { const std::shared_ptr tmp_obj = std::make_shared(d_CNAV_Message->get_utc_model()); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(tmp_obj)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(tmp_obj), d_channel)); } const auto default_precision = std::cout.precision(); std::cout << TEXT_MAGENTA << "New " << ((d_system == CnavSystem::GPS) ? "GPS" : "QZSS") diff --git a/src/algorithms/telemetry_decoder/gnuradio_blocks/sbas_l1_telemetry_decoder_gs.cc b/src/algorithms/telemetry_decoder/gnuradio_blocks/sbas_l1_telemetry_decoder_gs.cc index 8cdb33b82..9f1737189 100644 --- a/src/algorithms/telemetry_decoder/gnuradio_blocks/sbas_l1_telemetry_decoder_gs.cc +++ b/src/algorithms/telemetry_decoder/gnuradio_blocks/sbas_l1_telemetry_decoder_gs.cc @@ -20,6 +20,7 @@ #include "SBAS_L1.h" #include "gnss_synchro.h" #include "sbas_raw_message.h" +#include "telemetry_message_stamp.h" #include "viterbi_decoder_sbas.h" #include // for scoped_lock #include // for mp @@ -567,6 +568,8 @@ int sbas_l1_telemetry_decoder_gs::general_work(int noutput_items __attribute__(( Gnss_Synchro current_symbol{}; // structure to save the synchronization information and send the output object to the next block // 1. Copy the current tracking output current_symbol = in[0]; + // Navigation data sent to the PVT is stamped with this symbol + const TelemetryWorkScope symbol_stamp(this, current_symbol.Tracking_sample_counter); // copy correlation samples into samples vector d_sample_buf.push_back(current_symbol.Prompt_I); // add new symbol to the symbol queue @@ -682,7 +685,7 @@ int sbas_l1_telemetry_decoder_gs::general_work(int noutput_items __attribute__(( message_sample_stamp, static_cast(d_satellite.get_PRN()), valid_msg.second); - this->message_port_pub(pmt::mp("telemetry"), pmt::make_any(sbas_raw_message)); + this->message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(sbas_raw_message), d_channel)); #if __cplusplus == 201103L const int default_precision = std::cout.precision(); #else diff --git a/src/algorithms/telemetry_decoder/gnuradio_blocks/telemetry_message_stamp.h b/src/algorithms/telemetry_decoder/gnuradio_blocks/telemetry_message_stamp.h new file mode 100644 index 000000000..3a10069b2 --- /dev/null +++ b/src/algorithms/telemetry_decoder/gnuradio_blocks/telemetry_message_stamp.h @@ -0,0 +1,94 @@ +/*! + * \file telemetry_message_stamp.h + * \brief Stamps the navigation data that telemetry decoders send to the PVT + * \author Carles Fernandez Prades, 2026 cfernandez(at)cttc.es + * + * ----------------------------------------------------------------------------- + * + * GNSS-SDR is a Global Navigation Satellite System software-defined receiver. + * This file is part of GNSS-SDR. + * + * Copyright (C) 2010-2026 (see AUTHORS file for a list of contributors) + * SPDX-License-Identifier: GPL-3.0-or-later + * + * ----------------------------------------------------------------------------- + */ + +#ifndef GNSS_SDR_TELEMETRY_MESSAGE_STAMP_H +#define GNSS_SDR_TELEMETRY_MESSAGE_STAMP_H + +#include "deterministic_clock.h" +#include +#include +#include +#include + +/** \addtogroup Telemetry_Decoder + * \{ */ +/** \addtogroup Telemetry_Decoder_gnuradio_blocks telemetry_decoder_gr_blocks + * \{ */ + +/*! + * \brief With GNSS-SDR.deterministic=true, wraps \p msg as + * ((sample stamp . channel) . msg), where the stamp is that of the symbol + * being decoded (see DeterministicClock::Scope), so that the PVT applies it at + * the first epoch past that sample. Otherwise, returns \p msg. + */ +inline pmt::pmt_t stamp_telemetry_message(const pmt::pmt_t& msg, int32_t channel) +{ + if (!DeterministicClock::instance().enabled()) + { + return msg; + } + return pmt::cons(pmt::cons(pmt::from_uint64(DeterministicClock::scope_stamp()), pmt::from_long(channel)), msg); +} + + +/*! + * \brief Scope of a call to the general_work() of a telemetry decoder. + * Messages published inside it carry \p stamp, the sample stamp of the symbol + * being decoded (see stamp_telemetry_message()). With + * GNSS-SDR.deterministic=true, the tracking block upstream counts the symbols + * as consumed only when the scope ends, once the messages that they cause + * (e.g., telemetry faults) have been published, so that it cannot run past + * the sample at which they take effect. Construct it before consume_each(). + */ +class TelemetryWorkScope +{ +public: + TelemetryWorkScope(gr::block* block, uint64_t stamp) + : d_stamp(stamp), + d_block(DeterministicClock::instance().enabled() ? block : nullptr) + { + if (d_block) + { + DeterministicClock::instance().set_consumed(d_block, d_block->nitems_read(0)); + } + } + + ~TelemetryWorkScope() + { + // A decoder that throws may not have published its messages + if (d_block && !unwinding()) + { + DeterministicClock::instance().set_consumed(d_block, d_block->nitems_read(0)); + } + } + + TelemetryWorkScope(const TelemetryWorkScope&) = delete; + TelemetryWorkScope& operator=(const TelemetryWorkScope&) = delete; + +private: +#if defined(__cpp_lib_uncaught_exceptions) + bool unwinding() const { return std::uncaught_exceptions() > d_exceptions; } + const int d_exceptions{std::uncaught_exceptions()}; +#else + bool unwinding() const { return std::uncaught_exception(); } +#endif + const DeterministicClock::Scope d_stamp; + gr::block* d_block; +}; + +/** \} */ +/** \} */ +#endif // GNSS_SDR_TELEMETRY_MESSAGE_STAMP_H diff --git a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.cc b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.cc index e5d43111a..36100e68b 100644 --- a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.cc +++ b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.cc @@ -843,6 +843,17 @@ dll_pll_veml_tracking::dll_pll_veml_tracking(const Dll_Pll_Conf &conf_) d_timetag_waiting = false; set_tag_propagation_policy(TPP_DONT); // no tag propagation, the time tag will be adjusted and regenerated in work() d_last_tow_received = std::make_shared(); + + if (d_det.enabled()) + { + if (d_trk_parameters.tow_to_trk) + { + LOG(WARNING) << "tow_to_trk is ignored with GNSS-SDR.deterministic=true"; + d_trk_parameters.tow_to_trk = false; + } + // Inputs needed beyond the progress: see forecast() + d_det.require_span(2 * static_cast(d_trk_parameters.vector_length)); + } } @@ -858,6 +869,15 @@ void dll_pll_veml_tracking::forecast(int noutput_items, void dll_pll_veml_tracking::msg_handler_telemetry_to_trk(const pmt::pmt_t &msg) { + { + // Telemetry fault stamped with the sample of the offending symbol + // (GNSS-SDR.deterministic=true). It takes effect a lookahead later. + gr::thread::scoped_lock lock(d_setlock); + if (d_det.take_fault(msg, this->nitems_read(0), d_state != 0, d_channel)) + { + return; + } + } try { if (pmt::any_ref(msg).type().hash_code() == d_int_type_hash_code) @@ -902,6 +922,7 @@ void dll_pll_veml_tracking::start_tracking() d_acq_carrier_doppler_hz = d_acquisition_gnss_synchro->Acq_doppler_hz; d_acq_sample_stamp = d_acquisition_gnss_synchro->Acq_samplestamp_samples; d_tracking_time_start_sample = d_acq_sample_stamp; + d_det.start(d_acq_sample_stamp); // GNSS-SDR.deterministic=true d_carrier_doppler_hz = d_acq_carrier_doppler_hz; d_carrier_phase_step_rad = TWO_PI * d_carrier_doppler_hz / d_trk_parameters.fs_in; @@ -1400,7 +1421,15 @@ bool dll_pll_veml_tracking::cn0_and_tracking_lock_status(double coh_integration_ LOG(INFO) << "Loss of lock in channel " << d_channel << ", satellite " << Gnss_Satellite(d_systemName, d_acquisition_gnss_synchro->PRN) << " (carrier_lock_fail_counter:" << d_carrier_lock_fail_counter << " code_lock_fail_counter : " << d_code_lock_fail_counter << ")"; - this->message_port_pub(pmt::mp("events"), pmt::from_long(3)); // 3 -> loss of lock + if (d_det.enabled()) + { + // raised by general_work(), without the lock held + d_det.raise_loss(this->nitems_read(0)); + } + else + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(3)); // 3 -> loss of lock + } d_carrier_lock_fail_counter = 0; d_code_lock_fail_counter = 0; return false; @@ -2327,7 +2356,22 @@ uint64_t dll_pll_veml_tracking::tracking_elapsed_seconds(uint64_t sample_count) } -int dll_pll_veml_tracking::general_work(int noutput_items __attribute__((unused)), gr_vector_int &ninput_items, +int dll_pll_veml_tracking::general_work(int noutput_items, gr_vector_int &ninput_items, + gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) +{ + const int produced = process_input(noutput_items, ninput_items, input_items, output_items); + if (d_det.enabled()) + { + // The event reaches the control queue before the progress passes its stamp + d_det.dispatch(d_channel, [this](int event) { this->message_port_pub(pmt::mp("events"), pmt::from_long(event)); }); + // consume_each() has already moved the read pointer + d_det.publish(this->nitems_read(0)); + } + return produced; +} + + +int dll_pll_veml_tracking::process_input(int noutput_items __attribute__((unused)), gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock l(d_setlock); @@ -2339,6 +2383,12 @@ int dll_pll_veml_tracking::general_work(int noutput_items __attribute__((unused) d_tow_from_telemetry_ms = 0ULL; d_wn_from_telemetry = 0U; + if (d_det.fault_due(this->nitems_read(0), d_channel) && d_state != 0) + { + DLOG(INFO) << "Telemetry fault applied in ch " << this->d_channel; + d_carrier_lock_fail_counter = 200000; // force loss-of-lock condition + } + if (d_pull_in_transitory == true) { if (d_trk_parameters.pull_in_time_s < tracking_elapsed_seconds(this->nitems_read(0))) @@ -2379,6 +2429,13 @@ int dll_pll_veml_tracking::general_work(int noutput_items __attribute__((unused) } case 1: // Pull-in { + const uint64_t det_skip = d_det.samples_to_pull_in(this->nitems_read(0), d_channel); + if (det_skip > 0) + { + // GNSS-SDR.deterministic=true: pull in at the stamped sample + consume_each(static_cast(std::min(det_skip, static_cast(ninput_items[0])))); + return 0; + } // Signal alignment (skip samples until the incoming signal is aligned with local replica) // const int64_t acq_trk_diff_samples = static_cast(d_sample_counter) - static_cast(d_acq_sample_stamp); const int64_t acq_trk_diff_samples = static_cast(this->nitems_read(0)) - static_cast(d_acq_sample_stamp); @@ -2849,6 +2906,7 @@ int dll_pll_veml_tracking::general_work(int noutput_items __attribute__((unused) add_item_tag(0, this->nitems_written(0) + 1, tag.key, tag.value); } + d_det.record_output(this->nitems_written(0), current_synchro_data.Tracking_sample_counter); *out[0] = std::move(current_synchro_data); return 1; } diff --git a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.h b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.h index de5b46568..6ceb9812f 100644 --- a/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.h +++ b/src/algorithms/tracking/gnuradio_blocks/dll_pll_veml_tracking.h @@ -21,6 +21,7 @@ #include "bit_synchronizer.h" #include "cpu_multicorrelator_real_codes.h" +#include "deterministic_tracking.h" #include "dll_pll_conf.h" #include "exponential_smoother.h" #include "gnss_block_interface.h" @@ -85,6 +86,8 @@ private: explicit dll_pll_veml_tracking(const Dll_Pll_Conf &conf_); void msg_handler_telemetry_to_trk(const pmt::pmt_t &msg); + int process_input(int noutput_items, gr_vector_int &ninput_items, + gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); void do_correlation_step(const gr_complex *input_samples); void run_dll_pll(); // State 5: frequency-error-reduction Doppler-bin scan, run right after pull-in (state 1) @@ -257,6 +260,8 @@ private: bool d_wait_for_bit_edge{false}; bool d_b1c_prelock_output_pending{false}; bool d_carrier_phase_discontinuity{true}; // pending report of a new carrier phase ambiguity + + DeterministicTracking d_det{this}; // GNSS-SDR.deterministic=true }; diff --git a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.cc b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.cc index 0a2e148c7..995689093 100644 --- a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.cc +++ b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.cc @@ -141,6 +141,9 @@ Gps_L1_Ca_Gaussian_Tracking_cc::Gps_L1_Ca_Gaussian_Tracking_cc( d_dump_filename(dump_filename) { + // Inputs needed beyond the progress (GNSS-SDR.deterministic=true): see forecast() + d_det.require_span(2 * static_cast(d_vector_length)); + // Telemetry bit synchronization message port input this->message_port_register_in(pmt::mp("preamble_timestamp_s")); this->message_port_register_out(pmt::mp("events")); @@ -253,6 +256,7 @@ void Gps_L1_Ca_Gaussian_Tracking_cc::start_tracking() d_acq_code_phase_samples = d_acquisition_gnss_synchro->Acq_delay_samples; d_acq_carrier_doppler_hz = d_acquisition_gnss_synchro->Acq_doppler_hz; d_acq_sample_stamp = d_acquisition_gnss_synchro->Acq_samplestamp_samples; + d_det.start(d_acq_sample_stamp); // GNSS-SDR.deterministic=true d_acq_carrier_doppler_step_hz = static_cast(d_acquisition_gnss_synchro->Acq_doppler_step); // Correct Kalman filter covariance according to acq doppler step size (3 sigma) @@ -264,7 +268,9 @@ void Gps_L1_Ca_Gaussian_Tracking_cc::start_tracking() int64_t acq_trk_diff_samples; double acq_trk_diff_seconds; - acq_trk_diff_samples = static_cast(d_sample_counter) - static_cast(d_acq_sample_stamp); // -d_vector_length; + // With GNSS-SDR.deterministic=true, the pull-in takes place at a stamped sample + const uint64_t pull_in_sample = d_det.enabled() ? d_det.pull_in_sample() : d_sample_counter; + acq_trk_diff_samples = static_cast(pull_in_sample) - static_cast(d_acq_sample_stamp); // -d_vector_length; DLOG(INFO) << "Number of samples between Acquisition and Tracking = " << acq_trk_diff_samples; acq_trk_diff_seconds = static_cast(acq_trk_diff_samples) / static_cast(d_fs_in); // Doppler effect Fd = (C / (C + Vr)) * F @@ -539,7 +545,21 @@ void Gps_L1_Ca_Gaussian_Tracking_cc::set_gnss_synchro(Gnss_Synchro *p_gnss_synch } -int Gps_L1_Ca_Gaussian_Tracking_cc::general_work(int noutput_items __attribute__((unused)), gr_vector_int &ninput_items __attribute__((unused)), +int Gps_L1_Ca_Gaussian_Tracking_cc::general_work(int noutput_items, gr_vector_int &ninput_items, + gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) +{ + const int produced = process_input(noutput_items, ninput_items, input_items, output_items); + if (d_det.enabled()) + { + // The event reaches the control queue before the progress passes its stamp + d_det.dispatch(d_channel, [this](int event) { this->message_port_pub(pmt::mp("events"), pmt::from_long(event)); }); + d_det.publish(d_sample_counter); + } + return produced; +} + + +int Gps_L1_Ca_Gaussian_Tracking_cc::process_input(int noutput_items __attribute__((unused)), gr_vector_int &ninput_items __attribute__((unused)), gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { // process vars @@ -562,6 +582,15 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::general_work(int noutput_items __attribute__ // Receiver signal alignment if (d_pull_in == true) { + const uint64_t det_skip = d_det.samples_to_pull_in(d_sample_counter, d_channel); + if (det_skip > 0) + { + // GNSS-SDR.deterministic=true: pull in at the stamped sample + const auto n_consume = static_cast(std::min(det_skip, static_cast(ninput_items[0]))); + d_sample_counter += static_cast(n_consume); + consume_each(n_consume); + return 0; + } // Signal alignment (skip samples until the incoming signal is aligned with local replica) uint64_t acq_to_trk_delay_samples = d_sample_counter - d_acq_sample_stamp; double acq_trk_shif_correction_samples = static_cast(d_current_prn_length_samples) - std::fmod(static_cast(acq_to_trk_delay_samples), static_cast(d_current_prn_length_samples)); @@ -579,6 +608,7 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::general_work(int noutput_items __attribute__ current_synchro_data.Carrier_Doppler_hz = d_carrier_doppler_hz; current_synchro_data.fs = d_fs_in; current_synchro_data.correlation_length_ms = 1; + d_det.record_output(this->nitems_written(0), d_sample_counter); *out[0] = std::move(current_synchro_data); // Kalman filter initialization reset kf_P_x = kf_P_x_ini; @@ -741,7 +771,15 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::general_work(int noutput_items __attribute__ { std::cout << "Loss of lock in channel " << d_channel << "!\n"; LOG(INFO) << "Loss of lock in channel " << d_channel << "!"; - this->message_port_pub(pmt::mp("events"), pmt::from_long(3)); // 3 -> loss of lock + if (d_det.enabled()) + { + // raised by general_work(), without the lock held + d_det.raise_loss(d_sample_counter); + } + else + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(3)); // 3 -> loss of lock + } d_carrier_lock_fail_counter = 0; d_enable_tracking = false; loss_of_lock = true; @@ -774,6 +812,7 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::general_work(int noutput_items __attribute__ // assign the GNU Radio block output data current_synchro_data.fs = d_fs_in; + d_det.record_output(this->nitems_written(0), current_synchro_data.Tracking_sample_counter); *out[0] = std::move(current_synchro_data); if (d_dump) diff --git a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.h b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.h index a463b749d..c58a36305 100644 --- a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.h +++ b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.h @@ -32,6 +32,7 @@ #include "bayesian_estimation.h" #include "cpu_multicorrelator_real_codes.h" +#include "deterministic_tracking.h" #include "gnss_block_interface.h" #include "gnss_synchro.h" #include "tracking_2nd_DLL_filter.h" @@ -86,6 +87,8 @@ public: void forecast(int noutput_items, gr_vector_int& ninput_items_required); private: + int process_input(int noutput_items, gr_vector_int& ninput_items, + gr_vector_const_void_star& input_items, gr_vector_void_star& output_items); friend gps_l1_ca_gaussian_tracking_cc_sptr gps_l1_ca_gaussian_make_tracking_cc(uint32_t order, int64_t fs_in, @@ -193,6 +196,7 @@ private: // processing samples counters uint64_t d_sample_counter; + DeterministicTracking d_det{this}; // GNSS-SDR.deterministic=true uint64_t d_acq_sample_stamp; // CN0 estimation and lock detector diff --git a/src/algorithms/tracking/gnuradio_blocks/kf_tracking.cc b/src/algorithms/tracking/gnuradio_blocks/kf_tracking.cc index 329733bac..f1b2e0003 100644 --- a/src/algorithms/tracking/gnuradio_blocks/kf_tracking.cc +++ b/src/algorithms/tracking/gnuradio_blocks/kf_tracking.cc @@ -138,6 +138,9 @@ kf_tracking::kf_tracking(const Kf_Conf &conf_) d_dump_mat(d_trk_parameters.dump_mat && d_dump), d_acc_carrier_phase_initialized(false) { + // Inputs needed beyond the progress (GNSS-SDR.deterministic=true): see forecast() + d_det.require_span(2 * static_cast(d_trk_parameters.vector_length)); + #if GNURADIO_GREATER_THAN_38 this->set_relative_rate(1, static_cast(d_trk_parameters.vector_length)); #else @@ -632,6 +635,15 @@ void kf_tracking::forecast(int noutput_items, void kf_tracking::msg_handler_telemetry_to_trk(const pmt::pmt_t &msg) { + { + // Telemetry fault stamped with the sample of the offending symbol + // (GNSS-SDR.deterministic=true). It takes effect a lookahead later. + gr::thread::scoped_lock lock(d_setlock); + if (d_det.take_fault(msg, d_sample_counter, d_state != 0, d_channel)) + { + return; + } + } try { if (pmt::any_ref(msg).type().hash_code() == d_int_type_hash_code) @@ -681,6 +693,7 @@ void kf_tracking::start_tracking() d_acq_code_phase_samples = d_acquisition_gnss_synchro->Acq_delay_samples; d_acq_carrier_doppler_hz = d_acquisition_gnss_synchro->Acq_doppler_hz; d_acq_sample_stamp = d_acquisition_gnss_synchro->Acq_samplestamp_samples; + d_det.start(d_acq_sample_stamp); // GNSS-SDR.deterministic=true d_carrier_doppler_kf_hz = d_acq_carrier_doppler_hz; d_carrier_phase_step_rad = TWO_PI * d_carrier_doppler_kf_hz / d_trk_parameters.fs_in; @@ -1119,7 +1132,15 @@ bool kf_tracking::cn0_and_tracking_lock_status(double coh_integration_time_s) LOG(INFO) << "Loss of lock in channel " << d_channel << " (carrier_lock_fail_counter:" << d_carrier_lock_fail_counter << " code_lock_fail_counter : " << d_code_lock_fail_counter << ")"; - this->message_port_pub(pmt::mp("events"), pmt::from_long(3)); // 3 -> loss of lock + if (d_det.enabled()) + { + // raised by general_work(), without the lock held + d_det.raise_loss(d_sample_counter); + } + else + { + this->message_port_pub(pmt::mp("events"), pmt::from_long(3)); // 3 -> loss of lock + } d_carrier_lock_fail_counter = 0; d_code_lock_fail_counter = 0; return false; @@ -1741,7 +1762,21 @@ void kf_tracking::stop_tracking() } -int kf_tracking::general_work(int noutput_items __attribute__((unused)), gr_vector_int &ninput_items, +int kf_tracking::general_work(int noutput_items, gr_vector_int &ninput_items, + gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) +{ + const int produced = process_input(noutput_items, ninput_items, input_items, output_items); + if (d_det.enabled()) + { + // The event reaches the control queue before the progress passes its stamp + d_det.dispatch(d_channel, [this](int event) { this->message_port_pub(pmt::mp("events"), pmt::from_long(event)); }); + d_det.publish(d_sample_counter); + } + return produced; +} + + +int kf_tracking::process_input(int noutput_items __attribute__((unused)), gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock l(d_setlock); @@ -1750,6 +1785,12 @@ int kf_tracking::general_work(int noutput_items __attribute__((unused)), gr_vect Gnss_Synchro current_synchro_data = Gnss_Synchro(); current_synchro_data.Flag_valid_symbol_output = false; + if (d_det.fault_due(d_sample_counter, d_channel) && d_state != 0) + { + DLOG(INFO) << "Telemetry fault applied in ch " << this->d_channel; + d_carrier_lock_fail_counter = 200000; // force loss-of-lock condition + } + if (d_pull_in_transitory == true) { if (d_trk_parameters.pull_in_time_s < (d_sample_counter - d_acq_sample_stamp) / static_cast(d_trk_parameters.fs_in)) @@ -1770,6 +1811,15 @@ int kf_tracking::general_work(int noutput_items __attribute__((unused)), gr_vect } case 1: // Pull-in { + const uint64_t det_skip = d_det.samples_to_pull_in(d_sample_counter, d_channel); + if (det_skip > 0) + { + // GNSS-SDR.deterministic=true: pull in at the stamped sample + const auto n_consume = static_cast(std::min(det_skip, static_cast(ninput_items[0]))); + d_sample_counter += static_cast(n_consume); + consume_each(n_consume); + return 0; + } // Signal alignment (skip samples until the incoming signal is aligned with local replica) const int64_t acq_trk_diff_samples = static_cast(d_sample_counter) - static_cast(d_acq_sample_stamp); const double acq_trk_diff_seconds = static_cast(acq_trk_diff_samples) / d_trk_parameters.fs_in; @@ -2050,6 +2100,7 @@ int kf_tracking::general_work(int noutput_items __attribute__((unused)), gr_vect // output that carries it current_synchro_data.Flag_carrier_phase_continuous = !d_carrier_phase_discontinuity; d_carrier_phase_discontinuity = false; + d_det.record_output(this->nitems_written(0), current_synchro_data.Tracking_sample_counter); *out[0] = std::move(current_synchro_data); return 1; } diff --git a/src/algorithms/tracking/gnuradio_blocks/kf_tracking.h b/src/algorithms/tracking/gnuradio_blocks/kf_tracking.h index 1320a3722..06695b565 100644 --- a/src/algorithms/tracking/gnuradio_blocks/kf_tracking.h +++ b/src/algorithms/tracking/gnuradio_blocks/kf_tracking.h @@ -26,6 +26,7 @@ #endif #include "cpu_multicorrelator_real_codes.h" +#include "deterministic_tracking.h" #include "exponential_smoother.h" #include "gnss_block_interface.h" #include "gnss_time.h" // for timetags produced by File_Timestamp_Signal_Source @@ -73,6 +74,8 @@ public: void forecast(int noutput_items, gr_vector_int &ninput_items_required); private: + int process_input(int noutput_items, gr_vector_int &ninput_items, + gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); friend kf_tracking_sptr kf_make_tracking(const Kf_Conf &conf_); explicit kf_tracking(const Kf_Conf &conf_); @@ -197,6 +200,7 @@ private: double d_beta; uint64_t d_sample_counter; + DeterministicTracking d_det{this}; // GNSS-SDR.deterministic=true uint64_t d_acq_sample_stamp; float *d_prompt_data_shift; diff --git a/src/algorithms/tracking/libs/CMakeLists.txt b/src/algorithms/tracking/libs/CMakeLists.txt index c61cb05bf..7909193a0 100644 --- a/src/algorithms/tracking/libs/CMakeLists.txt +++ b/src/algorithms/tracking/libs/CMakeLists.txt @@ -7,6 +7,7 @@ set(TRACKING_LIB_SOURCES cpu_multicorrelator.cc + deterministic_tracking.cc cpu_multicorrelator_real_codes.cc cpu_multicorrelator_16sc.cc lock_detectors.cc @@ -25,6 +26,7 @@ set(TRACKING_LIB_SOURCES set(TRACKING_LIB_HEADERS cpu_multicorrelator.h + deterministic_tracking.h cpu_multicorrelator_real_codes.h cpu_multicorrelator_16sc.h lock_detectors.h @@ -94,6 +96,14 @@ target_link_libraries(tracking_libs Gnuradio::runtime ) +# buffer_reader moved out of buffer.h in newer GNU Radio releases. +find_path(GNURADIO_BUFFER_READER_INCLUDE_DIR gnuradio/buffer_reader.h + HINTS ${GNURADIO_RUNTIME_INCLUDE_DIRS} +) +if(GNURADIO_BUFFER_READER_INCLUDE_DIR) + target_compile_definitions(tracking_libs PRIVATE GNURADIO_HAS_BUFFER_READER_H=1) +endif() + if(ENABLE_GLOG_AND_GFLAGS) target_link_libraries(tracking_libs PRIVATE Glog::glog) target_compile_definitions(tracking_libs PRIVATE -DUSE_GLOG_AND_GFLAGS=1) diff --git a/src/algorithms/tracking/libs/deterministic_tracking.cc b/src/algorithms/tracking/libs/deterministic_tracking.cc new file mode 100644 index 000000000..b2fc6e7ae --- /dev/null +++ b/src/algorithms/tracking/libs/deterministic_tracking.cc @@ -0,0 +1,249 @@ +/*! + * \file deterministic_tracking.cc + * \brief Bookkeeping of a tracking block in deterministic processing + * \author Carles Fernandez Prades, 2026 cfernandez(at)cttc.es + * + * ----------------------------------------------------------------------------- + * + * GNSS-SDR is a Global Navigation Satellite System software-defined receiver. + * This file is part of GNSS-SDR. + * + * Copyright (C) 2010-2026 (see AUTHORS file for a list of contributors) + * SPDX-License-Identifier: GPL-3.0-or-later + * + * ----------------------------------------------------------------------------- + */ + +#include "deterministic_tracking.h" +#include +#include +#include +#include + +#if GNURADIO_HAS_BUFFER_READER_H +#include +#endif + +#if USE_GLOG_AND_GFLAGS +#include +#else +#include +#endif + + +DeterministicTracking::DeterministicTracking(gr::block* block) + : d_block(block) +{ + auto& clock = DeterministicClock::instance(); + if (clock.enabled()) + { + d_producer = clock.register_producer(DeterministicProducer::Kind::Tracking); + d_producer->set_bound([this]() { return downstream_bound(); }); + } +} + + +DeterministicTracking::~DeterministicTracking() +{ + if (d_producer) + { + d_producer->set_bound(nullptr); + } +} + + +void DeterministicTracking::require_span(uint64_t samples) const +{ + if (d_producer) + { + DeterministicClock::instance().require_span(samples); + } +} + + +void DeterministicTracking::start(uint64_t acq_stamp) +{ + if (!d_producer) + { + return; + } + // At a sample that the block has not consumed yet + std::lock_guard lock(d_mutex); + d_start = acq_stamp + DeterministicClock::instance().lookahead(); + d_session_start = d_start; + d_fault = NO_SAMPLE_STAMP; +} + + +uint64_t DeterministicTracking::pull_in_sample() +{ + std::lock_guard lock(d_mutex); + return d_start; +} + + +uint64_t DeterministicTracking::samples_to_pull_in(uint64_t position, uint32_t channel) +{ + if (!d_producer) + { + return 0; + } + std::lock_guard lock(d_mutex); + if (d_start == NO_SAMPLE_STAMP) + { + return 0; + } + if (position < d_start) + { + return d_start - position; + } + if (position > d_start) + { + LOG(ERROR) << "Deterministic pull-in in channel " << channel << " started " + << position - d_start << " samples after its stamped start " << d_start; + } + d_start = NO_SAMPLE_STAMP; + return 0; +} + + +void DeterministicTracking::record_output(uint64_t item, uint64_t stamp) +{ + if (!d_producer) + { + return; + } + std::lock_guard lock(d_mutex); + d_output_stamps.emplace_back(item, stamp); +} + + +void DeterministicTracking::raise_loss(uint64_t stamp) +{ + std::lock_guard lock(d_mutex); + d_loss = stamp; +} + + +void DeterministicTracking::dispatch(uint32_t channel, const std::function& fallback) +{ + if (!d_producer) + { + return; + } + uint64_t stamp = NO_SAMPLE_STAMP; + { + std::lock_guard lock(d_mutex); + std::swap(stamp, d_loss); + } + if (stamp != NO_SAMPLE_STAMP && + !DeterministicClock::instance().emit_channel_event(static_cast(channel), DeterministicClock::TRK_LOSS, stamp)) + { + fallback(DeterministicClock::TRK_LOSS); + } +} + + +void DeterministicTracking::publish(uint64_t position) +{ + if (d_producer) + { + d_producer->set_progress(position); + } +} + + +bool DeterministicTracking::take_fault(const pmt::pmt_t& msg, uint64_t position, bool tracking, uint32_t channel) +{ + // (1 . sample stamp of the offending symbol), see stamp_telemetry_message() + if (!pmt::is_pair(msg) || !pmt::is_integer(pmt::car(msg)) || pmt::to_long(pmt::car(msg)) != 1 || !pmt::is_uint64(pmt::cdr(msg))) + { + return false; + } + if (!d_producer) + { + return true; + } + const uint64_t stamp = pmt::to_uint64(pmt::cdr(msg)); + std::lock_guard lock(d_mutex); + // Ignore faults of a previous satellite + if (tracking && stamp >= d_session_start) + { + const uint64_t effective = stamp + DeterministicClock::instance().lookahead(); + if (position > effective) + { + LOG(ERROR) << "Deterministic telemetry fault in channel " << channel << " arrived " + << position - effective << " samples late"; + } + d_fault = std::min(d_fault, stamp); + } + return true; +} + + +bool DeterministicTracking::fault_due(uint64_t position, uint32_t channel) +{ + if (!d_producer) + { + return false; + } + std::lock_guard lock(d_mutex); + // Read the decoder's synchronous handoff on every work call. A GNU Radio + // message may arrive after the scheduler has already checked its queue. + auto& clock = DeterministicClock::instance(); + const uint64_t reported = clock.take_telemetry_fault(static_cast(channel), d_session_start); + if (reported != NO_SAMPLE_STAMP && position > reported + clock.lookahead()) + { + LOG(ERROR) << "Deterministic telemetry fault in channel " << channel << " arrived " + << position - (reported + clock.lookahead()) << " samples late"; + } + d_fault = std::min(d_fault, reported); + if (d_fault == NO_SAMPLE_STAMP || position < d_fault + DeterministicClock::instance().lookahead()) + { + return false; + } + d_fault = NO_SAMPLE_STAMP; + return true; +} + + +uint64_t DeterministicTracking::downstream_bound() +{ + const auto state = d_block->detail(); + if (!state || state->noutputs() < 1) + { + return NO_SAMPLE_STAMP; + } + const auto output = state->output(0); + if (!output) + { + return NO_SAMPLE_STAMP; + } + // A telemetry decoder consumes a symbol before publishing its faults, so + // count only the symbols that it has finished with (see TelemetryWorkScope) + const auto& clock = DeterministicClock::instance(); + uint64_t consumed = NO_SAMPLE_STAMP; + { + gr::thread::scoped_lock lock(*output->mutex()); + for (size_t r = 0; r < output->nreaders(); r++) + { + const auto& reader = output->reader(r); + const gr::block* reader_block = nullptr; + try + { + reader_block = reader->link().get(); + } + catch (const std::exception&) + { + // The reading block is gone + } + consumed = std::min(consumed, clock.consumed(reader_block, reader->nitems_read())); + } + } + std::lock_guard lock(d_mutex); + while (!d_output_stamps.empty() && d_output_stamps.front().first < consumed) + { + d_output_stamps.pop_front(); + } + return d_output_stamps.empty() ? NO_SAMPLE_STAMP : d_output_stamps.front().second; +} diff --git a/src/algorithms/tracking/libs/deterministic_tracking.h b/src/algorithms/tracking/libs/deterministic_tracking.h new file mode 100644 index 000000000..c52a875a6 --- /dev/null +++ b/src/algorithms/tracking/libs/deterministic_tracking.h @@ -0,0 +1,117 @@ +/*! + * \file deterministic_tracking.h + * \brief Bookkeeping of a tracking block in deterministic processing + * \author Carles Fernandez Prades, 2026 cfernandez(at)cttc.es + * + * With GNSS-SDR.deterministic=true (see DeterministicClock), a tracking block + * pulls in at a stamped sample, raises loss of lock in its own thread, applies + * telemetry faults at a stamped sample, and publishes a progress that its + * telemetry decoder cannot fall too far behind. + * + * ----------------------------------------------------------------------------- + * + * GNSS-SDR is a Global Navigation Satellite System software-defined receiver. + * This file is part of GNSS-SDR. + * + * Copyright (C) 2010-2026 (see AUTHORS file for a list of contributors) + * SPDX-License-Identifier: GPL-3.0-or-later + * + * ----------------------------------------------------------------------------- + */ + +#ifndef GNSS_SDR_DETERMINISTIC_TRACKING_H +#define GNSS_SDR_DETERMINISTIC_TRACKING_H + +#include "deterministic_clock.h" +#include +#include +#include +#include +#include +#include +#include +#include + +/** \addtogroup Tracking + * \{ */ +/** \addtogroup Tracking_libs + * \{ */ + + +/*! + * \brief Deterministic-processing state of a tracking block. It does nothing + * unless GNSS-SDR.deterministic=true. + */ +class DeterministicTracking +{ +public: + /*! + * \brief Registers \p block as a producer of channel events, if enabled. + * Its progress is bounded by the first of its outputs that the blocks + * downstream have not finished with yet (see DeterministicClock::consumed()). + */ + explicit DeterministicTracking(gr::block* block); + ~DeterministicTracking(); + DeterministicTracking(const DeterministicTracking&) = delete; + DeterministicTracking& operator=(const DeterministicTracking&) = delete; + + bool enabled() const { return static_cast(d_producer); } + + //! Declares the input needed beyond the progress (e.g., the forecast) + void require_span(uint64_t samples) const; + + //! start_tracking(): the pull-in takes place one lookahead after \p acq_stamp + void start(uint64_t acq_stamp); + + //! Input sample of the pending pull-in, NO_SAMPLE_STAMP if none + uint64_t pull_in_sample(); + + /*! + * \brief Samples to consume before pulling in at the stamped sample, from + * input position \p position (0 to pull in now). Clears the pending start + * once it is reached. + */ + uint64_t samples_to_pull_in(uint64_t position, uint32_t channel); + + //! Remembers the sample stamp of output item \p item + void record_output(uint64_t item, uint64_t stamp); + + //! Defers a loss of lock, which may be raised with the block lock held, to dispatch() + void raise_loss(uint64_t stamp); + + /*! + * \brief Applies the deferred loss of lock, if any, in the calling thread. + * Calls \p fallback (which should publish the event) if the channel has + * no event sink. + */ + void dispatch(uint32_t channel, const std::function& fallback); + + //! Publishes the input position reached + void publish(uint64_t position); + + /*! + * \brief Takes a telemetry fault stamped by the telemetry decoder. + * \return false if \p msg is not one. + */ + bool take_fault(const pmt::pmt_t& msg, uint64_t position, bool tracking, uint32_t channel); + + //! Reads the synchronous fault handoff; true once when a fault is due at \p position. + bool fault_due(uint64_t position, uint32_t channel); + +private: + uint64_t downstream_bound(); + + gr::block* d_block; + std::shared_ptr d_producer; + std::mutex d_mutex; + std::deque> d_output_stamps; // (output item, sample stamp) not read downstream yet + uint64_t d_start{NO_SAMPLE_STAMP}; // pull-in sample + uint64_t d_session_start{0}; // pull-in sample of the current satellite + uint64_t d_loss{NO_SAMPLE_STAMP}; // deferred loss of lock + uint64_t d_fault{NO_SAMPLE_STAMP}; // telemetry fault waiting for its effective sample +}; + + +/** \} */ +/** \} */ +#endif // GNSS_SDR_DETERMINISTIC_TRACKING_H diff --git a/src/core/interfaces/signal_source_interface.h b/src/core/interfaces/signal_source_interface.h index 440d0ddcf..ec30f8a3b 100644 --- a/src/core/interfaces/signal_source_interface.h +++ b/src/core/interfaces/signal_source_interface.h @@ -60,6 +60,14 @@ public: */ virtual bool is_real_time() const { return true; } + /*! + * \brief True if the source can wait for the blocks that read it without + * losing samples, as a replay of a recording, throttled or not. False if + * samples are lost when the receiver does not keep up, as with a radio + * front end. + */ + virtual bool can_wait() const { return !is_real_time(); } + protected: SignalSourceInterface() { diff --git a/src/core/libs/CMakeLists.txt b/src/core/libs/CMakeLists.txt index d1460eb97..918410bda 100644 --- a/src/core/libs/CMakeLists.txt +++ b/src/core/libs/CMakeLists.txt @@ -17,6 +17,7 @@ set(CORE_LIBS_SOURCES gnss_crypto.cc gnss_sdr_sample_counter.cc gnss_sdr_supl_client.cc + horizon_gate.cc ini.cc INIReader.cc nav_message_monitor.cc @@ -36,6 +37,7 @@ set(CORE_LIBS_HEADERS gnss_crypto.h gnss_sdr_sample_counter.h gnss_sdr_supl_client.h + horizon_gate.h ini.h INIReader.h nav_message_monitor.h @@ -109,6 +111,14 @@ target_link_libraries(core_libs Pugixml::pugixml ) +# buffer_reader moved out of buffer.h in newer GNU Radio releases. +find_path(GNURADIO_BUFFER_READER_INCLUDE_DIR gnuradio/buffer_reader.h + HINTS ${GNURADIO_RUNTIME_INCLUDE_DIRS} +) +if(GNURADIO_BUFFER_READER_INCLUDE_DIR) + target_compile_definitions(core_libs PRIVATE GNURADIO_HAS_BUFFER_READER_H=1) +endif() + if(ENABLE_GLOG_AND_GFLAGS) target_link_libraries(core_libs PRIVATE Gflags::gflags Glog::glog) target_compile_definitions(core_libs PRIVATE -DUSE_GLOG_AND_GFLAGS=1) diff --git a/src/core/libs/channel_event.cc b/src/core/libs/channel_event.cc index b23b004da..e10d962c4 100644 --- a/src/core/libs/channel_event.cc +++ b/src/core/libs/channel_event.cc @@ -16,13 +16,14 @@ #include "channel_event.h" -channel_event_sptr channel_event_make(int channel_id, int event_type) +channel_event_sptr channel_event_make(int channel_id, int event_type, uint64_t sample_stamp) { - return channel_event_sptr(new Channel_Event(channel_id, event_type)); + return channel_event_sptr(new Channel_Event(channel_id, event_type, sample_stamp)); } -Channel_Event::Channel_Event(int channel_id_, int event_type_) +Channel_Event::Channel_Event(int channel_id_, int event_type_, uint64_t sample_stamp_) : channel_id(channel_id_), - event_type(event_type_) + event_type(event_type_), + sample_stamp(sample_stamp_) { } diff --git a/src/core/libs/channel_event.h b/src/core/libs/channel_event.h index 6ca91c67a..d2ab0e9de 100644 --- a/src/core/libs/channel_event.h +++ b/src/core/libs/channel_event.h @@ -17,6 +17,8 @@ #ifndef GNSS_SDR_CHANNEL_EVENT_H #define GNSS_SDR_CHANNEL_EVENT_H +#include +#include #include /** \addtogroup Core @@ -29,17 +31,23 @@ class Channel_Event; using channel_event_sptr = std::shared_ptr; -channel_event_sptr channel_event_make(int channel_id, int event_type); +/*! + * \brief Makes a channel event. \p sample_stamp is the input sample at which + * the event happened, used to order events in deterministic processing. + */ +channel_event_sptr channel_event_make(int channel_id, int event_type, + uint64_t sample_stamp = std::numeric_limits::max()); class Channel_Event { public: int channel_id; int event_type; + uint64_t sample_stamp; private: - friend channel_event_sptr channel_event_make(int channel_id, int event_type); - Channel_Event(int channel_id_, int event_type_); + friend channel_event_sptr channel_event_make(int channel_id, int event_type, uint64_t sample_stamp); + Channel_Event(int channel_id_, int event_type_, uint64_t sample_stamp_); }; diff --git a/src/core/libs/horizon_gate.cc b/src/core/libs/horizon_gate.cc new file mode 100644 index 000000000..45970305e --- /dev/null +++ b/src/core/libs/horizon_gate.cc @@ -0,0 +1,111 @@ +/*! + * \file horizon_gate.cc + * \brief Block that releases a stream up to the deterministic horizon + * \author Carles Fernandez Prades, 2026 cfernandez(at)cttc.es + * + * ----------------------------------------------------------------------------- + * + * GNSS-SDR is a Global Navigation Satellite System software-defined receiver. + * This file is part of GNSS-SDR. + * + * Copyright (C) 2010-2026 (see AUTHORS file for a list of contributors) + * SPDX-License-Identifier: GPL-3.0-or-later + * + * ----------------------------------------------------------------------------- + */ + +#include "horizon_gate.h" +#include "deterministic_clock.h" +#include +#include +#include +#include +#include +#include + +#if GNURADIO_HAS_BUFFER_READER_H +#include +#endif + +#if USE_GLOG_AND_GFLAGS +#include +#else +#include +#endif + +namespace +{ +// Waiting is bounded so that the scheduler can stop the block +constexpr std::chrono::milliseconds kHorizonWait(10); +constexpr std::chrono::seconds kStallReport(10); +} // namespace + + +horizon_gate_sptr make_horizon_gate(size_t item_size, uint64_t batch_items) +{ + return horizon_gate_sptr(new horizon_gate(item_size, batch_items)); +} + + +horizon_gate::horizon_gate(size_t item_size, uint64_t batch_items) + : gr::block("horizon_gate", + gr::io_signature::make(1, 1, static_cast(item_size)), + gr::io_signature::make(1, 1, static_cast(item_size))), + item_size_(item_size) +{ + // Wake the readers once per batch, not whenever one of them frees space + set_output_multiple(static_cast(std::min(std::max(batch_items, 1), + static_cast(std::numeric_limits::max() / 2)))); +} + + +bool horizon_gate::input_finished() const +{ + const auto state = detail(); + if (!state || state->ninputs() == 0) + { + return false; + } + const auto input = state->input(0); + gr::thread::scoped_lock lock(*input->mutex()); + return input->done(); +} + + +void horizon_gate::forecast(int noutput_items, gr_vector_int& ninput_items_required) +{ + // A whole batch of input, except for the tail of the stream + ninput_items_required[0] = input_finished() ? 1 : noutput_items; +} + + +int horizon_gate::general_work(int noutput_items, gr_vector_int& ninput_items, + gr_vector_const_void_star& input_items, gr_vector_void_star& output_items) +{ + auto& clock = DeterministicClock::instance(); + const uint64_t released = nitems_written(0); + if (clock.horizon() <= released && !clock.wait_beyond(released, kHorizonWait)) + { + // Nothing consumed: the scheduler calls again, after the wait + const auto now = std::chrono::steady_clock::now(); + if (!stalled_) + { + stalled_ = true; + stalled_since_ = now; + } + else if (!stall_reported_ && now - stalled_since_ > kStallReport) + { + stall_reported_ = true; + LOG(WARNING) << "Deterministic horizon stalled at sample " << released + << " (lowest producer progress " << clock.min_progress() << ")"; + } + return 0; + } + stalled_ = false; + stall_reported_ = false; + const uint64_t allowance = clock.horizon() - released; + const int count = static_cast(std::min(allowance, static_cast(std::min(noutput_items, ninput_items[0])))); + std::memcpy(output_items[0], input_items[0], static_cast(count) * item_size_); + consume_each(count); + return count; +} diff --git a/src/core/libs/horizon_gate.h b/src/core/libs/horizon_gate.h new file mode 100644 index 000000000..c9474322a --- /dev/null +++ b/src/core/libs/horizon_gate.h @@ -0,0 +1,66 @@ +/*! + * \file horizon_gate.h + * \brief Block that releases a stream up to the deterministic horizon + * \author Carles Fernandez Prades, 2026 cfernandez(at)cttc.es + * + * ----------------------------------------------------------------------------- + * + * GNSS-SDR is a Global Navigation Satellite System software-defined receiver. + * This file is part of GNSS-SDR. + * + * Copyright (C) 2010-2026 (see AUTHORS file for a list of contributors) + * SPDX-License-Identifier: GPL-3.0-or-later + * + * ----------------------------------------------------------------------------- + */ + +#ifndef GNSS_SDR_HORIZON_GATE_H +#define GNSS_SDR_HORIZON_GATE_H + +#include "gnss_block_interface.h" +#include +#include +#include +#include + +/** \addtogroup Core + * \{ */ +/** \addtogroup Core_Receiver_Library + * \{ */ + +class horizon_gate; +using horizon_gate_sptr = gnss_shared_ptr; + +/*! + * \brief Makes a block that copies its input until the number of items set + * by DeterministicClock::horizon(), so that no reader of its output sees an + * item beyond it. + * \param item_size Size of a stream item, in bytes. + * \param batch_items Items released at once, except at the end of the stream. + */ +horizon_gate_sptr make_horizon_gate(size_t item_size, uint64_t batch_items); + +/*! + * \brief Copies a stream up to the deterministic horizon. + */ +class horizon_gate : public gr::block +{ +public: + void forecast(int noutput_items, gr_vector_int& ninput_items_required) override; + int general_work(int noutput_items, gr_vector_int& ninput_items, + gr_vector_const_void_star& input_items, gr_vector_void_star& output_items) override; + +private: + friend horizon_gate_sptr make_horizon_gate(size_t item_size, uint64_t batch_items); + horizon_gate(size_t item_size, uint64_t batch_items); + bool input_finished() const; + + std::chrono::steady_clock::time_point stalled_since_; + size_t item_size_; + bool stalled_ = false; + bool stall_reported_ = false; +}; + +/** \} */ +/** \} */ +#endif // GNSS_SDR_HORIZON_GATE_H diff --git a/src/core/receiver/control_thread.cc b/src/core/receiver/control_thread.cc index 86589f5ec..f6cb1c9de 100644 --- a/src/core/receiver/control_thread.cc +++ b/src/core/receiver/control_thread.cc @@ -25,6 +25,7 @@ #include "control_thread.h" #include "concurrent_map.h" #include "configuration_interface.h" +#include "deterministic_clock.h" #include "file_configuration.h" #include "galileo_almanac.h" #include "galileo_ephemeris.h" @@ -63,7 +64,9 @@ #include // for numeric_limits #include // for map #include // for pthread_cancel +#include // for priority_queue #include // for invalid_argument +#include // for tie #if USE_GLOG_AND_GFLAGS #include @@ -296,22 +299,7 @@ void ControlThread::event_dispatcher(bool &valid_event, pmt::pmt_t &msg) } else if (msg_type_hash_code == command_event_type_hash_code_) { - const auto new_event = wht::any_cast(pmt::any_ref(msg)); - DLOG(INFO) << "New command event rx from ch id: " << new_event->command_id - << " what: " << new_event->event_type; - - if (new_event->command_id == 200) - { - apply_action(new_event->event_type); - } - else - { - if (new_event->command_id == 300) // some TC commands require also actions from control_thread - { - apply_action(new_event->event_type); - } - flowgraph_->apply_action(new_event->command_id, new_event->event_type); - } + dispatch_command_event(msg); } else { @@ -340,6 +328,120 @@ void ControlThread::event_dispatcher(bool &valid_event, pmt::pmt_t &msg) } +void ControlThread::dispatch_command_event(const pmt::pmt_t &msg) +{ + const auto new_event = wht::any_cast(pmt::any_ref(msg)); + DLOG(INFO) << "New command event rx from ch id: " << new_event->command_id + << " what: " << new_event->event_type; + + if (new_event->command_id == 200) + { + apply_action(new_event->event_type); + } + else + { + if (new_event->command_id == 300) // some TC commands require also actions from control_thread + { + apply_action(new_event->event_type); + } + flowgraph_->apply_action(new_event->command_id, new_event->event_type); + } +} + + +void ControlThread::run_deterministic_loop() +{ + struct StampedEvent + { + uint64_t stamp; + int channel; + int type; + }; + const auto later = [](const StampedEvent &a, const StampedEvent &b) { + return std::tie(a.stamp, a.channel, a.type) > std::tie(b.stamp, b.channel, b.type); + }; + std::priority_queue, decltype(later)> pending(later); + auto &clock = DeterministicClock::instance(); + const uint64_t tick = clock.tick(); + const uint64_t lookahead = clock.lookahead(); + // Releasing the stream in quanta spares scheduler wakeups. The lookahead + // covers 1.25 times the largest input span of a producer (see + // DeterministicClock::require_span()), so one quantum less still does. + const uint64_t quantum = std::max(1, lookahead / 8); + uint64_t next_tick = tick; + uint64_t handled = 0; // every event stamped below this has been handled + pmt::pmt_t msg; + bool have_msg = false; + while (flowgraph_->running() && !stop_) + { + // Read the progress first: events stamped below it are queued by now + const uint64_t progress = clock.min_progress(); + while (have_msg || control_queue_->try_pop(msg)) + { + have_msg = false; + processed_control_messages_++; + const size_t msg_type_hash_code = pmt::any_ref(msg).type().hash_code(); + if (msg_type_hash_code == channel_event_type_hash_code_) + { + const auto new_event = wht::any_cast(pmt::any_ref(msg)); + if (new_event->sample_stamp == NO_SAMPLE_STAMP || new_event->sample_stamp < handled) + { + LOG(ERROR) << "Deterministic processing received event " << new_event->event_type << " from channel " + << new_event->channel_id << " stamped " << new_event->sample_stamp << ", below " << handled; + } + pending.push(StampedEvent{new_event->sample_stamp == NO_SAMPLE_STAMP ? handled : new_event->sample_stamp, + new_event->channel_id, new_event->event_type}); + } + else if (msg_type_hash_code == command_event_type_hash_code_) + { + dispatch_command_event(msg); + } + else + { + DLOG(INFO) << "Control Queue: unknown object type!\n"; + } + } + if (stop_ || progress == NO_SAMPLE_STAMP) + { + break; + } + // Handle events and ticks stamped below the progress, in stamp + // order. An event goes before a tick with the same stamp. + while (!receiver_on_standby_) + { + const uint64_t next_event = pending.empty() ? NO_SAMPLE_STAMP : pending.top().stamp; + if (next_tick < progress && next_tick < next_event) + { + const DeterministicClock::Scope cause(next_tick); + flowgraph_->acquisition_manager(0); // start acquisition of untracked satellites + next_tick += tick; + } + else if (next_event < progress) + { + const StampedEvent event = pending.top(); + pending.pop(); + DLOG(INFO) << "Deterministic event from ch id: " << event.channel << " what: " << event.type << " at sample " << event.stamp; + const DeterministicClock::Scope cause(event.stamp); + flowgraph_->apply_action(event.channel, event.type); + } + else + { + break; + } + } + handled = progress; + const uint64_t horizon = progress + lookahead; + clock.advance_horizon(horizon - horizon % quantum); + if (flowgraph_->data_path_done()) + { + LOG(INFO) << "Deterministic processing: the PVT block has processed the whole input"; + break; + } + have_msg = control_queue_->timed_wait_and_pop(msg, 1); + } +} + + /* * Runs the control thread that manages the receiver control plane * @@ -415,8 +517,12 @@ int ControlThread::run() flowgraph_); #endif // Main loop to read and process the control messages + if (flowgraph_->deterministic()) + { + run_deterministic_loop(); + } pmt::pmt_t msg; - while (flowgraph_->running() && !stop_) + while (flowgraph_->running() && !stop_ && !flowgraph_->deterministic()) { // read event messages, triggered by event signaling with a 100 ms timeout to perform low priority receiver management tasks bool valid_event = control_queue_->timed_wait_and_pop(msg, 100); diff --git a/src/core/receiver/control_thread.h b/src/core/receiver/control_thread.h index 8d8233750..0a7e43acf 100644 --- a/src/core/receiver/control_thread.h +++ b/src/core/receiver/control_thread.h @@ -140,6 +140,14 @@ private: */ void event_dispatcher(bool &valid_event, pmt::pmt_t &msg); + void dispatch_command_event(const pmt::pmt_t &msg); + + /* + * Control loop of GNSS-SDR.deterministic=true: channel events and + * maintenance ticks are handled in sample-stamp order, see DeterministicClock + */ + void run_deterministic_loop(); + // Read {ephemeris, iono, utc, ref loc, ref time} assistance from a local XML file previously recorded bool read_assistance_from_XML(); diff --git a/src/core/receiver/gnss_flowgraph.cc b/src/core/receiver/gnss_flowgraph.cc index 1f9d6d62c..d70a82475 100644 --- a/src/core/receiver/gnss_flowgraph.cc +++ b/src/core/receiver/gnss_flowgraph.cc @@ -36,6 +36,7 @@ #include "channel_fsm.h" #include "channel_interface.h" #include "configuration_interface.h" +#include "deterministic_clock.h" #include "gnss_block_factory.h" #include "gnss_block_interface.h" #include "gnss_frequencies.h" @@ -43,7 +44,9 @@ #include "gnss_sdr_flags.h" #include "gnss_sdr_make_unique.h" #include "gnss_synchro_monitor.h" +#include "horizon_gate.h" #include "nav_message_monitor.h" +#include "pcps_acquisition_adapter.h" #include "qzss.h" #include "signal_conditioner.h" #include "signal_source_interface.h" @@ -52,6 +55,8 @@ #include // for boost::lexical_cast #include // for boost::tokenizer #include // for basic_block +#include // for block +#include // for block_detail #include // for gr::filter::firdes #include // for io_signature #include // for top_block, make_top_block @@ -139,7 +144,8 @@ GNSSFlowgraph::GNSSFlowgraph(std::shared_ptr configurati running_(false), multiband_(GNSSFlowgraph::is_multiband()), enable_osnma_rx_(false), - enable_e6_has_rx_(false) + enable_e6_has_rx_(false), + deterministic_(configuration_->property("GNSS-SDR.deterministic", false)) { enable_fpga_offloading_ = configuration_->property("GNSS-SDR.enable_FPGA", false); // Skip the assisted acquisition of secondary signals reported as not @@ -150,6 +156,16 @@ GNSSFlowgraph::GNSSFlowgraph(std::shared_ptr configurati // Paced by the receiver time reported by the observables block every // 100 ms (or every epoch, if longer): higher rates act as that rate. acquisition_retry_min_interval_s_ = (acquisition_max_retry_rate_hz > 0.0) ? (1.0 / acquisition_max_retry_rate_hz) : 0.0; + if (deterministic_) + { + // Before the blocks are created, so that they register with it + const double fs = configuration_->property("GNSS-SDR.internal_fs_sps", 0.0); + const double lookahead_ms = configuration_->property("GNSS-SDR.deterministic_lookahead_ms", 100.0); + const double tick_ms = configuration_->property("GNSS-SDR.deterministic_tick_ms", 100.0); + DeterministicClock::instance().enable(fs, + static_cast(std::max(0.0, std::ceil(lookahead_ms * fs / 1000.0))), + static_cast(std::max(0.0, std::ceil(tick_ms * fs / 1000.0)))); + } init(); } @@ -161,6 +177,10 @@ GNSSFlowgraph::~GNSSFlowgraph() { GNSSFlowgraph::disconnect(); } + if (deterministic_) + { + DeterministicClock::instance().disable(); + } } @@ -433,6 +453,11 @@ void GNSSFlowgraph::start() void GNSSFlowgraph::stop() { + if (deterministic_) + { + // Do not hold the stream while the blocks stop + DeterministicClock::instance().open_horizon(); + } for (const auto& chan : channels_) { chan->stop_channel(); // stop the acquisition or tracking operation @@ -471,6 +496,13 @@ void GNSSFlowgraph::connect() return; } + if (deterministic_ && !deterministic_configuration_is_supported()) + { + std::cerr << "Unable to connect flowgraph\n"; + print_help(); + return; + } + #if ENABLE_FPGA if (enable_fpga_offloading_ == true) { @@ -1360,7 +1392,21 @@ void GNSSFlowgraph::connect_conditioner_output(size_t conditioner_id, StreamEndp } const std::string role = conditioner->role(); const auto& plan = conditioner_plans_.at(conditioner_id); - if (plan.batch_items > 0) + if (deterministic_) + { + // Readers never see a sample beyond the deterministic horizon. The + // released samples that some reader has not consumed yet span at + // most one lookahead. + const size_t item_size = upstream.block->output_signature()->sizeof_stream_item(upstream.port); + const uint64_t lookahead = DeterministicClock::instance().lookahead(); + // Same quantum as the horizon, see ControlThread::run_deterministic_loop() + const auto gate = make_horizon_gate(item_size, std::max(1, lookahead / 8)); + gate->set_min_output_buffer(0, static_cast(std::max(plan.min_buffer_items, lookahead + lookahead / 2))); // NOLINT(google-runtime-int) + top_block_->connect(upstream.block, upstream.port, gate, 0); + upstream.block = gate; + upstream.port = 0; + } + else if (plan.batch_items > 0) { if (!conditioner_deadlines_) { @@ -2152,7 +2198,7 @@ void GNSSFlowgraph::acquisition_manager(unsigned int who) if (signal_available) { channels_[current_channel]->set_signal(gnss_signal); - start_acquisition = is_primary_freq || assistance_available || !configuration_->property("GNSS-SDR.assist_dual_frequency_acq", multiband_); + start_acquisition = is_primary_freq || assistance_available || !assist_dual_frequency_acq(); } // else: nothing searchable for this signal now. Leave the channel // idle instead of starting a doomed acquisition; acquisition_manager() @@ -2171,7 +2217,7 @@ void GNSSFlowgraph::acquisition_manager(unsigned int who) DLOG(INFO) << "Channel " << current_channel << " Starting acquisition " << channels_[current_channel]->get_signal().get_satellite() << ", Signal " << channels_[current_channel]->get_signal().get_signal_str(); - if (assistance_available == true && configuration_->property("GNSS-SDR.assist_dual_frequency_acq", multiband_)) + if (assistance_available == true && assist_dual_frequency_acq()) { // Use the projected primary-band Doppler; the role flag can retain a full search. const std::string acq_role = block_factory::get_role_name(configuration_.get(), "Acquisition_", channels_[current_channel]->get_signal().get_signal_str(), static_cast(current_channel)); @@ -2361,8 +2407,7 @@ void GNSSFlowgraph::apply_action(unsigned int who, unsigned int what) // Retry the same satellite unless it is in acquisition cooldown (a // signal that locks and drops at once would loop here). { - double receiver_time_s = 0.0; - channels_status_->get_current_status_pvt(&receiver_time_s); + const double receiver_time_s = control_receiver_time_s(); if (acq_channels_count_ < max_acq_channels_ && !InAcquisitionCooldown(gs, receiver_time_s)) { // try to acquire the same satellite @@ -2549,6 +2594,203 @@ bool GNSSFlowgraph::visibility_aware_search_enabled() const } +bool GNSSFlowgraph::data_path_done() const +{ + if (!pvt_) + { + return false; + } + const auto* pvt_block = dynamic_cast(pvt_->get_left_block().get()); + if (pvt_block == nullptr) + { + return false; + } + const auto state = pvt_block->detail(); + return state && state->done(); +} + + +bool GNSSFlowgraph::deterministic_configuration_is_supported() +{ + // Features that read live receiver state, or depend on wall-clock time + std::vector unsupported; + if (enable_fpga_offloading_) + { + unsupported.emplace_back("GNSS-SDR.enable_FPGA=true"); + } + if (configuration_->property("GNSS-SDR.internal_fs_sps", 0.0) <= 0.0) + { + unsupported.emplace_back("an unset GNSS-SDR.internal_fs_sps"); + } + if (configuration_->property("GNSS-SDR.use_acquisition_resampler", false)) + { + // Only the PCPS acquisition converts its sample counts to the stream + // rate, which needs the decimation of the resampler that + // connect_signal_conditioners_to_channels() puts in front of it. + int other_acquisitions = 0; + std::set mismatched_signals; + for (const auto& channel_interface : channels_) + { + const auto channel = std::dynamic_pointer_cast(channel_interface); + if (!channel) + { + continue; + } + const auto signal = channel->get_signal().get_signal_str(); + const auto decimation = acquisition_decimation_for_signal(signal); + const auto pcps = std::dynamic_pointer_cast(channel->acquisition()); + if (!pcps) + { + other_acquisitions += decimation > 1 ? 1 : 0; + } + else if (pcps->resampler_decimation() != decimation) + { + mismatched_signals.insert(signal); + } + } + if (other_acquisitions > 0) + { + unsupported.emplace_back("GNSS-SDR.use_acquisition_resampler=true in " + std::to_string(other_acquisitions) + " channel(s) with an acquisition implementation other than PCPS"); + } + for (const auto& signal : mismatched_signals) + { + unsupported.emplace_back("GNSS-SDR.use_acquisition_resampler=true for signal " + signal + ", whose acquisition expects a decimation other than that of its resampler"); + } + } + if (visibility_aware_search_enabled()) + { + unsupported.emplace_back("GNSS-SDR.enable_visibility_aware_search=true"); + } + if (configuration_->property("GNSS-SDR.SUPL_gps_enabled", false) || configuration_->property("GNSS-SDR.AGNSS_XML_enabled", false)) + { + unsupported.emplace_back("GNSS assistance (GNSS-SDR.SUPL_gps_enabled or GNSS-SDR.AGNSS_XML_enabled)"); + } + if (configuration_->property("GNSS-SDR.assist_dual_frequency_acq", false)) + { + unsupported.emplace_back("GNSS-SDR.assist_dual_frequency_acq=true"); + } + // The PVT applies authentication results, HAS corrections and NTRIP + // corrections when they arrive, not at a stamped epoch + if (enable_osnma_rx_ && configuration_->property("GNSS-SDR.osnma_mode", std::string("")) == "strict") + { + unsupported.emplace_back("GNSS-SDR.osnma_mode=strict"); + } + if (enable_e6_has_rx_ && configuration_->property("PVT.use_has_corrections", true)) + { + unsupported.emplace_back("Galileo HAS corrections (PVT.use_has_corrections=true, the default with Galileo E6 channels)"); + } + if (configuration_->property("PVT.ntrip_client_enabled", false)) + { + unsupported.emplace_back("NTRIP corrections (PVT.ntrip_client_enabled=true)"); + } + // The E6 telemetry decoders take the time of week of the E1, E5a or E5b + // decoders from the Galileo TOW map when it arrives + bool galileo_tow_source = false; + std::set standby_roles; + for (int ch = 0; ch < channels_count_; ch++) + { + if (!channels_.at(ch)) + { + continue; + } + const auto signal = channels_.at(ch)->get_signal().get_signal_str(); + galileo_tow_source = galileo_tow_source || is_galileo_tow_source(signal); + // An idle search that does not consume holds the stream back forever + const auto acq_role = block_factory::get_role_name(configuration_.get(), "Acquisition_", signal, ch); + if (configuration_->property(acq_role + ".blocking_on_standby", false)) + { + standby_roles.insert(acq_role); + } + } + if (enable_e6_has_rx_ && galileo_tow_source) + { + unsupported.emplace_back("Galileo E6 channels together with Galileo E1, E5a or E5b channels (Galileo TOW map)"); + } + for (const auto& role : standby_roles) + { + unsupported.emplace_back(role + ".blocking_on_standby=true"); + } + if (!(configuration_->property("GNSS-SDR.deterministic_lookahead_ms", 100.0) > 0.0)) + { + unsupported.emplace_back("a GNSS-SDR.deterministic_lookahead_ms that is not positive"); + } + if (!(configuration_->property("GNSS-SDR.deterministic_tick_ms", 100.0) >= 1.0)) + { + // Maintenance would run at nearly every sample + unsupported.emplace_back("a GNSS-SDR.deterministic_tick_ms below 1 ms"); + } + for (const auto& source : sig_source_) + { + if (source && !source->can_wait()) + { + // Holding the stream back would drop samples + unsupported.emplace_back(source->role() + ": a real-time signal source"); + } + } + const auto& clock = DeterministicClock::instance(); + // The observables block computes an epoch one epoch age after its clock + // sample. By then, the stream must have released the channel data up to + // just after the epoch, so the lookahead must leave room for it. + const auto observable_interval_ms = configuration_->property("GNSS-SDR.observable_interval_ms", 20U); + const double lookahead_ms = 1000.0 * static_cast(clock.lookahead()) / clock.sampling_rate(); + const double max_lookahead_ms = static_cast(observables_clock_delay_ms(observable_interval_ms)) - DETERMINISTIC_OBSERVABLES_MARGIN_MS - DETERMINISTIC_SYMBOL_MARGIN_MS; + if (clock.sampling_rate() > 0.0 && lookahead_ms > max_lookahead_ms) + { + unsupported.emplace_back("a lookahead of " + std::to_string(lookahead_ms) + " ms (GNSS-SDR.deterministic_lookahead_ms, or the input span of a channel) above " + + std::to_string(max_lookahead_ms) + " ms with GNSS-SDR.observable_interval_ms=" + std::to_string(observable_interval_ms)); + } + const auto acquisitions = static_cast(clock.count_producers(DeterministicProducer::Kind::Acquisition)); + if (acquisitions != channels_count_) + { + unsupported.emplace_back(std::to_string(channels_count_ - acquisitions) + " channel(s) with an acquisition implementation that does not support it (assisted, FPGA)"); + } + const auto trackings = static_cast(clock.count_producers(DeterministicProducer::Kind::Tracking)); + if (trackings != channels_count_) + { + unsupported.emplace_back(std::to_string(channels_count_ - trackings) + " channel(s) with a tracking implementation that does not support it (TCP connector, GPU, FPGA)"); + } + if (!unsupported.empty()) + { + help_hint_ += " * GNSS-SDR.deterministic=true does not support:\n"; + for (const auto& item : unsupported) + { + help_hint_ += " - " + item + "\n"; + } + return false; + } + if (configuration_->property("GNSS-SDR.telecommand_enabled", false)) + { + LOG(WARNING) << "Telecommands are applied when they arrive: they make deterministic processing depend on their timing"; + } + LOG(INFO) << "Deterministic processing: lookahead of " << clock.lookahead() << " samples (" + << 1000.0 * static_cast(clock.lookahead()) / clock.sampling_rate() << " ms), control tick of " + << clock.tick() << " samples"; + return true; +} + + +bool GNSSFlowgraph::assist_dual_frequency_acq() const +{ + // Deterministic processing does not read the live tracking status + return !deterministic_ && configuration_->property("GNSS-SDR.assist_dual_frequency_acq", multiband_); +} + + +double GNSSFlowgraph::control_receiver_time_s() const +{ + if (deterministic_) + { + // Time of the event being handled + const uint64_t stamp = DeterministicClock::scope_stamp(); + const double fs = DeterministicClock::instance().sampling_rate(); + return (stamp == NO_SAMPLE_STAMP || fs <= 0.0) ? 0.0 : static_cast(stamp) / fs; + } + double receiver_time_s = 0.0; + channels_status_->get_current_status_pvt(&receiver_time_s); + return receiver_time_s; +} + + void GNSSFlowgraph::stop_duplicated_satellite_channels() { std::lock_guard lock(signal_list_mutex_); @@ -2941,7 +3183,7 @@ Gnss_Signal GNSSFlowgraph::search_next_signal(const std::string& searched_signal double cooldown_receiver_time_s = 0.0; if (acquisition_retry_min_interval_s_ > 0.0) { - channels_status_->get_current_status_pvt(&cooldown_receiver_time_s); + cooldown_receiver_time_s = control_receiver_time_s(); } if (available_signals.empty()) @@ -2998,8 +3240,9 @@ Gnss_Signal GNSSFlowgraph::search_next_signal(const std::string& searched_signal break; } - const bool any_assist_configured = std::any_of(assist_signal_candidates.begin(), assist_signal_candidates.end(), - [&](const std::string& assist_signal) { return configuration_->property("Channels_" + assist_signal + ".count", 0) > 0; }); + // Deterministic processing does not read the live tracking status + const bool any_assist_configured = !deterministic_ && std::any_of(assist_signal_candidates.begin(), assist_signal_candidates.end(), + [&](const std::string& assist_signal) { return configuration_->property("Channels_" + assist_signal + ".count", 0) > 0; }); // A BeiDou band without an enabled assisting band must acquire on its // own, even when another constellation makes the receiver multiband. @@ -3220,7 +3463,7 @@ Gnss_Signal GNSSFlowgraph::search_next_signal(const std::string& searched_signal if (found_signal == false) { // With dual-frequency assistance required, wait for a tracked primary band. - if (!assist_signal_candidates.empty() && configuration_->property("GNSS-SDR.assist_dual_frequency_acq", multiband_)) + if (!assist_signal_candidates.empty() && assist_dual_frequency_acq()) { signal_available = false; constexpr double kNoAssistLogThrottleS = 5.0; diff --git a/src/core/receiver/gnss_flowgraph.h b/src/core/receiver/gnss_flowgraph.h index 284d0dae9..ec4d15741 100644 --- a/src/core/receiver/gnss_flowgraph.h +++ b/src/core/receiver/gnss_flowgraph.h @@ -200,6 +200,21 @@ public: */ void stop_duplicated_satellite_channels(); + /*! + * \brief Whether GNSS-SDR.deterministic=true: events are handled in + * sample-stamp order, see DeterministicClock. + */ + bool deterministic() const + { + return deterministic_; + } + + /*! + * \brief Whether the PVT block has processed its whole input, after the + * signal source has finished. + */ + bool data_path_done() const; + #if ENABLE_FPGA void start_acquisition_helper(); @@ -208,6 +223,9 @@ public: private: uint32_t doppler_bins_for_uncertainty(const std::string& acq_role, double uncertainty_hz) const; + bool deterministic_configuration_is_supported(); + bool assist_dual_frequency_acq() const; + double control_receiver_time_s() const; void init(); // Populates the SV PRN list available for acquisition and tracking int connect_desktop_flowgraph(); @@ -386,6 +404,7 @@ private: bool enable_osnma_rx_; bool enable_e6_has_rx_; bool enable_secondary_signal_status_gating_; + bool deterministic_; }; diff --git a/src/core/system_parameters/CMakeLists.txt b/src/core/system_parameters/CMakeLists.txt index 5e215286c..6fb67c69b 100644 --- a/src/core/system_parameters/CMakeLists.txt +++ b/src/core/system_parameters/CMakeLists.txt @@ -6,6 +6,7 @@ set(SYSTEM_PARAMETERS_SOURCES + deterministic_clock.cc gnss_almanac.cc gnss_ephemeris.cc gnss_satellite.cc @@ -43,6 +44,7 @@ set(SYSTEM_PARAMETERS_SOURCES ) set(SYSTEM_PARAMETERS_HEADERS + deterministic_clock.h gnss_almanac.h gnss_ephemeris.h gnss_satellite.h diff --git a/src/core/system_parameters/deterministic_clock.cc b/src/core/system_parameters/deterministic_clock.cc new file mode 100644 index 000000000..7c1c404aa --- /dev/null +++ b/src/core/system_parameters/deterministic_clock.cc @@ -0,0 +1,295 @@ +/*! + * \file deterministic_clock.cc + * \brief Sample-time control plane for deterministic processing + * \author Carles Fernandez Prades, 2026 cfernandez(at)cttc.es + * + * ----------------------------------------------------------------------------- + * + * GNSS-SDR is a Global Navigation Satellite System software-defined receiver. + * This file is part of GNSS-SDR. + * + * Copyright (C) 2010-2026 (see AUTHORS file for a list of contributors) + * SPDX-License-Identifier: GPL-3.0-or-later + * + * ----------------------------------------------------------------------------- + */ + +#include "deterministic_clock.h" +#include +#include + +namespace +{ +thread_local uint64_t current_scope_stamp = NO_SAMPLE_STAMP; +} // namespace + + +DeterministicProducer::DeterministicProducer(Kind kind) + : progress_(0), + kind_(kind) +{ +} + + +void DeterministicProducer::set_progress(uint64_t samples) +{ + uint64_t current = progress_.load(std::memory_order_relaxed); + while (samples > current && !progress_.compare_exchange_weak(current, samples, std::memory_order_release, std::memory_order_relaxed)) + { + } +} + + +void DeterministicProducer::set_bound(std::function bound) +{ + std::lock_guard lock(bound_mutex_); + bound_ = std::move(bound); +} + + +uint64_t DeterministicProducer::progress() const +{ + const uint64_t progress = progress_.load(std::memory_order_acquire); + std::lock_guard lock(bound_mutex_); + return bound_ ? std::min(progress, bound_()) : progress; +} + + +DeterministicClock::DeterministicClock() + : horizon_(0), + lookahead_(0), + enabled_(false), + sampling_rate_(0.0), + tick_(0) +{ +} + + +DeterministicClock& DeterministicClock::instance() +{ + static DeterministicClock clock; + return clock; +} + + +void DeterministicClock::enable(double sampling_rate, uint64_t lookahead_samples, uint64_t tick_samples) +{ + std::lock_guard lock(mutex_); + producers_.clear(); + sinks_.clear(); + telemetry_faults_.clear(); + sampling_rate_ = sampling_rate; + tick_ = std::max(tick_samples, 1); + lookahead_.store(std::max(lookahead_samples, 1), std::memory_order_release); + horizon_.store(0, std::memory_order_release); + enabled_.store(true, std::memory_order_release); + std::lock_guard consumed_lock(consumed_mutex_); + consumed_.clear(); +} + + +void DeterministicClock::disable() +{ + { + std::lock_guard lock(mutex_); + enabled_.store(false, std::memory_order_release); + producers_.clear(); + sinks_.clear(); + telemetry_faults_.clear(); + horizon_.store(NO_SAMPLE_STAMP, std::memory_order_release); + } + { + std::lock_guard lock(consumed_mutex_); + consumed_.clear(); + } + horizon_cv_.notify_all(); +} + + +double DeterministicClock::sampling_rate() const +{ + std::lock_guard lock(mutex_); + return sampling_rate_; +} + + +uint64_t DeterministicClock::tick() const +{ + std::lock_guard lock(mutex_); + return tick_; +} + + +void DeterministicClock::require_span(uint64_t samples) +{ + // Leave room for the integration that follows the span + const uint64_t needed = samples + samples / 4 + 1; + uint64_t current = lookahead_.load(std::memory_order_relaxed); + while (needed > current && !lookahead_.compare_exchange_weak(current, needed, std::memory_order_release, std::memory_order_relaxed)) + { + } +} + + +uint64_t DeterministicClock::effective_sample(uint64_t stamp) const +{ + return stamp == NO_SAMPLE_STAMP ? 0 : stamp + lookahead(); +} + + +std::shared_ptr DeterministicClock::register_producer(DeterministicProducer::Kind kind) +{ + auto producer = std::make_shared(kind); + std::lock_guard lock(mutex_); + producers_.push_back(producer); + return producer; +} + + +size_t DeterministicClock::count_producers(DeterministicProducer::Kind kind) const +{ + std::lock_guard lock(mutex_); + return static_cast(std::count_if(producers_.begin(), producers_.end(), + [kind](const std::weak_ptr& weak) { + const auto producer = weak.lock(); + return producer && producer->kind() == kind; + })); +} + + +uint64_t DeterministicClock::min_progress() const +{ + std::vector> live; + { + std::lock_guard lock(mutex_); + live.reserve(producers_.size()); + for (const auto& weak : producers_) + { + auto producer = weak.lock(); + if (producer) + { + live.push_back(std::move(producer)); + } + } + } + uint64_t result = NO_SAMPLE_STAMP; + for (const auto& producer : live) + { + result = std::min(result, producer->progress()); + } + return result; +} + + +void DeterministicClock::set_channel_event_sink(int32_t channel, ChannelEventSink sink) +{ + std::lock_guard lock(mutex_); + sinks_[channel] = std::move(sink); +} + + +bool DeterministicClock::emit_channel_event(int32_t channel, int event, uint64_t stamp) const +{ + ChannelEventSink sink; + { + std::lock_guard lock(mutex_); + const auto it = sinks_.find(channel); + if (it == sinks_.end() || !it->second) + { + return false; + } + sink = it->second; + } + const Scope scope(stamp); + sink(event); + return true; +} + + +void DeterministicClock::report_telemetry_fault(int32_t channel, uint64_t stamp) +{ + std::lock_guard lock(mutex_); + telemetry_faults_[channel].push_back(stamp); +} + + +uint64_t DeterministicClock::take_telemetry_fault(int32_t channel, uint64_t session_start) +{ + std::lock_guard lock(mutex_); + const auto it = telemetry_faults_.find(channel); + if (it == telemetry_faults_.end()) + { + return NO_SAMPLE_STAMP; + } + uint64_t stamp = NO_SAMPLE_STAMP; + for (const auto candidate : it->second) + { + if (candidate >= session_start) + { + stamp = std::min(stamp, candidate); + } + } + telemetry_faults_.erase(it); + return stamp; +} + + +void DeterministicClock::set_consumed(const void* consumer, uint64_t items) +{ + std::lock_guard lock(consumed_mutex_); + consumed_[consumer] = items; +} + + +uint64_t DeterministicClock::consumed(const void* consumer, uint64_t read) const +{ + std::lock_guard lock(consumed_mutex_); + const auto it = consumed_.find(consumer); + return it == consumed_.end() ? read : std::min(it->second, read); +} + + +void DeterministicClock::advance_horizon(uint64_t samples) +{ + { + std::lock_guard lock(mutex_); + if (samples <= horizon_.load(std::memory_order_relaxed)) + { + return; + } + horizon_.store(samples, std::memory_order_release); + } + horizon_cv_.notify_all(); +} + + +void DeterministicClock::open_horizon() +{ + advance_horizon(NO_SAMPLE_STAMP); +} + + +bool DeterministicClock::wait_beyond(uint64_t released, std::chrono::milliseconds timeout) +{ + std::unique_lock lock(mutex_); + return horizon_cv_.wait_for(lock, timeout, [this, released]() { return horizon_.load(std::memory_order_acquire) > released; }); +} + + +DeterministicClock::Scope::Scope(uint64_t stamp) + : previous_(current_scope_stamp) +{ + current_scope_stamp = stamp; +} + + +DeterministicClock::Scope::~Scope() +{ + current_scope_stamp = previous_; +} + + +uint64_t DeterministicClock::scope_stamp() +{ + return current_scope_stamp; +} diff --git a/src/core/system_parameters/deterministic_clock.h b/src/core/system_parameters/deterministic_clock.h new file mode 100644 index 000000000..fce0d45c3 --- /dev/null +++ b/src/core/system_parameters/deterministic_clock.h @@ -0,0 +1,250 @@ +/*! + * \file deterministic_clock.h + * \brief Sample-time control plane for deterministic processing + * \author Carles Fernandez Prades, 2026 cfernandez(at)cttc.es + * + * With GNSS-SDR.deterministic=true, every action that crosses threads takes + * effect at a sample stamp that depends only on the input stream: + * + * - Event producers (acquisition and tracking blocks) publish their progress: + * the sample count below which they have raised all their channel events. + * - The control thread handles the events in stamp order, up to the lowest + * progress c, and then lets the stream advance up to the horizon c + L, + * where L is the lookahead. + * - An action caused by an event stamped s takes effect at sample s + L, + * which no block has consumed yet. + * + * ----------------------------------------------------------------------------- + * + * GNSS-SDR is a Global Navigation Satellite System software-defined receiver. + * This file is part of GNSS-SDR. + * + * Copyright (C) 2010-2026 (see AUTHORS file for a list of contributors) + * SPDX-License-Identifier: GPL-3.0-or-later + * + * ----------------------------------------------------------------------------- + */ + +#ifndef GNSS_SDR_DETERMINISTIC_CLOCK_H +#define GNSS_SDR_DETERMINISTIC_CLOCK_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** \addtogroup Core + * \{ */ +/** \addtogroup System_Parameters + * \{ */ + +//! Marks the absence of a sample stamp +constexpr uint64_t NO_SAMPLE_STAMP = std::numeric_limits::max(); + +/*! + * \brief Channel data beyond an epoch that the observables block takes into + * account before computing it, in ms of signal: one tracking output after the + * epoch, for the interpolation. + */ +constexpr uint32_t DETERMINISTIC_OBSERVABLES_MARGIN_MS = 40; + +/*! + * \brief Signal time that the telemetry decoders may need to deliver a + * symbol after tracking has produced it, in ms. + */ +constexpr uint32_t DETERMINISTIC_SYMBOL_MARGIN_MS = 20; + +/*! + * \brief Progress of a block that can raise channel events, or that receives + * messages to apply at a sample stamp. + */ +class DeterministicProducer +{ +public: + enum class Kind + { + Acquisition, + Tracking, + Observables + }; + + explicit DeterministicProducer(Kind kind); + + Kind kind() const { return kind_; } + + /*! + * \brief Sets the sample count below which all the events of this block + * have been raised. It never decreases. + */ + void set_progress(uint64_t samples); + + /*! + * \brief Sets a bound on the progress that is computed every time the + * control thread reads it, e.g. from the state of downstream blocks. + */ + void set_bound(std::function bound); + + //! Progress, limited by the bound if there is one + uint64_t progress() const; + +private: + std::atomic progress_; + mutable std::mutex bound_mutex_; + std::function bound_; + const Kind kind_; +}; + + +/*! + * \brief Process-wide state of the deterministic processing mode. + */ +class DeterministicClock +{ +public: + //! Channel events, numbered as the "events" messages of the channel blocks + enum ChannelEvent : int + { + ACQ_POSITIVE = 1, + ACQ_NEGATIVE = 2, + TRK_LOSS = 3 + }; + + using ChannelEventSink = std::function; + + static DeterministicClock& instance(); + + DeterministicClock(const DeterministicClock&) = delete; + DeterministicClock& operator=(const DeterministicClock&) = delete; + + /*! + * \brief Enables the mode. Blocks created afterwards register as producers. + * \param sampling_rate Rate of the stamps, in samples per second. + * \param lookahead_samples Delay between an event and its effect. + * \param tick_samples Period of the control-plane maintenance tasks. + */ + void enable(double sampling_rate, uint64_t lookahead_samples, uint64_t tick_samples); + + //! Disables the mode and forgets producers, sinks and horizon. + void disable(); + + bool enabled() const { return enabled_.load(std::memory_order_acquire); } + double sampling_rate() const; + uint64_t lookahead() const { return lookahead_.load(std::memory_order_acquire); } + uint64_t tick() const; + + /*! + * \brief Raises the lookahead so that a producer that needs \p samples of + * input beyond its progress can always get them. Call before the + * flowgraph starts. + */ + void require_span(uint64_t samples); + + /*! + * \brief Sample at which an action caused by an event stamped \p stamp + * takes effect. Stream start if \p stamp is NO_SAMPLE_STAMP. + */ + uint64_t effective_sample(uint64_t stamp) const; + + std::shared_ptr register_producer(DeterministicProducer::Kind kind); + size_t count_producers(DeterministicProducer::Kind kind) const; + + //! Lowest progress among live producers, NO_SAMPLE_STAMP if there are none + uint64_t min_progress() const; + + /*! + * \brief Lets a channel handle its events in the thread that raises + * them, so that they reach the control queue before the producer + * progresses past their stamp. + */ + void set_channel_event_sink(int32_t channel, ChannelEventSink sink); + + /*! + * \brief Hands an event stamped \p stamp to the sink of \p channel. + * \return false if the channel has no sink. + */ + bool emit_channel_event(int32_t channel, int event, uint64_t stamp) const; + + //! Records a telemetry fault before the decoder releases its progress. + void report_telemetry_fault(int32_t channel, uint64_t stamp); + + /*! + * \brief Drains queued faults, returning the earliest stamp in this + * tracking session, or NO_SAMPLE_STAMP. Ignores stamps before \p session_start. + */ + uint64_t take_telemetry_fault(int32_t channel, uint64_t session_start); + + /*! + * \brief A block that consumes its input before it publishes the messages + * that the input causes reports here that it has finished with its first + * \p items input items, messages included. + */ + void set_consumed(const void* consumer, uint64_t items); + + /*! + * \brief Input items that \p consumer has finished with: those reported by + * set_consumed(), or \p read (its read count) if it reports none. + */ + uint64_t consumed(const void* consumer, uint64_t read) const; + + //! Number of samples that the stream may release + uint64_t horizon() const { return horizon_.load(std::memory_order_acquire); } + + //! Moves the horizon forward to \p samples (never backwards) + void advance_horizon(uint64_t samples); + + //! Releases the whole stream (end of the run) + void open_horizon(); + + /*! + * \brief Waits up to \p timeout for the horizon to exceed \p released. + * \return true if it does. + */ + bool wait_beyond(uint64_t released, std::chrono::milliseconds timeout); + + /*! + * \brief Stamp of the event that the calling thread is handling. Actions + * taken inside the scope are caused by that event. + */ + class Scope + { + public: + explicit Scope(uint64_t stamp); + ~Scope(); + Scope(const Scope&) = delete; + Scope& operator=(const Scope&) = delete; + + private: + uint64_t previous_; + }; + + //! Stamp of the innermost Scope of the calling thread, or NO_SAMPLE_STAMP + static uint64_t scope_stamp(); + +private: + DeterministicClock(); + + mutable std::mutex mutex_; + std::condition_variable horizon_cv_; + std::vector> producers_; + std::map sinks_; + std::map> telemetry_faults_; + mutable std::mutex consumed_mutex_; + std::map consumed_; + std::atomic horizon_; + std::atomic lookahead_; + std::atomic enabled_; + double sampling_rate_; + uint64_t tick_; +}; + + +/** \} */ +/** \} */ +#endif // GNSS_SDR_DETERMINISTIC_CLOCK_H diff --git a/tests/system-tests/position_test.cc b/tests/system-tests/position_test.cc index 8a131e8fb..218be57c5 100644 --- a/tests/system-tests/position_test.cc +++ b/tests/system-tests/position_test.cc @@ -287,17 +287,7 @@ int PositionSystemTest::configure_receiver() config->set_property("GNSS-SDR.observation_date", "2014-12-20"); } config->set_property("GNSS-SDR.GPS_banned_prns", std::to_string(1)); - // Set the assistance system parameters - config->set_property("GNSS-SDR.SUPL_read_gps_assistance_xml", "false"); - config->set_property("GNSS-SDR.SUPL_gps_enabled", "false"); - config->set_property("GNSS-SDR.SUPL_gps_ephemeris_server", "supl.google.com"); - config->set_property("GNSS-SDR.SUPL_gps_ephemeris_port", std::to_string(7275)); - config->set_property("GNSS-SDR.SUPL_gps_acquisition_server", "supl.google.com"); - config->set_property("GNSS-SDR.SUPL_gps_acquisition_port", std::to_string(7275)); - config->set_property("GNSS-SDR.SUPL_MCC", std::to_string(244)); - config->set_property("GNSS-SDR.SUPL_MNC", std::to_string(5)); - config->set_property("GNSS-SDR.SUPL_LAC", "0x59e2"); - config->set_property("GNSS-SDR.SUPL_CI", "0x31b0"); + config->set_property("GNSS-SDR.deterministic", "true"); // Set the Signal Source config->set_property("SignalSource.implementation", "File_Signal_Source"); diff --git a/tests/unit-tests/signal-processing-blocks/observables/deterministic_observables_test.cc b/tests/unit-tests/signal-processing-blocks/observables/deterministic_observables_test.cc new file mode 100644 index 000000000..bedee4e1b --- /dev/null +++ b/tests/unit-tests/signal-processing-blocks/observables/deterministic_observables_test.cc @@ -0,0 +1,129 @@ +/*! + * \file deterministic_observables_test.cc + * \brief Checks progress bounds for deterministic observables with short lookaheads + * \author Carles Fernandez-Prades, 2026. cfernandez(at)cttc.es + * + * ----------------------------------------------------------------------------- + * + * GNSS-SDR is a Global Navigation Satellite System software-defined receiver. + * This file is part of GNSS-SDR. + * + * Copyright (C) 2010-2026 (see AUTHORS file for a list of contributors) + * SPDX-License-Identifier: GPL-3.0-or-later + * + * ----------------------------------------------------------------------------- + */ + +#include "deterministic_clock.h" +#include "gnss_synchro.h" +#include "hybrid_observables_gs.h" +#include "obs_conf.h" +#include "stream_batcher_limits.h" +#include +#include +#include +#include +#include +#include +#include + + +class DeterministicObservablesTest : public ::testing::Test +{ +protected: + void SetUp() override + { + DeterministicClock::instance().enable(4000000.0, 4000, 400000); + } + + void TearDown() override + { + DeterministicClock::instance().disable(); + } + + void check_clock_progress(bool always_output, bool expand_lookahead) + { + Obs_Conf conf; + conf.nchannels_in = 2; + conf.nchannels_out = 1; + conf.always_output_gs = always_output; + auto observables = hybrid_observables_gs_make(conf); + auto& clock = DeterministicClock::instance(); + if (expand_lookahead) + { + // Flowgraph construction creates observables before channels, + // whose acquisition/tracking spans may raise the lookahead. + clock.require_span(400000); + } + + // Allocate stream buffers, then drive work manually to control exactly + // when the downstream PVT consumer finishes each output epoch. + const auto item_size = sizeof(Gnss_Synchro); + auto channel_source = gr::blocks::vector_source_b::make(std::vector{}, false, item_size); + auto clock_source = gr::blocks::vector_source_b::make(std::vector{}, false, item_size); + auto pvt_sink = gr::blocks::null_sink::make(item_size); + auto top_block = gr::make_top_block("deterministic_observables_test"); + top_block->connect(channel_source, 0, observables, 0); + top_block->connect(clock_source, 0, observables, 1); + top_block->connect(observables, 0, pvt_sink, 0); + top_block->run(); + + Gnss_Synchro channel{}; + Gnss_Synchro clock_input{}; + Gnss_Synchro output{}; + clock_input.fs = 4000000; + gr_vector_const_void_star inputs{&channel, &clock_input}; + gr_vector_void_star outputs{&output}; + gr_vector_int available{0, 1}; + const uint64_t samples_per_tick = conf.observable_interval_ms * 4000ULL; + const uint64_t history_ticks = observables_clock_ticks(conf.observable_interval_ms); + const uint64_t quantum = std::max(1, clock.lookahead() / 8); + for (uint64_t tick = 1; tick <= 50; ++tick) + { + SCOPED_TRACE(tick); + clock_input.Tracking_sample_counter = tick * samples_per_tick; + const uint64_t horizon = clock.min_progress() + clock.lookahead(); + // The same rounding used by the control thread must still + // release the next clock tick; otherwise the graph deadlocks. + ASSERT_GE(horizon - horizon % quantum, clock_input.Tracking_sample_counter); + const int produced = observables->general_work(1, available, inputs, outputs); + ASSERT_EQ(produced, always_output ? 1 : 0); + if (produced > 0) + { + observables->produce(0, produced); + const uint64_t pending_progress = clock.min_progress(); + pvt_sink->consume_each(produced); + if (tick >= history_ticks) + { + // An unread PVT epoch must retain its bound, + // even though observables has computed it. + EXPECT_GT(clock.min_progress(), pending_progress); + } + } + } + } +}; + + +TEST_F(DeterministicObservablesTest, ShortLookaheadWithPvtOutput) +{ + check_clock_progress(true, false); +} + + +TEST_F(DeterministicObservablesTest, ShortLookaheadWithoutValidObservations) +{ + check_clock_progress(false, false); +} + + +TEST_F(DeterministicObservablesTest, ExpandedLookaheadWithPvtOutput) +{ + check_clock_progress(true, true); +} + + +TEST_F(DeterministicObservablesTest, ExpandedLookaheadWithoutValidObservations) +{ + check_clock_progress(false, true); +} diff --git a/tests/unit-tests/signal-processing-blocks/sources/ion_gsms_chunk_data_test.cc b/tests/unit-tests/signal-processing-blocks/sources/ion_gsms_chunk_data_test.cc index a333ac129..14d214cb3 100644 --- a/tests/unit-tests/signal-processing-blocks/sources/ion_gsms_chunk_data_test.cc +++ b/tests/unit-tests/signal-processing-blocks/sources/ion_gsms_chunk_data_test.cc @@ -629,6 +629,40 @@ TEST(IONGSMSFileSourceTest, ConcatenatesSegmentsForSameStream) } +TEST(IONGSMSFileSourceTest, ConcatenatesSegmentsWithDifferentChunkCounts) +{ + const fs::path data_path = fs::path(GetTempDir()) / "ion_gsms_file_source_different_chunk_counts.bin"; + const std::vector chunk_counts{127, 128, 131}; + const std::vector packed_samples{0x55, 0xAA, 0xFF}; + const std::vector decoded_samples{1, -2, -1}; + const auto stream = make_stream(GnssMetadata::IonStream::IF, "TC", 2, 2048, 1024); + const auto chunk = make_chunk(stream, 1, 256); + std::vector blocks(chunk_counts.size()); + std::vector segments; + std::vector bytes; + std::vector expected; + for (std::size_t i = 0; i < chunk_counts.size(); ++i) + { + blocks[i].Cycles(1); + for (std::size_t j = 0; j < chunk_counts[i]; ++j) + { + blocks[i].Chunks().push_back(chunk); + } + segments.push_back({data_path, &blocks[i], bytes.size()}); + bytes.insert(bytes.end(), chunk_counts[i] * 256, packed_samples[i]); + expected.insert(expected.end(), chunk_counts[i] * 1024, decoded_samples[i]); + } + write_binary_file(data_path, bytes); + + // Each segment fits a modest buffer, but their cycle-size LCM is + // 2180644864 items, beyond GNU Radio's signed integer limit. + const auto output = run_file_source(segments); + EXPECT_EQ(expected, output); + + fs::remove(data_path); +} + + TEST(IONGSMSFileSourceTest, StartsReadingAtProvidedBlockOffset) { const fs::path temp_dir(GetTempDir()); diff --git a/tests/unit-tests/signal-processing-blocks/telemetry_decoder/deterministic_telemetry_fault_test.cc b/tests/unit-tests/signal-processing-blocks/telemetry_decoder/deterministic_telemetry_fault_test.cc new file mode 100644 index 000000000..709b5a993 --- /dev/null +++ b/tests/unit-tests/signal-processing-blocks/telemetry_decoder/deterministic_telemetry_fault_test.cc @@ -0,0 +1,358 @@ +/*! + * \file deterministic_telemetry_fault_test.cc + * \brief Checks deterministic telemetry fault handoff and progress ordering + * \author Carles Fernandez-Prades, 2026. cfernandez(at)cttc.es + * + * ----------------------------------------------------------------------------- + * + * GNSS-SDR is a Global Navigation Satellite System software-defined receiver. + * This file is part of GNSS-SDR. + * + * Copyright (C) 2010-2026 (see AUTHORS file for a list of contributors) + * SPDX-License-Identifier: GPL-3.0-or-later + * + * ----------------------------------------------------------------------------- + */ + +#include "deterministic_clock.h" +#include "deterministic_tracking.h" +#include "galileo_telemetry_decoder_gs.h" +#include "gnss_satellite.h" +#include "gnss_synchro.h" +#include "gps_l1_ca_telemetry_decoder_gs.h" +#include "gps_l2c_telemetry_decoder_gs.h" +#include "gps_l5_telemetry_decoder_gs.h" +#include "horizon_gate.h" +#include "telemetry_message_stamp.h" +#include "tlm_conf.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +class DeterministicTelemetryFaultTest : public ::testing::Test +{ +protected: + void SetUp() override + { + DeterministicClock::instance().enable(1000.0, 100, 100); + } + + void TearDown() override + { + DeterministicClock::instance().disable(); + } + + void check_fault_order(const gr::block_sptr& decoder) + { + // Let GNU Radio allocate the stream buffers, then drive work directly + // with no scheduler threads so that the publication boundary is observable. + auto source = gr::blocks::vector_source_b::make(std::vector(sizeof(Gnss_Synchro), 0), false, sizeof(Gnss_Synchro)); + auto sink = gr::blocks::null_sink::make(sizeof(Gnss_Synchro)); + auto top_block = gr::make_top_block("deterministic_telemetry_fault_test"); + top_block->connect(source, 0, decoder, 0); + top_block->connect(decoder, 0, sink, 0); + top_block->run(); + + // No scheduler dispatches telemetry messages during these work calls. + // An invalid destination also catches any accidental asynchronous fault. + const auto port = pmt::mp("telemetry_to_trk"); + decoder->message_port_sub(port, pmt::cons(sink->alias_pmt(), pmt::mp("faults"))); + + auto& clock = DeterministicClock::instance(); + DeterministicTracking tracking(source.get()); + tracking.start(0); + Gnss_Synchro symbol{}; + symbol.Prompt_I = 1.0; + symbol.fs = 1000; + Gnss_Synchro output{}; + gr_vector_const_void_star inputs{&symbol}; + gr_vector_void_star outputs{&output}; + gr_vector_int available{1}; + bool fault_applied = false; + for (uint64_t i = 1; i <= 20000; ++i) + { + symbol.Tracking_sample_counter = i * 20; + const uint64_t consumed = decoder->nitems_read(0); + tracking.record_output(consumed, symbol.Tracking_sample_counter); + tracking.publish(symbol.Tracking_sample_counter + clock.lookahead()); + ASSERT_EQ(clock.min_progress(), symbol.Tracking_sample_counter); + ASSERT_EQ(decoder->general_work(1, available, inputs, outputs), 1); + EXPECT_EQ(decoder->nitems_read(0), consumed + 1); + EXPECT_GT(clock.min_progress(), symbol.Tracking_sample_counter); + const uint64_t effective = clock.effective_sample(symbol.Tracking_sample_counter); + EXPECT_FALSE(tracking.fault_due(effective - 1, 0)); + if (tracking.fault_due(effective, 0)) + { + EXPECT_FALSE(tracking.fault_due(effective, 0)); + fault_applied = true; + break; + } + } + EXPECT_TRUE(fault_applied); + } +}; + + +TEST_F(DeterministicTelemetryFaultTest, GpsL1CaFaultWithoutMessageDispatch) +{ + auto decoder = gps_l1_ca_make_telemetry_decoder_gs(Tlm_Conf{}); + decoder->set_satellite(Gnss_Satellite("GPS", 1)); + check_fault_order(decoder); +} + + +TEST_F(DeterministicTelemetryFaultTest, GalileoInavFaultWithoutMessageDispatch) +{ + auto decoder = galileo_make_telemetry_decoder_gs(Tlm_Conf{}, 1); + decoder->set_satellite(Gnss_Satellite("Galileo", 1)); + check_fault_order(decoder); +} + + +TEST_F(DeterministicTelemetryFaultTest, GpsL2cFaultWithoutMessageDispatch) +{ + auto decoder = gps_l2c_make_telemetry_decoder_gs(Tlm_Conf{}); + decoder->set_satellite(Gnss_Satellite("GPS", 1)); + check_fault_order(decoder); +} + + +TEST_F(DeterministicTelemetryFaultTest, GpsL5FaultWithoutMessageDispatch) +{ + auto decoder = gps_l5_make_telemetry_decoder_gs(Tlm_Conf{}); + decoder->set_satellite(Gnss_Satellite("GPS", 1)); + check_fault_order(decoder); +} + + +TEST_F(DeterministicTelemetryFaultTest, FaultsAreIsolatedByChannelAndTrackingSession) +{ + auto source = gr::blocks::vector_source_b::make(std::vector{0}); + DeterministicTracking tracking(source.get()); + tracking.start(100); // This session starts at sample 200. + auto& clock = DeterministicClock::instance(); + clock.report_telemetry_fault(0, 199); + clock.report_telemetry_fault(1, 200); + clock.report_telemetry_fault(0, 220); + clock.report_telemetry_fault(0, 200); + EXPECT_FALSE(tracking.fault_due(299, 0)); + EXPECT_TRUE(tracking.fault_due(300, 0)); + EXPECT_FALSE(tracking.fault_due(320, 0)); + EXPECT_EQ(clock.take_telemetry_fault(1, 200), 200U); + + clock.report_telemetry_fault(0, 250); + tracking.start(200); // A restarted session must ignore the old fault. + EXPECT_FALSE(tracking.fault_due(400, 0)); + clock.report_telemetry_fault(0, 300); + EXPECT_TRUE(tracking.fault_due(400, 0)); +} + + +TEST_F(DeterministicTelemetryFaultTest, NewRunClearsQueuedFaults) +{ + auto& clock = DeterministicClock::instance(); + clock.report_telemetry_fault(0, 100); + clock.enable(1000.0, 100, 100); + EXPECT_EQ(clock.take_telemetry_fault(0, 0), NO_SAMPLE_STAMP); + clock.report_telemetry_fault(0, 100); + clock.disable(); + EXPECT_EQ(clock.take_telemetry_fault(0, 0), NO_SAMPLE_STAMP); +} + + +TEST_F(DeterministicTelemetryFaultTest, ProgressWaitsForWorkScopeToFinish) +{ + auto source = gr::blocks::vector_source_b::make(std::vector{0}); + auto sink = gr::blocks::null_sink::make(1); + auto top_block = gr::make_top_block("telemetry_scope_test"); + top_block->connect(source, 0, sink, 0); + top_block->run(); + auto& clock = DeterministicClock::instance(); + const auto consumed = sink->nitems_read(0); + DeterministicTracking tracking(source.get()); + tracking.record_output(consumed, 100); + tracking.publish(200); + { + const TelemetryWorkScope scope(sink.get(), 100); + sink->consume_each(1); + EXPECT_EQ(clock.min_progress(), 100U); + clock.report_telemetry_fault(0, 100); + EXPECT_EQ(clock.min_progress(), 100U); + } + EXPECT_EQ(clock.min_progress(), 200U); + EXPECT_TRUE(tracking.fault_due(200, 0)); + + const auto finished = sink->nitems_read(0); + tracking.record_output(finished, 200); + tracking.publish(300); + EXPECT_THROW( + { + const TelemetryWorkScope scope(sink.get(), 200); + sink->consume_each(1); + throw std::runtime_error("decoder failed before handing off its fault"); + }, + std::runtime_error); + EXPECT_EQ(clock.consumed(static_cast(sink.get()), sink->nitems_read(0)), finished); + EXPECT_EQ(clock.min_progress(), 200U); +} + + +struct DeterministicFaultSchedulerState +{ + std::mutex mutex; + std::condition_variable condition; + bool paused = false; + bool published = false; + bool resume = false; + std::atomic applied_at{NO_SAMPLE_STAMP}; +}; + + +class DeterministicFaultTrackingBlock : public gr::block +{ +public: + explicit DeterministicFaultTrackingBlock(DeterministicFaultSchedulerState& state) + : gr::block("fault_tracking_test", gr::io_signature::make(1, 1, 1), gr::io_signature::make(1, 1, 1)), + d_state(state), + d_tracking(this) + { + auto fault_port = pmt::mp("telemetry_to_trk"); + d_pause_port = pmt::mp("pause_after_fault_queue"); + // GNU Radio drains the message ports in this comparator's order. + // Pause only after it has checked the fault port for this iteration. + if (pmt::comparator{}(d_pause_port, fault_port)) + { + std::swap(d_pause_port, fault_port); + } + message_port_register_in(fault_port); + message_port_register_in(d_pause_port); + set_msg_handler(fault_port, [this](const pmt::pmt_t& msg) { + d_tracking.take_fault(msg, nitems_read(0), true, 0); + }); + set_msg_handler(d_pause_port, [this](const pmt::pmt_t&) { + std::unique_lock lock(d_state.mutex); + d_state.paused = true; + d_state.condition.notify_all(); + d_state.condition.wait_for(lock, std::chrono::seconds(5), [this] { return d_state.resume; }); + }); + d_tracking.start(0); + } + + void forecast(int, gr_vector_int& required) override { required[0] = 10; } + + int general_work(int, gr_vector_int&, gr_vector_const_void_star&, gr_vector_void_star& output) override + { + if (d_tracking.fault_due(nitems_read(0), 0)) + { + d_state.applied_at.store(nitems_read(0)); + } + consume_each(10); + d_tracking.publish(nitems_read(0)); + if (nitems_read(0) == 200) + { + _post(d_pause_port, pmt::PMT_T); + } + if (nitems_read(0) == 100) + { + d_tracking.record_output(nitems_written(0), 100); + static_cast(output[0])[0] = 0; + return 1; + } + return 0; + } + +private: + DeterministicFaultSchedulerState& d_state; + DeterministicTracking d_tracking; + pmt::pmt_t d_pause_port; +}; + + +class DeterministicFaultTelemetryBlock : public gr::block +{ +public: + explicit DeterministicFaultTelemetryBlock(DeterministicFaultSchedulerState& state) + : gr::block("fault_telemetry_test", gr::io_signature::make(1, 1, 1), gr::io_signature::make(0, 0, 0)), + d_state(state) + { + } + + int general_work(int, gr_vector_int&, gr_vector_const_void_star&, gr_vector_void_star&) override + { + { + const TelemetryWorkScope scope(this, 100); + consume_each(1); + std::unique_lock lock(d_state.mutex); + d_state.condition.wait_for(lock, std::chrono::seconds(5), [this] { return d_state.paused; }); + DeterministicClock::instance().report_telemetry_fault(0, 100); + } + std::lock_guard lock(d_state.mutex); + d_state.published = true; + return 0; + } + +private: + DeterministicFaultSchedulerState& d_state; +}; + + +TEST_F(DeterministicTelemetryFaultTest, FaultReportedAfterSchedulerChecksMessages) +{ + auto& clock = DeterministicClock::instance(); + DeterministicFaultSchedulerState state; + auto source = gr::blocks::vector_source_b::make(std::vector(400, 0)); + auto gate = make_horizon_gate(1, 1); + auto tracking = gnss_shared_ptr(new DeterministicFaultTrackingBlock(state)); + auto telemetry = gnss_shared_ptr(new DeterministicFaultTelemetryBlock(state)); + auto top_block = gr::make_top_block("deterministic_fault_scheduler_test"); + top_block->connect(source, 0, gate, 0); + top_block->connect(gate, 0, tracking, 0); + top_block->connect(tracking, 0, telemetry, 0); + top_block->start(); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (state.applied_at.load() == NO_SAMPLE_STAMP && std::chrono::steady_clock::now() < deadline) + { + clock.advance_horizon(clock.min_progress() + clock.lookahead()); + uint64_t released; + { + const auto output = gate->detail()->output(0); + gr::thread::scoped_lock lock(*output->mutex()); + released = gate->nitems_written(0); + } + { + std::lock_guard lock(state.mutex); + // Give tracking enough input to cross the effective sample + // before it gets another chance to dispatch queued messages. + if (state.published && released >= 300) + { + state.resume = true; + state.condition.notify_all(); + } + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + { + std::lock_guard lock(state.mutex); + state.resume = true; + state.condition.notify_all(); + } + clock.open_horizon(); + top_block->stop(); + top_block->wait(); + EXPECT_TRUE(state.paused); + EXPECT_TRUE(state.published); + EXPECT_EQ(state.applied_at.load(), 200U); +} diff --git a/tests/unit_tests_core.cc b/tests/unit_tests_core.cc index 31b74447e..faa7e3525 100644 --- a/tests/unit_tests_core.cc +++ b/tests/unit_tests_core.cc @@ -42,10 +42,12 @@ #include "unit-tests/signal-processing-blocks/libs/beidou_b2a_signal_replica_test.cc" #include "unit-tests/signal-processing-blocks/libs/item_type_helpers_test.cc" #include "unit-tests/signal-processing-blocks/libs/rtklib_lli_test.cc" +#include "unit-tests/signal-processing-blocks/observables/deterministic_observables_test.cc" #include "unit-tests/signal-processing-blocks/resampler/direct_resampler_conditioner_cc_test.cc" #include "unit-tests/signal-processing-blocks/resampler/mmse_resampler_test.cc" #include "unit-tests/signal-processing-blocks/sources/gnss_sdr_valve_test.cc" #include "unit-tests/signal-processing-blocks/sources/unpack_2bit_samples_test.cc" +#include "unit-tests/signal-processing-blocks/telemetry_decoder/deterministic_telemetry_fault_test.cc" #include "unit-tests/signal-processing-blocks/telemetry_decoder/galileo_fnav_inav_decoder_test.cc" #include "unit-tests/signal-processing-blocks/telemetry_decoder/sbas_l1_telemetry_decoder_test.cc" diff --git a/utils/reproducibility/ieee-access18/L2-access18.conf b/utils/reproducibility/ieee-access18/L2-access18.conf index 622929cd5..c00c348ec 100644 --- a/utils/reproducibility/ieee-access18/L2-access18.conf +++ b/utils/reproducibility/ieee-access18/L2-access18.conf @@ -5,7 +5,7 @@ ;######### GLOBAL OPTIONS ################## ;internal_fs_sps: Internal signal sampling frequency after the signal conditioning stage [samples per second]. GNSS-SDR.internal_fs_sps=3000000 - +GNSS-SDR.deterministic=true ;######### SIGNAL_SOURCE CONFIG ############ ;#implementation: Use [File_Signal_Source] or [UHD_Signal_Source] From e873769aa43be18ba6e0652bcdea4f3dd8c7943a Mon Sep 17 00:00:00 2001 From: Carles Fernandez Date: Mon, 26 Oct 2026 11:25:51 +0100 Subject: [PATCH 05/11] Fix CI failures --- .../pcps_acquisition_adapter_custom.cc | 12 +++++----- .../libs/libswiftcnav/swift_common.h | 5 ----- .../deterministic_telemetry_fault_test.cc | 22 ++++++++++++------- 3 files changed, 20 insertions(+), 19 deletions(-) diff --git a/src/algorithms/acquisition/adapters/pcps_acquisition_adapter_custom.cc b/src/algorithms/acquisition/adapters/pcps_acquisition_adapter_custom.cc index 836a37095..79a0eddcd 100644 --- a/src/algorithms/acquisition/adapters/pcps_acquisition_adapter_custom.cc +++ b/src/algorithms/acquisition/adapters/pcps_acquisition_adapter_custom.cc @@ -181,7 +181,7 @@ Acq_Conf get_acq_conf( std::unique_ptr threshold_compute; boost::optional default_folding_factor; - boost::optional required_sampled_ms; + uint32_t required_sampled_ms = 0; // 0: any coherent integration time uint32_t max_sampled_ms = std::numeric_limits::max(); if (implementation == "GPS_L1_CA_PCPS_QuickSync_Acquisition") @@ -235,8 +235,8 @@ Acq_Conf get_acq_conf( } acq_parameters.ms_per_code = ms_per_code; - acq_parameters.sampled_ms = required_sampled_ms ? *required_sampled_ms : ms_per_code; // Set as default value - acq_parameters.dump_filename = default_dump_filename; // Set as default value + acq_parameters.sampled_ms = required_sampled_ms != 0 ? required_sampled_ms : ms_per_code; // Set as default value + acq_parameters.dump_filename = default_dump_filename; // Set as default value acq_parameters.SetFromConfiguration(configuration, role, chip_rate, opt_freq); #if USE_GLOG_AND_GFLAGS @@ -266,11 +266,11 @@ Acq_Conf get_acq_conf( std::cout << "Too high coherent integration time. Changing to " << max_sampled_ms << "ms\n"; } - if (required_sampled_ms && acq_parameters.sampled_ms != *required_sampled_ms) + if (required_sampled_ms != 0 && acq_parameters.sampled_ms != required_sampled_ms) { LOG(WARNING) << implementation << " requires " << role << ".coherent_integration_time_ms=" - << *required_sampled_ms << ". Changing to " << *required_sampled_ms << " ms"; - acq_parameters.sampled_ms = *required_sampled_ms; + << required_sampled_ms << ". Changing to " << required_sampled_ms << " ms"; + acq_parameters.sampled_ms = required_sampled_ms; } acq_parameters.num_codes = acq_parameters.sampled_ms / ms_per_code; diff --git a/src/algorithms/telemetry_decoder/libs/libswiftcnav/swift_common.h b/src/algorithms/telemetry_decoder/libs/libswiftcnav/swift_common.h index 9943c6347..cf0ba39f8 100644 --- a/src/algorithms/telemetry_decoder/libs/libswiftcnav/swift_common.h +++ b/src/algorithms/telemetry_decoder/libs/libswiftcnav/swift_common.h @@ -31,11 +31,6 @@ * \{ */ -#define ABS(x) ((x) < 0 ? -(x) : (x)) -#define MIN(x, y) (((x) < (y)) ? (x) : (y)) -#define MAX(x, y) (((x) > (y)) ? (x) : (y)) -#define CLAMP_DIFF(a, b) (MAX((a), (b)) - (b)) - #include #include #include diff --git a/tests/unit-tests/signal-processing-blocks/telemetry_decoder/deterministic_telemetry_fault_test.cc b/tests/unit-tests/signal-processing-blocks/telemetry_decoder/deterministic_telemetry_fault_test.cc index 709b5a993..08cc0eaaa 100644 --- a/tests/unit-tests/signal-processing-blocks/telemetry_decoder/deterministic_telemetry_fault_test.cc +++ b/tests/unit-tests/signal-processing-blocks/telemetry_decoder/deterministic_telemetry_fault_test.cc @@ -265,13 +265,12 @@ public: { _post(d_pause_port, pmt::PMT_T); } - if (nitems_read(0) == 100) - { - d_tracking.record_output(nitems_written(0), 100); - static_cast(output[0])[0] = 0; - return 1; - } - return 0; + // One symbol per call, stamped with the sample it reaches. A call + // without output would wait, in GNU Radio >= 3.10, until the decoder + // that holds a symbol leaves its work call (output blocked callback). + d_tracking.record_output(nitems_written(0), nitems_read(0)); + static_cast(output[0])[0] = 0; + return 1; } private: @@ -292,9 +291,16 @@ public: int general_work(int, gr_vector_int&, gr_vector_const_void_star&, gr_vector_void_star&) override { + // One symbol per call. The tracking block stamps symbol k with + // sample 10 * (k + 1); the fault is raised by the one at sample 100. + const uint64_t stamp = 10 * (nitems_read(0) + 1); { - const TelemetryWorkScope scope(this, 100); + const TelemetryWorkScope scope(this, stamp); consume_each(1); + if (stamp != 100) + { + return 0; + } std::unique_lock lock(d_state.mutex); d_state.condition.wait_for(lock, std::chrono::seconds(5), [this] { return d_state.paused; }); DeterministicClock::instance().report_telemetry_fault(0, 100); From e01ce536bf6f175829a256db6fa6b877d61743a6 Mon Sep 17 00:00:00 2001 From: Carles Fernandez Date: Mon, 26 Oct 2026 12:43:24 +0100 Subject: [PATCH 06/11] Delete move operations in StreamBatcherDeadline and its Impl --- src/algorithms/libs/stream_batcher_deadline.cc | 4 ++++ src/algorithms/libs/stream_batcher_deadline.h | 2 ++ 2 files changed, 6 insertions(+) diff --git a/src/algorithms/libs/stream_batcher_deadline.cc b/src/algorithms/libs/stream_batcher_deadline.cc index 081d7681a..c1ee8dbe1 100644 --- a/src/algorithms/libs/stream_batcher_deadline.cc +++ b/src/algorithms/libs/stream_batcher_deadline.cc @@ -44,6 +44,10 @@ public: changed_.notify_one(); worker_.join(); } + Impl(const Impl&) = delete; + Impl& operator=(const Impl&) = delete; + Impl(Impl&&) = delete; + Impl& operator=(Impl&&) = delete; std::mutex mutex_; std::condition_variable changed_; diff --git a/src/algorithms/libs/stream_batcher_deadline.h b/src/algorithms/libs/stream_batcher_deadline.h index 1f26f42a4..953022724 100644 --- a/src/algorithms/libs/stream_batcher_deadline.h +++ b/src/algorithms/libs/stream_batcher_deadline.h @@ -34,6 +34,8 @@ public: ~StreamBatcherDeadline(); StreamBatcherDeadline(const StreamBatcherDeadline&) = delete; StreamBatcherDeadline& operator=(const StreamBatcherDeadline&) = delete; + StreamBatcherDeadline(StreamBatcherDeadline&&) = delete; + StreamBatcherDeadline& operator=(StreamBatcherDeadline&&) = delete; uint64_t add(std::function notify); void remove(uint64_t id); From 6564d6148f76ca76c7056867fbefdb868266d473 Mon Sep 17 00:00:00 2001 From: Carles Fernandez Date: Mon, 26 Oct 2026 16:54:36 +0100 Subject: [PATCH 07/11] Write the accumulated carrier phase as double in all tracking dumps Extend the change of the previous merge to the remaining tracking blocks: kf_tracking and gps_l1_ca_gaussian_tracking_cc (binary dump and .mat file; records grow from 96 to 100 bytes), and the GPS L1 C/A and Galileo E1 TCP connector and GPS L1 C/A GPU blocks (records grow from 88 to 92 bytes). The Galileo E1 TCP connector block accumulated the carrier phase in a float, which is now a double. Update the KF readers in utils/matlab and utils/python accordingly. Tracking_Dump_Reader now takes the record layout, since the FPGA and Gaussian tests read dumps that lack the TOW and WN fields (and, for the Gaussian block, have the carrier noise variance in place of the code frequency rate) with the dll_pll_veml_tracking layout. Add a CHANGELOG entry. --- docs/CHANGELOG.md | 5 +++ .../galileo_e1_tcp_connector_tracking_cc.cc | 11 +++--- .../galileo_e1_tcp_connector_tracking_cc.h | 2 +- .../gps_l1_ca_dll_pll_tracking_gpu_cc.cc | 9 ++--- .../gps_l1_ca_gaussian_tracking_cc.cc | 16 ++++----- .../gps_l1_ca_tcp_connector_tracking_cc.cc | 9 ++--- .../tracking/gnuradio_blocks/kf_tracking.cc | 16 ++++----- .../libs/tracking_dump_reader.cc | 36 ++++++++++++++----- .../libs/tracking_dump_reader.h | 20 +++++++++-- .../gps_l1_ca_dll_pll_tracking_test_fpga.cc | 2 +- .../gps_l1_ca_gaussian_tracking_test.cc | 2 +- .../tracking/tracking_pull-in_test_fpga.cc | 2 +- .../libs/gps_l1_ca_kf_read_tracking_dump.m | 10 +++--- .../lib/gps_l1_ca_kf_read_tracking_dump.py | 4 +-- 14 files changed, 92 insertions(+), 52 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 4b55984e8..a8c737f3d 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -181,6 +181,11 @@ All notable changes to GNSS-SDR will be documented in this file. week, so that channels are reported as soon as tracking locks. This also lets the secondary-band acquisition assistance start once the primary-band signal is locked, instead of after its time of week is decoded. +- The accumulated carrier phase is now stored as a `double` in the tracking + dumps (binary and `.mat`) of all tracking implementations, instead of a + `float` whose resolution drops to 0.0625 rad at 10^6 rad. Each binary record + is now 4 bytes longer, and the MATLAB and Python readers in `utils/` are + updated accordingly. See the definitions of concepts and metrics at https://gnss-sdr.org/design-forces/ diff --git a/src/algorithms/tracking/gnuradio_blocks/galileo_e1_tcp_connector_tracking_cc.cc b/src/algorithms/tracking/gnuradio_blocks/galileo_e1_tcp_connector_tracking_cc.cc index 6c2c0e8d3..6ba5fe010 100644 --- a/src/algorithms/tracking/gnuradio_blocks/galileo_e1_tcp_connector_tracking_cc.cc +++ b/src/algorithms/tracking/gnuradio_blocks/galileo_e1_tcp_connector_tracking_cc.cc @@ -352,7 +352,7 @@ int Galileo_E1_Tcp_Connector_Tracking_cc::general_work(int noutput_items __attri // New code Doppler frequency estimation d_code_freq_chips = GALILEO_E1_CODE_CHIP_RATE_CPS + ((d_carrier_doppler_hz * GALILEO_E1_CODE_CHIP_RATE_CPS) / GALILEO_E1_FREQ_HZ); // carrier phase accumulator for (K) doppler estimation - d_acc_carrier_phase_rad -= static_cast(TWO_PI * d_carrier_doppler_hz * GALILEO_E1_CODE_PERIOD_S); + d_acc_carrier_phase_rad -= TWO_PI * d_carrier_doppler_hz * GALILEO_E1_CODE_PERIOD_S; // remnant carrier phase to prevent overflow in the code NCO d_rem_carr_phase_rad = d_rem_carr_phase_rad + static_cast(TWO_PI * d_carrier_doppler_hz * GALILEO_E1_CODE_PERIOD_S); d_rem_carr_phase_rad = fmod(d_rem_carr_phase_rad, TWO_PI); @@ -480,6 +480,7 @@ int Galileo_E1_Tcp_Connector_Tracking_cc::general_work(int noutput_items __attri float tmp_VE = 0.0; float tmp_VL = 0.0; float tmp_float; + double tmp_double; prompt_I = d_correlator_outs[1].real(); prompt_Q = d_correlator_outs[1].imag(); tmp_E = std::abs(d_correlator_outs[0]); @@ -498,9 +499,9 @@ int Galileo_E1_Tcp_Connector_Tracking_cc::general_work(int noutput_items __attri d_dump_file.write(reinterpret_cast(&prompt_Q), sizeof(float)); // PRN start sample stamp d_dump_file.write(reinterpret_cast(&d_sample_counter), sizeof(uint64_t)); - // accumulated carrier phase - tmp_float = static_cast(d_acc_carrier_phase_rad); - d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); + // accumulated carrier phase (double, since it grows without bound) + tmp_double = d_acc_carrier_phase_rad; + d_dump_file.write(reinterpret_cast(&tmp_double), sizeof(double)); // carrier and code frequency tmp_float = static_cast(d_carrier_doppler_hz); d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); @@ -524,7 +525,7 @@ int Galileo_E1_Tcp_Connector_Tracking_cc::general_work(int noutput_items __attri // AUX vars (for debug purposes) tmp_float = 0.0; d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); - auto tmp_double = static_cast(d_sample_counter + d_correlation_length_samples); + tmp_double = static_cast(d_sample_counter + d_correlation_length_samples); d_dump_file.write(reinterpret_cast(&tmp_double), sizeof(double)); // PRN uint32_t prn_ = d_acquisition_gnss_synchro->PRN; diff --git a/src/algorithms/tracking/gnuradio_blocks/galileo_e1_tcp_connector_tracking_cc.h b/src/algorithms/tracking/gnuradio_blocks/galileo_e1_tcp_connector_tracking_cc.h index 1277cbed6..fd0bb687d 100644 --- a/src/algorithms/tracking/gnuradio_blocks/galileo_e1_tcp_connector_tracking_cc.h +++ b/src/algorithms/tracking/gnuradio_blocks/galileo_e1_tcp_connector_tracking_cc.h @@ -139,7 +139,7 @@ private: // tracking vars double d_code_freq_chips; float d_carrier_doppler_hz; - float d_acc_carrier_phase_rad; + double d_acc_carrier_phase_rad; float d_acc_code_phase_secs; float d_code_phase_samples; size_t d_port_ch0; diff --git a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_dll_pll_tracking_gpu_cc.cc b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_dll_pll_tracking_gpu_cc.cc index 79556b884..32e113356 100644 --- a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_dll_pll_tracking_gpu_cc.cc +++ b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_dll_pll_tracking_gpu_cc.cc @@ -521,6 +521,7 @@ int Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc::general_work(int noutput_items __attribut float tmp_VE = 0.0; float tmp_VL = 0.0; float tmp_float; + double tmp_double; prompt_I = d_correlator_outs[1].real(); prompt_Q = d_correlator_outs[1].imag(); tmp_E = std::abs(d_correlator_outs[0]); @@ -539,9 +540,9 @@ int Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc::general_work(int noutput_items __attribut d_dump_file.write(reinterpret_cast(&prompt_Q), sizeof(float)); // PRN start sample stamp d_dump_file.write(reinterpret_cast(&d_sample_counter), sizeof(uint64_t)); - // accumulated carrier phase - tmp_float = static_cast(d_acc_carrier_phase_cycles * TWO_PI); - d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); + // accumulated carrier phase (double, since it grows without bound) + tmp_double = d_acc_carrier_phase_cycles * TWO_PI; + d_dump_file.write(reinterpret_cast(&tmp_double), sizeof(double)); // carrier and code frequency tmp_float = static_cast(d_carrier_doppler_hz); d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); @@ -565,7 +566,7 @@ int Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc::general_work(int noutput_items __attribut // AUX vars (for debug purposes) tmp_float = code_error_chips_Ti * CURRENT_INTEGRATION_TIME_S; d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); - double tmp_double = static_cast(d_sample_counter + d_correlation_length_samples); + tmp_double = static_cast(d_sample_counter + d_correlation_length_samples); d_dump_file.write(reinterpret_cast(&tmp_double), sizeof(double)); // PRN uint32_t prn_ = d_acquisition_gnss_synchro->PRN; diff --git a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.cc b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.cc index 995689093..8c4cd51cb 100644 --- a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.cc +++ b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.cc @@ -387,8 +387,8 @@ int32_t Gps_L1_Ca_Gaussian_Tracking_cc::save_matfile() { // READ DUMP FILE std::ifstream::pos_type size; - int32_t number_of_double_vars = 1; - int32_t number_of_float_vars = 19; + int32_t number_of_double_vars = 2; + int32_t number_of_float_vars = 18; int32_t epoch_size_bytes = sizeof(uint64_t) + sizeof(double) * number_of_double_vars + sizeof(float) * number_of_float_vars + sizeof(uint32_t); std::ifstream dump_file; @@ -422,7 +422,7 @@ int32_t Gps_L1_Ca_Gaussian_Tracking_cc::save_matfile() auto Prompt_I = std::vector(num_epoch); auto Prompt_Q = std::vector(num_epoch); auto PRN_start_sample_count = std::vector(num_epoch); - auto acc_carrier_phase_rad = std::vector(num_epoch); + auto acc_carrier_phase_rad = std::vector(num_epoch); auto carrier_doppler_hz = std::vector(num_epoch); auto carrier_dopplerrate_hz2 = std::vector(num_epoch); auto code_freq_chips = std::vector(num_epoch); @@ -451,7 +451,7 @@ int32_t Gps_L1_Ca_Gaussian_Tracking_cc::save_matfile() dump_file.read(reinterpret_cast(&Prompt_I[i]), sizeof(float)); dump_file.read(reinterpret_cast(&Prompt_Q[i]), sizeof(float)); dump_file.read(reinterpret_cast(&PRN_start_sample_count[i]), sizeof(uint64_t)); - dump_file.read(reinterpret_cast(&acc_carrier_phase_rad[i]), sizeof(float)); + dump_file.read(reinterpret_cast(&acc_carrier_phase_rad[i]), sizeof(double)); dump_file.read(reinterpret_cast(&carrier_doppler_hz[i]), sizeof(float)); dump_file.read(reinterpret_cast(&carrier_dopplerrate_hz2[i]), sizeof(float)); dump_file.read(reinterpret_cast(&code_freq_chips[i]), sizeof(float)); @@ -492,7 +492,7 @@ int32_t Gps_L1_Ca_Gaussian_Tracking_cc::save_matfile() write_matlab_var<2, float>("Prompt_I", Prompt_I.data(), matfp, dims); write_matlab_var<2, float>("Prompt_Q", Prompt_Q.data(), matfp, dims); write_matlab_var<2, uint64_t>("PRN_start_sample_count", PRN_start_sample_count.data(), matfp, dims); - write_matlab_var<2, float>("acc_carrier_phase_rad", acc_carrier_phase_rad.data(), matfp, dims); + write_matlab_var<2, double>("acc_carrier_phase_rad", acc_carrier_phase_rad.data(), matfp, dims); write_matlab_var<2, float>("carrier_doppler_hz", carrier_doppler_hz.data(), matfp, dims); write_matlab_var<2, float>("carrier_dopplerrate_hz2", carrier_dopplerrate_hz2.data(), matfp, dims); write_matlab_var<2, float>("code_freq_chips", code_freq_chips.data(), matfp, dims); @@ -845,9 +845,9 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::process_input(int noutput_items __attribute_ d_dump_file.write(reinterpret_cast(&prompt_Q), sizeof(float)); // PRN start sample stamp d_dump_file.write(reinterpret_cast(&d_sample_counter), sizeof(uint64_t)); - // accumulated carrier phase - tmp_float = static_cast(d_acc_carrier_phase_rad); - d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); + // accumulated carrier phase (double, since it grows without bound) + tmp_double = d_acc_carrier_phase_rad; + d_dump_file.write(reinterpret_cast(&tmp_double), sizeof(double)); // carrier and code frequency tmp_float = static_cast(d_carrier_doppler_hz); d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); diff --git a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_tcp_connector_tracking_cc.cc b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_tcp_connector_tracking_cc.cc index 84fb84f0a..2c0ff2b6c 100644 --- a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_tcp_connector_tracking_cc.cc +++ b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_tcp_connector_tracking_cc.cc @@ -510,6 +510,7 @@ int Gps_L1_Ca_Tcp_Connector_Tracking_cc::general_work(int noutput_items __attrib float tmp_VE = 0.0; float tmp_VL = 0.0; float tmp_float; + double tmp_double; prompt_I = d_correlator_outs[1].real(); prompt_Q = d_correlator_outs[1].imag(); tmp_E = std::abs(d_correlator_outs[0]); @@ -528,9 +529,9 @@ int Gps_L1_Ca_Tcp_Connector_Tracking_cc::general_work(int noutput_items __attrib d_dump_file.write(reinterpret_cast(&prompt_Q), sizeof(float)); // PRN start sample stamp d_dump_file.write(reinterpret_cast(&d_sample_counter), sizeof(uint64_t)); - // accumulated carrier phase - tmp_float = static_cast(d_acc_carrier_phase_rad); - d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); + // accumulated carrier phase (double, since it grows without bound) + tmp_double = d_acc_carrier_phase_rad; + d_dump_file.write(reinterpret_cast(&tmp_double), sizeof(double)); // carrier and code frequency tmp_float = static_cast(d_carrier_doppler_hz); d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); @@ -554,7 +555,7 @@ int Gps_L1_Ca_Tcp_Connector_Tracking_cc::general_work(int noutput_items __attrib // AUX vars (for debug purposes) tmp_float = 0.0; d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); - auto tmp_double = static_cast(d_sample_counter + d_correlation_length_samples); + tmp_double = static_cast(d_sample_counter + d_correlation_length_samples); d_dump_file.write(reinterpret_cast(&tmp_double), sizeof(double)); // PRN uint32_t prn_ = d_acquisition_gnss_synchro->PRN; diff --git a/src/algorithms/tracking/gnuradio_blocks/kf_tracking.cc b/src/algorithms/tracking/gnuradio_blocks/kf_tracking.cc index 353c9cd42..2ef5d27ea 100644 --- a/src/algorithms/tracking/gnuradio_blocks/kf_tracking.cc +++ b/src/algorithms/tracking/gnuradio_blocks/kf_tracking.cc @@ -1540,9 +1540,9 @@ void kf_tracking::log_data() // PRN start sample stamp tmp_long_int = d_sample_counter + static_cast(d_current_prn_length_samples); d_dump_file.write(reinterpret_cast(&tmp_long_int), sizeof(uint64_t)); - // accumulated carrier phase - tmp_float = static_cast(d_acc_carrier_phase_rad); - d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); + // accumulated carrier phase (double, since it grows without bound) + tmp_double = d_acc_carrier_phase_rad; + d_dump_file.write(reinterpret_cast(&tmp_double), sizeof(double)); // carrier and code frequency tmp_float = static_cast(d_carrier_doppler_kf_hz); d_dump_file.write(reinterpret_cast(&tmp_float), sizeof(float)); @@ -1590,8 +1590,8 @@ int32_t kf_tracking::save_matfile() const { // READ DUMP FILE std::ifstream::pos_type size; - const int32_t number_of_double_vars = 1; - const int32_t number_of_float_vars = 19; + const int32_t number_of_double_vars = 2; + const int32_t number_of_float_vars = 18; const int32_t epoch_size_bytes = sizeof(uint64_t) + sizeof(double) * number_of_double_vars + sizeof(float) * number_of_float_vars + sizeof(uint32_t); std::ifstream dump_file; @@ -1631,7 +1631,7 @@ int32_t kf_tracking::save_matfile() const auto Prompt_I = std::vector(num_epoch); auto Prompt_Q = std::vector(num_epoch); auto PRN_start_sample_count = std::vector(num_epoch); - auto acc_carrier_phase_rad = std::vector(num_epoch); + auto acc_carrier_phase_rad = std::vector(num_epoch); auto carrier_doppler_hz = std::vector(num_epoch); auto carrier_doppler_rate_hz = std::vector(num_epoch); auto code_freq_chips = std::vector(num_epoch); @@ -1659,7 +1659,7 @@ int32_t kf_tracking::save_matfile() const dump_file.read(reinterpret_cast(&Prompt_I[i]), sizeof(float)); dump_file.read(reinterpret_cast(&Prompt_Q[i]), sizeof(float)); dump_file.read(reinterpret_cast(&PRN_start_sample_count[i]), sizeof(uint64_t)); - dump_file.read(reinterpret_cast(&acc_carrier_phase_rad[i]), sizeof(float)); + dump_file.read(reinterpret_cast(&acc_carrier_phase_rad[i]), sizeof(double)); dump_file.read(reinterpret_cast(&carrier_doppler_hz[i]), sizeof(float)); dump_file.read(reinterpret_cast(&carrier_doppler_rate_hz[i]), sizeof(float)); dump_file.read(reinterpret_cast(&code_freq_chips[i]), sizeof(float)); @@ -1700,7 +1700,7 @@ int32_t kf_tracking::save_matfile() const write_matlab_var<2, float>("Prompt_I", Prompt_I.data(), matfp, dims); write_matlab_var<2, float>("Prompt_Q", Prompt_Q.data(), matfp, dims); write_matlab_var<2, uint64_t>("PRN_start_sample_count", PRN_start_sample_count.data(), matfp, dims); - write_matlab_var<2, float>("acc_carrier_phase_rad", acc_carrier_phase_rad.data(), matfp, dims); + write_matlab_var<2, double>("acc_carrier_phase_rad", acc_carrier_phase_rad.data(), matfp, dims); write_matlab_var<2, float>("carrier_doppler_hz", carrier_doppler_hz.data(), matfp, dims); write_matlab_var<2, float>("carrier_doppler_rate_hz", carrier_doppler_rate_hz.data(), matfp, dims); write_matlab_var<2, float>("code_freq_chips", code_freq_chips.data(), matfp, dims); diff --git a/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.cc b/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.cc index e9cf068cb..d061edb85 100644 --- a/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.cc +++ b/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.cc @@ -19,6 +19,11 @@ #include #include +Tracking_Dump_Reader::Tracking_Dump_Reader(Tracking_Dump_Layout layout) : d_layout(layout) +{ +} + + bool Tracking_Dump_Reader::read_binary_obs() { try @@ -35,8 +40,17 @@ bool Tracking_Dump_Reader::read_binary_obs() d_dump_file.read(reinterpret_cast(&carrier_doppler_hz), sizeof(float)); d_dump_file.read(reinterpret_cast(&carrier_doppler_rate_hz_s), sizeof(float)); d_dump_file.read(reinterpret_cast(&code_freq_chips), sizeof(float)); - d_dump_file.read(reinterpret_cast(&code_freq_rate_chips), sizeof(float)); - d_dump_file.read(reinterpret_cast(&carr_error_hz), sizeof(float)); + if (d_layout == Tracking_Dump_Layout::GPS_L1_CA_GAUSSIAN) + { + // no code frequency rate, and the carrier noise variance follows the carrier error + d_dump_file.read(reinterpret_cast(&carr_error_hz), sizeof(float)); + d_dump_file.read(reinterpret_cast(&carr_noise_sigma2), sizeof(float)); + } + else + { + d_dump_file.read(reinterpret_cast(&code_freq_rate_chips), sizeof(float)); + d_dump_file.read(reinterpret_cast(&carr_error_hz), sizeof(float)); + } d_dump_file.read(reinterpret_cast(&carr_error_filt_hz), sizeof(float)); d_dump_file.read(reinterpret_cast(&code_error_chips), sizeof(float)); d_dump_file.read(reinterpret_cast(&code_error_filt_chips), sizeof(float)); @@ -45,8 +59,11 @@ bool Tracking_Dump_Reader::read_binary_obs() d_dump_file.read(reinterpret_cast(&aux1), sizeof(float)); d_dump_file.read(reinterpret_cast(&aux2), sizeof(double)); d_dump_file.read(reinterpret_cast(&PRN), sizeof(unsigned int)); - d_dump_file.read(reinterpret_cast(&TOW_ms), sizeof(uint64_t)); - d_dump_file.read(reinterpret_cast(&WN), sizeof(int32_t)); + if (d_layout == Tracking_Dump_Layout::DLL_PLL_VEML) + { + d_dump_file.read(reinterpret_cast(&TOW_ms), sizeof(uint64_t)); + d_dump_file.read(reinterpret_cast(&WN), sizeof(int32_t)); + } } catch (const std::ifstream::failure &e) { @@ -71,11 +88,12 @@ bool Tracking_Dump_Reader::restart() int64_t Tracking_Dump_Reader::num_epochs() { std::ifstream::pos_type size; - int number_of_double_vars = 2; - int number_of_float_vars = 18; - int epoch_size_bytes = sizeof(uint64_t) + sizeof(double) * number_of_double_vars + - sizeof(float) * number_of_float_vars + sizeof(unsigned int) + - sizeof(uint64_t) + sizeof(int32_t); + const int number_of_double_vars = 2; + const int number_of_float_vars = 18; + const int tow_wn_size_bytes = (d_layout == Tracking_Dump_Layout::DLL_PLL_VEML) ? sizeof(uint64_t) + sizeof(int32_t) : 0; + const int epoch_size_bytes = sizeof(uint64_t) + sizeof(double) * number_of_double_vars + + sizeof(float) * number_of_float_vars + sizeof(unsigned int) + + tow_wn_size_bytes; std::ifstream tmpfile(d_dump_filename.c_str(), std::ios::binary | std::ios::ate); if (tmpfile.is_open()) { diff --git a/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.h b/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.h index 860882888..20fcf4b32 100644 --- a/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.h +++ b/tests/unit-tests/signal-processing-blocks/libs/tracking_dump_reader.h @@ -22,9 +22,21 @@ #include #include +/*! + * \brief Record layout of a tracking dump file, which depends on the block + * that wrote it. + */ +enum class Tracking_Dump_Layout +{ + DLL_PLL_VEML, //!< dll_pll_veml_tracking: ends with PRN, TOW and WN (112 bytes) + DLL_PLL_VEML_FPGA, //!< dll_pll_veml_tracking_fpga and kf_tracking: ends with PRN (100 bytes) + GPS_L1_CA_GAUSSIAN //!< gps_l1_ca_gaussian_tracking_cc: no code frequency rate, ends with PRN (100 bytes) +}; + class Tracking_Dump_Reader { public: + explicit Tracking_Dump_Reader(Tracking_Dump_Layout layout = Tracking_Dump_Layout::DLL_PLL_VEML); ~Tracking_Dump_Reader(); bool read_binary_obs(); bool restart(); @@ -51,10 +63,11 @@ public: float carrier_doppler_hz; float carrier_doppler_rate_hz_s; float code_freq_chips; - float code_freq_rate_chips; + float code_freq_rate_chips{}; // not in GPS_L1_CA_GAUSSIAN dumps // PLL commands float carr_error_hz; + float carr_noise_sigma2{}; // only in GPS_L1_CA_GAUSSIAN dumps float carr_error_filt_hz; // DLL commands @@ -70,12 +83,13 @@ public: double aux2; unsigned int PRN; - uint64_t TOW_ms; - int32_t WN; + uint64_t TOW_ms{}; // only in DLL_PLL_VEML dumps + int32_t WN{}; // only in DLL_PLL_VEML dumps private: std::string d_dump_filename; std::ifstream d_dump_file; + Tracking_Dump_Layout d_layout; }; #endif // GNSS_SDR_TRACKING_DUMP_READER_H diff --git a/tests/unit-tests/signal-processing-blocks/tracking/gps_l1_ca_dll_pll_tracking_test_fpga.cc b/tests/unit-tests/signal-processing-blocks/tracking/gps_l1_ca_dll_pll_tracking_test_fpga.cc index 4de91aaaa..3d18e8a0c 100644 --- a/tests/unit-tests/signal-processing-blocks/tracking/gps_l1_ca_dll_pll_tracking_test_fpga.cc +++ b/tests/unit-tests/signal-processing-blocks/tracking/gps_l1_ca_dll_pll_tracking_test_fpga.cc @@ -612,7 +612,7 @@ TEST_F(GpsL1CADllPllTrackingTestFpga, ValidationOfResultsFpga) } // load the measured values - Tracking_Dump_Reader trk_dump; + Tracking_Dump_Reader trk_dump(Tracking_Dump_Layout::DLL_PLL_VEML_FPGA); ASSERT_NO_THROW( { if (trk_dump.open_obs_file(std::string("./tracking_ch_0.dat")) == false) diff --git a/tests/unit-tests/signal-processing-blocks/tracking/gps_l1_ca_gaussian_tracking_test.cc b/tests/unit-tests/signal-processing-blocks/tracking/gps_l1_ca_gaussian_tracking_test.cc index 1b0c1b145..8213ea603 100644 --- a/tests/unit-tests/signal-processing-blocks/tracking/gps_l1_ca_gaussian_tracking_test.cc +++ b/tests/unit-tests/signal-processing-blocks/tracking/gps_l1_ca_gaussian_tracking_test.cc @@ -520,7 +520,7 @@ TEST_F(GpsL1CAGaussianTrackingTest, ValidationOfResults) } // load the measured values - Tracking_Dump_Reader trk_dump; + Tracking_Dump_Reader trk_dump(Tracking_Dump_Layout::GPS_L1_CA_GAUSSIAN); ASSERT_EQ(trk_dump.open_obs_file(std::string("./tracking_ch_0.dat")), true) << "Failure opening tracking dump file"; diff --git a/tests/unit-tests/signal-processing-blocks/tracking/tracking_pull-in_test_fpga.cc b/tests/unit-tests/signal-processing-blocks/tracking/tracking_pull-in_test_fpga.cc index c72defc6b..582d63b4c 100644 --- a/tests/unit-tests/signal-processing-blocks/tracking/tracking_pull-in_test_fpga.cc +++ b/tests/unit-tests/signal-processing-blocks/tracking/tracking_pull-in_test_fpga.cc @@ -1216,7 +1216,7 @@ TEST_F(TrackingPullInTestFpga, ValidationOfResults) #endif { // load the measured values - Tracking_Dump_Reader trk_dump; + Tracking_Dump_Reader trk_dump(Tracking_Dump_Layout::DLL_PLL_VEML_FPGA); ASSERT_EQ(trk_dump.open_obs_file(std::string("./tracking_ch_0.dat")), true) << "Failure opening tracking dump file"; diff --git a/utils/matlab/libs/gps_l1_ca_kf_read_tracking_dump.m b/utils/matlab/libs/gps_l1_ca_kf_read_tracking_dump.m index b8a2ff8dc..8d94781ec 100644 --- a/utils/matlab/libs/gps_l1_ca_kf_read_tracking_dump.m +++ b/utils/matlab/libs/gps_l1_ca_kf_read_tracking_dump.m @@ -18,9 +18,9 @@ function [GNSS_tracking] = gps_l1_ca_kf_read_tracking_dump (filename, count) m = nargchk (1,2,nargin); -num_float_vars = 19; +num_float_vars = 18; num_unsigned_long_int_vars = 1; -num_double_vars = 1; +num_double_vars = 2; num_unsigned_int_vars = 1; if(~isempty(strfind(computer('arch'), '64'))) @@ -75,9 +75,9 @@ else fseek(f,bytes_shift,'bof'); % move to next interleaved float v8 = fread (f, count, 'long', skip_bytes_each_read - unsigned_long_int_size_bytes); bytes_shift = bytes_shift + unsigned_long_int_size_bytes; - fseek(f,bytes_shift,'bof'); % move to next float - v9 = fread (f, count, 'float', skip_bytes_each_read - float_size_bytes); - bytes_shift = bytes_shift + float_size_bytes; + fseek(f,bytes_shift,'bof'); % move to next double + v9 = fread (f, count, 'double', skip_bytes_each_read - double_size_bytes); + bytes_shift = bytes_shift + double_size_bytes; fseek(f,bytes_shift,'bof'); % move to next float v10 = fread (f, count, 'float', skip_bytes_each_read - float_size_bytes); bytes_shift = bytes_shift + float_size_bytes; diff --git a/utils/python/lib/gps_l1_ca_kf_read_tracking_dump.py b/utils/python/lib/gps_l1_ca_kf_read_tracking_dump.py index 534a4b074..8cdab5b7d 100644 --- a/utils/python/lib/gps_l1_ca_kf_read_tracking_dump.py +++ b/utils/python/lib/gps_l1_ca_kf_read_tracking_dump.py @@ -31,7 +31,7 @@ import struct # in src/algorithms/tracking/gnuradio_blocks/kf_tracking.cc # # Fields are written back-to-back. Unlike the DLL/PLL VEML dump, the KF dump -# ends at PRN (no TOW_ms / WN fields), so a record is 22 fields / 96 bytes. +# ends at PRN (no TOW_ms / WN fields), so a record is 22 fields / 100 bytes. # '<' selects little-endian / standard sizes / no alignment padding. _RECORD_FORMAT = '<' + ( 'f' # VE -> Magnitude of the Very Early correlator. @@ -42,7 +42,7 @@ _RECORD_FORMAT = '<' + ( 'f' # prompt_I -> Prompt correlator, In-phase component. 'f' # prompt_Q -> Prompt correlator, Quadrature component. 'Q' # PRN_start_sample -> Sample counter from tracking start. - 'f' # acc_carrier_phase_rad -> Accumulated carrier phase, in rad. + 'd' # acc_carrier_phase_rad -> Accumulated carrier phase, in rad. 'f' # carrier_doppler_hz -> KF carrier Doppler estimate, in Hz. 'f' # carrier_doppler_rate_hz2 -> KF carrier Doppler rate, in Hz/s. 'f' # code_freq_hz -> KF code frequency, in chips/s. From 4baba9d479ac1348d1e7ebdcc2bf5c21fa5a78f0 Mon Sep 17 00:00:00 2001 From: Carles Fernandez Date: Tue, 27 Oct 2026 08:49:26 +0100 Subject: [PATCH 08/11] Fix tracking blocks --- .../gps_l1_ca_dll_pll_tracking_gpu_cc.cc | 120 +++++++++++----- .../gps_l1_ca_dll_pll_tracking_gpu_cc.h | 9 ++ .../gps_l1_ca_gaussian_tracking_cc.cc | 114 ++++++++++++---- .../gps_l1_ca_gaussian_tracking_cc.h | 9 ++ .../gps_l1_ca_tcp_connector_tracking_cc.cc | 129 +++++++++++++----- .../gps_l1_ca_tcp_connector_tracking_cc.h | 10 ++ 6 files changed, 302 insertions(+), 89 deletions(-) diff --git a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_dll_pll_tracking_gpu_cc.cc b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_dll_pll_tracking_gpu_cc.cc index 32e113356..e2875cf62 100644 --- a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_dll_pll_tracking_gpu_cc.cc +++ b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_dll_pll_tracking_gpu_cc.cc @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -170,6 +171,12 @@ Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc::Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc( d_carrier_phase_step_rad = 0.0; d_acc_carrier_phase_initialized = false; + + d_Prompt_I_history.set_capacity(GPS_CA_PREAMBLE_LENGTH_SYMBOLS); + d_P_bit_accu = gr_complex(0.0, 0.0); + d_current_bit_symbol = 0; + d_bit_synchronized = false; + d_Flag_PLL_180_deg_phase_locked = false; // set_min_output_buffer((int64_t)300); } @@ -238,6 +245,13 @@ void Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc::start_tracking() d_pll_to_dll_assist_secs_Ti = 0.0; d_code_phase_samples = d_acq_code_phase_samples; + // navigation data bit synchronization starts over + d_Prompt_I_history.clear(); + d_P_bit_accu = gr_complex(0.0, 0.0); + d_current_bit_symbol = 0; + d_bit_synchronized = false; + d_Flag_PLL_180_deg_phase_locked = false; + sys = std::string(1, d_acquisition_gnss_synchro->System); // DEBUG OUTPUT @@ -326,6 +340,29 @@ void Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc::check_carrier_phase_coherent_initializat } +bool Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc::acquire_bit_sync() +{ + // ******* preamble correlation at the 1 ms prompt rate ******** + if (d_Prompt_I_history.size() < static_cast(GPS_CA_PREAMBLE_LENGTH_SYMBOLS)) + { + return false; + } + int32_t corr_value = 0; + for (int32_t i = 0; i < GPS_CA_PREAMBLE_LENGTH_SYMBOLS; i++) + { + const bool symbol_is_one = d_Prompt_I_history[i] >= 0.0F; // symbols clipping + corr_value += (symbol_is_one == (GPS_CA_PREAMBLE_SYMBOLS_STR[i] == '1')) ? 1 : -1; + } + if (std::abs(corr_value) == GPS_CA_PREAMBLE_LENGTH_SYMBOLS) + { + // The last prompt closes a bit, so the next one opens a new bit + d_Flag_PLL_180_deg_phase_locked = (corr_value < 0); + return true; + } + return false; +} + + int Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc::general_work(int noutput_items __attribute__((unused)), gr_vector_int &ninput_items __attribute__((unused)), gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @@ -345,6 +382,7 @@ int Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc::general_work(int noutput_items __attribut double dll_code_error_secs_Ti = 0.0; double carr_phase_error_secs_Ti = 0.0; bool loss_of_lock = false; + int produced = 0; if (d_enable_tracking == true) { @@ -356,14 +394,10 @@ int Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc::general_work(int noutput_items __attribut const int32_t acq_to_trk_delay_samples = d_sample_counter - d_acq_sample_stamp; const double acq_trk_shif_correction_samples = d_correlation_length_samples - fmod(static_cast(acq_to_trk_delay_samples), static_cast(d_correlation_length_samples)); const int32_t samples_offset = round(d_acq_code_phase_samples + acq_trk_shif_correction_samples); - current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast(samples_offset); - current_synchro_data.fs = d_fs_in; - current_synchro_data.correlation_length_ms = 1; - *out[0] = std::move(current_synchro_data); d_sample_counter += static_cast(samples_offset); // count for the processed samples d_pull_in = false; consume_each(samples_offset); // shift input to perform alignment with local replica - return 1; + return 0; } // ################# CARRIER WIPEOFF AND CORRELATORS ############################## @@ -439,7 +473,7 @@ int Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc::general_work(int noutput_items __attribut #if USE_GLOG_AND_GFLAGS if (d_cn0_estimation_counter < FLAGS_cn0_samples) #else - if (d_cn0_estimation_counter < absl::getFlag(FLAGS_cn0_samples)) + if (d_cn0_estimation_counter < absl::GetFlag(FLAGS_cn0_samples)) #endif { // fill buffer with prompt correlator output values @@ -485,16 +519,55 @@ int Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc::general_work(int noutput_items __attribut check_carrier_phase_coherent_initialization(); } + // ########### NAVIGATION DATA BIT SYNCHRONIZATION ########## + // The telemetry decoder takes one symbol per navigation data bit + bool bit_completed = false; + if (!loss_of_lock) + { + if (d_bit_synchronized) + { + d_P_bit_accu += d_correlator_outs[1]; + d_current_bit_symbol++; + if (d_current_bit_symbol == GPS_CA_TELEMETRY_SYMBOLS_PER_BIT) + { + d_current_bit_symbol = 0; + bit_completed = true; + } + } + else + { + d_Prompt_I_history.push_back(d_correlator_outs[1].real()); + if (acquire_bit_sync()) + { + d_bit_synchronized = true; + d_Prompt_I_history.clear(); + d_P_bit_accu = gr_complex(0.0, 0.0); + d_current_bit_symbol = 0; + LOG(INFO) << "GPS L1 C/A tracking bit synchronization locked in channel " << d_channel + << " for satellite " << Gnss_Satellite(systemName[sys], d_acquisition_gnss_synchro->PRN); + } + } + } + // ########### Output the tracking data to navigation and PVT ########## - current_synchro_data.Prompt_I = static_cast((d_correlator_outs[1]).real()); - current_synchro_data.Prompt_Q = static_cast((d_correlator_outs[1]).imag()); - current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast(d_correlation_length_samples); - current_synchro_data.Code_phase_samples = d_rem_code_phase_samples; - current_synchro_data.Carrier_phase_rads = TWO_PI * d_acc_carrier_phase_cycles; - current_synchro_data.Carrier_Doppler_hz = d_carrier_doppler_hz; - current_synchro_data.CN0_dB_hz = d_CN0_SNV_dB_Hz; - current_synchro_data.Flag_valid_symbol_output = !loss_of_lock; - current_synchro_data.correlation_length_ms = 1; + if (bit_completed || loss_of_lock) + { + const gr_complex prompt = bit_completed ? d_P_bit_accu : d_correlator_outs[1]; + current_synchro_data.Prompt_I = static_cast(prompt.real()); + current_synchro_data.Prompt_Q = static_cast(prompt.imag()); + current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast(d_correlation_length_samples); + current_synchro_data.Code_phase_samples = d_rem_code_phase_samples; + current_synchro_data.Carrier_phase_rads = TWO_PI * d_acc_carrier_phase_cycles; + current_synchro_data.Carrier_Doppler_hz = d_carrier_doppler_hz; + current_synchro_data.CN0_dB_hz = d_CN0_SNV_dB_Hz; + current_synchro_data.Flag_valid_symbol_output = !loss_of_lock; + current_synchro_data.Flag_PLL_180_deg_phase_locked = d_Flag_PLL_180_deg_phase_locked; + current_synchro_data.correlation_length_ms = 1; + current_synchro_data.fs = d_fs_in; + *out[0] = std::move(current_synchro_data); + d_P_bit_accu = gr_complex(0.0, 0.0); + produced = 1; + } } else { @@ -502,16 +575,8 @@ int Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc::general_work(int noutput_items __attribut { d_correlator_outs[n] = gr_complex(0, 0); } - - current_synchro_data.System = {'G'}; - current_synchro_data.correlation_length_ms = 1; - current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast(d_correlation_length_samples); } - // assign the GNU Radio block output data - current_synchro_data.fs = d_fs_in; - *out[0] = std::move(current_synchro_data); - if (d_dump) { // MULTIPLEXED FILE RECORDING - Record results to file @@ -581,12 +646,5 @@ int Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc::general_work(int noutput_items __attribut consume_each(d_correlation_length_samples); // this is necessary in gr::block derivates d_sample_counter += d_correlation_length_samples; // count for the processed samples - if (d_enable_tracking || loss_of_lock) - { - return 1; - } - else - { - return 0; - } + return produced; // one item per navigation data bit, plus the loss of lock indication } diff --git a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_dll_pll_tracking_gpu_cc.h b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_dll_pll_tracking_gpu_cc.h index f093a2865..05a9e2af9 100644 --- a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_dll_pll_tracking_gpu_cc.h +++ b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_dll_pll_tracking_gpu_cc.h @@ -27,6 +27,7 @@ #include "gnss_synchro.h" #include "tracking_2nd_DLL_filter.h" #include "tracking_FLL_PLL_filter.h" +#include #include #include #include @@ -93,6 +94,7 @@ private: void update_local_code(); void update_local_carrier(); void check_carrier_phase_coherent_initialization(); + bool acquire_bit_sync(); // PLL and DLL filter library Tracking_2nd_DLL_filter d_code_loop_filter; @@ -160,6 +162,13 @@ private: int32_t d_carrier_lock_fail_counter; int32_t d_cn0_estimation_counter; + // navigation data bit synchronization (the telemetry decoder takes 20 ms bits) + boost::circular_buffer d_Prompt_I_history; + gr_complex d_P_bit_accu; + int32_t d_current_bit_symbol; + bool d_bit_synchronized; + bool d_Flag_PLL_180_deg_phase_locked; + // control vars bool d_acc_carrier_phase_initialized; bool d_enable_tracking; diff --git a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.cc b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.cc index 8c4cd51cb..e41be3e3c 100644 --- a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.cc +++ b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.cc @@ -36,6 +36,7 @@ #include #include #include +#include #include #include #include @@ -136,6 +137,11 @@ Gps_L1_Ca_Gaussian_Tracking_cc::Gps_L1_Ca_Gaussian_Tracking_cc( d_carrier_lock_threshold(absl::GetFlag(FLAGS_carrier_lock_th)), #endif d_carrier_lock_fail_counter(0), + d_Prompt_I_history(GPS_CA_PREAMBLE_LENGTH_SYMBOLS), + d_P_bit_accu(0.0, 0.0), + d_current_bit_symbol(0), + d_bit_synchronized(false), + d_Flag_PLL_180_deg_phase_locked(false), d_enable_tracking(false), d_pull_in(false), d_dump_filename(dump_filename) @@ -324,6 +330,13 @@ void Gps_L1_Ca_Gaussian_Tracking_cc::start_tracking() d_code_phase_samples = d_acq_code_phase_samples; + // navigation data bit synchronization starts over + d_Prompt_I_history.clear(); + d_P_bit_accu = gr_complex(0.0, 0.0); + d_current_bit_symbol = 0; + d_bit_synchronized = false; + d_Flag_PLL_180_deg_phase_locked = false; + sys = std::string(1, d_acquisition_gnss_synchro->System); // enable tracking @@ -512,6 +525,29 @@ int32_t Gps_L1_Ca_Gaussian_Tracking_cc::save_matfile() } +bool Gps_L1_Ca_Gaussian_Tracking_cc::acquire_bit_sync() +{ + // ******* preamble correlation at the 1 ms prompt rate ******** + if (d_Prompt_I_history.size() < static_cast(GPS_CA_PREAMBLE_LENGTH_SYMBOLS)) + { + return false; + } + int32_t corr_value = 0; + for (int32_t i = 0; i < GPS_CA_PREAMBLE_LENGTH_SYMBOLS; i++) + { + const bool symbol_is_one = d_Prompt_I_history[i] >= 0.0F; // symbols clipping + corr_value += (symbol_is_one == (GPS_CA_PREAMBLE_SYMBOLS_STR[i] == '1')) ? 1 : -1; + } + if (std::abs(corr_value) == GPS_CA_PREAMBLE_LENGTH_SYMBOLS) + { + // The last prompt closes a bit, so the next one opens a new bit + d_Flag_PLL_180_deg_phase_locked = (corr_value < 0); + return true; + } + return false; +} + + void Gps_L1_Ca_Gaussian_Tracking_cc::set_channel(uint32_t channel) { gr::thread::scoped_lock l(d_setlock); @@ -567,6 +603,7 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::process_input(int noutput_items __attribute_ code_error_chips = 0.0; code_error_filt_chips = 0.0; bool loss_of_lock = false; + int produced = 0; // Block input data and block output stream pointers const auto *in = reinterpret_cast(input_items[0]); @@ -604,12 +641,6 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::process_input(int noutput_items __attribute_ d_sample_counter += samples_offset; // count for the processed samples d_pull_in = false; - current_synchro_data.Carrier_phase_rads = d_acc_carrier_phase_rad; - current_synchro_data.Carrier_Doppler_hz = d_carrier_doppler_hz; - current_synchro_data.fs = d_fs_in; - current_synchro_data.correlation_length_ms = 1; - d_det.record_output(this->nitems_written(0), d_sample_counter); - *out[0] = std::move(current_synchro_data); // Kalman filter initialization reset kf_P_x = kf_P_x_ini; // Update Kalman states based on acquisition information @@ -625,7 +656,7 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::process_input(int noutput_items __attribute_ bayes_estimator.init(arma::zeros(1, 1), bayes_kappa, bayes_nu, (kf_H * kf_P_x_ini * kf_H.t() + kf_R) * (bayes_nu + 2)); consume_each(samples_offset); // shift input to perform alignment with local replica - return 1; + return 0; } // ################# CARRIER WIPEOFF AND CORRELATORS ############################## @@ -785,16 +816,56 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::process_input(int noutput_items __attribute_ loss_of_lock = true; } } + // ########### NAVIGATION DATA BIT SYNCHRONIZATION ########## + // The telemetry decoder takes one symbol per navigation data bit + bool bit_completed = false; + if (!loss_of_lock) + { + if (d_bit_synchronized) + { + d_P_bit_accu += d_correlator_outs[1]; + d_current_bit_symbol++; + if (d_current_bit_symbol == GPS_CA_TELEMETRY_SYMBOLS_PER_BIT) + { + d_current_bit_symbol = 0; + bit_completed = true; + } + } + else + { + d_Prompt_I_history.push_back(d_correlator_outs[1].real()); + if (acquire_bit_sync()) + { + d_bit_synchronized = true; + d_Prompt_I_history.clear(); + d_P_bit_accu = gr_complex(0.0, 0.0); + d_current_bit_symbol = 0; + LOG(INFO) << "GPS L1 C/A tracking bit synchronization locked in channel " << d_channel + << " for satellite " << Gnss_Satellite(systemName[sys], d_acquisition_gnss_synchro->PRN); + } + } + } + // ########### Output the tracking data to navigation and PVT ########## - current_synchro_data.Prompt_I = static_cast((d_correlator_outs[1]).real()); - current_synchro_data.Prompt_Q = static_cast((d_correlator_outs[1]).imag()); - current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast(d_current_prn_length_samples); - current_synchro_data.Code_phase_samples = d_rem_code_phase_samples; - current_synchro_data.Carrier_phase_rads = d_acc_carrier_phase_rad; - current_synchro_data.Carrier_Doppler_hz = d_carrier_doppler_hz; - current_synchro_data.CN0_dB_hz = d_CN0_SNV_dB_Hz; - current_synchro_data.Flag_valid_symbol_output = !loss_of_lock; - current_synchro_data.correlation_length_ms = 1; + if (bit_completed || loss_of_lock) + { + const gr_complex prompt = bit_completed ? d_P_bit_accu : d_correlator_outs[1]; + current_synchro_data.Prompt_I = static_cast(prompt.real()); + current_synchro_data.Prompt_Q = static_cast(prompt.imag()); + current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast(d_current_prn_length_samples); + current_synchro_data.Code_phase_samples = d_rem_code_phase_samples; + current_synchro_data.Carrier_phase_rads = d_acc_carrier_phase_rad; + current_synchro_data.Carrier_Doppler_hz = d_carrier_doppler_hz; + current_synchro_data.CN0_dB_hz = d_CN0_SNV_dB_Hz; + current_synchro_data.Flag_valid_symbol_output = !loss_of_lock; + current_synchro_data.Flag_PLL_180_deg_phase_locked = d_Flag_PLL_180_deg_phase_locked; + current_synchro_data.correlation_length_ms = 1; + current_synchro_data.fs = d_fs_in; + d_det.record_output(this->nitems_written(0), current_synchro_data.Tracking_sample_counter); + *out[0] = std::move(current_synchro_data); + d_P_bit_accu = gr_complex(0.0, 0.0); + produced = 1; + } kf_iter++; } @@ -804,17 +875,8 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::process_input(int noutput_items __attribute_ { d_correlator_outs[n] = gr_complex(0, 0); } - - current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast(d_current_prn_length_samples); - current_synchro_data.System = {'G'}; - current_synchro_data.correlation_length_ms = 1; } - // assign the GNU Radio block output data - current_synchro_data.fs = d_fs_in; - d_det.record_output(this->nitems_written(0), current_synchro_data.Tracking_sample_counter); - *out[0] = std::move(current_synchro_data); - if (d_dump) { // MULTIPLEXED FILE RECORDING - Record results to file @@ -889,5 +951,5 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::process_input(int noutput_items __attribute_ consume_each(d_current_prn_length_samples); // this is necessary in gr::block derivates d_sample_counter += d_current_prn_length_samples; // count for the processed samples - return 1; // output tracking result ALWAYS even in the case of d_enable_tracking==false + return produced; // one item per navigation data bit, plus the loss of lock indication } diff --git a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.h b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.h index c58a36305..d377698b1 100644 --- a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.h +++ b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_gaussian_tracking_cc.h @@ -38,6 +38,7 @@ #include "tracking_2nd_DLL_filter.h" #include "tracking_2nd_PLL_filter.h" #include +#include #include #include // for volk_gnsssdr::vector #include @@ -117,6 +118,7 @@ private: int32_t bce_kappa); int32_t save_matfile(); + bool acquire_bit_sync(); // tracking configuration vars uint32_t d_order; @@ -207,6 +209,13 @@ private: double d_carrier_lock_threshold; int32_t d_carrier_lock_fail_counter; + // navigation data bit synchronization (the telemetry decoder takes 20 ms bits) + boost::circular_buffer d_Prompt_I_history; + gr_complex d_P_bit_accu; + int32_t d_current_bit_symbol; + bool d_bit_synchronized; + bool d_Flag_PLL_180_deg_phase_locked; + // control vars bool d_enable_tracking; bool d_pull_in; diff --git a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_tcp_connector_tracking_cc.cc b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_tcp_connector_tracking_cc.cc index 2c0ff2b6c..e729b229e 100644 --- a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_tcp_connector_tracking_cc.cc +++ b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_tcp_connector_tracking_cc.cc @@ -33,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -113,6 +114,11 @@ Gps_L1_Ca_Tcp_Connector_Tracking_cc::Gps_L1_Ca_Tcp_Connector_Tracking_cc( d_carrier_lock_threshold(static_cast(absl::GetFlag(FLAGS_carrier_lock_th))), #endif d_control_id(0), + d_Prompt_I_history(GPS_CA_PREAMBLE_LENGTH_SYMBOLS), + d_P_bit_accu(0.0, 0.0), + d_current_bit_symbol(0), + d_bit_synchronized(false), + d_Flag_PLL_180_deg_phase_locked(false), d_enable_tracking(false), d_pull_in(false), d_dump(dump) @@ -215,6 +221,13 @@ void Gps_L1_Ca_Tcp_Connector_Tracking_cc::start_tracking() d_code_phase_samples = d_acq_code_phase_samples; + // navigation data bit synchronization starts over + d_Prompt_I_history.clear(); + d_P_bit_accu = gr_complex(0.0, 0.0); + d_current_bit_symbol = 0; + d_bit_synchronized = false; + d_Flag_PLL_180_deg_phase_locked = false; + sys = std::string(1, d_acquisition_gnss_synchro->System); // DEBUG OUTPUT @@ -256,6 +269,29 @@ Gps_L1_Ca_Tcp_Connector_Tracking_cc::~Gps_L1_Ca_Tcp_Connector_Tracking_cc() } +bool Gps_L1_Ca_Tcp_Connector_Tracking_cc::acquire_bit_sync() +{ + // ******* preamble correlation at the 1 ms prompt rate ******** + if (d_Prompt_I_history.size() < static_cast(GPS_CA_PREAMBLE_LENGTH_SYMBOLS)) + { + return false; + } + int32_t corr_value = 0; + for (int32_t i = 0; i < GPS_CA_PREAMBLE_LENGTH_SYMBOLS; i++) + { + const bool symbol_is_one = d_Prompt_I_history[i] >= 0.0F; // symbols clipping + corr_value += (symbol_is_one == (GPS_CA_PREAMBLE_SYMBOLS_STR[i] == '1')) ? 1 : -1; + } + if (std::abs(corr_value) == GPS_CA_PREAMBLE_LENGTH_SYMBOLS) + { + // The last prompt closes a bit, so the next one opens a new bit + d_Flag_PLL_180_deg_phase_locked = (corr_value < 0); + return true; + } + return false; +} + + void Gps_L1_Ca_Tcp_Connector_Tracking_cc::set_channel(uint32_t channel) { d_channel = channel; @@ -303,6 +339,7 @@ int Gps_L1_Ca_Tcp_Connector_Tracking_cc::general_work(int noutput_items __attrib float code_error = 0.0; float code_nco = 0.0; bool loss_of_lock = false; + int produced = 0; Tcp_Packet_Data tcp_data; // GNSS_SYNCHRO OBJECT to interchange data between tracking->telemetry_decoder @@ -329,14 +366,11 @@ int Gps_L1_Ca_Tcp_Connector_Tracking_cc::general_work(int noutput_items __attrib acq_to_trk_delay_samples = d_sample_counter - d_acq_sample_stamp; acq_trk_shif_correction_samples = d_next_prn_length_samples - std::fmod(static_cast(acq_to_trk_delay_samples), static_cast(d_next_prn_length_samples)); samples_offset = std::round(d_acq_code_phase_samples + acq_trk_shif_correction_samples); - current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast(samples_offset); - current_synchro_data.fs = d_fs_in; - *out[0] = std::move(current_synchro_data); d_sample_counter_seconds = d_sample_counter_seconds + (static_cast(samples_offset) / static_cast(d_fs_in)); d_sample_counter = d_sample_counter + static_cast(samples_offset); // count for the processed samples d_pull_in = false; consume_each(samples_offset); // shift input to perform alignment with local replica - return 1; + return 0; } // Update the prn length based on code freq (variable) and @@ -357,6 +391,10 @@ int Gps_L1_Ca_Tcp_Connector_Tracking_cc::general_work(int noutput_items __attrib static_cast(d_code_phase_step_chips), d_current_prn_length_samples); + // carrier phase at the end of this block, so that the next one starts where this one ended + d_rem_carr_phase_rad = static_cast(std::fmod(static_cast(d_rem_carr_phase_rad) + carr_phase_step_rad * static_cast(d_current_prn_length_samples), TWO_PI)); + d_acc_carrier_phase_rad -= carr_phase_step_rad * static_cast(d_current_prn_length_samples); + // Variable used for control d_control_id++; @@ -464,41 +502,73 @@ int Gps_L1_Ca_Tcp_Connector_Tracking_cc::general_work(int noutput_items __attrib } } - // ########### Output the tracking data to navigation and PVT ########## - - current_synchro_data.Prompt_I = static_cast((*d_Prompt).real()); - current_synchro_data.Prompt_Q = static_cast((*d_Prompt).imag()); // compute remnant code phase samples AFTER the Tracking timestamp d_rem_code_phase_samples = K_blk_samples - d_current_prn_length_samples; // rounding error < 1 sample - current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast(d_current_prn_length_samples); - current_synchro_data.Code_phase_samples = d_rem_code_phase_samples; - current_synchro_data.Carrier_phase_rads = static_cast(d_acc_carrier_phase_rad); - current_synchro_data.Carrier_Doppler_hz = static_cast(d_carrier_doppler_hz); - current_synchro_data.CN0_dB_hz = static_cast(d_CN0_SNV_dB_Hz); - current_synchro_data.Flag_valid_symbol_output = !loss_of_lock; - current_synchro_data.correlation_length_ms = 1; + + // ########### NAVIGATION DATA BIT SYNCHRONIZATION ########## + // The telemetry decoder takes one symbol per navigation data bit + bool bit_completed = false; + if (!loss_of_lock) + { + if (d_bit_synchronized) + { + d_P_bit_accu += *d_Prompt; + d_current_bit_symbol++; + if (d_current_bit_symbol == GPS_CA_TELEMETRY_SYMBOLS_PER_BIT) + { + d_current_bit_symbol = 0; + bit_completed = true; + } + } + else + { + d_Prompt_I_history.push_back((*d_Prompt).real()); + if (acquire_bit_sync()) + { + d_bit_synchronized = true; + d_Prompt_I_history.clear(); + d_P_bit_accu = gr_complex(0.0, 0.0); + d_current_bit_symbol = 0; + LOG(INFO) << "GPS L1 C/A tracking bit synchronization locked in channel " << d_channel + << " for satellite " << Gnss_Satellite(systemName[sys], d_acquisition_gnss_synchro->PRN); + } + } + } + + // ########### Output the tracking data to navigation and PVT ########## + if (bit_completed || loss_of_lock) + { + const gr_complex prompt = bit_completed ? d_P_bit_accu : *d_Prompt; + current_synchro_data.Prompt_I = static_cast(prompt.real()); + current_synchro_data.Prompt_Q = static_cast(prompt.imag()); + current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast(d_current_prn_length_samples); + current_synchro_data.Code_phase_samples = d_rem_code_phase_samples; + current_synchro_data.Carrier_phase_rads = static_cast(d_acc_carrier_phase_rad); + current_synchro_data.Carrier_Doppler_hz = static_cast(d_carrier_doppler_hz); + current_synchro_data.CN0_dB_hz = static_cast(d_CN0_SNV_dB_Hz); + current_synchro_data.Flag_valid_symbol_output = !loss_of_lock; + current_synchro_data.Flag_PLL_180_deg_phase_locked = d_Flag_PLL_180_deg_phase_locked; + current_synchro_data.correlation_length_ms = 1; + current_synchro_data.System = {'G'}; + current_synchro_data.Signal[0] = '1'; + current_synchro_data.Signal[1] = 'C'; + current_synchro_data.Signal[2] = '\0'; + current_synchro_data.fs = d_fs_in; + *out[0] = std::move(current_synchro_data); + d_P_bit_accu = gr_complex(0.0, 0.0); + produced = 1; + } } else { *d_Early = gr_complex(0.0, 0.0); *d_Prompt = gr_complex(0.0, 0.0); *d_Late = gr_complex(0.0, 0.0); - // GNSS_SYNCHRO OBJECT to interchange data between tracking->telemetry_decoder - current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast(d_correlation_length_samples); // When tracking is disabled an array of 1's is sent to maintain the TCP connection boost::array tx_variables_array = {{1, 1, 1, 1, 1, 1, 1, 1, 0}}; d_tcp_com.send_receive_tcp_packet_gps_l1_ca(tx_variables_array, &tcp_data); } - // assign the GNU Radio block output data - current_synchro_data.System = {'G'}; - current_synchro_data.Signal[0] = '1'; - current_synchro_data.Signal[1] = 'C'; - current_synchro_data.Signal[2] = '\0'; - - current_synchro_data.fs = d_fs_in; - *out[0] = std::move(current_synchro_data); - if (d_dump) { // MULTIPLEXED FILE RECORDING - Record results to file @@ -571,10 +641,5 @@ int Gps_L1_Ca_Tcp_Connector_Tracking_cc::general_work(int noutput_items __attrib d_sample_counter_seconds = d_sample_counter_seconds + (static_cast(d_current_prn_length_samples) / static_cast(d_fs_in)); d_sample_counter += d_current_prn_length_samples; // count for the processed samples - if (d_enable_tracking || loss_of_lock) - { - return 1; - } - - return 0; + return produced; // one item per navigation data bit, plus the loss of lock indication } diff --git a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_tcp_connector_tracking_cc.h b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_tcp_connector_tracking_cc.h index 5c29377e8..d1c309a0b 100644 --- a/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_tcp_connector_tracking_cc.h +++ b/src/algorithms/tracking/gnuradio_blocks/gps_l1_ca_tcp_connector_tracking_cc.h @@ -27,6 +27,7 @@ #include "gnss_block_interface.h" #include "gnss_synchro.h" #include "tcp_communication.h" +#include #include #include // for volk_gnsssdr::vector #include @@ -90,6 +91,8 @@ private: float early_late_space_chips, size_t port_ch0); + bool acquire_bit_sync(); + volk_gnsssdr::vector d_ca_code; // correlator volk_gnsssdr::vector d_local_code_shift_chips; @@ -147,6 +150,13 @@ private: float d_carrier_lock_threshold; float d_control_id; + // navigation data bit synchronization (the telemetry decoder takes 20 ms bits) + boost::circular_buffer d_Prompt_I_history; + gr_complex d_P_bit_accu; + int32_t d_current_bit_symbol; + bool d_bit_synchronized; + bool d_Flag_PLL_180_deg_phase_locked; + bool d_enable_tracking; bool d_pull_in; bool d_dump; From 28ee074f75cabbefdcb8012dc54da30408da5f2e Mon Sep 17 00:00:00 2001 From: Carles Fernandez Date: Tue, 27 Oct 2026 09:32:38 +0100 Subject: [PATCH 09/11] Fix for GNU Radio 3.7 --- .../observables/deterministic_observables_test.cc | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/unit-tests/signal-processing-blocks/observables/deterministic_observables_test.cc b/tests/unit-tests/signal-processing-blocks/observables/deterministic_observables_test.cc index bedee4e1b..ee9fa473d 100644 --- a/tests/unit-tests/signal-processing-blocks/observables/deterministic_observables_test.cc +++ b/tests/unit-tests/signal-processing-blocks/observables/deterministic_observables_test.cc @@ -20,13 +20,18 @@ #include "obs_conf.h" #include "stream_batcher_limits.h" #include -#include #include #include #include #include #include +#ifdef GR_GREATER_38 +#include +#else +#include +#endif + class DeterministicObservablesTest : public ::testing::Test { From 53b877a4dc48dc5efdeec9f47d9dbf8638233a1d Mon Sep 17 00:00:00 2001 From: Carles Fernandez Date: Tue, 27 Oct 2026 09:35:38 +0100 Subject: [PATCH 10/11] Fixes for GNU Radio 3.7 --- .../sources/ion_gsms_chunk_data_test.cc | 8 +++++++- .../deterministic_telemetry_fault_test.cc | 7 ++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/tests/unit-tests/signal-processing-blocks/sources/ion_gsms_chunk_data_test.cc b/tests/unit-tests/signal-processing-blocks/sources/ion_gsms_chunk_data_test.cc index 14d214cb3..9ed54a0a7 100644 --- a/tests/unit-tests/signal-processing-blocks/sources/ion_gsms_chunk_data_test.cc +++ b/tests/unit-tests/signal-processing-blocks/sources/ion_gsms_chunk_data_test.cc @@ -20,7 +20,6 @@ #include "ion_gsms.h" #include "ion_gsms_chunk_data.h" #include "ion_gsms_signal_source.h" -#include #include #include #include @@ -32,6 +31,13 @@ #include #include +#ifdef GR_GREATER_38 +#include +#else +#include +#include +#endif + namespace { GnssMetadata::IonStream make_stream( diff --git a/tests/unit-tests/signal-processing-blocks/telemetry_decoder/deterministic_telemetry_fault_test.cc b/tests/unit-tests/signal-processing-blocks/telemetry_decoder/deterministic_telemetry_fault_test.cc index 08cc0eaaa..9630fa4c3 100644 --- a/tests/unit-tests/signal-processing-blocks/telemetry_decoder/deterministic_telemetry_fault_test.cc +++ b/tests/unit-tests/signal-processing-blocks/telemetry_decoder/deterministic_telemetry_fault_test.cc @@ -27,7 +27,6 @@ #include "tlm_conf.h" #include #include -#include #include #include #include @@ -41,6 +40,12 @@ #include #include +#ifdef GR_GREATER_38 +#include +#else +#include +#endif + class DeterministicTelemetryFaultTest : public ::testing::Test { From 96cf62225f805d4b707572759539786d282cde7d Mon Sep 17 00:00:00 2001 From: Carles Fernandez Date: Tue, 27 Oct 2026 09:55:49 +0100 Subject: [PATCH 11/11] Fix Matlab script --- .../libs/gps_l1_ca_kf_read_tracking_dump.m | 25 +++++++------------ 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/utils/matlab/libs/gps_l1_ca_kf_read_tracking_dump.m b/utils/matlab/libs/gps_l1_ca_kf_read_tracking_dump.m index 8d94781ec..9af45c0f7 100644 --- a/utils/matlab/libs/gps_l1_ca_kf_read_tracking_dump.m +++ b/utils/matlab/libs/gps_l1_ca_kf_read_tracking_dump.m @@ -19,24 +19,17 @@ function [GNSS_tracking] = gps_l1_ca_kf_read_tracking_dump (filename, count) m = nargchk (1,2,nargin); num_float_vars = 18; -num_unsigned_long_int_vars = 1; +num_unsigned_int64_vars = 1; num_double_vars = 2; num_unsigned_int_vars = 1; -if(~isempty(strfind(computer('arch'), '64'))) - % 64-bit computer - double_size_bytes = 8; - unsigned_long_int_size_bytes = 8; - float_size_bytes = 4; - unsigned_int_size_bytes = 4; -else - double_size_bytes = 8; - unsigned_long_int_size_bytes = 4; - float_size_bytes = 4; - unsigned_int_size_bytes = 4; -end +double_size_bytes = 8; +% The writer stores the sample counter as uint64_t on every platform. +unsigned_int64_size_bytes = 8; +float_size_bytes = 4; +unsigned_int_size_bytes = 4; -skip_bytes_each_read = float_size_bytes * num_float_vars + unsigned_long_int_size_bytes * num_unsigned_long_int_vars + ... +skip_bytes_each_read = float_size_bytes * num_float_vars + unsigned_int64_size_bytes * num_unsigned_int64_vars + ... double_size_bytes * num_double_vars + num_unsigned_int_vars*unsigned_int_size_bytes; bytes_shift = 0; @@ -73,8 +66,8 @@ else v7 = fread (f, count, 'float', skip_bytes_each_read - float_size_bytes); bytes_shift = bytes_shift + float_size_bytes; fseek(f,bytes_shift,'bof'); % move to next interleaved float - v8 = fread (f, count, 'long', skip_bytes_each_read - unsigned_long_int_size_bytes); - bytes_shift = bytes_shift + unsigned_long_int_size_bytes; + v8 = fread (f, count, 'uint64', skip_bytes_each_read - unsigned_int64_size_bytes); + bytes_shift = bytes_shift + unsigned_int64_size_bytes; fseek(f,bytes_shift,'bof'); % move to next double v9 = fread (f, count, 'double', skip_bytes_each_read - double_size_bytes); bytes_shift = bytes_shift + double_size_bytes;