diff --git a/src/lib/timesync/CMakeLists.txt b/src/lib/timesync/CMakeLists.txt index dc150e0e795..a2ed8e1840f 100644 --- a/src/lib/timesync/CMakeLists.txt +++ b/src/lib/timesync/CMakeLists.txt @@ -36,3 +36,5 @@ px4_add_library(timesync Timesync.hpp ) target_link_libraries(timesync) + +px4_add_functional_gtest(SRC TimesyncTest.cpp LINKLIBS timesync) diff --git a/src/lib/timesync/Timesync.cpp b/src/lib/timesync/Timesync.cpp index 9d8d798f619..c034f2ad139 100644 --- a/src/lib/timesync/Timesync.cpp +++ b/src/lib/timesync/Timesync.cpp @@ -54,7 +54,7 @@ void Timesync::update(const uint64_t now_us, const int64_t remote_timestamp_ns, uint64_t rtt_us = now_us - (originate_timestamp_ns / 1000ULL); // Calculate the difference of this sample from the current estimate - uint64_t deviation = llabs((int64_t)_time_offset - offset_us); + uint64_t deviation = llabs(offset() - offset_us); if (rtt_us < MAX_RTT_SAMPLE) { // Only use samples with low RTT @@ -73,21 +73,8 @@ void Timesync::update(const uint64_t now_us, const int64_t remote_timestamp_ns, } else { - // Filter gain scheduling - if (!sync_converged()) { - // Interpolate with a sigmoid function - const float progress = (float) _sequence / (float) CONVERGENCE_WINDOW; - double p = (double)(1.f - expf(0.5f * (1.f - 1.f / (1.f - progress)))); - _filter_alpha = p * ALPHA_GAIN_FINAL + (1.0 - p) * ALPHA_GAIN_INITIAL; - _filter_beta = p * BETA_GAIN_FINAL + (1.0 - p) * BETA_GAIN_INITIAL; - - } else { - _filter_alpha = ALPHA_GAIN_FINAL; - _filter_beta = BETA_GAIN_FINAL; - } - // Perform filter update - add_sample(offset_us); + add_sample(offset_us, now_us); // Increment sequence counter after filter update _sequence++; @@ -113,7 +100,7 @@ void Timesync::update(const uint64_t now_us, const int64_t remote_timestamp_ns, tsync_status.source_protocol = _source; tsync_status.remote_timestamp = remote_timestamp_ns / 1000ULL; tsync_status.observed_offset = offset_us; - tsync_status.estimated_offset = (int64_t)_time_offset; + tsync_status.estimated_offset = offset(); tsync_status.round_trip_time = rtt_us; tsync_status.timestamp = hrt_absolute_time(); @@ -125,41 +112,91 @@ uint64_t Timesync::sync_stamp(uint64_t usec) { // Only return synchronised stamp if we have converged to a good value if (sync_converged()) { - return usec + (int64_t)_time_offset; + return usec + offset(); } else { return hrt_absolute_time(); } } -void Timesync::add_sample(int64_t offset_us) +/* + * Hybrid Kalman filter: + * https://en.wikipedia.org/wiki/Kalman_filter#Hybrid_Kalman_filter + * + * State: + * x = [theta; gamma] + * theta = t_local - t_remote : clock offset [s] + * gamma = d(theta)/dt : clock skew [s/s], the relative rate error of the two clocks + * + * Model: + * dx/dt = F x + w(t), F = [0 1; 0 0], w(t) ~ N(0, Q), Q = diag(q_o, q_s) + * z_k = H x_k + v_k, H = [1 0], v_k ~ N(0, R) + * where Q is the continuous-time noise spectral density, q_o = OFFSET_RANDOM_WALK, + * q_s = SKEW_RANDOM_WALK, R = MEASUREMENT_NOISE_STD^2, and z_k is the offset observed + * from one timesync round trip. + * + * Prediction: the hybrid filter integrates, over the time dt since the last sample, + * dx/dt = F x + * dP/dt = F P + P F^T + Q + * For this F and Q both have an exact closed-form solution: + * x <- A x, A = [1 dt; 0 1] (offset += skew * dt, skew unchanged) + * P <- A P A^T + Q_d, Q_d = [q_o dt + q_s dt^3/3 q_s dt^2/2; + * q_s dt^2/2 q_s dt ] + * + * Q_d is the noise added over dt. Each random walk adds q dt to its own variance. + * The skew noise also leaks into the offset through offset += skew * dt, which + * gives the dt^2/2 and dt^3/3 terms. A skew kick w at s seconds before the end of + * dt changes the skew by w and the offset by s w. Summing over the interval: + * cov(offset, skew) += integral_0^dt q_s s ds = q_s dt^2/2 + * var(offset) += integral_0^dt q_s s^2 ds = q_s dt^3/3 + * + * https://en.wikipedia.org/wiki/Discretization#Discretization_of_process_noise + */ +void Timesync::add_sample(int64_t offset_us, uint64_t now_us) { - // Online exponential smoothing filter. The derivative of the estimate is also - // estimated in order to produce an estimate without steady state lag: - // https://en.wikipedia.org/wiki/Exponential_smoothing#Double_exponential_smoothing - double time_offset_prev = _time_offset; + static constexpr double R = MEASUREMENT_NOISE_STD * MEASUREMENT_NOISE_STD; + const double offset_s = offset_us * 1e-6; if (_sequence == 0) { // First offset sample - _time_offset = offset_us; + _time_offset = offset_s; + _time_skew = 0.0; + _var_offset = R; + _cov_offset_skew = 0.0; + _var_skew = INITIAL_SKEW_STD * INITIAL_SKEW_STD; } else { - // Update the clock offset estimate - _time_offset = _filter_alpha * offset_us + (1.0 - _filter_alpha) * (_time_offset + _time_skew); + const double dt = (now_us - _last_sample_us) * 1e-6; - // Update the clock skew estimate - _time_skew = _filter_beta * (_time_offset - time_offset_prev) + (1.0 - _filter_beta) * _time_skew; + // Predict: x <- A x, P <- A P A^T + Q_d, written out in Horner form. + _time_offset += _time_skew * dt; + _var_offset += dt * (OFFSET_RANDOM_WALK + 2.0 * _cov_offset_skew + dt * (_var_skew + dt * SKEW_RANDOM_WALK / 3.0)); + _cov_offset_skew += dt * (_var_skew + dt * SKEW_RANDOM_WALK / 2.0); + _var_skew += dt * SKEW_RANDOM_WALK; + + // Update: S = H P H^T + R, K = P H^T / S, x <- x + K (z - H x), P <- (I - K H) P + const double innovation = offset_s - _time_offset; + const double innovation_var = _var_offset + R; + const double k_offset = _var_offset / innovation_var; + const double k_skew = _cov_offset_skew / innovation_var; + + _time_offset += k_offset * innovation; + _time_skew += k_skew * innovation; + + _var_skew -= k_skew * _cov_offset_skew; + _var_offset *= (1.0 - k_offset); + _cov_offset_skew *= (1.0 - k_offset); } + + _last_sample_us = now_us; } void Timesync::reset_filter() { - // Do a full reset of all statistics and parameters + // The filter state is initialized by the first sample after the reset (_sequence == 0). + // Clear the offset because it is reported before that sample arrives. _sequence = 0; _time_offset = 0.0; - _time_skew = 0.0; - _filter_alpha = ALPHA_GAIN_INITIAL; - _filter_beta = BETA_GAIN_INITIAL; _high_deviation_count = 0; _high_rtt_count = 0; } diff --git a/src/lib/timesync/Timesync.hpp b/src/lib/timesync/Timesync.hpp index 4844713442d..edfd92c7dd9 100644 --- a/src/lib/timesync/Timesync.hpp +++ b/src/lib/timesync/Timesync.hpp @@ -52,27 +52,17 @@ using namespace time_literals; static constexpr time_t PX4_EPOCH_SECS = 1234567890ULL; -// Filter gains -// -// Alpha : Used to smooth the overall clock offset estimate. Smaller values will lead -// to a smoother estimate, but track time drift more slowly, introducing a bias -// in the estimate. Larger values will cause low-amplitude oscillations. -// -// Beta : Used to smooth the clock skew estimate. Smaller values will lead to a -// tighter estimation of the skew (derivative), but will negatively affect how fast the -// filter reacts to clock skewing (e.g cause by temperature changes to the oscillator). -// Larger values will cause large-amplitude oscillations. -static constexpr double ALPHA_GAIN_INITIAL = 0.05; -static constexpr double BETA_GAIN_INITIAL = 0.05; -static constexpr double ALPHA_GAIN_FINAL = 0.003; -static constexpr double BETA_GAIN_FINAL = 0.003; +// Kalman filter tuning. The model is defined above Timesync::add_sample(). +// MEASUREMENT_NOISE_STD : sqrt(R), std of an observed offset [s], mostly asymmetric link delay +// OFFSET_RANDOM_WALK : q_o, offset random walk density [s^2/s], damps the response to offset steps +// SKEW_RANDOM_WALK : q_s, skew random walk density [1/s], higher follows clock corrections faster +// INITIAL_SKEW_STD : prior skew std [s/s], i.e. crystal tolerance +static constexpr double MEASUREMENT_NOISE_STD = 1e-3; +static constexpr double OFFSET_RANDOM_WALK = 1e-8; +static constexpr double SKEW_RANDOM_WALK = 7e-13; +static constexpr double INITIAL_SKEW_STD = 100e-6; -// Filter gain scheduling -// -// The filter interpolates between the INITIAL and FINAL gains while the number of -// exhanged timesync packets is less than CONVERGENCE_WINDOW. A lower value will -// allow the timesync to converge faster, but with potentially less accurate initial -// offset and skew estimates. +// Number of exchanged timesync packets before the estimate is considered converged. static constexpr uint32_t CONVERGENCE_WINDOW = 500; // Outlier rejection and filter reset @@ -104,7 +94,7 @@ public: */ uint64_t sync_stamp(uint64_t usec); - int64_t offset() const { return (int64_t)_time_offset; } + int64_t offset() const { return (int64_t)(_time_offset * 1e6); } // [us] /** * Return true if the timesync algorithm converged to a good estimate, @@ -121,20 +111,22 @@ public: private: /** - * Online exponential filter to smooth time offset + * Kalman filter update of time offset and skew */ - void add_sample(int64_t offset_us); + void add_sample(int64_t offset_us, uint64_t now_us); uORB::PublicationMulti _timesync_status_pub{ORB_ID(timesync_status)}; uint32_t _sequence{0}; // Timesync statistics - double _time_offset{0}; - double _time_skew{0}; + double _time_offset{0}; // [s] + double _time_skew{0}; // [s/s] - // Filter parameters - double _filter_alpha{ALPHA_GAIN_INITIAL}; - double _filter_beta{BETA_GAIN_INITIAL}; + // Filter covariance + double _var_offset{0}; // [s^2] + double _cov_offset_skew{0}; // [s] + double _var_skew{0}; // [-] + uint64_t _last_sample_us{0}; // Outlier rejection and filter reset uint32_t _high_deviation_count{0}; diff --git a/src/lib/timesync/TimesyncTest.cpp b/src/lib/timesync/TimesyncTest.cpp new file mode 100644 index 00000000000..b8e03a7ba51 --- /dev/null +++ b/src/lib/timesync/TimesyncTest.cpp @@ -0,0 +1,172 @@ +/**************************************************************************** + * + * Copyright (c) 2026 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/** + * Timesync convergence on a simulated remote clock (7 ppm drift, +-0.5 ms noise) with a step or ramp correction. + */ + +#include + +#include "Timesync.hpp" + +#include +#include +#include + +namespace +{ + +struct Scenario { + double rate_hz{1.0}; // timesync rate after the initial burst + bool burst{true}; // uXRCE-DDS: fast exchange until converged + double disturbance_us{0.0}; // size of the remote clock correction + double disturbance_start_s{180.0}; + double disturbance_duration_s{0.0}; // 0: step, > 0: ramp + double duration_s{1800.0}; +}; + +struct Result { + double max_error_before_disturbance_us{0.0}; + double last_error_above_10ms_s{0.0}; // time after the disturbance start + double last_error_above_1ms_s{0.0}; +}; + +Result runScenario(const Scenario &scenario) +{ + static constexpr double OFFSET_US = -1000e6; // remote clock 1000 s ahead + static constexpr double DRIFT_PPM = 7.0; + static constexpr int64_t NOISE_US = 500; + static constexpr double BURST_INTERVAL_US = 15e3; + + std::mt19937 rng(1); + Timesync timesync; + Result result{}; + double time_us = 1e6; + + for (uint32_t sample = 0; time_us < scenario.duration_s * 1e6; sample++) { + const bool in_burst = scenario.burst && (sample < CONVERGENCE_WINDOW); + time_us += in_burst ? BURST_INTERVAL_US : 1e6 / scenario.rate_hz; + const double time_s = time_us * 1e-6; + const double since_disturbance_s = time_s - scenario.disturbance_start_s; + + double disturbance_us = 0.0; + + if (since_disturbance_s >= 0.0) { + const double progress = (scenario.disturbance_duration_s > 0.0) + ? std::min(1.0, since_disturbance_s / scenario.disturbance_duration_s) : 1.0; + disturbance_us = progress * scenario.disturbance_us; + } + + const double true_offset_us = OFFSET_US + DRIFT_PPM * time_s + disturbance_us; + const int64_t noise_us = static_cast(rng() % (2 * NOISE_US + 1)) - NOISE_US; + const int64_t observed_offset_us = llround(true_offset_us) + noise_us; + + // Zero round-trip time + const uint64_t now_us = static_cast(time_us); + const int64_t remote_ns = (static_cast(now_us) - observed_offset_us) * 1000; + timesync.update(now_us, remote_ns, static_cast(now_us) * 1000); + + if (!timesync.sync_converged()) { + continue; + } + + const double error_us = std::fabs(static_cast(timesync.offset()) - true_offset_us); + + if (since_disturbance_s < 0.0) { + if (time_s > 60.0) { + result.max_error_before_disturbance_us = std::max(result.max_error_before_disturbance_us, error_us); + } + + } else { + if (error_us > 10000.0) { + result.last_error_above_10ms_s = since_disturbance_s; + } + + if (error_us > 1000.0) { + result.last_error_above_1ms_s = since_disturbance_s; + } + } + } + + return result; +} + +void expectRecovery(const Result &result) +{ + EXPECT_LE(result.last_error_above_10ms_s, 30.0); + EXPECT_LE(result.last_error_above_1ms_s, 300.0); +} + +} // namespace + +TEST(TimesyncTest, SteadyStateAccuracy) +{ + Scenario scenario{}; + scenario.disturbance_start_s = 1e9; // never + const Result result = runScenario(scenario); + EXPECT_LT(result.max_error_before_disturbance_us, 1500.0); +} + +TEST(TimesyncTest, RecoversFromRemoteClockStepForward) +{ + Scenario scenario{}; + scenario.disturbance_us = 60e3; + expectRecovery(runScenario(scenario)); +} + +TEST(TimesyncTest, RecoversFromRemoteClockStepBackward) +{ + Scenario scenario{}; + scenario.disturbance_us = -90e3; + expectRecovery(runScenario(scenario)); +} + +TEST(TimesyncTest, RecoversFromRemoteClockRamp) +{ + Scenario scenario{}; + scenario.disturbance_us = 60e3; + scenario.disturbance_duration_s = 60.0; + expectRecovery(runScenario(scenario)); +} + +TEST(TimesyncTest, IndependentOfSampleRate) +{ + // MAVLink: constant 10 Hz, no burst + Scenario scenario{}; + scenario.rate_hz = 10.0; + scenario.burst = false; + scenario.disturbance_us = 60e3; + const Result result = runScenario(scenario); + EXPECT_LT(result.max_error_before_disturbance_us, 1500.0); + expectRecovery(result); +}