Merge branch 'next' into joebre-evk1029-shm-pr-v2

Resolve the CHANGELOG conflict, and fix the EVK1029 shared-memory input
on top of the merge:

- In shared-memory mode, Evk1029SignalSource is real-time and cannot
  wait, so the deterministic mode refuses it and the Signal Conditioner
  no longer plans it as an unthrottled replay. Read
  shm_stop_on_buffer_overflow only on Linux, avoiding an unused variable
  warning elsewhere.
- Stopping the receiver no longer hangs when EVK1029_CtrlApp is idle,
  has crashed or has been restarted. ReadBlock() waits at most 100 ms at
  a time, RawStreamReader::read() then returns to its caller (see
  end_of_stream()), and Evk1029Source releases a decode worker waiting
  for data when GNU Radio stops the flowgraph. The stream ends if the
  producer publishes nothing for SignalSource.shm_stall_timeout_s
  seconds (default 5, 0 waits forever).
- request_stop() bumps data_event before waking the reader, and
  ReadBlock() takes its snapshot of data_event before checking the stop
  flag, the ring and the stream state, so that no wake-up is lost.
- Count overflows and producer silence from the first sample read, not
  from the attach: nothing reads the ring while the flowgraph is built,
  so shm_stop_on_buffer_overflow=true stopped the receiver at startup.

Update the CHANGELOG entry with the actual parameter names and the new
shm_stall_timeout_s parameter.
This commit is contained in:
Carles Fernandez committed 2026-10-27 12:27:16 +01:00
commit 5ce2f5ad2f
114 files changed
+5226 -937

No files matched your search

@@ -91,6 +91,7 @@
#include <fstream> // for ofstream
#include <iomanip> // for put_time, setprecision
#include <iostream> // for operator<<
#include <iterator> // for make_move_iterator
#include <locale> // for locale
#include <sstream> // for ostringstream
#include <stdexcept> // 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<StampedTelemetry> 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<uint64_t> epoch_samples;
if (d_deterministic)
{
epoch_samples.assign(noutput_items, NO_SAMPLE_STAMP);
std::vector<gr::tag_t> 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<uint64_t>(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<const Gnss_Synchro**>(&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.";
}
}
@@ -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<StampedTelemetry> d_det_telemetry;
uint64_t d_det_epoch_sample{NO_SAMPLE_STAMP};
bool d_deterministic{false};
};
@@ -49,6 +49,7 @@
#include "qzss_signal_replica.h"
#include "sbas_signal_replica.h"
#include "signal_flag.h"
#include <cmath>
#if USE_GLOG_AND_GFLAGS
#include <glog/logging.h>
@@ -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<unsigned int>(std::lround(acq_parameters_.resampler_ratio)) : 1U;
}
void PcpsAcquisitionAdapter::set_local_code()
{
volk_gnsssdr::vector<std::complex<float>> code(acq_parameters_.code_length);
@@ -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
*/
@@ -181,6 +181,7 @@ Acq_Conf get_acq_conf(
std::unique_ptr<ThresholdComputeInterface> threshold_compute;
boost::optional<uint32_t> default_folding_factor;
uint32_t required_sampled_ms = 0; // 0: any coherent integration time
uint32_t max_sampled_ms = std::numeric_limits<uint32_t>::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 != 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
@@ -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 != 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;
}
acq_parameters.num_codes = acq_parameters.sampled_ms / ms_per_code;
acq_parameters.code_length = static_cast<unsigned int>(round(acq_parameters.fs_in / (chip_rate / code_length_chips)));
acq_parameters.vector_length = acq_parameters.code_length * acq_parameters.num_codes;
@@ -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<uint64_t>(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::complex<f
}
int galileo_e5a_noncoherentIQ_acquisition_caf_cc::general_work(int noutput_items __attribute__((unused)),
int galileo_e5a_noncoherentIQ_acquisition_caf_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_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<uint64_t>(1) * static_cast<uint64_t>(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<uint64_t>(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<uint64_t>(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;
}
}
@@ -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 <gnuradio/block.h>
@@ -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<ChannelFsm> d_channel_fsm;
@@ -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<uint64_t>(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<float> *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<uint64_t>(d_fft_size) * static_cast<uint64_t>(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;
}
}
@@ -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 <gnuradio/block.h>
@@ -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<ChannelFsm> d_channel_fsm;
std::unique_ptr<gnss_fft_complex_fwd> d_fft_if;
@@ -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<uint64_t>(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<int>(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<uint64_t>(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<gr::thread::thread>(&pcps_acquisition::acquisition_core, this, window_stamp);
d_worker = std::make_unique<gr::thread::thread>(&pcps_acquisition::acquisition_worker, this, window_stamp);
if (d_buffer_sample_count >= d_data_buffer_size)
{
d_worker_active = true;
@@ -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;
@@ -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<uint64_t>(d_fft_size) * std::max(1U, d_acq_params.max_dwells) + 10 * static_cast<uint64_t>(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<uint64_t>(1) * static_cast<uint64_t>(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)
{
@@ -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 <armadillo>
@@ -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<ChannelFsm> d_channel_fsm;
@@ -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<uint64_t>(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<float> *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<uint64_t>(d_fft_size) * static_cast<uint64_t>(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;
}
}
@@ -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 <gnuradio/block.h>
@@ -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<ChannelFsm> d_channel_fsm;
@@ -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<uint64_t>(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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<uint64_t>(d_fft_size) * static_cast<uint64_t>(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<uint64_t>(d_fft_size) * ninput_items[0]; // sample counter
keep_input = d_det.enabled() && d_active;
if (!keep_input)
{
d_sample_counter += static_cast<uint64_t>(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<int>(d_max_dwells - d_in_dwell_count), ninput_items[0]);
for (uint32_t i = 0; i < num_dwells; i++)
{
const auto *in = reinterpret_cast<const gr_complex *>(input_items[i]);
std::copy(in, in + d_fft_size, d_in_buffer[d_in_dwell_count++].data());
const auto *in = reinterpret_cast<const gr_complex *>(input_items[0]) + static_cast<size_t>(i) * d_fft_size;
std::copy(in, in + d_fft_size, d_in_buffer[d_in_dwell_count].data());
d_sample_counter += static_cast<uint64_t>(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<int>(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<std::mutex> 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<uint64_t>(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<uint64_t>(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<uint64_t>(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<uint64_t>(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;
}
@@ -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 <gnuradio/block.h>
#include <gnuradio/gr_complex.h>
#include "opencl/cl.hpp"
#include <atomic>
#include <cstdint>
#include <fstream>
#include <memory> // for weak_ptr
#include <mutex>
#include <string>
#include <vector>
@@ -111,11 +114,19 @@ public:
*/
inline void set_active(bool active) override
{
std::lock_guard<std::mutex> 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<uint64_t> 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<int> d_state; // set by the acquisition cores
int d_opencl;
uint32_t d_max_dwells;
uint32_t d_well_count;
std::atomic<uint32_t> 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<uint32_t> d_in_dwell_count; // dwells in d_in_buffer
bool d_active;
bool d_core_working;
std::atomic<bool> d_active;
std::atomic<bool> 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<ChannelFsm> d_channel_fsm;
@@ -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<uint64_t>(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<int64_t>(d_vector_length) < static_cast<int64_t>(d_samples_per_code) * static_cast<int64_t>(d_folding_factor))
@@ -155,6 +158,23 @@ void pcps_quicksync_acquisition_cc::set_local_code(std::complex<float>* 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<uint64_t>(d_vector_length) * static_cast<uint64_t>(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;
}
@@ -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 <gnuradio/block.h>
@@ -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<ChannelFsm> d_channel_fsm;
@@ -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<uint64_t>(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<float> *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<uint64_t>(d_fft_size) * static_cast<uint64_t>(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;
}
}
@@ -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 <gnuradio/block.h>
@@ -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<ChannelFsm> d_channel_fsm;
std::unique_ptr<gnss_fft_complex_fwd> d_fft_if;
@@ -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)
@@ -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 <algorithm>
#if USE_GLOG_AND_GFLAGS
#include <glog/logging.h>
#else
#include <absl/log/log.h>
#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<std::mutex> 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<std::mutex> 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<int>(std::min<uint64_t>(needed, static_cast<uint64_t>(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<std::mutex> lock(d_mutex);
d_floor = std::max(d_floor, sample);
}
void DeterministicAcquisition::raise(int event, uint64_t stamp)
{
std::lock_guard<std::mutex> lock(d_mutex);
d_event = event;
d_stamp = stamp;
}
void DeterministicAcquisition::begin_call(uint64_t consumed)
{
if (!d_producer)
{
return;
}
std::lock_guard<std::mutex> lock(d_mutex);
d_call_start = consumed;
}
void DeterministicAcquisition::raise(int event)
{
std::lock_guard<std::mutex> lock(d_mutex);
d_event = event;
d_stamp = d_call_start;
}
void DeterministicAcquisition::dispatch(uint32_t channel, const std::function<void(int)>& fallback)
{
if (!d_producer)
{
return;
}
uint64_t stamp = NO_SAMPLE_STAMP;
int event = 0;
{
std::lock_guard<std::mutex> 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<int32_t>(channel), event, clock_sample(stamp)))
{
fallback(event);
}
std::lock_guard<std::mutex> 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<std::mutex> 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));
}
@@ -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 <cstdint>
#include <functional>
#include <memory>
#include <mutex>
/** \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<bool>(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<void(int)>& 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<DeterministicProducer> 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
@@ -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 <stdexcept> // 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<int32_t>(channel_),
[msg_rx](int event) { msg_rx->dispatch_event(event); });
}
}
+4 -3
View File
@@ -18,6 +18,7 @@
#include "channel_fsm.h"
#include "channel_event.h"
#include "deterministic_clock.h"
#include <utility>
#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())));
}
@@ -68,39 +68,44 @@ channel_msg_receiver_cc::channel_msg_receiver_cc(std::shared_ptr<ChannelFsm> 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";
@@ -20,6 +20,7 @@
#include "channel_fsm.h"
#include <gnuradio/block.h>
#include <pmt/pmt.h>
#include <cstdint>
#include <memory>
/** \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<ChannelFsm> channel_fsm, bool repeat);
channel_msg_receiver_cc(std::shared_ptr<ChannelFsm> channel_fsm, bool repeat);
@@ -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_;
@@ -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<void(uint64_t)> notify);
void remove(uint64_t id);
@@ -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
)
@@ -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<uint64_t>(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<uint64_t>(std::ceil(age_ms * fs / 1000.0));
d_det_pending_trk = std::vector<std::deque<Gnss_Synchro>>(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<int32_t>(d_nchannels_in) - 1; n++)
{
ninput_items_required[n] = 0;
@@ -1206,6 +1242,184 @@ void hybrid_observables_gs::propagate_sensor_data(const std::vector<Gnss_Synchro
}
void hybrid_observables_gs::add_trk_obs(uint32_t n, const Gnss_Synchro &trk)
{
// 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] = trk;
// 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 (!trk.Flag_carrier_phase_continuous)
{
d_channel_phase_discontinuity_pending[n] = true;
}
// Push the valid tracking Gnss_Synchros to their corresponding deque
if (trk.Flag_valid_word)
{
if (std::string(trk.Signal, 2) == std::string("E6"))
{
if (d_conf.enable_E6 == false)
{
return;
}
}
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 != 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<std::mutex> 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<std::mutex> 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<int32_t>(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<const Gnss_Synchro **>(&input_items[0]);
auto **out = reinterpret_cast<Gnss_Synchro **>(&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<gr::tag_t> 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<Gnss_Synchro> 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;
}
@@ -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 <boost/circular_buffer.hpp> // for boost::circular_buffer
#include <gnuradio/block.h> // for block
#include <gnuradio/types.h> // for gr_vector_int
#include <atomic> // for std::atomic
#include <cstddef> // for size_t
#include <cstdint> // for int32_t
#include <deque> // for std::deque
#include <fstream> // for std::ofstream
#include <memory> // for std::shared, std:unique_ptr
#include <mutex> // for std::mutex
#include <queue> // for std::queue
#include <string> // for std::string
#include <typeinfo> // 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<DeterministicProducer> d_det_producer;
std::vector<std::deque<Gnss_Synchro>> d_det_pending_trk; // channel data not taken into account yet
std::deque<std::pair<uint64_t, pmt::pmt_t>> d_det_pvt_messages; // (effective sample, message)
std::deque<std::pair<uint64_t, uint64_t>> d_det_output_stamps; // (output item, epoch sample) not read by the PVT yet
std::mutex d_det_stamps_mutex;
std::atomic<uint64_t> 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
};
/** \} */
@@ -119,7 +119,10 @@ Evk1029SignalSource::Evk1029SignalSource(
item_size_(sizeof(int8_t)),
rf_channels_(static_cast<unsigned int>(getRfChannels())),
enable_throttle_control_(configuration->property(role + ".enable_throttle_control"s, false)),
enable_freq_xlating_(configuration->property(role + ".enable_freq_xlating"s, false))
enable_freq_xlating_(configuration->property(role + ".enable_freq_xlating"s, false)),
// Backward compatible: a configuration that only ever set ".filename"
// (every existing one) implicitly means file mode.
shared_memory_input_(configuration->property(role + ".input"s, "file"s) == "shared_memory"s)
{
const std::string filename = configuration->property(role + ".filename"s, "data.bin"s);
// NOTE: this must be the RAW (pre-decimation) ADC sample rate of the capture
@@ -130,26 +133,22 @@ Evk1029SignalSource::Evk1029SignalSource(
const int64_t default_fs = configuration->property("GNSS-SDR.internal_fs_sps"s, int64_t(0));
const int64_t fs = configuration->property(role + ".sampling_frequency"s, default_fs);
// Backward compatible: a configuration that only ever set ".filename"
// (every existing one) implicitly means file mode.
const std::string input_mode = configuration->property(role + ".input"s, "file"s);
const bool shared_memory_input = (input_mode == "shared_memory"s);
if (!shared_memory_input && input_mode != "file"s)
if (!shared_memory_input_ && input_mode != "file"s)
{
throw std::invalid_argument(role + ".input='" + input_mode + "' is not 'file' or 'shared_memory'");
}
#ifndef EVK1029_SHM_INPUT
if (shared_memory_input)
if (shared_memory_input_)
{
throw std::invalid_argument(role + ".input='shared_memory' requires Linux (shm_open/mmap/futex); this build was configured without it");
}
#endif
const std::string shm_name = configuration->property(role + ".shm_name"s, "/evk1029_stream"s);
const bool shm_stop_on_buffer_overflow = configuration->property(role + ".shm_stop_on_buffer_overflow"s, false);
const double seconds_to_skip = configuration->property(role + ".seconds_to_skip"s, 0.0);
uint64_t bytes_to_skip = 0;
if (seconds_to_skip > 0.0 && shared_memory_input)
if (seconds_to_skip > 0.0 && shared_memory_input_)
{
LOG(WARNING) << role << ".seconds_to_skip has no meaning in shared_memory mode (there is no recorded "
<< "position to seek to in a live stream); ignoring it.";
@@ -171,7 +170,7 @@ Evk1029SignalSource::Evk1029SignalSource(
rf_channels_ = 1;
}
if (shared_memory_input && enable_throttle_control_)
if (shared_memory_input_ && enable_throttle_control_)
{
LOG(WARNING) << role << ": enable_throttle_control has no meaning in shared_memory mode (the live "
<< "producer already paces the data); ignoring it.";
@@ -179,7 +178,7 @@ Evk1029SignalSource::Evk1029SignalSource(
}
DLOG(INFO) << "EVK1029 Signal Source: input=" << input_mode << " ("
<< (shared_memory_input ? shm_name : filename) << "), fs=" << fs << ", item_size=" << item_size_
<< (shared_memory_input_ ? shm_name : filename) << "), fs=" << fs << ", item_size=" << item_size_
<< ", RF_channels=" << rf_channels_ << ", seconds_to_skip=" << seconds_to_skip;
std::vector<Evk1029FreqXlatingBand> freq_xlating_bands;
@@ -237,10 +236,12 @@ Evk1029SignalSource::Evk1029SignalSource(
}
std::unique_ptr<RawStreamReader> reader;
if (shared_memory_input)
if (shared_memory_input_)
{
#ifdef EVK1029_SHM_INPUT
reader = std::make_unique<SharedMemoryStreamReader>(shm_name, 30.0, shm_stop_on_buffer_overflow);
const bool shm_stop_on_buffer_overflow = configuration->property(role + ".shm_stop_on_buffer_overflow"s, false);
const double shm_stall_timeout_s = configuration->property(role + ".shm_stall_timeout_s"s, 5.0);
reader = std::make_unique<SharedMemoryStreamReader>(shm_name, 30.0, shm_stop_on_buffer_overflow, shm_stall_timeout_s);
#endif
}
else
@@ -30,7 +30,10 @@
* rather than losing data there; a real overflow, reported by
* EVK1029_CtrlApp's IF_TO_AXIS flag as an event count, is logged by default
* or stops the stream if role + ".shm_stop_on_buffer_overflow" = true
* (default false).
* (default false). Overflows are counted from the first sample read, not
* while the flowgraph is being built. If the producer publishes nothing for
* role + ".shm_stall_timeout_s" seconds (default 5, 0 waits forever), the
* stream ends as if at EOF (a hung, crashed or restarted EVK1029_CtrlApp).
*
* With role + ".enable_freq_xlating" = true, Evk1029Source itself translates,
* filters and decimates each band (role + ".band<n>_*" parameters, n <
@@ -94,7 +97,8 @@ public:
void connect(gr::top_block_sptr top_block) override;
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 is_real_time() const override { return shared_memory_input_ || enable_throttle_control_; }
bool can_wait() const override { return !shared_memory_input_; } // a throttle waits too, a live stream does not
private:
Evk1029Source_sptr evk1029_source_;
@@ -109,6 +113,7 @@ private:
bool enable_throttle_control_;
bool enable_freq_xlating_;
bool shared_memory_input_;
};
@@ -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;
@@ -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
{
@@ -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;
@@ -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
{
@@ -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 <gnuradio/io_signature.h>
#include <gnuradio/math.h>
@@ -72,7 +73,7 @@ std::size_t max_history(const std::vector<Evk1029FreqXlatingBand>& 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;
}
@@ -157,7 +158,7 @@ Evk1029Source::Evk1029Source(std::unique_ptr<RawStreamReader> reader, Concurrent
{
Band b;
b.composite_fir.resize(band.taps.size());
const float fwT0 = static_cast<float>(2.0 * GR_M_PI * band.center_freq / sampling_frequency);
const auto fwT0 = static_cast<float>(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<float>(i) * fwT0));
@@ -427,7 +428,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;
}
@@ -513,7 +518,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;
@@ -21,6 +21,7 @@
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <stdexcept>
#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::size_t>(std::numeric_limits<int>::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<int>(maximum_item_rate_));
}
current_segment_index_ = 0;
advance_to_next_segment();
}
@@ -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 <set>
@@ -36,6 +37,20 @@
#include <absl/log/log.h>
#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<pmt::pmt_t> *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<int> &channel_selector,
@@ -1255,7 +1270,7 @@ int labsat23_source::parse_ls23_data(int noutput_items, std::vector<gr_complex *
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;
}
else
@@ -1310,7 +1325,7 @@ int labsat23_source::parse_ls23_data(int noutput_items, std::vector<gr_complex *
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;
}
else
@@ -1359,7 +1374,7 @@ int labsat23_source::parse_ls23_data(int noutput_items, std::vector<gr_complex *
{
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;
}
else
@@ -1405,7 +1420,7 @@ int labsat23_source::parse_ls23_data(int noutput_items, std::vector<gr_complex *
}
std::cout << "Last file reached, LabSat source stop\n";
d_queue->push(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::vector<gr_complex *
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;
}
}
@@ -1455,7 +1470,7 @@ int labsat23_source::parse_ls3w_data(int noutput_items, std::vector<gr_complex *
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;
}
}
@@ -1489,7 +1504,7 @@ int labsat23_source::parse_ls4_data(int noutput_items, std::vector<gr_complex *>
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<gr_complex *>
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;
}
}
@@ -19,6 +19,7 @@
#include "gnss_sdr_valve.h"
#include "command_event.h"
#include "deterministic_clock.h"
#include <gnuradio/io_signature.h> // for io_signature
#include <algorithm> // for min
#include <cstring> // 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!
@@ -17,7 +17,6 @@
#include "ion_gsms_chunk_data.h"
#include <algorithm>
#include <array>
#include <cstring>
#include <limits>
#include <stdexcept>
@@ -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<uint8_t>(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<std::string>& 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<int> output_items(outputs.size(), 0);
auto* chunk_byte = static_cast<uint8_t*>(buffer_);
for (std::size_t value = 0; value < 256; ++value)
{
*chunk_byte = static_cast<uint8_t>(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<uint8_t>(outputs, output_items);
}
}
void IONGSMSChunkData::write_from_byte_lut(gr_vector_void_star& outputs, std::vector<int>& output_items) const
{
const int8_t* row = byte_lut_.data() + static_cast<const uint8_t*>(buffer_)[0] * byte_lut_row_size_;
for (int output_index : output_stream_indices_)
{
const auto relative_output_index = static_cast<std::size_t>(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<int8_t*>(outputs[output_index]);
std::copy(items, items + item_count, out);
outputs[output_index] = out + item_count;
output_items[output_index] += static_cast<int>(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<int>& output_items)
{
if (!byte_lut_.empty())
{
write_from_byte_lut(outputs, output_items);
return;
}
switch (sizeword_)
{
case 1:
@@ -218,7 +320,7 @@ template <typename WT>
void IONGSMSChunkData::unpack_words(gr_vector_void_star& outputs, std::vector<int>& output_items)
{
WT* data = static_cast<WT*>(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<in
}
}
IONGSMSChunkUnpackingCtx<WT> ctx{data, countwords_, chunk_.Shift() == GnssMetadata::Chunk::Right};
IONGSMSChunkUnpackingCtx<WT> 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<char*>(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<char*>(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<std::size_t>(output_index) - output_stream_offset_;
const auto items_written = output_items[output_index] - initial_output_items[output_index];
outputs[output_index] = static_cast<char*>(outputs[output_index]) + items_written * output_stream_item_size_[relative_output_index];
outputs[output_index] = static_cast<char*>(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<in
template <typename WT>
std::size_t IONGSMSChunkData::write_stream_samples(
IONGSMSChunkUnpackingCtx<WT>& 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<WT, int8_t>(ctx, lump.Shift(), stream, stream_encoding, reinterpret_cast<int8_t**>(out));
items_written = write_n_samples<WT, int8_t>(ctx, stream, reinterpret_cast<int8_t**>(out));
}
else if (sample_bitsize <= 16)
else if (stream.output_item_bits <= 16)
{
items_written = write_n_samples<WT, int16_t>(ctx, lump.Shift(), stream, stream_encoding, reinterpret_cast<int16_t**>(out));
items_written = write_n_samples<WT, int16_t>(ctx, stream, reinterpret_cast<int16_t**>(out));
}
else if (sample_bitsize <= 32)
else if (stream.output_item_bits <= 32)
{
items_written = write_n_samples<WT, int32_t>(ctx, lump.Shift(), stream, stream_encoding, reinterpret_cast<int32_t**>(out));
items_written = write_n_samples<WT, int32_t>(ctx, stream, reinterpret_cast<int32_t**>(out));
}
else if (sample_bitsize <= 64)
else if (stream.output_item_bits <= 64)
{
items_written = write_n_samples<WT, int64_t>(ctx, lump.Shift(), stream, stream_encoding, reinterpret_cast<int64_t**>(out));
items_written = write_n_samples<WT, int64_t>(ctx, stream, reinterpret_cast<int64_t**>(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 <typename WT, typename OT>
std::size_t IONGSMSChunkData::write_n_samples(
IONGSMSChunkUnpackingCtx<WT>& 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<uint8_t>(stream.Quantization());
const auto items_per_sample = stream_is_complex(stream.Format()) ? 2U : 1U;
std::vector<std::array<OT, 2>> 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<OT*>(*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<OT, 2> sample{};
const auto first = decode_sample<OT>(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<OT>(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<OT>(-first) : first;
samples.push_back(sample);
sample[0] = (stream.format == GnssMetadata::IonStream::IFn) ? static_cast<OT>(-first) : first;
continue;
}
const auto second = decode_sample<OT>(sample_bitsize, ctx.read_bits(sample_bitsize), stream_encoding);
switch (stream.Format())
const auto second = decode_sample<OT>(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<OT*>(*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 <typename WT>
std::size_t IONGSMSChunkData::write_fp32_samples(
IONGSMSChunkUnpackingCtx<WT>& 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<float> samples;
samples.reserve(stream.RateFactor());
for (std::size_t i = 0; i < stream.RateFactor(); ++i)
auto* sample_out = static_cast<float*>(*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<float*>(*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<gr_complex> 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<gr_complex*>(*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;
}
@@ -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 <typename WT>
void unpack_words(gr_vector_void_star& outputs, std::vector<int>& output_items);
void build_byte_lut();
void write_from_byte_lut(gr_vector_void_star& outputs, std::vector<int>& output_items) const;
template <typename WT>
std::size_t write_stream_samples(
static std::size_t write_stream_samples(
IONGSMSChunkUnpackingCtx<WT>& ctx,
const GnssMetadata::Lump& lump,
const GnssMetadata::IonStream& stream,
GnssMetadata::StreamEncoding stream_encoding,
const stream_metadata_t& stream,
void** out);
template <typename WT, typename OT>
std::size_t write_n_samples(
static std::size_t write_n_samples(
IONGSMSChunkUnpackingCtx<WT>& ctx,
GnssMetadata::Lump::LumpShift lump_shift,
const GnssMetadata::IonStream& stream,
GnssMetadata::StreamEncoding stream_encoding,
const stream_metadata_t& stream,
OT** out);
template <typename WT>
std::size_t write_fp32_samples(
static std::size_t write_fp32_samples(
IONGSMSChunkUnpackingCtx<WT>& ctx,
GnssMetadata::Lump::LumpShift lump_shift,
const GnssMetadata::IonStream& stream,
const stream_metadata_t& stream,
void** out);
template <typename Sample>
@@ -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<std::size_t> output_stream_item_size_;
std::vector<std::size_t> 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<stream_metadata_t> streams_;
std::vector<int> 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<int8_t> byte_lut_;
std::vector<std::size_t> byte_lut_output_offset_;
std::size_t byte_lut_row_size_ = 0;
void* buffer_ = nullptr;
};
@@ -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<uint64_t>(data_[first_word_index]) >> shift) & mask;
}
uint64_t value = 0;
for (std::size_t bit = 0; bit < bit_count; ++bit)
{
@@ -35,12 +35,19 @@ public:
virtual ~RawStreamReader() = default;
//! A short read (> 0, < requested_bytes) is normal, like POSIX read().
//! May block unboundedly (e.g. waiting on a live producer); returns 0
//! only once the stream has truly and permanently ended.
//! Returns 0 once the stream has permanently ended or, for a live
//! stream, if nothing arrived within a short poll interval, so that the
//! caller can check whether it has to stop; end_of_stream() tells which.
virtual std::size_t read(uint8_t* destination, std::size_t requested_bytes) = 0;
//! Unblocks a concurrent read(); no-op default for a reader that can't
//! block (FileStreamReader). Called from Evk1029Source's destructor.
//! After read() returned 0: true if the stream has ended, false if it
//! just had nothing new yet. The default suits readers that block until
//! there is data or the stream ends (FileStreamReader).
virtual bool end_of_stream() const { return true; }
//! Ends the stream: a concurrent or later read() returns 0 promptly.
//! Safe to call from another thread than read()'s. No-op default for a
//! reader that can't block (FileStreamReader).
virtual void request_stop() {}
};
@@ -28,8 +28,16 @@
#include <absl/log/log.h>
#endif
SharedMemoryStreamReader::SharedMemoryStreamReader(const std::string& shm_name, double connect_timeout_seconds, bool stop_on_overflow)
: stop_on_overflow_(stop_on_overflow)
namespace
{
// How long read() waits for the producer before returning to its caller
constexpr struct timespec kPollInterval = {0, 100000000}; // 100 ms
} // namespace
SharedMemoryStreamReader::SharedMemoryStreamReader(const std::string& shm_name, double connect_timeout_seconds, bool stop_on_overflow, double stall_timeout_seconds)
: stop_on_overflow_(stop_on_overflow),
stall_timeout_seconds_(stall_timeout_seconds)
{
LOG(INFO) << "EVK1029_Source: waiting for shared-memory producer on '" << shm_name << "' ...";
const auto deadline = std::chrono::steady_clock::now() + std::chrono::duration<double>(connect_timeout_seconds);
@@ -72,10 +80,13 @@ SharedMemoryStreamReader::~SharedMemoryStreamReader()
void SharedMemoryStreamReader::request_stop()
{
// The flag alone won't wake a ReadBlock() already asleep in FUTEX_WAIT.
// The flag alone won't wake a ReadBlock() already asleep in FUTEX_WAIT,
// and a wake-up alone is lost on one that has snapshotted data_event but
// not called FUTEX_WAIT yet: bump the word too (see shm_ring.h).
stop_requested_.store(true, std::memory_order_release);
if (ring_.header)
{
ring_.header->data_event.fetch_add(1, std::memory_order_acq_rel);
shm_ring::FutexWakeAll(ring_.header->data_event);
}
}
@@ -83,14 +94,59 @@ void SharedMemoryStreamReader::request_stop()
std::size_t SharedMemoryStreamReader::read(uint8_t* destination, std::size_t requested_bytes)
{
if (ended_)
{
return 0;
}
if (!started_)
{
// The flowgraph is built between the attach and the first read(),
// and nothing reads the ring meanwhile: neither an overflow nor the
// producer's silence during that time is a gap in the processed stream.
started_ = true;
const uint64_t overflow_now = ring_.header->overflow_event_count.load(std::memory_order_relaxed);
if (overflow_now != last_seen_overflow_count_)
{
LOG(INFO) << "EVK1029_Source: " << overflow_now - last_seen_overflow_count_
<< " IF_TO_AXIS hardware overflow(s) reported while the receiver was starting; ignored";
last_seen_overflow_count_ = overflow_now;
}
last_block_time_ = std::chrono::steady_clock::now();
}
if (pending_pos_ >= pending_.size())
{
pending_.clear();
pending_pos_ = 0;
if (!shm_ring::ReadBlock(ring_, pending_, &stop_requested_))
const shm_ring::ReadResult result = shm_ring::ReadBlock(ring_, pending_, &stop_requested_, &kPollInterval);
if (result == shm_ring::ReadResult::TimedOut)
{
return 0; // producer ended the stream, or we were asked to stop -- both mean EOF here
const double silence = std::chrono::duration<double>(std::chrono::steady_clock::now() - last_block_time_).count();
if (stall_timeout_seconds_ > 0.0 && silence >= stall_timeout_seconds_)
{
LOG(ERROR) << "EVK1029_Source: no data from the shared-memory producer for " << silence
<< " s -- is EVK1029_CtrlApp still streaming? Ending the stream (shm_stall_timeout_s=" << stall_timeout_seconds_ << ")";
ended_ = true;
}
return 0;
}
if (result != shm_ring::ReadResult::Block)
{
if (result == shm_ring::ReadResult::Error)
{
LOG(ERROR) << "EVK1029_Source: the shared-memory producer reported an error; ending the stream";
}
else if (result == shm_ring::ReadResult::Corrupted)
{
LOG(ERROR) << "EVK1029_Source: shared-memory block length larger than the block size; ending the stream";
}
else if (result == shm_ring::ReadResult::EndOfStream)
{
LOG(INFO) << "EVK1029_Source: the shared-memory producer ended the stream";
}
ended_ = true; // also on request_stop()
return 0;
}
last_block_time_ = std::chrono::steady_clock::now();
// No byte count is available (the hardware only has a sticky overflow bit), so this can't be zero-filled.
const uint64_t overflow_now = ring_.header->overflow_event_count.load(std::memory_order_relaxed);
@@ -102,6 +158,7 @@ std::size_t SharedMemoryStreamReader::read(uint8_t* destination, std::size_t req
{
LOG(ERROR) << "EVK1029_Source: " << new_events
<< " IF_TO_AXIS hardware overflow(s) reported; stopping (shm_stop_on_buffer_overflow=true)";
ended_ = true;
return 0;
}
LOG(WARNING) << "EVK1029_Source: " << new_events
@@ -20,6 +20,7 @@
#include "raw_stream_reader.h"
#include "shm_ring.h"
#include <atomic>
#include <chrono>
#include <cstdint>
#include <string>
#include <vector>
@@ -36,10 +37,13 @@ public:
// Retries for up to connect_timeout_seconds if the producer (EVK1029_CtrlApp)
// hasn't created the ring yet -- a late-starting producer is recoverable.
// stop_on_overflow: stop (as EOF) on a reported overflow instead of just logging it (see read()).
explicit SharedMemoryStreamReader(const std::string& shm_name, double connect_timeout_seconds = 30.0, bool stop_on_overflow = false);
// stall_timeout_seconds: end the stream if the producer publishes nothing for that long while
// the stream is running (a hung, crashed or restarted producer); 0 waits forever.
explicit SharedMemoryStreamReader(const std::string& shm_name, double connect_timeout_seconds = 30.0, bool stop_on_overflow = false, double stall_timeout_seconds = 5.0);
~SharedMemoryStreamReader() override;
std::size_t read(uint8_t* destination, std::size_t requested_bytes) override;
bool end_of_stream() const override { return ended_; }
void request_stop() override;
private:
@@ -48,8 +52,12 @@ private:
std::size_t pending_pos_ = 0;
std::atomic<bool> stop_requested_{false};
bool stop_on_overflow_ = false;
double stall_timeout_seconds_ = 5.0;
std::chrono::steady_clock::time_point last_block_time_; // see read()
bool started_ = false; // read() was called
bool ended_ = false;
// overflow_event_count as of the last check; initialized post-attach, not 0 (see read()).
// overflow_event_count as of the last check; initialized at the first read(), not 0 (see read()).
uint64_t last_seen_overflow_count_ = 0;
};
+48 -28
View File
@@ -4,9 +4,10 @@
* EVK1029 byte stream between EVK1029_CtrlApp (producer) and this consumer
* (SharedMemoryStreamReader).
*
* Verbatim copy of EVK1029_CtrlApp's own evk1029/shm_ring.hpp: the two repos
* Derived from EVK1029_CtrlApp's own evk1029/shm_ring.hpp: the two repos
* build separately, but both mmap the same region, so the struct layout and
* kMagic/kVersion must match -- Attach() refuses a mismatched version.
* kMagic/kVersion must match -- Attach() refuses a mismatched version. The
* consumer side (ReadBlock()) is GNSS-SDR's own.
*
* Wire format: [Header][Block 0][Block 1]...[Block N-1], each block an
* 8-byte payload-length prefix (real USB chunks aren't always exactly
@@ -17,7 +18,9 @@
* futex() needs 32-bit and the sequence counters are 64-bit -- a waiting
* side snapshots the event word, re-checks the real condition (lost-wakeup
* guard), then futex_waits on the snapshot. Never FUTEX_PRIVATE_FLAG: waited
* on across processes, not threads.
* on across processes, not threads. Whatever ends a wait (a new block, a
* terminal state, a stop request) is published before the event word is
* bumped, so the snapshot must be taken before checking any of them.
*
* The *_waiters counters only let a side skip the futex_wake() syscall when
* nobody is blocked; they can go stale without losing a wakeup, since
@@ -40,8 +43,10 @@
#include <algorithm>
#include <atomic>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <ctime>
#include <fcntl.h>
#include <linux/futex.h>
#include <string>
@@ -114,16 +119,17 @@ inline uint8_t* BlockPtr(void* base, uint32_t index, uint32_t block_size)
static_cast<std::size_t>(index) * static_cast<std::size_t>(block_size);
}
inline int64_t RawFutex(std::atomic<uint32_t>* word, int op, uint32_t val)
inline int64_t RawFutex(std::atomic<uint32_t>* word, int op, uint32_t val, const struct timespec* timeout = nullptr)
{
return syscall(SYS_futex, reinterpret_cast<uint32_t*>(word), op, val, nullptr, nullptr, 0);
return syscall(SYS_futex, reinterpret_cast<uint32_t*>(word), op, val, timeout, nullptr, 0);
}
inline void FutexWait(std::atomic<uint32_t>& word, uint32_t expected)
// timeout is relative, nullptr waits forever. Returns false only if it
// expired: the caller's own loop re-checks the real condition regardless of
// why this returned otherwise (EAGAIN/EINTR/spurious).
inline bool FutexWait(std::atomic<uint32_t>& word, uint32_t expected, const struct timespec* timeout = nullptr)
{
// Return value ignored: the caller's own loop re-checks the real
// condition regardless of why this returned (EAGAIN/EINTR/spurious).
RawFutex(&word, FUTEX_WAIT, expected);
return !(RawFutex(&word, FUTEX_WAIT, expected, timeout) == -1 && errno == ETIMEDOUT);
}
inline void FutexWakeAll(std::atomic<uint32_t>& word)
@@ -133,11 +139,12 @@ inline void FutexWakeAll(std::atomic<uint32_t>& word)
// Increments waiters before the futex syscall, so a concurrent
// WakeIfWaiting() is guaranteed to see it (see the file comment).
inline void WaitOn(std::atomic<uint32_t>& word, uint32_t expected, std::atomic<uint32_t>& waiters)
inline bool WaitOn(std::atomic<uint32_t>& word, uint32_t expected, std::atomic<uint32_t>& waiters, const struct timespec* timeout = nullptr)
{
waiters.fetch_add(1, std::memory_order_acq_rel);
FutexWait(word, expected);
const bool woken = FutexWait(word, expected, timeout);
waiters.fetch_sub(1, std::memory_order_acq_rel);
return woken;
}
inline void WakeIfWaiting(std::atomic<uint32_t>& word, const std::atomic<uint32_t>& waiters)
@@ -313,36 +320,49 @@ inline bool WriteBlock(MappedRing& ring, const uint8_t* data, std::size_t len, c
return true;
}
// Blocks while empty and the stream hasn't ended; false once empty AND
// Stopped/EndOfStream/Error, on a corrupted length prefix, or on abortFlag.
inline bool ReadBlock(MappedRing& ring, std::vector<uint8_t>& out, const std::atomic<bool>* abortFlag = nullptr)
enum class ReadResult
{
Block, // out holds the next block
TimedOut, // nothing new within the timeout; the stream has not ended
EndOfStream, // empty and Stopped/EndOfStream
Error, // empty and Error
Corrupted, // a length prefix larger than the block
Aborted, // abortFlag was set
};
// Waits up to timeout (relative, nullptr waits forever) for the next block.
// Blocks published before a terminal state are still delivered; a raised
// abortFlag ends the read even if blocks are pending. Whoever raises
// abortFlag must then bump data_event and wake its waiters.
inline ReadResult ReadBlock(MappedRing& ring, std::vector<uint8_t>& out, const std::atomic<bool>* abortFlag = nullptr, const struct timespec* timeout = nullptr)
{
Header& h = *ring.header;
for (;;)
{
const uint64_t w = h.write_seq.load(std::memory_order_acquire);
const uint64_t r = h.read_seq.load(std::memory_order_relaxed);
if (w != r)
// Snapshot first, see the file comment
const uint32_t expected = h.data_event.load(std::memory_order_acquire);
if (abortFlag && abortFlag->load(std::memory_order_acquire))
{
return ReadResult::Aborted;
}
if (h.write_seq.load(std::memory_order_acquire) != h.read_seq.load(std::memory_order_relaxed))
{
break;
}
const auto state = static_cast<StreamState>(h.state.load(std::memory_order_acquire));
if (state == StreamState::Stopped || state == StreamState::EndOfStream || state == StreamState::Error)
if (state == StreamState::Error)
{
return false;
return ReadResult::Error;
}
if (abortFlag && abortFlag->load(std::memory_order_acquire))
if (state == StreamState::Stopped || state == StreamState::EndOfStream)
{
return false;
return ReadResult::EndOfStream;
}
const uint32_t expected = h.data_event.load(std::memory_order_acquire);
if (h.write_seq.load(std::memory_order_acquire) != h.read_seq.load(std::memory_order_relaxed))
if (!WaitOn(h.data_event, expected, h.data_waiters, timeout))
{
break;
return ReadResult::TimedOut;
}
WaitOn(h.data_event, expected, h.data_waiters);
}
const uint64_t r = h.read_seq.load(std::memory_order_relaxed);
@@ -354,7 +374,7 @@ inline bool ReadBlock(MappedRing& ring, std::vector<uint8_t>& out, const std::at
if (len > payloadCap)
{
// Corrupted/mismatched producer -- would read past the block.
return false;
return ReadResult::Corrupted;
}
out.resize(static_cast<std::size_t>(len));
std::memcpy(out.data(), blk + sizeof(uint64_t), static_cast<std::size_t>(len));
@@ -363,7 +383,7 @@ inline bool ReadBlock(MappedRing& ring, std::vector<uint8_t>& out, const std::at
h.read_seq.store(r + 1, std::memory_order_release);
h.space_event.fetch_add(1, std::memory_order_release);
WakeIfWaiting(h.space_event, h.space_waiters);
return true;
return ReadResult::Block;
}
} // namespace shm_ring
@@ -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)
@@ -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<Beidou_Cnav1_Ephemeris>(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<Beidou_Cnav1_Iono>(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<Beidou_Cnav1_Utc_Model>(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<Beidou_Cnav1_PageData_Message>(page_msg)));
message_port_pub(pmt::mp("telemetry"), stamp_telemetry_message(pmt::make_any(std::make_shared<Beidou_Cnav1_PageData_Message>(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++;
@@ -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<Beidou_Cnav1_Ephemeris>(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<const Gnss_Synchro*>(input_items[0]);
auto* out = reinterpret_cast<Gnss_Synchro*>(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;
@@ -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<Beidou_Dnav_Ephemeris> tmp_obj = std::make_shared<Beidou_Dnav_Ephemeris>(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<Beidou_Dnav_Utc_Model> tmp_obj = std::make_shared<Beidou_Dnav_Utc_Model>(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<Beidou_Dnav_Iono> tmp_obj = std::make_shared<Beidou_Dnav_Iono>(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<Beidou_Dnav_Almanac> tmp_obj = std::make_shared<Beidou_Dnav_Almanac>(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);
@@ -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<Galileo_Reduced_CED>(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<Galileo_Iono> tmp_obj = std::make_shared<Galileo_Iono>(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<Galileo_Utc_Model> tmp_obj = std::make_shared<Galileo_Utc_Model>(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<Galileo_Almanac_Helper> tmp_obj = std::make_shared<Galileo_Almanac_Helper>(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<Galileo_Ephemeris> tmp_obj = std::make_shared<Galileo_Ephemeris>(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<Galileo_Iono> tmp_obj = std::make_shared<Galileo_Iono>(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<Galileo_Utc_Model> tmp_obj = std::make_shared<Galileo_Utc_Model>(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;
@@ -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();
@@ -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<Glonass_Gnav_Ephemeris> tmp_obj = std::make_shared<Glonass_Gnav_Ephemeris>(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<Glonass_Gnav_Utc_Model> tmp_obj = std::make_shared<Glonass_Gnav_Utc_Model>(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<Glonass_Gnav_Almanac>
tmp_obj = std::make_shared<Glonass_Gnav_Almanac>(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);
@@ -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<Gps_Ephemeris> tmp_obj = std::make_shared<Gps_Ephemeris>(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<Gps_Ephemeris> tmp_obj = std::make_shared<Gps_Ephemeris>(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<Gps_Ephemeris> tmp_obj = std::make_shared<Gps_Ephemeris>(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<Qzss_Iono> tmp_obj = std::make_shared<Qzss_Iono>(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<Gps_Iono> tmp_obj = std::make_shared<Gps_Iono>(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<Qzss_Utc_Model> tmp_obj = std::make_shared<Qzss_Utc_Model>(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<Gps_Utc_Model> tmp_obj = std::make_shared<Gps_Utc_Model>(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<Gps_Almanac> tmp_obj = std::make_shared<Gps_Almanac>(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<Qzss_Iono> tmp_obj = std::make_shared<Qzss_Iono>(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<Gps_Iono> tmp_obj = std::make_shared<Gps_Iono>(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<Qzss_Utc_Model> tmp_obj = std::make_shared<Qzss_Utc_Model>(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<Gps_Utc_Model> tmp_obj = std::make_shared<Gps_Utc_Model>(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<Gps_Almanac> tmp_obj = std::make_shared<Gps_Almanac>(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);
@@ -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 &current_gs);
bool is_PLL_180_deg_phase_locked();
bool gps_word_parityCheck(uint32_t gpsword);
@@ -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<Gnss_Synchro *>(output_items[0]); // Get the output buffer pointer
const auto *in = reinterpret_cast<const Gnss_Synchro *>(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<Gps_CNAV_Ephemeris> tmp_obj = std::make_shared<Gps_CNAV_Ephemeris>(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<Gps_CNAV_Eop> tmp_obj = std::make_shared<Gps_CNAV_Eop>(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<Gps_CNAV_Iono> tmp_obj = std::make_shared<Gps_CNAV_Iono>(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<Gps_CNAV_Utc_Model> tmp_obj = std::make_shared<Gps_CNAV_Utc_Model>(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
@@ -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<Gps_CNAV_Ephemeris> tmp_obj = std::make_shared<Gps_CNAV_Ephemeris>(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<Qzss_CNAV_Eop> tmp_obj = std::make_shared<Qzss_CNAV_Eop>(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<Gps_CNAV_Eop> tmp_obj = std::make_shared<Gps_CNAV_Eop>(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<Qzss_CNAV_Iono> tmp_obj = std::make_shared<Qzss_CNAV_Iono>(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<Gps_CNAV_Iono> tmp_obj = std::make_shared<Gps_CNAV_Iono>(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<Qzss_CNAV_Utc_Model> tmp_obj = std::make_shared<Qzss_CNAV_Utc_Model>(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<Gps_CNAV_Utc_Model> tmp_obj = std::make_shared<Gps_CNAV_Utc_Model>(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")
@@ -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 <gnuradio/thread/thread.h> // for scoped_lock
#include <pmt/pmt_sugar.h> // 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<uint32_t>(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
@@ -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 <gnuradio/block.h>
#include <pmt/pmt.h>
#include <cstdint>
#include <exception>
/** \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
@@ -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 <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
@@ -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<TOW_to_trk>();
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<uint64_t>(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)
@@ -867,7 +887,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)
@@ -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;
@@ -1195,6 +1216,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 +1416,25 @@ 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 << ")";
this->message_port_pub(pmt::mp("events"), pmt::from_long(3)); // 3 -> loss of lock
<< " code_lock_fail_counter : " << d_code_lock_fail_counter
<< (d_force_loss_of_lock ? " forced" : "") << ")";
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;
d_force_loss_of_lock = false;
return false;
}
return true;
@@ -1909,9 +1941,9 @@ void dll_pll_veml_tracking::log_data()
// PRN start sample stamp
tmp_long_int = this->nitems_read(0) + static_cast<uint64_t>(d_current_prn_length_samples);
d_dump_file.write(reinterpret_cast<char *>(&tmp_long_int), sizeof(uint64_t));
// accumulated carrier phase
tmp_float = static_cast<float>(d_acc_carrier_phase_rad);
d_dump_file.write(reinterpret_cast<char *>(&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<char *>(&tmp_double), sizeof(double));
// carrier and code frequency
tmp_float = static_cast<float>(d_carrier_doppler_hz);
d_dump_file.write(reinterpret_cast<char *>(&tmp_float), sizeof(float));
@@ -1965,8 +1997,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 +2039,7 @@ int32_t dll_pll_veml_tracking::save_matfile() const
auto Prompt_I = std::vector<float>(num_epoch);
auto Prompt_Q = std::vector<float>(num_epoch);
auto PRN_start_sample_count = std::vector<uint64_t>(num_epoch);
auto acc_carrier_phase_rad = std::vector<float>(num_epoch);
auto acc_carrier_phase_rad = std::vector<double>(num_epoch);
auto carrier_doppler_hz = std::vector<float>(num_epoch);
auto carrier_doppler_rate_hz = std::vector<float>(num_epoch);
auto code_freq_chips = std::vector<float>(num_epoch);
@@ -2037,7 +2069,7 @@ int32_t dll_pll_veml_tracking::save_matfile() const
dump_file.read(reinterpret_cast<char *>(&Prompt_I[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&Prompt_Q[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&PRN_start_sample_count[i]), sizeof(uint64_t));
dump_file.read(reinterpret_cast<char *>(&acc_carrier_phase_rad[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&acc_carrier_phase_rad[i]), sizeof(double));
dump_file.read(reinterpret_cast<char *>(&carrier_doppler_hz[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&carrier_doppler_rate_hz[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&code_freq_chips[i]), sizeof(float));
@@ -2080,7 +2112,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);
@@ -2327,7 +2359,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 +2386,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_force_loss_of_lock = true;
}
if (d_pull_in_transitory == true)
{
if (d_trk_parameters.pull_in_time_s < tracking_elapsed_seconds(this->nitems_read(0)))
@@ -2379,6 +2432,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<int>(std::min<uint64_t>(det_skip, static_cast<uint64_t>(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<int64_t>(d_sample_counter) - static_cast<int64_t>(d_acq_sample_stamp);
const int64_t acq_trk_diff_samples = static_cast<int64_t>(this->nitems_read(0)) - static_cast<int64_t>(d_acq_sample_stamp);
@@ -2459,7 +2519,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<int>(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';
}
@@ -2849,6 +2909,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;
}
@@ -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,9 @@ 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
DeterministicTracking d_det{this}; // GNSS-SDR.deterministic=true
};
@@ -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;
}
@@ -1135,9 +1137,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<char *>(&tmp_long_int), sizeof(uint64_t));
// accumulated carrier phase
tmp_float = static_cast<float>(d_acc_carrier_phase_rad);
d_dump_file.write(reinterpret_cast<char *>(&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<char *>(&tmp_double), sizeof(double));
// carrier and code frequency
tmp_float = static_cast<float>(d_carrier_doppler_hz);
d_dump_file.write(reinterpret_cast<char *>(&tmp_float), sizeof(float));
@@ -1185,8 +1187,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 +1228,7 @@ int32_t dll_pll_veml_tracking_fpga::save_matfile() const
auto Prompt_I = std::vector<float>(num_epoch);
auto Prompt_Q = std::vector<float>(num_epoch);
auto PRN_start_sample_count = std::vector<uint64_t>(num_epoch);
auto acc_carrier_phase_rad = std::vector<float>(num_epoch);
auto acc_carrier_phase_rad = std::vector<double>(num_epoch);
auto carrier_doppler_hz = std::vector<float>(num_epoch);
auto carrier_doppler_rate_hz = std::vector<float>(num_epoch);
auto code_freq_chips = std::vector<float>(num_epoch);
@@ -1254,7 +1256,7 @@ int32_t dll_pll_veml_tracking_fpga::save_matfile() const
dump_file.read(reinterpret_cast<char *>(&Prompt_I[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&Prompt_Q[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&PRN_start_sample_count[i]), sizeof(uint64_t));
dump_file.read(reinterpret_cast<char *>(&acc_carrier_phase_rad[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&acc_carrier_phase_rad[i]), sizeof(double));
dump_file.read(reinterpret_cast<char *>(&carrier_doppler_hz[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&carrier_doppler_rate_hz[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&code_freq_chips[i]), sizeof(float));
@@ -1295,7 +1297,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);
@@ -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<int>(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';
}
@@ -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
};
@@ -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<float>(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<float>(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<float>(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<char *>(&prompt_Q), sizeof(float));
// PRN start sample stamp
d_dump_file.write(reinterpret_cast<char *>(&d_sample_counter), sizeof(uint64_t));
// accumulated carrier phase
tmp_float = static_cast<float>(d_acc_carrier_phase_rad);
d_dump_file.write(reinterpret_cast<char *>(&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<char *>(&tmp_double), sizeof(double));
// carrier and code frequency
tmp_float = static_cast<float>(d_carrier_doppler_hz);
d_dump_file.write(reinterpret_cast<char *>(&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<char *>(&tmp_float), sizeof(float));
auto tmp_double = static_cast<double>(d_sample_counter + d_correlation_length_samples);
tmp_double = static_cast<double>(d_sample_counter + d_correlation_length_samples);
d_dump_file.write(reinterpret_cast<char *>(&tmp_double), sizeof(double));
// PRN
uint32_t prn_ = d_acquisition_gnss_synchro->PRN;
@@ -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;
@@ -25,6 +25,7 @@
#include <gnuradio/io_signature.h>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cuda_profiler_api.h>
#include <iostream>
#include <memory>
@@ -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<size_t>(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<double>(acq_to_trk_delay_samples), static_cast<double>(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<uint64_t>(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<uint64_t>(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<double>((d_correlator_outs[1]).real());
current_synchro_data.Prompt_Q = static_cast<double>((d_correlator_outs[1]).imag());
current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast<uint64_t>(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<double>(prompt.real());
current_synchro_data.Prompt_Q = static_cast<double>(prompt.imag());
current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast<uint64_t>(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<uint64_t>(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
@@ -521,6 +586,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<float>(d_correlator_outs[0]);
@@ -539,9 +605,9 @@ int Gps_L1_Ca_Dll_Pll_Tracking_GPU_cc::general_work(int noutput_items __attribut
d_dump_file.write(reinterpret_cast<char *>(&prompt_Q), sizeof(float));
// PRN start sample stamp
d_dump_file.write(reinterpret_cast<char *>(&d_sample_counter), sizeof(uint64_t));
// accumulated carrier phase
tmp_float = static_cast<float>(d_acc_carrier_phase_cycles * TWO_PI);
d_dump_file.write(reinterpret_cast<char *>(&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<char *>(&tmp_double), sizeof(double));
// carrier and code frequency
tmp_float = static_cast<float>(d_carrier_doppler_hz);
d_dump_file.write(reinterpret_cast<char *>(&tmp_float), sizeof(float));
@@ -565,7 +631,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<char *>(&tmp_float), sizeof(float));
double tmp_double = static_cast<double>(d_sample_counter + d_correlation_length_samples);
tmp_double = static_cast<double>(d_sample_counter + d_correlation_length_samples);
d_dump_file.write(reinterpret_cast<char *>(&tmp_double), sizeof(double));
// PRN
uint32_t prn_ = d_acquisition_gnss_synchro->PRN;
@@ -580,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
}
@@ -27,6 +27,7 @@
#include "gnss_synchro.h"
#include "tracking_2nd_DLL_filter.h"
#include "tracking_FLL_PLL_filter.h"
#include <boost/circular_buffer.hpp>
#include <gnuradio/block.h>
#include <fstream>
#include <map>
@@ -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<float> 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;
@@ -36,6 +36,7 @@
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <memory>
@@ -136,11 +137,19 @@ 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)
{
// Inputs needed beyond the progress (GNSS-SDR.deterministic=true): see forecast()
d_det.require_span(2 * static_cast<uint64_t>(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 +262,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<double>(d_acquisition_gnss_synchro->Acq_doppler_step);
// Correct Kalman filter covariance according to acq doppler step size (3 sigma)
@@ -264,7 +274,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<int64_t>(d_sample_counter) - static_cast<int64_t>(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<int64_t>(pull_in_sample) - static_cast<int64_t>(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<float>(acq_trk_diff_samples) / static_cast<float>(d_fs_in);
// Doppler effect Fd = (C / (C + Vr)) * F
@@ -318,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
@@ -381,8 +400,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;
@@ -416,7 +435,7 @@ int32_t Gps_L1_Ca_Gaussian_Tracking_cc::save_matfile()
auto Prompt_I = std::vector<float>(num_epoch);
auto Prompt_Q = std::vector<float>(num_epoch);
auto PRN_start_sample_count = std::vector<uint64_t>(num_epoch);
auto acc_carrier_phase_rad = std::vector<float>(num_epoch);
auto acc_carrier_phase_rad = std::vector<double>(num_epoch);
auto carrier_doppler_hz = std::vector<float>(num_epoch);
auto carrier_dopplerrate_hz2 = std::vector<float>(num_epoch);
auto code_freq_chips = std::vector<float>(num_epoch);
@@ -445,7 +464,7 @@ int32_t Gps_L1_Ca_Gaussian_Tracking_cc::save_matfile()
dump_file.read(reinterpret_cast<char *>(&Prompt_I[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&Prompt_Q[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&PRN_start_sample_count[i]), sizeof(uint64_t));
dump_file.read(reinterpret_cast<char *>(&acc_carrier_phase_rad[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&acc_carrier_phase_rad[i]), sizeof(double));
dump_file.read(reinterpret_cast<char *>(&carrier_doppler_hz[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&carrier_dopplerrate_hz2[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&code_freq_chips[i]), sizeof(float));
@@ -486,7 +505,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);
@@ -506,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<size_t>(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);
@@ -539,7 +581,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
@@ -547,6 +603,7 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::general_work(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<const gr_complex *>(input_items[0]);
@@ -562,6 +619,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<int>(std::min<uint64_t>(det_skip, static_cast<uint64_t>(ninput_items[0])));
d_sample_counter += static_cast<uint64_t>(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<double>(d_current_prn_length_samples) - std::fmod(static_cast<double>(acq_to_trk_delay_samples), static_cast<double>(d_current_prn_length_samples));
@@ -575,11 +641,6 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::general_work(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;
*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
@@ -595,7 +656,7 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::general_work(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 ##############################
@@ -741,22 +802,70 @@ 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;
}
}
// ########### 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<double>((d_correlator_outs[1]).real());
current_synchro_data.Prompt_Q = static_cast<double>((d_correlator_outs[1]).imag());
current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast<uint64_t>(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<double>(prompt.real());
current_synchro_data.Prompt_Q = static_cast<double>(prompt.imag());
current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast<uint64_t>(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++;
}
@@ -766,16 +875,8 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::general_work(int noutput_items __attribute__
{
d_correlator_outs[n] = gr_complex(0, 0);
}
current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast<uint64_t>(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;
*out[0] = std::move(current_synchro_data);
if (d_dump)
{
// MULTIPLEXED FILE RECORDING - Record results to file
@@ -806,9 +907,9 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::general_work(int noutput_items __attribute__
d_dump_file.write(reinterpret_cast<char *>(&prompt_Q), sizeof(float));
// PRN start sample stamp
d_dump_file.write(reinterpret_cast<char *>(&d_sample_counter), sizeof(uint64_t));
// accumulated carrier phase
tmp_float = static_cast<float>(d_acc_carrier_phase_rad);
d_dump_file.write(reinterpret_cast<char *>(&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<char *>(&tmp_double), sizeof(double));
// carrier and code frequency
tmp_float = static_cast<float>(d_carrier_doppler_hz);
d_dump_file.write(reinterpret_cast<char *>(&tmp_float), sizeof(float));
@@ -850,5 +951,5 @@ int Gps_L1_Ca_Gaussian_Tracking_cc::general_work(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
}
@@ -32,11 +32,13 @@
#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"
#include "tracking_2nd_PLL_filter.h"
#include <armadillo>
#include <boost/circular_buffer.hpp>
#include <gnuradio/block.h>
#include <volk_gnsssdr/volk_gnsssdr_alloc.h> // for volk_gnsssdr::vector
#include <fstream>
@@ -86,6 +88,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,
@@ -114,6 +118,7 @@ private:
int32_t bce_kappa);
int32_t save_matfile();
bool acquire_bit_sync();
// tracking configuration vars
uint32_t d_order;
@@ -193,6 +198,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
@@ -203,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<float> 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;
@@ -33,6 +33,7 @@
#include <gnuradio/io_signature.h>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <sstream>
@@ -113,6 +114,11 @@ Gps_L1_Ca_Tcp_Connector_Tracking_cc::Gps_L1_Ca_Tcp_Connector_Tracking_cc(
d_carrier_lock_threshold(static_cast<float>(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<size_t>(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<float>(acq_to_trk_delay_samples), static_cast<float>(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<uint64_t>(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<double>(samples_offset) / static_cast<double>(d_fs_in));
d_sample_counter = d_sample_counter + static_cast<uint64_t>(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<float>(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<float>(std::fmod(static_cast<double>(d_rem_carr_phase_rad) + carr_phase_step_rad * static_cast<double>(d_current_prn_length_samples), TWO_PI));
d_acc_carrier_phase_rad -= carr_phase_step_rad * static_cast<double>(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<double>((*d_Prompt).real());
current_synchro_data.Prompt_Q = static_cast<double>((*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<uint64_t>(d_current_prn_length_samples);
current_synchro_data.Code_phase_samples = d_rem_code_phase_samples;
current_synchro_data.Carrier_phase_rads = static_cast<double>(d_acc_carrier_phase_rad);
current_synchro_data.Carrier_Doppler_hz = static_cast<double>(d_carrier_doppler_hz);
current_synchro_data.CN0_dB_hz = static_cast<double>(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<double>(prompt.real());
current_synchro_data.Prompt_Q = static_cast<double>(prompt.imag());
current_synchro_data.Tracking_sample_counter = d_sample_counter + static_cast<uint64_t>(d_current_prn_length_samples);
current_synchro_data.Code_phase_samples = d_rem_code_phase_samples;
current_synchro_data.Carrier_phase_rads = static_cast<double>(d_acc_carrier_phase_rad);
current_synchro_data.Carrier_Doppler_hz = static_cast<double>(d_carrier_doppler_hz);
current_synchro_data.CN0_dB_hz = static_cast<double>(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<uint64_t>(d_correlation_length_samples);
// When tracking is disabled an array of 1's is sent to maintain the TCP connection
boost::array<float, NUM_TX_VARIABLES_GPS_L1_CA> 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
@@ -510,6 +580,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<float>(d_correlator_outs[0]);
@@ -528,9 +599,9 @@ int Gps_L1_Ca_Tcp_Connector_Tracking_cc::general_work(int noutput_items __attrib
d_dump_file.write(reinterpret_cast<char *>(&prompt_Q), sizeof(float));
// PRN start sample stamp
d_dump_file.write(reinterpret_cast<char *>(&d_sample_counter), sizeof(uint64_t));
// accumulated carrier phase
tmp_float = static_cast<float>(d_acc_carrier_phase_rad);
d_dump_file.write(reinterpret_cast<char *>(&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<char *>(&tmp_double), sizeof(double));
// carrier and code frequency
tmp_float = static_cast<float>(d_carrier_doppler_hz);
d_dump_file.write(reinterpret_cast<char *>(&tmp_float), sizeof(float));
@@ -554,7 +625,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<char *>(&tmp_float), sizeof(float));
auto tmp_double = static_cast<double>(d_sample_counter + d_correlation_length_samples);
tmp_double = static_cast<double>(d_sample_counter + d_correlation_length_samples);
d_dump_file.write(reinterpret_cast<char *>(&tmp_double), sizeof(double));
// PRN
uint32_t prn_ = d_acquisition_gnss_synchro->PRN;
@@ -570,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<double>(d_current_prn_length_samples) / static_cast<double>(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
}
@@ -27,6 +27,7 @@
#include "gnss_block_interface.h"
#include "gnss_synchro.h"
#include "tcp_communication.h"
#include <boost/circular_buffer.hpp>
#include <gnuradio/block.h>
#include <volk_gnsssdr/volk_gnsssdr_alloc.h> // for volk_gnsssdr::vector
#include <fstream>
@@ -90,6 +91,8 @@ private:
float early_late_space_chips,
size_t port_ch0);
bool acquire_bit_sync();
volk_gnsssdr::vector<gr_complex> d_ca_code;
// correlator
volk_gnsssdr::vector<float> 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<float> 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;
@@ -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<uint64_t>(d_trk_parameters.vector_length));
#if GNURADIO_GREATER_THAN_38
this->set_relative_rate(1, static_cast<uint64_t>(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)
@@ -641,7 +653,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;
}
}
}
@@ -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;
@@ -853,6 +866,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 +1127,25 @@ 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 << ")";
this->message_port_pub(pmt::mp("events"), pmt::from_long(3)); // 3 -> loss of lock
<< " code_lock_fail_counter : " << d_code_lock_fail_counter
<< (d_force_loss_of_lock ? " forced" : "") << ")";
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;
d_force_loss_of_lock = false;
return false;
}
return true;
@@ -1516,9 +1540,9 @@ void kf_tracking::log_data()
// PRN start sample stamp
tmp_long_int = d_sample_counter + static_cast<uint64_t>(d_current_prn_length_samples);
d_dump_file.write(reinterpret_cast<char *>(&tmp_long_int), sizeof(uint64_t));
// accumulated carrier phase
tmp_float = static_cast<float>(d_acc_carrier_phase_rad);
d_dump_file.write(reinterpret_cast<char *>(&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<char *>(&tmp_double), sizeof(double));
// carrier and code frequency
tmp_float = static_cast<float>(d_carrier_doppler_kf_hz);
d_dump_file.write(reinterpret_cast<char *>(&tmp_float), sizeof(float));
@@ -1566,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;
@@ -1607,7 +1631,7 @@ int32_t kf_tracking::save_matfile() const
auto Prompt_I = std::vector<float>(num_epoch);
auto Prompt_Q = std::vector<float>(num_epoch);
auto PRN_start_sample_count = std::vector<uint64_t>(num_epoch);
auto acc_carrier_phase_rad = std::vector<float>(num_epoch);
auto acc_carrier_phase_rad = std::vector<double>(num_epoch);
auto carrier_doppler_hz = std::vector<float>(num_epoch);
auto carrier_doppler_rate_hz = std::vector<float>(num_epoch);
auto code_freq_chips = std::vector<float>(num_epoch);
@@ -1635,7 +1659,7 @@ int32_t kf_tracking::save_matfile() const
dump_file.read(reinterpret_cast<char *>(&Prompt_I[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&Prompt_Q[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&PRN_start_sample_count[i]), sizeof(uint64_t));
dump_file.read(reinterpret_cast<char *>(&acc_carrier_phase_rad[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&acc_carrier_phase_rad[i]), sizeof(double));
dump_file.read(reinterpret_cast<char *>(&carrier_doppler_hz[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&carrier_doppler_rate_hz[i]), sizeof(float));
dump_file.read(reinterpret_cast<char *>(&code_freq_chips[i]), sizeof(float));
@@ -1676,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);
@@ -1741,7 +1765,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 +1788,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_force_loss_of_lock = true;
}
if (d_pull_in_transitory == true)
{
if (d_trk_parameters.pull_in_time_s < (d_sample_counter - d_acq_sample_stamp) / static_cast<int>(d_trk_parameters.fs_in))
@@ -1770,6 +1814,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<int>(std::min<uint64_t>(det_skip, static_cast<uint64_t>(ninput_items[0])));
d_sample_counter += static_cast<uint64_t>(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<int64_t>(d_sample_counter) - static_cast<int64_t>(d_acq_sample_stamp);
const double acq_trk_diff_seconds = static_cast<double>(acq_trk_diff_samples) / d_trk_parameters.fs_in;
@@ -1823,7 +1876,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<int>(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';
}
@@ -2050,6 +2103,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;
}
@@ -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;
@@ -231,6 +235,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
@@ -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)
@@ -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 <gnuradio/block_detail.h>
#include <gnuradio/buffer.h>
#include <algorithm>
#include <exception>
#if GNURADIO_HAS_BUFFER_READER_H
#include <gnuradio/buffer_reader.h>
#endif
#if USE_GLOG_AND_GFLAGS
#include <glog/logging.h>
#else
#include <absl/log/log.h>
#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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> lock(d_mutex);
d_output_stamps.emplace_back(item, stamp);
}
void DeterministicTracking::raise_loss(uint64_t stamp)
{
std::lock_guard<std::mutex> lock(d_mutex);
d_loss = stamp;
}
void DeterministicTracking::dispatch(uint32_t channel, const std::function<void(int)>& fallback)
{
if (!d_producer)
{
return;
}
uint64_t stamp = NO_SAMPLE_STAMP;
{
std::lock_guard<std::mutex> lock(d_mutex);
std::swap(stamp, d_loss);
}
if (stamp != NO_SAMPLE_STAMP &&
!DeterministicClock::instance().emit_channel_event(static_cast<int32_t>(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<std::mutex> 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<std::mutex> 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<int32_t>(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<std::mutex> 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;
}
@@ -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 <gnuradio/block.h>
#include <pmt/pmt.h>
#include <cstdint>
#include <deque>
#include <functional>
#include <memory>
#include <mutex>
#include <utility>
/** \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<bool>(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<void(int)>& 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<DeterministicProducer> d_producer;
std::mutex d_mutex;
std::deque<std::pair<uint64_t, uint64_t>> 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
@@ -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()
{
+10
View File
@@ -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)
+5 -4
View File
@@ -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_)
{
}
+11 -3
View File
@@ -17,6 +17,8 @@
#ifndef GNSS_SDR_CHANNEL_EVENT_H
#define GNSS_SDR_CHANNEL_EVENT_H
#include <cstdint>
#include <limits>
#include <memory>
/** \addtogroup Core
@@ -29,17 +31,23 @@ class Channel_Event;
using channel_event_sptr = std::shared_ptr<Channel_Event>;
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<uint64_t>::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_);
};
-11
View File
@@ -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;
}
+111
View File
@@ -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 <gnuradio/block_detail.h>
#include <gnuradio/buffer.h>
#include <gnuradio/io_signature.h>
#include <algorithm>
#include <cstring>
#include <limits>
#if GNURADIO_HAS_BUFFER_READER_H
#include <gnuradio/buffer_reader.h>
#endif
#if USE_GLOG_AND_GFLAGS
#include <glog/logging.h>
#else
#include <absl/log/log.h>
#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<int>(item_size)),
gr::io_signature::make(1, 1, static_cast<int>(item_size))),
item_size_(item_size)
{
// Wake the readers once per batch, not whenever one of them frees space
set_output_multiple(static_cast<int>(std::min<uint64_t>(std::max<uint64_t>(batch_items, 1),
static_cast<uint64_t>(std::numeric_limits<int>::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<int>(std::min<uint64_t>(allowance, static_cast<uint64_t>(std::min(noutput_items, ninput_items[0]))));
std::memcpy(output_items[0], input_items[0], static_cast<size_t>(count) * item_size_);
consume_each(count);
return count;
}
+66
View File
@@ -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 <gnuradio/block.h>
#include <chrono>
#include <cstddef>
#include <cstdint>
/** \addtogroup Core
* \{ */
/** \addtogroup Core_Receiver_Library
* \{ */
class horizon_gate;
using horizon_gate_sptr = gnss_shared_ptr<horizon_gate>;
/*!
* \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
+286 -223
View File
@@ -15,6 +15,7 @@
*/
#include "supl.h"
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
@@ -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;
}
+2 -1
View File
@@ -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);
+123 -17
View File
@@ -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 <limits> // for numeric_limits
#include <map> // for map
#include <pthread.h> // for pthread_cancel
#include <queue> // for priority_queue
#include <stdexcept> // for invalid_argument
#include <tuple> // for tie
#if USE_GLOG_AND_GFLAGS
#include <glog/logging.h>
@@ -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<command_event_sptr>(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<command_event_sptr>(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<StampedEvent, std::vector<StampedEvent>, 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<uint64_t>(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<channel_event_sptr>(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);
+8
View File
@@ -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();
+253 -10
View File
@@ -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 <boost/lexical_cast.hpp> // for boost::lexical_cast
#include <boost/tokenizer.hpp> // for boost::tokenizer
#include <gnuradio/basic_block.h> // for basic_block
#include <gnuradio/block.h> // for block
#include <gnuradio/block_detail.h> // for block_detail
#include <gnuradio/filter/firdes.h> // for gr::filter::firdes
#include <gnuradio/io_signature.h> // for io_signature
#include <gnuradio/top_block.h> // for top_block, make_top_block
@@ -139,7 +144,8 @@ GNSSFlowgraph::GNSSFlowgraph(std::shared_ptr<ConfigurationInterface> 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<ConfigurationInterface> 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<uint64_t>(std::max(0.0, std::ceil(lookahead_ms * fs / 1000.0))),
static_cast<uint64_t>(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<uint64_t>(1, lookahead / 8));
gate->set_min_output_buffer(0, static_cast<long>(std::max<uint64_t>(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<int>(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<gr::block*>(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<std::string> 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<std::string> mismatched_signals;
for (const auto& channel_interface : channels_)
{
const auto channel = std::dynamic_pointer_cast<Channel>(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<PcpsAcquisitionAdapter>(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<std::string> 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<double>(clock.lookahead()) / clock.sampling_rate();
const double max_lookahead_ms = static_cast<double>(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<int>(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<int>(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<double>(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<double>(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<std::mutex> 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;
+19
View File
@@ -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_;
};
@@ -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
@@ -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 <algorithm>
#include <utility>
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<uint64_t()> bound)
{
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> lock(mutex_);
producers_.clear();
sinks_.clear();
telemetry_faults_.clear();
sampling_rate_ = sampling_rate;
tick_ = std::max<uint64_t>(tick_samples, 1);
lookahead_.store(std::max<uint64_t>(lookahead_samples, 1), std::memory_order_release);
horizon_.store(0, std::memory_order_release);
enabled_.store(true, std::memory_order_release);
std::lock_guard<std::mutex> consumed_lock(consumed_mutex_);
consumed_.clear();
}
void DeterministicClock::disable()
{
{
std::lock_guard<std::mutex> 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<std::mutex> lock(consumed_mutex_);
consumed_.clear();
}
horizon_cv_.notify_all();
}
double DeterministicClock::sampling_rate() const
{
std::lock_guard<std::mutex> lock(mutex_);
return sampling_rate_;
}
uint64_t DeterministicClock::tick() const
{
std::lock_guard<std::mutex> 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<DeterministicProducer> DeterministicClock::register_producer(DeterministicProducer::Kind kind)
{
auto producer = std::make_shared<DeterministicProducer>(kind);
std::lock_guard<std::mutex> lock(mutex_);
producers_.push_back(producer);
return producer;
}
size_t DeterministicClock::count_producers(DeterministicProducer::Kind kind) const
{
std::lock_guard<std::mutex> lock(mutex_);
return static_cast<size_t>(std::count_if(producers_.begin(), producers_.end(),
[kind](const std::weak_ptr<DeterministicProducer>& weak) {
const auto producer = weak.lock();
return producer && producer->kind() == kind;
}));
}
uint64_t DeterministicClock::min_progress() const
{
std::vector<std::shared_ptr<DeterministicProducer>> live;
{
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> lock(mutex_);
telemetry_faults_[channel].push_back(stamp);
}
uint64_t DeterministicClock::take_telemetry_fault(int32_t channel, uint64_t session_start)
{
std::lock_guard<std::mutex> 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<std::mutex> lock(consumed_mutex_);
consumed_[consumer] = items;
}
uint64_t DeterministicClock::consumed(const void* consumer, uint64_t read) const
{
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> 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;
}
@@ -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 <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <vector>
/** \addtogroup Core
* \{ */
/** \addtogroup System_Parameters
* \{ */
//! Marks the absence of a sample stamp
constexpr uint64_t NO_SAMPLE_STAMP = std::numeric_limits<uint64_t>::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<uint64_t()> bound);
//! Progress, limited by the bound if there is one
uint64_t progress() const;
private:
std::atomic<uint64_t> progress_;
mutable std::mutex bound_mutex_;
std::function<uint64_t()> 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<void(int event)>;
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<DeterministicProducer> 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<std::weak_ptr<DeterministicProducer>> producers_;
std::map<int32_t, ChannelEventSink> sinks_;
std::map<int32_t, std::vector<uint64_t>> telemetry_faults_;
mutable std::mutex consumed_mutex_;
std::map<const void*, uint64_t> consumed_;
std::atomic<uint64_t> horizon_;
std::atomic<uint64_t> lookahead_;
std::atomic<bool> enabled_;
double sampling_rate_;
uint64_t tick_;
};
/** \} */
/** \} */
#endif // GNSS_SDR_DETERMINISTIC_CLOCK_H