From e3727fa71abb087d17ec9fa2a059855ad95067ca Mon Sep 17 00:00:00 2001 From: Jacob Dahl Date: Sat, 30 May 2026 16:37:13 -0600 Subject: [PATCH] feat(clock_offset_estimator): add leaky-min clock-offset estimator Estimates the offset between a remote node clock and FC HRT by tracking the minimum of (local - remote), then maps remote timestamps into HRT; residual bias is the minimum observed transport latency. Unit-tested for convergence, jitter hold, and clock-discontinuity reset. --- src/lib/CMakeLists.txt | 1 + src/lib/clock_offset_estimator/CMakeLists.txt | 44 +++++ .../ClockOffsetEstimatorTest.cpp | 175 ++++++++++++++++++ .../clock_offset_estimator.cpp | 70 +++++++ .../clock_offset_estimator.hpp | 65 +++++++ 5 files changed, 355 insertions(+) create mode 100644 src/lib/clock_offset_estimator/CMakeLists.txt create mode 100644 src/lib/clock_offset_estimator/ClockOffsetEstimatorTest.cpp create mode 100644 src/lib/clock_offset_estimator/clock_offset_estimator.cpp create mode 100644 src/lib/clock_offset_estimator/clock_offset_estimator.hpp diff --git a/src/lib/CMakeLists.txt b/src/lib/CMakeLists.txt index 33d58ab640d..23e971064d0 100644 --- a/src/lib/CMakeLists.txt +++ b/src/lib/CMakeLists.txt @@ -39,6 +39,7 @@ add_subdirectory(button EXCLUDE_FROM_ALL) add_subdirectory(cdev EXCLUDE_FROM_ALL) add_subdirectory(cdrstream EXCLUDE_FROM_ALL) add_subdirectory(circuit_breaker EXCLUDE_FROM_ALL) +add_subdirectory(clock_offset_estimator EXCLUDE_FROM_ALL) add_subdirectory(collision_prevention EXCLUDE_FROM_ALL) add_subdirectory(component_information EXCLUDE_FROM_ALL) add_subdirectory(control_allocation EXCLUDE_FROM_ALL) diff --git a/src/lib/clock_offset_estimator/CMakeLists.txt b/src/lib/clock_offset_estimator/CMakeLists.txt new file mode 100644 index 00000000000..17015bd18a2 --- /dev/null +++ b/src/lib/clock_offset_estimator/CMakeLists.txt @@ -0,0 +1,44 @@ +############################################################################ +# +# 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. +# +############################################################################ + +px4_add_library(clock_offset_estimator + clock_offset_estimator.cpp + clock_offset_estimator.hpp +) + +target_include_directories(clock_offset_estimator + PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} +) + +px4_add_unit_gtest(SRC ClockOffsetEstimatorTest.cpp LINKLIBS clock_offset_estimator) diff --git a/src/lib/clock_offset_estimator/ClockOffsetEstimatorTest.cpp b/src/lib/clock_offset_estimator/ClockOffsetEstimatorTest.cpp new file mode 100644 index 00000000000..e914b2314a1 --- /dev/null +++ b/src/lib/clock_offset_estimator/ClockOffsetEstimatorTest.cpp @@ -0,0 +1,175 @@ +/**************************************************************************** + * + * 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. + * + ****************************************************************************/ + +#include + +#include "clock_offset_estimator.hpp" + +// The estimator recovers the FC HRT of a remote event from two observables per +// message: the remote send timestamp and the local HRT at receipt. The model +// used throughout these tests is +// +// local_hrt = (remote_ts + kClockOffset) + transport +// \_______ send instant in HRT ______/ \__ CAN latency __/ +// +// where kClockOffset is the (constant) epoch difference between FC HRT and the +// remote clock, and transport >= 0 is the one-way bus latency (jittery). The +// estimator tracks the *minimum* observed (local - remote), so toLocal() returns +// the send instant in HRT, biased late by only the minimum transport seen. + +namespace +{ +constexpr int64_t kClockOffset = 4'000'000; // HRT - remote clock [us] +constexpr uint64_t kStartRemote = 1'000'000; // first remote send time [us] +constexpr uint64_t kPeriod = 100'000; // 10 Hz fix cadence [us] + +// HRT at which a message sent at remote_us with the given transport arrives. +constexpr uint64_t arrival_hrt(uint64_t remote_us, uint64_t transport_us) +{ + return static_cast(static_cast(remote_us) + kClockOffset) + transport_us; +} + +// HRT of the send instant itself (what toLocal() should converge toward). +constexpr uint64_t send_hrt(uint64_t remote_us) +{ + return static_cast(static_cast(remote_us) + kClockOffset); +} +} // namespace + +TEST(ClockOffsetEstimator, ReturnsZeroWhenRemoteTimestampUnknown) +{ + ClockOffsetEstimator estimator; + + // A node that leaves its send timestamp unset (0) cannot be mapped. + EXPECT_EQ(estimator.toLocal(0, 5'000'000), 0u); + + // The rejected sample must not corrupt state: a real sample still bootstraps. + EXPECT_EQ(estimator.toLocal(kStartRemote, arrival_hrt(kStartRemote, 3'000)), + arrival_hrt(kStartRemote, 3'000)); +} + +TEST(ClockOffsetEstimator, FirstSampleMapsToReceiptTime) +{ + ClockOffsetEstimator estimator; + + // With a single observation there is no transport floor to subtract yet, so + // the best the estimator can do is anchor the remote epoch to receipt time. + const uint64_t local = arrival_hrt(kStartRemote, 12'000); + EXPECT_EQ(estimator.toLocal(kStartRemote, local), local); +} + +TEST(ClockOffsetEstimator, RecoversSendInstantUpToConstantTransport) +{ + ClockOffsetEstimator estimator; + + // With a constant transport the residual bias is exactly that transport from + // the very first sample, and the mapping is stable across the whole stream. + constexpr uint64_t kTransport = 5'000; + + for (unsigned k = 0; k < 5; ++k) { + const uint64_t remote = kStartRemote + k * kPeriod; + const uint64_t local = arrival_hrt(remote, kTransport); + + EXPECT_EQ(estimator.toLocal(remote, local), send_hrt(remote) + kTransport); + } +} + +TEST(ClockOffsetEstimator, ConvergesToMinTransportWithinTwoCycles) +{ + ClockOffsetEstimator estimator; + + // Per-message transport: the first sample is a bad (late) one, so the + // bootstrap over-estimates the floor. The true floor (3 ms) appears by the + // third sample and must then survive the 40 ms jitter spike at index 3. + constexpr uint64_t kTransport[] = {50'000, 8'000, 3'000, 40'000, 3'500, 3'000}; + constexpr uint64_t kMinTransport = 3'000; + // Between floor observations the leaky-min drifts up at kMaxClockDriftPpm + // (100 ppm); over a handful of 10 Hz cycles that is a few tens of us. + constexpr uint64_t kLeakSlack = 100; + + for (unsigned k = 0; k < 6; ++k) { + const uint64_t remote = kStartRemote + k * kPeriod; + const uint64_t local = arrival_hrt(remote, kTransport[k]); + + const hrt_abstime mapped = estimator.toLocal(remote, local); + + // Causal at all times: at/after the nav-send, at/before receipt. + EXPECT_GE(mapped, send_hrt(remote)); + EXPECT_LE(mapped, local); + + if (k == 0) { + // Bootstrap: still 50 ms off the true send instant. + EXPECT_EQ(mapped - send_hrt(remote), kTransport[0]); + + } else if (k >= 2) { + // Converged (and held): the residual bias has collapsed from 50 ms + // to the minimum observed transport, and the 40 ms spike at k == 3 + // does not pull the estimate back up. + EXPECT_GE(mapped, send_hrt(remote) + kMinTransport); + EXPECT_LE(mapped, send_hrt(remote) + kMinTransport + kLeakSlack); + } + } +} + +TEST(ClockOffsetEstimator, ResetsOnRemoteClockDiscontinuity) +{ + ClockOffsetEstimator estimator; + + constexpr uint64_t kTransport = 3'000; + + // Converge on a steady stream. + uint64_t remote = kStartRemote; + + for (unsigned k = 0; k < 4; ++k) { + remote = kStartRemote + k * kPeriod; + EXPECT_EQ(estimator.toLocal(remote, arrival_hrt(remote, kTransport)), + send_hrt(remote) + kTransport); + } + + // The node clock steps back 1 s (> kResetThresholdUs) while HRT keeps + // running: the next send timestamp is 1 s behind the established chain. The + // resulting lag jump must re-bootstrap rather than be tracked as a new floor. + const uint64_t hrt_now = arrival_hrt(remote + kPeriod, kTransport); // continuous HRT + const uint64_t remote_jump = (remote + kPeriod) - 1'000'000; // node UTC steps back 1 s + + EXPECT_EQ(estimator.toLocal(remote_jump, hrt_now), hrt_now); // re-bootstrapped to receipt + + // After the step the FC-HRT-to-node offset is 1 s larger; the estimator + // reconverges on the new baseline and stays causal. + const uint64_t remote_next = remote_jump + kPeriod; + const uint64_t hrt_next = hrt_now + kPeriod; + const hrt_abstime mapped = estimator.toLocal(remote_next, hrt_next); + + EXPECT_LE(mapped, hrt_next); + EXPECT_EQ(mapped, hrt_next); // constant transport again -> maps to receipt +} diff --git a/src/lib/clock_offset_estimator/clock_offset_estimator.cpp b/src/lib/clock_offset_estimator/clock_offset_estimator.cpp new file mode 100644 index 00000000000..ce8ad8aa884 --- /dev/null +++ b/src/lib/clock_offset_estimator/clock_offset_estimator.cpp @@ -0,0 +1,70 @@ +/**************************************************************************** + * + * 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. + * + ****************************************************************************/ + +#include "clock_offset_estimator.hpp" + +hrt_abstime ClockOffsetEstimator::toLocal(uint64_t remote_us, hrt_abstime local_us) +{ + if (remote_us == 0) { + return 0; + } + + const int64_t lag = static_cast(local_us) - static_cast(remote_us); + + if (!_initialized || lag > _link_offset_us + kResetThresholdUs) { + // Bootstrap, or remote-clock discontinuity. + _link_offset_us = lag; + _initialized = true; + + } else { + // Drift the floor up at the worst-case relative clock rate so we don't + // pin below the true offset when HRT runs faster than the remote. + const hrt_abstime dt = (local_us > _last_update_us) ? (local_us - _last_update_us) : 0; + _link_offset_us += static_cast(dt) * kMaxClockDriftPpm / 1'000'000; + + if (lag < _link_offset_us) { + _link_offset_us = lag; + } + } + + _last_update_us = local_us; + + const int64_t result = static_cast(remote_us) + _link_offset_us; + + // Mapped HRT cannot lie after receipt. + if (result <= 0 || result > static_cast(local_us)) { + return 0; + } + + return static_cast(result); +} diff --git a/src/lib/clock_offset_estimator/clock_offset_estimator.hpp b/src/lib/clock_offset_estimator/clock_offset_estimator.hpp new file mode 100644 index 00000000000..c6b6122d41e --- /dev/null +++ b/src/lib/clock_offset_estimator/clock_offset_estimator.hpp @@ -0,0 +1,65 @@ +/**************************************************************************** + * + * 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. + * + ****************************************************************************/ + +#pragma once + +#include +#include + +// Estimates the offset between a remote node's clock and the FC HRT timebase +// with a leaky-min filter on (HRT_recv - remote_ts), then maps remote +// timestamps into HRT. Residual bias is the minimum observed transport delay; +// the offset drifts upward between observations to track clock skew, and +// hard-resets on jumps larger than any plausible transport stall. +class ClockOffsetEstimator +{ +public: + ClockOffsetEstimator() = default; + ~ClockOffsetEstimator() = default; + + // Returns the HRT estimate of the remote event, or 0 if unavailable. + // remote_us: remote timestamp [us], same epoch across calls; 0 if unknown. + // local_us: HRT when the carrying message arrived. + hrt_abstime toLocal(uint64_t remote_us, hrt_abstime local_us); + +private: + // 100 ppm envelopes raw HSE crystals over temperature; TCXOs are a few ppm. + static constexpr int64_t kMaxClockDriftPpm{100}; + + // Upward lag jumps beyond this are treated as remote-clock discontinuities. + static constexpr int64_t kResetThresholdUs{500'000}; + + int64_t _link_offset_us{0}; + hrt_abstime _last_update_us{0}; + bool _initialized{false}; +};