Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion protobufs
32 changes: 32 additions & 0 deletions src/Time.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* @file Time.cpp
* @brief Monotonic uptime clock with test injection and a rollover-immune 64-bit form.
*
* getMillis() is a thin wrapper over the platform millis() (or the injected test clock).
* getMillis64() extends it to 64 bits with a software carry: it samples the 32-bit clock and
* bumps a high word each time the low word wraps. The sampler must be polled at least once per
* ~49.7-day wrap window to catch every wrap - trivially satisfied by normal device activity.
* It keeps mutable static state, so it is not ISR-safe (documented in Time.h).
*/
#include "Time.h"

uint32_t Time::getMillis()
{
#ifdef PIO_UNIT_TESTING
if (Time::useTestClock)
return Time::testNowMs;
#endif
return millis();
}

uint64_t Time::getMillis64()
{
static uint32_t lastLow = 0; // last 32-bit sample
static uint32_t highWord = 0; // number of observed wraps

uint32_t now = Time::getMillis();
if (now < lastLow)
highWord++; // low word wrapped since last call
lastLow = now;
return (static_cast<uint64_t>(highWord) << 32) | now;
}
61 changes: 61 additions & 0 deletions src/Time.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#pragma once
#ifndef _MT_TIME_H
#define _MT_TIME_H
Comment thread
NomDeTom marked this conversation as resolved.
Resolved

#include <Arduino.h>

/**
* Monotonic uptime clock - the single seam for "milliseconds since boot".
*
* Why this exists:
* - Test injection: any unit test can drive a virtual timebase via setTestMillis() /
* advanceTestMillis() instead of sleeping real seconds. One seam for all suites - no
* per-module test clock (this replaces the ad-hoc HopScalingModule::s_testNowMs /
* TrafficManagementModule::clockMs patterns).
* - Rollover immunity: getMillis64() never wraps (uint32 millis() wraps at ~49.7 days, which
* routers/repeaters exceed). Use it for any "duration over days" logic.
*
* This is uptime, NOT wall-clock. For wall-clock seconds (RTC/GPS/NTP) use getTime() in
* src/gps/RTC.h - a separate axis that can jump and be unset.
*
* Hot/ISR paths use getMillis() (32-bit, a drop-in for millis(), rollover-safe only with the
* unsigned-subtraction idiom `(uint32_t)(now - then)`). getMillis64() keeps mutable static
* carry state and is NOT ISR-safe - call it from normal task context only.
* An interrupt landing mid-update of that state (a read-then-write with no locking) could tear
* it, corrupting the high word for every caller afterward, not just the interrupted one.
*/
namespace Time
{
#ifdef PIO_UNIT_TESTING
// Test-only virtual clock. Default: OFF - getMillis() returns real millis() so suites that
// rely on real time are unaffected by the seam. A test opts in by calling setTestMillis().
inline uint32_t testNowMs = 0;
inline bool useTestClock = false;

inline void setTestMillis(uint32_t ms)
{
testNowMs = ms;
useTestClock = true;
}
inline void advanceTestMillis(uint32_t deltaMs)
{
testNowMs += deltaMs;
useTestClock = true;
}
// Restore real-clock behaviour (call in test tearDown if a suite mixes real and fake time).
inline void useRealClock()
{
useTestClock = false;
testNowMs = 0;
}
#endif

/// Milliseconds since boot, 32-bit (wraps ~49.7 days). Drop-in for millis().
uint32_t getMillis();

/// Milliseconds since boot, 64-bit, rollover-immune. Non-ISR use only.
uint64_t getMillis64();

} // namespace Time

#endif
4 changes: 4 additions & 0 deletions src/configuration.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.

#include <Arduino.h>

// Monotonic uptime clock seam (Time::getMillis / getMillis64). Hosted here so the whole
// codebase can use it without per-file includes; see src/Time.h.
#include "Time.h"

#if __has_include("Melopero_RV3028.h")
#include "Melopero_RV3028.h"
#endif
Expand Down
9 changes: 9 additions & 0 deletions src/gps/RTC.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include "configuration.h"
#include "detect/ScanI2C.h"
#include "main.h"
#include "mesh/MeshService.h"
#include "modules/NodeInfoModule.h"
#include <Throttle.h>
#include <sys/time.h>
Expand All @@ -17,12 +18,20 @@ uint32_t lastSetFromPhoneNtpOrGps = 0;
static uint32_t lastTimeValidationWarning = 0;
static const uint32_t TIME_VALIDATION_WARNING_INTERVAL_MS = 15000; // 15 seconds

// Despite the name, this now reacts to two distinct quality-crossing events sharing one call
// site: NodeInfo recheck on "we had no time source at all before" (unchanged), and rx_time
// reconciliation on "we just reached RTCQualityFromNet or better" (new) - see
// MeshService::reconcilePendingRxTimes(). The thresholds differ, so both checks are independent.
static void triggerNodeInfoCheckOnTimeSource(RTCQuality oldQuality, RTCQuality newQuality)
{
if (oldQuality == RTCQualityNone && newQuality > RTCQualityNone && nodeInfoModule) {
LOG_DEBUG("Time source acquired (%s -> %s), triggering NodeInfo recheck", RtcName(oldQuality), RtcName(newQuality));
nodeInfoModule->triggerImmediateNodeInfoCheck();
}
if (oldQuality < RTCQualityFromNet && newQuality >= RTCQualityFromNet && service) {
LOG_DEBUG("RTC net quality reached (%s -> %s), reconciling rx_time", RtcName(oldQuality), RtcName(newQuality));
service->reconcilePendingRxTimes();
}
}

RTCQuality getRTCQuality()
Expand Down
50 changes: 48 additions & 2 deletions src/mesh/MeshService.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,36 @@ NodeNum MeshService::getNodenumFromRequestId(uint32_t request_id)
return nodenum;
}

// A packet stamped with has_rx_time == false is carrying a millis() snapshot from the moment it
// was received, not a wall-clock reading (see Router::dispatchReceived) - the device had no
// trustworthy time source yet, commonly because it has no GPS and the phone hadn't connected.
// Once the clock becomes trustworthy, back-calculate the real reception epoch from how much
// uptime has elapsed since that snapshot, rather than leaving the packet stuck presence-absent
// (or worse, silently wrong) for its remaining time in the queue.
void MeshService::reconcilePendingRxTimes()
{
const uint32_t nowEpoch = getValidTime(RTCQualityFromNet);
if (nowEpoch == 0) // called before the clock was actually valid - nothing to reconcile against
return;
const uint32_t nowMillis = Time::getMillis();

for (int i = 0; i < toPhoneQueue.numUsed(); i++) {
meshtastic_MeshPacket *p = toPhoneQueue.dequeuePtr(0);
if (!p->has_rx_time) {
// Unsigned subtraction is wraparound-safe across a getMillis() rollover, matching
// the idiom already used throughout this codebase for elapsed-time math. Note this
// is only 32-bit-safe even though Time::getMillis64() exists: rx_time is a 32-bit
// wire field, so the placeholder stashed at receipt (Router::dispatchReceived) was
// never more than a 32-bit snapshot to begin with - a 64-bit "now" here would have
// nothing wider to compare against.
const uint32_t elapsedMs = nowMillis - p->rx_time;
p->rx_time = nowEpoch - (elapsedMs / 1000);
p->has_rx_time = true;
}
toPhoneQueue.enqueue(p, 0);
}
}

#if MESHTASTIC_ENABLE_FRAME_INJECTION
// Deliver a client-supplied frame into the receive pipeline as if it arrived off the LoRa chip. Mirrors
// the portduino SimRadio SIMULATOR_APP unwrap so the same host wire format works on real hardware: the
Expand Down Expand Up @@ -220,7 +250,12 @@ void MeshService::injectAsReceived(meshtastic_MeshPacket &p)
mp->rx_rssi = -40;
mp->has_rx_rssi = true;
}
mp->rx_time = getValidTime(RTCQualityFromNet);
// rx_time has explicit presence: store a Time::getMillis() placeholder, not a literal 0, when
// we don't have a trustworthy wall clock yet (this packet re-enters the receive pipeline via
// enqueueReceivedMessage below, so Router::dispatchReceived will normally overwrite this
// anyway - but don't rely on that; a bare 0 would misdirect
// MeshService::reconcilePendingRxTimes() if it were ever read before that happens).
stampRxTime(mp);
LOG_INFO("inject: RX from=0x%08x to=0x%08x id=0x%08x ch=%d %s", mp->from, mp->to, mp->id, mp->channel,
mp->which_payload_variant == meshtastic_MeshPacket_encrypted_tag ? "encrypted" : "decoded");
router->enqueueReceivedMessage(mp);
Expand Down Expand Up @@ -258,7 +293,11 @@ void MeshService::handleToRadio(meshtastic_MeshPacket &p)
if (p.id == 0)
p.id = generatePacketId(); // If the phone didn't supply one, then pick one

p.rx_time = getValidTime(RTCQualityFromNet); // Record the time the packet arrived from the phone
// Record the time the packet arrived from the phone. rx_time has explicit presence: store a
// Time::getMillis() placeholder, not a literal 0, on the rare chance the phone connected
// without yet handing us net-quality time - a bare 0 would misdirect
// MeshService::reconcilePendingRxTimes() if this packet is later echoed into toPhoneQueue.
stampRxTime(&p);

IF_SCREEN(if (p.decoded.portnum == meshtastic_PortNum_TEXT_MESSAGE_APP && p.decoded.payload.size > 0 &&
p.to != NODENUM_BROADCAST && p.to != 0) // DM only
Expand Down Expand Up @@ -595,6 +634,13 @@ bool MeshService::isToPhoneQueueEmpty()

uint32_t MeshService::GetTimeSinceMeshPacket(const meshtastic_MeshPacket *mp)
{
// rx_time has explicit presence: while has_rx_time is false, rx_time may hold a millis()
// placeholder rather than a wall-clock reading (see Router::dispatchReceived), which would
// otherwise subtract to a huge bogus "age" here instead of a negative one the clamp below
// would catch.
if (!mp->has_rx_time)
return 0;

uint32_t now = getTime();

uint32_t last_seen = mp->rx_time;
Expand Down
6 changes: 6 additions & 0 deletions src/mesh/MeshService.h
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,12 @@ class MeshService
// search the queue for a request id and return the matching nodenum
NodeNum getNodenumFromRequestId(uint32_t request_id);

// Rewrite any queued-for-phone packet whose rx_time is still an unresolved millis()
// placeholder (has_rx_time == false, see Router::dispatchReceived) into a real epoch, now
// that the wall clock is trustworthy. Called from RTC.cpp the moment RTC quality crosses
// RTCQualityFromNet - typically, the phone just connected and told us the real time.
void reconcilePendingRxTimes();

// Release QueueStatus packet to pool
void releaseQueueStatusToPool(meshtastic_QueueStatus *p) { queueStatusPool.release(p); }

Expand Down
13 changes: 12 additions & 1 deletion src/mesh/NodeDB.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3233,6 +3233,13 @@ uint32_t sinceLastSeen(const meshtastic_NodeInfoLite *n)

uint32_t sinceReceived(const meshtastic_MeshPacket *p)
{
// rx_time has explicit presence: while has_rx_time is false, rx_time may hold a millis()
// placeholder rather than a wall-clock reading (see Router::dispatchReceived), which would
// otherwise subtract to a huge bogus "age" here instead of a negative one the clamp below
// would catch.
if (!p->has_rx_time)
return 0;

uint32_t now = getTime();

int delta = (int)(now - p->rx_time);
Expand Down Expand Up @@ -3629,7 +3636,11 @@ void NodeDB::updateFrom(const meshtastic_MeshPacket &mp)
return;
}

if (mp.rx_time) // if the packet has a valid timestamp use it to update our last_heard
// rx_time has explicit presence: a truthy-but-unknown rx_time is now possible (a millis()
// placeholder pending MeshService::reconcilePendingRxTimes()), so gate on has_rx_time, not
// truthiness - `if (mp.rx_time)` would otherwise stamp last_heard with a boot-relative
// millis() count rather than a real epoch.
if (mp.has_rx_time)
info->last_heard = mp.rx_time;

// Gate on the packet actually having been received over our own radio, not on rx_snr being
Expand Down
16 changes: 16 additions & 0 deletions src/mesh/PhoneAPI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1258,6 +1258,10 @@ meshtastic_MeshPacket PhoneAPI::makeReplayPositionPacket(NodeNum num, const mesh
// fix time (which is often 0 and, when present, already round-trips inside the payload
// via ConvertToPosition).
pkt.rx_time = header ? header->last_heard : 0;
// rx_time has explicit presence; last_heard has no presence bit of its own, but it is only
// ever written from a genuine has_rx_time-gated reception (see NodeDB::updateFrom), so a
// truthiness check on it is exact, not a heuristic - a legacy 0 unambiguously means "never".
pkt.has_rx_time = (header && header->last_heard != 0);
// Stable per-node/per-fix id: replaying the same unchanged history on every
// reconnect must not look like a brand new packet to the phone's history/dedup.
pkt.id = makeReplayPacketId(num, pkt.rx_time, meshtastic_PortNum_POSITION_APP);
Expand Down Expand Up @@ -1285,6 +1289,10 @@ meshtastic_MeshPacket PhoneAPI::makeReplayTelemetryPacket(NodeNum num, const mes
// No native timestamp on telemetry packets here; use last_heard.
const meshtastic_NodeInfoLite *header = nodeDB->getMeshNode(num);
pkt.rx_time = header ? header->last_heard : 0;
// rx_time has explicit presence; last_heard has no presence bit of its own, but it is only
// ever written from a genuine has_rx_time-gated reception (see NodeDB::updateFrom), so a
// truthiness check on it is exact, not a heuristic - a legacy 0 unambiguously means "never".
pkt.has_rx_time = (header && header->last_heard != 0);
pkt.id = makeReplayPacketId(num, pkt.rx_time, meshtastic_Telemetry_device_metrics_tag);
pkt.channel = header ? header->channel : 0;
pkt.rx_snr = header ? header->snr : 0;
Expand Down Expand Up @@ -1391,6 +1399,10 @@ meshtastic_MeshPacket PhoneAPI::makeReplayEnvironmentPacket(uint32_t num, const
pkt.to = NODENUM_BROADCAST;
const meshtastic_NodeInfoLite *header = nodeDB->getMeshNode(num);
pkt.rx_time = header ? header->last_heard : 0;
// rx_time has explicit presence; last_heard has no presence bit of its own, but it is only
// ever written from a genuine has_rx_time-gated reception (see NodeDB::updateFrom), so a
// truthiness check on it is exact, not a heuristic - a legacy 0 unambiguously means "never".
pkt.has_rx_time = (header && header->last_heard != 0);
pkt.id = makeReplayPacketId(num, pkt.rx_time, meshtastic_Telemetry_environment_metrics_tag);
pkt.channel = header ? header->channel : 0;
pkt.rx_snr = header ? header->snr : 0;
Expand Down Expand Up @@ -1456,6 +1468,10 @@ meshtastic_MeshPacket PhoneAPI::makeReplayStatusPacket(uint32_t num, const mesht
// StatusMessage has no native timestamp; use last_heard.
const meshtastic_NodeInfoLite *header = nodeDB->getMeshNode(num);
pkt.rx_time = header ? header->last_heard : 0;
// rx_time has explicit presence; last_heard has no presence bit of its own, but it is only
// ever written from a genuine has_rx_time-gated reception (see NodeDB::updateFrom), so a
// truthiness check on it is exact, not a heuristic - a legacy 0 unambiguously means "never".
pkt.has_rx_time = (header && header->last_heard != 0);
pkt.id = makeReplayPacketId(num, pkt.rx_time, meshtastic_PortNum_NODE_STATUS_APP);
pkt.channel = header ? header->channel : 0;
pkt.rx_snr = header ? header->snr : 0;
Expand Down
2 changes: 1 addition & 1 deletion src/mesh/RadioInterface.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -877,7 +877,7 @@ void printPacket(const char *prefix, const meshtastic_MeshPacket *p)
out += DEBUG_PORT.mt_sprintf(" len=%d", p->encrypted.size + sizeof(PacketHeader));
}

if (p->rx_time != 0)
if (p->has_rx_time) // rx_time has explicit presence; a millis() placeholder isn't a real reading to print
out += DEBUG_PORT.mt_sprintf(" rxtime=%u", p->rx_time);
if (p->rx_snr != 0.0)
out += DEBUG_PORT.mt_sprintf(" rxSNR=%g", p->rx_snr);
Expand Down
45 changes: 38 additions & 7 deletions src/mesh/Router.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,19 @@ PacketId generatePacketId()
return id;
}

RxTimeStamp computeRxTimeStamp()
{
const bool haveTime = getRTCQuality() >= RTCQualityFromNet;
return {haveTime ? getValidTime(RTCQualityFromNet) : Time::getMillis(), haveTime};
}

void stampRxTime(meshtastic_MeshPacket *p)
{
const RxTimeStamp ts = computeRxTimeStamp();
p->rx_time = ts.time;
p->has_rx_time = ts.valid;
}

meshtastic_MeshPacket *Router::allocForSending()
{
meshtastic_MeshPacket *p = packetPool.allocZeroed();
Expand All @@ -280,8 +293,10 @@ meshtastic_MeshPacket *Router::allocForSending()
p->to = NODENUM_BROADCAST;
p->hop_limit = Default::getConfiguredOrDefaultHopLimit(config.lora.hop_limit);
p->id = generatePacketId();
p->rx_time =
getValidTime(RTCQualityFromNet); // Just in case we process the packet locally - make sure it has a valid timestamp
// Just in case we process the packet locally - make sure it has a timestamp. rx_time has
// explicit presence (see dispatchReceived): fall back to a Time::getMillis() placeholder,
// not a fabricated real-looking value, when we don't have a trustworthy wall clock yet.
stampRxTime(p);

return p;
}
Expand Down Expand Up @@ -1307,10 +1322,21 @@ void Router::dispatchReceived(meshtastic_MeshPacket *p, RxSource src)

// Also, we should set the time from the ISR and it should have msec level resolution.
// Keep the decoded working packet and encrypted MQTT copy on the same local arrival timestamp.
const uint32_t rxTime = getValidTime(RTCQualityFromNet);
p->rx_time = rxTime;
if (p_encrypted)
p_encrypted->rx_time = rxTime;
//
// rx_time has explicit presence. When we don't yet have a trustworthy wall clock (no GPS,
// and the phone hasn't connected/handed us net time yet), stash Time::getMillis() as a
// placeholder instead of a fabricated real-looking value - has_rx_time=false marks it as not
// yet known. MeshService::reconcilePendingRxTimes() rewrites any such placeholder still
// sitting in toPhoneQueue into a real epoch, backdated by elapsed uptime, the moment the
// clock becomes trustworthy. Any other reader of rx_time must check has_rx_time first - the
// raw value is meaningless (a monotonic snapshot, not a wall-clock reading) while it's false.
const RxTimeStamp rxStamp = computeRxTimeStamp();
p->rx_time = rxStamp.time;
p->has_rx_time = rxStamp.valid;
if (p_encrypted) {
p_encrypted->rx_time = rxStamp.time;
p_encrypted->has_rx_time = rxStamp.valid;
}

// Take those raw bytes and convert them back into a well structured protobuf we can understand
auto decodedState = perhapsDecode(p);
Expand Down Expand Up @@ -1443,7 +1469,12 @@ void Router::perhapsHandleReceived(meshtastic_MeshPacket *p)
#if ARCH_PORTDUINO
// Even ignored packets get logged in the trace
if (portduino_config.traceFilename != "" || portduino_config.logoutputlevel == level_trace) {
p->rx_time = getValidTime(RTCQualityFromNet); // store the arrival timestamp for the phone
// store the arrival timestamp for the phone. rx_time has explicit presence: store a
// Time::getMillis() placeholder, not a literal 0, when the wall clock isn't trustworthy
// yet - this packet continues on through the rest of receive processing after the trace
// dump below, so a bare 0 here would carry the same reconcilePendingRxTimes() risk
// forward as every other rx_time write site.
stampRxTime(p);
LOG_TRACE("%s", MeshPacketSerializer::JsonSerializeEncrypted(p).c_str());
}
#endif
Expand Down
Loading
Loading