From 169186e05c467e2d9c59c3ddab5a9673d479fc51 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 09:33:45 -0600 Subject: [PATCH] feat: runtime-tune mesh clock batch, quorum and windows Sparse meshes may never fill the default 33-source batch, so the clock never steps. Add two persisted, explicitly paired commands: `clock mesh slots ` (batch size 3..33, quorum 2..slots) and `clock mesh tolerance ` (inlier window 1..65535, deadband 0..65535). No derived values: every figure must be sent, and a bad pair is rejected whole. Changing a setting drops the in-flight batch. /meshclock record is now v2 (10 bytes: enabled flag + the four knobs + CRC-16). v1 records (enabled flag only, as shipped) are still read: the flag carries, the knobs take the compile-time defaults, and the v1 bytes are kept as the backup of the migration save. Defaults are unchanged (33/22/60/60); the compile-time MESHCLOCK_SLOTS remains the upper bound. The status line now shows the configured knobs (slots=/ tol=/) in both states. Refs #12 --- MESHCLOCK.md | 70 +++- examples/simple_repeater/BatteryGate.cpp | 6 +- examples/simple_repeater/CliUtil.h | 11 + examples/simple_repeater/MeshClockSync.cpp | 237 ++++++++++++-- examples/simple_repeater/MeshClockSync.h | 51 ++- .../simple_repeater/MeshClockSyncConfig.h | 25 +- test/test_mesh_clock/test_mesh_clock.cpp | 305 +++++++++++++++++- 7 files changed, 628 insertions(+), 77 deletions(-) diff --git a/MESHCLOCK.md b/MESHCLOCK.md index e80905da..317af65d 100644 --- a/MESHCLOCK.md +++ b/MESHCLOCK.md @@ -25,7 +25,7 @@ an older timestamp is rejected and never enters the batch. The comparison is wrap-safe. The compiler supplies local build time, so sites whose build host uses a non-UTC timezone may conservatively reject some otherwise-current adverts. -When mesh clock sync is **on**, each distinct source contributes **one vote** per batch. +When mesh clock sync is **on**, each distinct source contributes **one vote** per batch (up to the configured batch size, default 33). When the batch fills, the repeater takes the **median** of the sources' predicted "now" and counts how many sources agree with it: @@ -61,15 +61,38 @@ collected over hours and its samples still cluster within seconds. | Command | Effect | |---|---| -| `clock mesh` | Status: `off now=`, or `on samples=/ last= now=` | +| `clock mesh` | Status: `off slots=/ tol=/ now=`, or `on samples=/ last= slots=/ tol=/ now=` | | `clock mesh on` | Enable | | `clock mesh off` | Disable | +| `clock mesh slots ` | Set the batch size and the quorum — both values are required and applied as a pair; persists | +| `clock mesh tolerance ` | Set the inlier window and the deadband — both values are required and applied as a pair; persists | + +`slots` is the distinct-sources-per-batch figure the batch fills at (the +compile-time `MESHCLOCK_SLOTS`, 33, is both the shipped default and the upper +bound; the valid runtime range is `3..33`). `min-agree` is the agreeing sources +the batch needs before the RTC is stepped (`2..slots`). `tolerance` is how +close a source must be to the median to count as an inlier (`1..65535` +seconds — zero is refused: it would deadlock consensus outright). `min-diff` +is the deadband: a median this close to the node's clock is left alone +(`0..65535` seconds; zero means the clock always steps). Both pairs are +validated independently: a bad pair is rejected as a whole, nothing is +applied, and the batch already in flight is dropped when a setting changes — +samples gathered under old rules never decide under new ones. An even `slots` +value is allowed; the median is then the upper-middle value. + +``` +> clock mesh slots 9 6 +OK - mesh clock slots 9/6 + +> clock mesh tolerance 300 120 +OK - mesh clock tolerance 300/120 +``` Like the other fork CLIs (`filter`, `battery`, `fleet`), the command is refused whole — nothing is enabled or disabled — when it is too long for the CLI's buffer (`Err - command too long`) or carries an odd number of double quotes (`Err - unbalanced quotes`); an unexpected extra word answers -`Err - clock mesh takes on|off`. +`Err - clock mesh takes on|off|slots|tolerance`. The status `last=` field is one of: @@ -91,40 +114,53 @@ even while sync is off. ``` > clock mesh -off now=2026-11-01T14:02:00Z +off slots=33/22 tol=60/60 now=2026-11-01T14:02:00Z > clock mesh on OK - mesh clock sync on > clock mesh -on samples=12/33 last=idle now=2026-11-01T14:05:00Z +on samples=12/33 last=idle slots=33/22 tol=60/60 now=2026-11-01T14:05:00Z + +> clock mesh slots 15 10 +OK - mesh clock slots 15/10 -# later, once a batch of 33 distinct sources has agreed > clock mesh -on samples=0/33 last=set(+31536000s) now=2027-11-01T14:05:00Z +on samples=12/15 last=idle slots=15/10 tol=60/60 now=2026-11-01T14:06:00Z + +# later, once a batch of sources has agreed +> clock mesh +on samples=0/15 last=set(+31536000s) slots=15/10 tol=60/60 now=2027-11-01T14:05:00Z ``` ## Persistence -Only the enabled flag persists, in **`/meshclock`** (4 bytes, CRC-checked). The -batch, the last result and its delta are RAM-only: a reboot always starts a fresh, -empty batch. A `clock mesh` command is written to flash about **3 seconds** later, -staged the same way as the other configs (scratch file, read back and checked, -previous config kept as a backup, then swapped in). +The enabled flag and the four tuning knobs persist, in **`/meshclock`** (10 +bytes, CRC-checked). The batch, the last result and its delta are RAM-only: a +reboot always starts a fresh, empty batch. A `clock mesh` command is written to +flash about **3 seconds** later, staged the same way as the other configs +(scratch file, read back and checked, previous config kept as a backup, then +swapped in). Records written by the original format (v1: the enabled flag +only) are still read — the flag carries over, the knobs take the defaults +above, and the v1 bytes are kept as the backup of the migration save. ## Defaults | Setting | Default | Meaning | |---|---|---| -| `MESHCLOCK_SLOTS` | 33 | distinct sources held per batch (= the quorum size) | +| `MESHCLOCK_SLOTS` | 33 | distinct sources held per batch (= the quorum size); also the runtime upper bound | | `MESHCLOCK_MIN_AGREE` | 22 | agreeing sources required to step the clock | | `MESHCLOCK_TOLERANCE_SECS` | 60 | how close a source must be to the median to agree | | `MESHCLOCK_MIN_DIFF_SECS` | 60 | below this difference the clock is left alone | -Sparse meshes may take a long time to hear 33 distinct sources; the feature then -simply never acts, which is the safe failure mode. Sites can override -`MESHCLOCK_SLOTS` and `MESHCLOCK_MIN_AGREE` at build time to shrink the batch and -quorum. The estimator uses the batch's middle value, so an odd capacity is +The defaults are also the compile-time fallback; `MESHCLOCK_SLOTS` doubles as +the runtime upper bound (the sample array is sized for it). Sites can override +them at build time (e.g. in `platformio.local.ini`), or — without rebuilding — +set them at runtime with `clock mesh slots` and `clock mesh tolerance`; the +runtime values persist. Sparse meshes may never hear 33 distinct sources: lower +the batch and quorum to fit what the mesh actually hears (e.g. `clock mesh +slots 9 6`), and set a wider tolerance if adverts' clocks wobble by more than +60 s. The estimator uses the batch's middle value, so an odd `slots` is recommended. ## Limits diff --git a/examples/simple_repeater/BatteryGate.cpp b/examples/simple_repeater/BatteryGate.cpp index 0504684a..dd46445f 100644 --- a/examples/simple_repeater/BatteryGate.cpp +++ b/examples/simple_repeater/BatteryGate.cpp @@ -192,11 +192,7 @@ static bool parseMilliVolts(const char* tok, uint16_t* out) { // why a millivolt token was refused: all digits but out of range, or not a // number at all (which is a usage mistake, not a value mistake) static void badMilliVolts(const char* tok, char* reply) { - bool numeric = (tok != NULL && tok[0] != 0); - for (const char* q = tok; numeric && *q; q++) { - if (*q < '0' || *q > '9') numeric = false; - } - if (numeric) { + if (allDigits(tok)) { snprintf(reply, CLI_REPLY_MAX, "Err - millivolts must be %d..%d", BATT_MV_MIN, BATT_MV_MAX); } else { snprintf(reply, CLI_REPLY_MAX, "%s", BATT_USAGE); diff --git a/examples/simple_repeater/CliUtil.h b/examples/simple_repeater/CliUtil.h index 04568ef1..362ca35b 100644 --- a/examples/simple_repeater/CliUtil.h +++ b/examples/simple_repeater/CliUtil.h @@ -365,6 +365,17 @@ inline void parseGroupText(const uint8_t* data, size_t len, char* sender, size_t text[cpy] = 0; } +// Is a token entirely ASCII digits (and not empty)? Used alongside +// parseIntRange to tell "digits but out of range" (a value mistake) apart from +// "not a number" (a usage mistake) so the error can say which it was. +inline bool allDigits(const char* tok) { + if (tok == NULL || tok[0] == 0) return false; + for (const char* q = tok; *q; q++) { + if (*q < '0' || *q > '9') return false; + } + return true; +} + // Parse a decimal token that must be entirely a number in [lo, hi]: a trailing // byte ("12x", "0x10"), an empty token and an out-of-range value are all // refused. Callers keep their own error wording, which is why this only diff --git a/examples/simple_repeater/MeshClockSync.cpp b/examples/simple_repeater/MeshClockSync.cpp index 1889f6ff..08af9ef3 100644 --- a/examples/simple_repeater/MeshClockSync.cpp +++ b/examples/simple_repeater/MeshClockSync.cpp @@ -27,12 +27,34 @@ MeshClockSync::MeshClockSync() { reset(); } -// The state a fresh node starts in: disabled, empty batch, no decision yet. One -// definition, so construction and reload cannot drift apart. +// The knob pair must satisfy the same rule the compile-time defaults do: +// quorum within [2, slots], batch size within the array the samples are sized +// for. One definition, shared by the setters, the CLI and the loader, so a +// value no route can produce is a value no route can apply. +static bool validSlots(uint8_t slots, uint8_t min_agree) { + if (slots < MESHCLOCK_SLOTS_MIN || slots > MESHCLOCK_SLOTS) return false; + if (min_agree < 2 || min_agree > slots) return false; + return true; +} + +// Zero tolerance would deadlock consensus outright (no advert ever lands +// within zero seconds of another), so it is the one value refused; the +// deadband has no such floor — 0 means the clock always steps. +static bool validTolerance(uint16_t tolerance) { + return tolerance >= 1; +} + +// The state a fresh node starts in: disabled, empty batch, no decision yet, +// knobs at the compile-time defaults. One definition, so construction and +// reload cannot drift apart. void MeshClockSync::reset() { memset(samples, 0, sizeof(samples)); count = 0; enabled = false; + slots = MESHCLOCK_SLOTS; + min_agree = MESHCLOCK_MIN_AGREE; + tolerance = MESHCLOCK_TOLERANCE_SECS; + min_diff = MESHCLOCK_MIN_DIFF_SECS; last_result = IDLE; last_delta = 0; save_flag.reset(); // a reset supersedes any edit still waiting to be written @@ -58,11 +80,31 @@ void MeshClockSync::setEnabled(bool on) { markDirty(); } +bool MeshClockSync::setSlots(uint8_t new_slots, uint8_t new_min_agree) { + if (!validSlots(new_slots, new_min_agree)) return false; + if (slots == new_slots && min_agree == new_min_agree) return true; // no-op: no dirty write + slots = new_slots; + min_agree = new_min_agree; + clear(); // samples gathered under the old quorum must not decide under the new one + markDirty(); + return true; +} + +bool MeshClockSync::setTolerance(uint16_t new_tolerance, uint16_t new_min_diff) { + if (!validTolerance(new_tolerance)) return false; + if (tolerance == new_tolerance && min_diff == new_min_diff) return true; // no-op + tolerance = new_tolerance; + min_diff = new_min_diff; + clear(); // samples gathered under the old window must not decide under the new one + markDirty(); + return true; +} + // ---------------------------------------------------------------- collection bool MeshClockSync::hasSource(const uint8_t* fp) const { - // linear scan: count <= MESHCLOCK_SLOTS, so it is cheaper than any index and - // needs no extra state + // linear scan: count <= slots (<= MESHCLOCK_SLOTS), so it is cheaper than any + // index and needs no extra state for (int i = 0; i < count; i++) { if (memcmp(samples[i].fp, fp, 4) == 0) return true; } @@ -83,7 +125,7 @@ void MeshClockSync::onAdvert(uint32_t advert_ts, const uint8_t* pub_key, uint32_ samples[count].offset = advert_ts - local_now; // uint32 wrap count++; - if (count == MESHCLOCK_SLOTS) evaluate(local_now); + if (count == slots) evaluate(local_now); } // ---------------------------------------------------------------- decision @@ -107,7 +149,7 @@ void MeshClockSync::evaluate(uint32_t local_now) { while (j >= 0 && sorted[j] > v) { sorted[j + 1] = sorted[j]; j--; } sorted[j + 1] = v; } - const uint32_t median = sorted[count / 2]; // odd batch: the single middle value + const uint32_t median = sorted[count / 2]; // odd batch: the middle value; even: the upper-middle // defensive floor check on the result if ((int32_t)(median - buildFloor()) < 0) { @@ -121,20 +163,20 @@ void MeshClockSync::evaluate(uint32_t local_now) { int inliers = 0; for (int i = 0; i < count; i++) { const uint32_t d = cand[i] > median ? cand[i] - median : median - cand[i]; - if (d <= MESHCLOCK_TOLERANCE_SECS) inliers++; + if (d <= tolerance) inliers++; } - if (inliers < MESHCLOCK_MIN_AGREE) { + if (inliers < min_agree) { last_result = NO_CONSENSUS; clear(); return; } - // deadband vs the node's own clock: a difference of MESHCLOCK_MIN_DIFF_SECS - // or less is in sync (the knob is the minimum difference that counts as out - // of sync, and MESHCLOCK.md says "within 60 s") + // deadband vs the node's own clock: a difference of min_diff or less is in + // sync (the knob is the minimum difference that counts as out of sync, and + // MESHCLOCK.md says "within 60 s" for the default) const uint32_t d = median > local_now ? median - local_now : local_now - median; last_delta = (int32_t)(median - local_now); // exact within ±68 years - if (d <= MESHCLOCK_MIN_DIFF_SECS) { + if (d <= min_diff) { last_result = IN_SYNC; clear(); return; @@ -153,20 +195,43 @@ void MeshClockSync::evaluate(uint32_t local_now) { // ---------------------------------------------------------------- persistence -// Format-level validity of a record: version, an enabled flag of 0/1, and the -// CRC. Shared by the file validator, the staged-save writeback check and load(), -// so no route can admit a record another refuses. +// Format-level validity of a v2 record: version, an enabled flag of 0/1, the +// shared knob rules and the CRC. Shared by the file validator, the staged-save +// writeback check and load(), so no route can admit a record another refuses. static bool clockRecordValid(const MeshClockCfg& rec) { if (rec.version != MESHCLOCK_CFG_VERSION) return false; if (rec.enabled > 1) return false; + if (!validSlots(rec.slots, rec.min_agree)) return false; + if (!validTolerance(rec.tolerance)) return false; return rec.crc == crc16_ccitt((const uint8_t*)&rec, offsetof(MeshClockCfg, crc)); } +// A v1 record (enabled flag only, no knobs): the format the feature shipped +// with. Still read as a last-resort source by load() — the flag carries, the +// knobs take the compile-time defaults, and the next save writes v2 — so a +// config written by the shipped firmware is never lost. +struct MeshClockCfgV1 { + uint8_t version; // 1 + uint8_t enabled; // 0/1 + uint16_t crc; // crc16_ccitt over the version + enabled bytes +}; +static_assert(sizeof(MeshClockCfgV1) == 4, "clock v1 record must stay 4 bytes"); + +static bool clockRecordValidV1(const MeshClockCfgV1& rec) { + if (rec.version != 1) return false; + if (rec.enabled > 1) return false; + return rec.crc == crc16_ccitt((const uint8_t*)&rec, offsetof(MeshClockCfgV1, crc)); +} + static bool clockWriteFile(File& f, void* ctx) { const MeshClockSync& c = *(const MeshClockSync*)ctx; MeshClockCfg rec; rec.version = MESHCLOCK_CFG_VERSION; rec.enabled = c.isEnabled() ? 1 : 0; + rec.slots = (uint8_t)c.getSlots(); + rec.min_agree = (uint8_t)c.getMinAgree(); + rec.tolerance = (uint16_t)c.getToleranceSecs(); + rec.min_diff = (uint16_t)c.getMinDiffSecs(); rec.crc = crc16_ccitt((const uint8_t*)&rec, offsetof(MeshClockCfg, crc)); return f.write((const uint8_t*)&rec, sizeof(rec)) == sizeof(rec); } @@ -180,11 +245,45 @@ static bool clockValidateFile(File& f, void* ctx) { return clockRecordValid(rec); } +static bool clockValidateFileV1(File& f, void* ctx) { + (void)ctx; + MeshClockCfgV1 rec; + if (f.read((uint8_t*)&rec, sizeof(rec)) != sizeof(rec)) return false; + uint8_t extra; + if (f.read(&extra, 1) != 0) return false; // record must be exactly sizeof(rec) + return clockRecordValidV1(rec); +} + +// usableFn for the staged save's canonical check only: accepts any format +// this firmware can load (v1 or v2), so a pre-v2 config is kept as the +// backup of the migration save rather than discarded for being old. The +// readback check for what this firmware writes stays strict (clockValidateFile). +static bool clockValidateFileAnyFormat(File& f, void* ctx) { + (void)ctx; + uint8_t ver; + if (f.read(&ver, 1) != 1) return false; + if (ver != 1 && ver != MESHCLOCK_CFG_VERSION) return false; + if (ver == 1) { + MeshClockCfgV1 rec; + rec.version = ver; + if (f.read(((uint8_t*)&rec) + 1, sizeof(rec) - 1) != sizeof(rec) - 1) return false; + uint8_t extra; + if (f.read(&extra, 1) != 0) return false; + return clockRecordValidV1(rec); + } + MeshClockCfg rec; + rec.version = ver; + if (f.read(((uint8_t*)&rec) + 1, sizeof(rec) - 1) != sizeof(rec) - 1) return false; + uint8_t extra; + if (f.read(&extra, 1) != 0) return false; + return clockRecordValid(rec); +} + void MeshClockSync::save(FILESYSTEM* fs) { // Staged save: scratch file, read back, keep the previous good file as a // backup, then promote — the same transaction every persisted config here uses. bool ok = saveStaged(fs, MESHCLOCK_CFG_FILE, clockWriteFile, this, - clockValidateFile, NULL, clockValidateFile, NULL); + clockValidateFile, NULL, clockValidateFileAnyFormat, NULL); if (ok) save_flag.clear(); else save_flag.retryLater(); } @@ -195,31 +294,56 @@ void MeshClockSync::load(FILESYSTEM* fs) { char path[64]; PersistLoadSource src = chooseConfigToLoad(fs, MESHCLOCK_CFG_FILE, clockValidateFile, NULL, path, sizeof(path)); + if (src != PERSIST_LOAD_NONE) { + File file = fsOpenRead(fs, path); + if (!file) return; + + MeshClockCfg rec; + const bool ok = file.read((uint8_t*)&rec, sizeof(rec)) == sizeof(rec); + file.close(); + if (!ok) return; + if (!clockRecordValid(rec)) return; // chooseConfigToLoad validated it; re-verify anyway + + enabled = (rec.enabled == 1); + slots = rec.slots; + min_agree = rec.min_agree; + tolerance = rec.tolerance; + min_diff = rec.min_diff; + + // Loaded from the backup, so put a good canonical file back at the next + // opportunity; the backup stays valid meanwhile. + if (src == PERSIST_LOAD_RECOVERED) markDirty(); + return; + } + + // No usable v2 record anywhere: migrate a v1 one if it exists (the format + // the feature shipped with). The enabled flag carries; the knobs take the + // compile-time defaults (reset() above), and the v1 bytes stay as the + // backup of the migrated save. + src = chooseConfigToLoad(fs, MESHCLOCK_CFG_FILE, clockValidateFileV1, NULL, + path, sizeof(path)); if (src == PERSIST_LOAD_NONE) return; // nothing usable: keep the defaults File file = fsOpenRead(fs, path); if (!file) return; - MeshClockCfg rec; + MeshClockCfgV1 rec; const bool ok = file.read((uint8_t*)&rec, sizeof(rec)) == sizeof(rec); file.close(); if (!ok) return; - if (!clockRecordValid(rec)) return; // chooseConfigToLoad validated it; re-verify anyway + if (!clockRecordValidV1(rec)) return; // re-verify anyway enabled = (rec.enabled == 1); - - // Loaded from the backup, so put a good canonical file back at the next - // opportunity; the backup stays valid meanwhile. - if (src == PERSIST_LOAD_RECOVERED) markDirty(); + markDirty(); // nothing was read into the knobs: reset() holds the defaults } // ---------------------------------------------------------------- CLI -#define MESHCLOCK_USAGE "Err - clock mesh takes on|off" +#define MESHCLOCK_USAGE "Err - clock mesh takes on|off|slots|tolerance" static void clockStatus(MeshClockSync& c, const char* now, char* reply) { CliBuf buf(reply, CLI_REPLY_MAX); if (c.isEnabled()) { - buf.add("on samples=%d/%d last=", c.getSampleCount(), MESHCLOCK_SLOTS); + buf.add("on samples=%d/%d last=", c.getSampleCount(), c.getSlots()); switch (c.getLastResult()) { case MeshClockSync::SET_CLOCK: buf.add("set(%+lds)", (long)c.getLastDeltaSecs()); @@ -240,9 +364,10 @@ static void clockStatus(MeshClockSync& c, const char* now, char* reply) { } else { buf.addStr("off"); } - // One append point: the time shows in both states and cannot drift between - // them. - buf.add(" now=%s", now); + // One append point: the time and the configured knobs show in both states + // and cannot drift between them. + buf.add(" slots=%d/%d tol=%d/%d now=%s", c.getSlots(), c.getMinAgree(), + c.getToleranceSecs(), c.getMinDiffSecs(), now); } void meshClockCLI(MeshClockSync& clock, const char* now, const char* command, char* reply) { @@ -264,6 +389,64 @@ void meshClockCLI(MeshClockSync& clock, const char* now, const char* command, ch if (!cliNoExtra(p, reply, MESHCLOCK_USAGE)) return; clock.setEnabled(false); strcpy(reply, "OK - mesh clock sync off"); + } else if (strcmp(cmd, "slots") == 0) { + // `clock mesh slots `: both values required, applied as + // a pair or not at all + char* tok = nextToken(&p); + long s; + if (!parseIntRange(tok, MESHCLOCK_SLOTS_MIN, MESHCLOCK_SLOTS, &s)) { + if (allDigits(tok)) { + snprintf(reply, CLI_REPLY_MAX, "Err - slots must be %d..%d", + MESHCLOCK_SLOTS_MIN, MESHCLOCK_SLOTS); + } else { + strcpy(reply, MESHCLOCK_USAGE); + } + return; + } + tok = nextToken(&p); + long a; + if (!parseIntRange(tok, 2, s, &a)) { + if (allDigits(tok)) { + snprintf(reply, CLI_REPLY_MAX, "Err - min-agree must be 2..%ld", s); + } else { + strcpy(reply, MESHCLOCK_USAGE); + } + return; + } + if (!cliNoExtra(p, reply, MESHCLOCK_USAGE)) return; + if (!clock.setSlots((uint8_t)s, (uint8_t)a)) { // prevalidated above; never claim applied + snprintf(reply, CLI_REPLY_MAX, "Err - min-agree must be 2..%ld", s); + return; + } + snprintf(reply, CLI_REPLY_MAX, "OK - mesh clock slots %ld/%ld", s, a); + } else if (strcmp(cmd, "tolerance") == 0) { + // `clock mesh tolerance `: both values required + char* tok = nextToken(&p); + long t; + if (!parseIntRange(tok, 1, 65535, &t)) { + if (allDigits(tok)) { + strcpy(reply, "Err - tolerance must be 1..65535 seconds"); + } else { + strcpy(reply, MESHCLOCK_USAGE); + } + return; + } + tok = nextToken(&p); + long d; + if (!parseIntRange(tok, 0, 65535, &d)) { + if (allDigits(tok)) { + strcpy(reply, "Err - min-diff must be 0..65535 seconds"); + } else { + strcpy(reply, MESHCLOCK_USAGE); + } + return; + } + if (!cliNoExtra(p, reply, MESHCLOCK_USAGE)) return; + if (!clock.setTolerance((uint16_t)t, (uint16_t)d)) { // prevalidated above; never claim applied + strcpy(reply, "Err - tolerance must be 1..65535 seconds"); + return; + } + snprintf(reply, CLI_REPLY_MAX, "OK - mesh clock tolerance %ld/%ld", t, d); } else { strcpy(reply, MESHCLOCK_USAGE); } diff --git a/examples/simple_repeater/MeshClockSync.h b/examples/simple_repeater/MeshClockSync.h index 798b8e04..74456df9 100644 --- a/examples/simple_repeater/MeshClockSync.h +++ b/examples/simple_repeater/MeshClockSync.h @@ -10,12 +10,18 @@ // batch (a 4-byte fingerprint of its advert key); when the batch fills, the // batch's median predicted "now" is taken, and if enough sources agree it steps // the RTC once and clears. The batch, the last result and its delta are -// RAM-only: a reboot starts an empty batch. Only the enabled flag persists, in -// /meshclock. The feature shares no state with AdvertRateLimiter or the filter, -// so it can be deleted cleanly if upstream ever adds its own clock feature. +// RAM-only: a reboot starts an empty batch. The enabled flag and the tuning +// knobs persist, in /meshclock. The feature shares no state with +// AdvertRateLimiter or the filter, so it can be deleted cleanly if upstream +// ever adds its own clock feature. // -// CLI: "clock mesh on|off" and a bare "clock mesh" status (with the node's -// current UTC time), handled by meshClockCLI() (see MeshClockSync.cpp). +// CLI: "clock mesh on|off", "clock mesh slots ", +// "clock mesh tolerance ", and a bare "clock mesh" +// status (with the node's current UTC time), handled by meshClockCLI() (see +// MeshClockSync.cpp). `clock mesh slots` sets the batch size and quorum (the +// compile-time MESHCLOCK_SLOTS is the shipped default and the upper bound — +// the sample array is sized for it). Both commands take both values — nothing +// is derived — and are rejected whole on a bad pair. #ifndef _MESH_CLOCK_SYNC_H #define _MESH_CLOCK_SYNC_H @@ -37,16 +43,21 @@ struct MeshClockSample { }; static_assert(sizeof(MeshClockSample) == 8, "clock sample must stay 8 bytes"); -// Persisted /meshclock record: the enabled flag plus a CRC-16 over it. A torn -// write of exactly the right length is otherwise undetectable on a record this -// small, and the CRC rides v1 from day one (no older format to stay compatible -// with). +// Persisted /meshclock record: the enabled flag plus the runtime tuning knobs +// and a CRC-16 over them. A torn write of exactly the right length is otherwise +// undetectable on a record this small. v1 records (enabled flag only) are still +// accepted by load() and migrated forward: the flag carries and the knobs take +// the compile-time defaults. struct MeshClockCfg { uint8_t version; // MESHCLOCK_CFG_VERSION uint8_t enabled; // 0/1 - uint16_t crc; // crc16_ccitt over the version + enabled bytes + uint8_t slots; // runtime batch capacity + uint8_t min_agree; // agreeing sources required to step the clock + uint16_t tolerance; // seconds an inlier may sit from the median + uint16_t min_diff; // seconds: closer than this to the node clock is "in sync" + uint16_t crc; // crc16_ccitt over the preceding bytes }; -static_assert(sizeof(MeshClockCfg) == 4, "clock config must stay 4 bytes"); +static_assert(sizeof(MeshClockCfg) == 10, "clock config must stay 10 bytes"); class MeshClockSync { public: @@ -65,6 +76,14 @@ public: bool isEnabled() const { return enabled; } void setEnabled(bool on); // persists; clears the batch on change + // Runtime tuning, persisted like the enabled flag. Both values must be sent + // and are validated as a pair; on any change the batch is dropped (like + // setEnabled), so samples gathered under old rules never decide under new + // ones. Tolerance is the inlier window, min_diff the deadband. Return false + // (nothing applied) on bad values. + bool setSlots(uint8_t slots, uint8_t min_agree); + bool setTolerance(uint16_t tolerance, uint16_t min_diff); + // Feed one signature-verified advert (the core verifies the signature before // MyMesh::onAdvertRecv). advert_ts is the signed timestamp, pub_key the // PUB_KEY_SIZE origin key, local_now this node's RTC now. @@ -78,15 +97,25 @@ public: int getSampleCount() const { return count; } Result getLastResult() const { return last_result; } int32_t getLastDeltaSecs() const { return last_delta; } // signed for display + int getSlots() const { return slots; } + int getMinAgree() const { return min_agree; } + int getToleranceSecs() const { return tolerance; } + int getMinDiffSecs() const { return min_diff; } // Lower plausibility bound for an advert timestamp: this firmware's build // epoch. Adverts dated earlier are refused. Exposed for the boundary test. static uint32_t buildFloor(); private: + // sized for the compile-time maximum; the runtime `slots` caps how much of + // it is used MeshClockSample samples[MESHCLOCK_SLOTS]; int count; bool enabled; + uint8_t slots; // runtime batch capacity (<= MESHCLOCK_SLOTS) + uint8_t min_agree; // runtime quorum + uint16_t tolerance; // runtime inlier window, seconds + uint16_t min_diff; // runtime deadband, seconds Result last_result; int32_t last_delta; LazySave save_flag; // needs save, written back by loop() diff --git a/examples/simple_repeater/MeshClockSyncConfig.h b/examples/simple_repeater/MeshClockSyncConfig.h index 89c9ffac..e1d27e60 100644 --- a/examples/simple_repeater/MeshClockSyncConfig.h +++ b/examples/simple_repeater/MeshClockSyncConfig.h @@ -8,38 +8,49 @@ // distinct sources held per batch. This is also the quorum size: the batch // fills, decides once, then clears, so there is no separate time window or -// second threshold. 33 is odd, so the median is the single middle value; a site -// with a sparser mesh can shrink both this and the quorum below. +// second threshold. This is both the shipped default and the compile-time +// upper bound the sample array is sized for; at runtime it can be lowered +// (with the quorum below) via `clock mesh slots` — see MESHCLOCK.md. +// 33 is odd, so the median is the single middle value. #ifndef MESHCLOCK_SLOTS #define MESHCLOCK_SLOTS 33 #endif // a candidate counts as agreeing with the median when it is within this many -// seconds of it +// seconds of it (default; runtime-tunable via `clock mesh tolerance`) #ifndef MESHCLOCK_TOLERANCE_SECS #define MESHCLOCK_TOLERANCE_SECS 60 #endif // agreeing sources required before the clock is stepped: two thirds of the -// default batch. Sites overriding MESHCLOCK_SLOTS should override this to keep -// their desired quorum fraction. +// default batch. This is the shipped default; `clock mesh slots` sets it at +// runtime together with the batch size. #ifndef MESHCLOCK_MIN_AGREE #define MESHCLOCK_MIN_AGREE 22 #endif // deadband: a median closer than this to the node's own clock is "close // enough", so the RTC is left alone and the batch reports in-sync +// (default; runtime-tunable via `clock mesh tolerance`) #ifndef MESHCLOCK_MIN_DIFF_SECS #define MESHCLOCK_MIN_DIFF_SECS 60 #endif -// persisted enabled flag (see MeshClockSync.cpp for the record) +// persisted config (see MeshClockSync.cpp for the record): v2 carries the +// enabled flag plus the runtime batch-size/quorum and tolerance/deadband knobs #ifndef MESHCLOCK_CFG_FILE #define MESHCLOCK_CFG_FILE "/meshclock" #endif -#define MESHCLOCK_CFG_VERSION 1 +#define MESHCLOCK_CFG_VERSION 2 + +// hard floor for the runtime batch size (`clock mesh slots`); a smaller batch +// has no median worth taking. Not a tunable — a range bound the CLI and the +// loader both enforce. +#define MESHCLOCK_SLOTS_MIN 3 static_assert(MESHCLOCK_MIN_AGREE >= 2 && MESHCLOCK_MIN_AGREE <= MESHCLOCK_SLOTS, "MESHCLOCK_MIN_AGREE must be within the batch"); +static_assert(MESHCLOCK_SLOTS_MIN >= 2 && MESHCLOCK_SLOTS_MIN <= MESHCLOCK_SLOTS, + "MESHCLOCK_SLOTS_MIN must be within the batch"); #endif // _MESH_CLOCK_SYNC_CONFIG_H diff --git a/test/test_mesh_clock/test_mesh_clock.cpp b/test/test_mesh_clock/test_mesh_clock.cpp index 53482245..2d52b02a 100644 --- a/test/test_mesh_clock/test_mesh_clock.cpp +++ b/test/test_mesh_clock/test_mesh_clock.cpp @@ -5,6 +5,7 @@ #include #include +#include #include // g_mock_millis (NativeShim.h is force-included) #include @@ -39,6 +40,15 @@ static void feed(MeshClockSync& c, int id, uint32_t advert_ts, uint32_t local_no c.onAdvert(advert_ts, key, local_now); } +// Hand-craft a v1 /meshclock record (enabled flag only, as the shipped +// firmware wrote it). `path` lets a test place one at the backup path. +static void writeV1File(NativeFS& fs, uint8_t enabled, const char* path) { + std::vector rec = { 1, enabled, 0, 0 }; + uint16_t crc = crc16_ccitt(rec.data(), 2); + memcpy(&rec[2], &crc, 2); + fs.files[path] = rec; +} + // ------------------------------------------------------------------ fixture struct ClockTest : public ::testing::Test { @@ -130,7 +140,7 @@ TEST_F(ClockTest, SaveOnlyWhenDirtyAndDue) { TEST_F(ClockTest, CorruptedCrcRejected) { clock.setEnabled(true); flushSave(); - fs.files[MESHCLOCK_CFG_FILE][3] ^= 0x01; // CRC high byte + fs.files[MESHCLOCK_CFG_FILE][9] ^= 0x01; // CRC high byte MeshClockSync loaded; loaded.begin(&fs); EXPECT_FALSE(loaded.isEnabled()); @@ -152,8 +162,8 @@ TEST_F(ClockTest, BadEnabledFlagRejected) { // rejects the record rather than the checksum std::vector& rec = fs.files[MESHCLOCK_CFG_FILE]; rec[1] = 2; - uint16_t crc = crc16_ccitt(rec.data(), 2); - memcpy(&rec[2], &crc, 2); + uint16_t crc = crc16_ccitt(rec.data(), offsetof(MeshClockCfg, crc)); + memcpy(&rec[8], &crc, 2); MeshClockSync loaded; loaded.begin(&fs); EXPECT_FALSE(loaded.isEnabled()); @@ -162,7 +172,7 @@ TEST_F(ClockTest, BadEnabledFlagRejected) { TEST_F(ClockTest, TruncatedFileRejected) { clock.setEnabled(true); flushSave(); - fs.files[MESHCLOCK_CFG_FILE].resize(2); // short of the 4-byte record + fs.files[MESHCLOCK_CFG_FILE].resize(2); // short of the 10-byte record MeshClockSync loaded; loaded.begin(&fs); EXPECT_FALSE(loaded.isEnabled()); @@ -171,7 +181,7 @@ TEST_F(ClockTest, TruncatedFileRejected) { TEST_F(ClockTest, OverlongFileRejected) { clock.setEnabled(true); flushSave(); - fs.files[MESHCLOCK_CFG_FILE].push_back(0); // record must be exactly 4 bytes + fs.files[MESHCLOCK_CFG_FILE].push_back(0); // record must be exactly 10 bytes MeshClockSync loaded; loaded.begin(&fs); EXPECT_FALSE(loaded.isEnabled()); @@ -347,20 +357,20 @@ TEST_F(ClockTest, CliSurface) { char reply[CLI_REPLY_MAX]; meshClockCLI(clock, NOW_TEXT, "", reply); - EXPECT_STREQ(reply, "off now=2026-11-01T14:05:00Z"); + EXPECT_STREQ(reply, "off slots=33/22 tol=60/60 now=2026-11-01T14:05:00Z"); meshClockCLI(clock, NOW_TEXT, "on", reply); EXPECT_STREQ(reply, "OK - mesh clock sync on"); EXPECT_TRUE(clock.isEnabled()); meshClockCLI(clock, NOW_TEXT, "", reply); - EXPECT_STREQ(reply, "on samples=0/33 last=idle now=2026-11-01T14:05:00Z"); + EXPECT_STREQ(reply, "on samples=0/33 last=idle slots=33/22 tol=60/60 now=2026-11-01T14:05:00Z"); meshClockCLI(clock, NOW_TEXT, "bogus", reply); - EXPECT_STREQ(reply, "Err - clock mesh takes on|off"); + EXPECT_STREQ(reply, "Err - clock mesh takes on|off|slots|tolerance"); meshClockCLI(clock, NOW_TEXT, "on extra", reply); - EXPECT_STREQ(reply, "Err - clock mesh takes on|off"); + EXPECT_STREQ(reply, "Err - clock mesh takes on|off|slots|tolerance"); EXPECT_TRUE(clock.isEnabled()); // a refused command changed nothing meshClockCLI(clock, NOW_TEXT, "off", reply); @@ -373,7 +383,282 @@ TEST_F(ClockTest, CliStatusShowsLastResult) { for (int i = 0; i < MESHCLOCK_SLOTS; i++) feed(clock, i, TRUE_NOW, WRONG_NOW); char reply[CLI_REPLY_MAX]; meshClockCLI(clock, NOW_TEXT, "", reply); - EXPECT_STREQ(reply, "on samples=0/33 last=set(+100000000s) now=2026-11-01T14:05:00Z"); + EXPECT_STREQ(reply, "on samples=0/33 last=set(+100000000s) slots=33/22 tol=60/60 now=2026-11-01T14:05:00Z"); +} + +// ---------------------------------------------------- runtime tuning knobs + +TEST_F(ClockTest, DefaultsAreCompileTimeValues) { + EXPECT_EQ(clock.getSlots(), MESHCLOCK_SLOTS); + EXPECT_EQ(clock.getMinAgree(), MESHCLOCK_MIN_AGREE); + EXPECT_EQ(clock.getToleranceSecs(), MESHCLOCK_TOLERANCE_SECS); + EXPECT_EQ(clock.getMinDiffSecs(), MESHCLOCK_MIN_DIFF_SECS); +} + +TEST_F(ClockTest, SlotsRoundTrips) { + clock.setSlots(15, 10); + EXPECT_EQ(clock.getSlots(), 15); + EXPECT_EQ(clock.getMinAgree(), 10); + flushSave(); + + MeshClockSync loaded; + loaded.begin(&fs); + EXPECT_EQ(loaded.getSlots(), 15); + EXPECT_EQ(loaded.getMinAgree(), 10); + // a knob that was never touched survives with its compile-time default + EXPECT_EQ(loaded.getToleranceSecs(), MESHCLOCK_TOLERANCE_SECS); +} + +TEST_F(ClockTest, ToleranceRoundTrips) { + clock.setTolerance(300, 200); + EXPECT_EQ(clock.getToleranceSecs(), 300); + EXPECT_EQ(clock.getMinDiffSecs(), 200); + flushSave(); + + MeshClockSync loaded; + loaded.begin(&fs); + EXPECT_EQ(loaded.getToleranceSecs(), 300); + EXPECT_EQ(loaded.getMinDiffSecs(), 200); + EXPECT_EQ(loaded.getSlots(), MESHCLOCK_SLOTS); +} + +TEST_F(ClockTest, SlotsRejectsBadValues) { + EXPECT_FALSE(clock.setSlots(MESHCLOCK_SLOTS_MIN - 1, 2)); // below the floor + EXPECT_FALSE(clock.setSlots(MESHCLOCK_SLOTS + 1, 2)); // above the array + EXPECT_FALSE(clock.setSlots(15, 1)); // quorum too small + EXPECT_FALSE(clock.setSlots(15, 16)); // quorum exceeds slots + EXPECT_EQ(clock.getSlots(), MESHCLOCK_SLOTS); // unchanged + EXPECT_EQ(clock.getMinAgree(), MESHCLOCK_MIN_AGREE); + // a same-value "set" is a no-op, not an error, and writes nothing + flushSave(); + EXPECT_FALSE(fs.exists(MESHCLOCK_CFG_FILE)); +} + +TEST_F(ClockTest, ToleranceRejectsBadValues) { + EXPECT_FALSE(clock.setTolerance(0, 60)); // zero tolerance deadlocks consensus + EXPECT_TRUE(clock.setTolerance(1, 0)); // a 0 deadband is meaningful: always step + EXPECT_EQ(clock.getToleranceSecs(), 1); + EXPECT_EQ(clock.getMinDiffSecs(), 0); +} + +TEST_F(ClockTest, SlotsChangeDropsInflightBatch) { + clock.setEnabled(true); + feed(clock, 0, TRUE_NOW, WRONG_NOW); + feed(clock, 1, TRUE_NOW, WRONG_NOW); + ASSERT_EQ(clock.getSampleCount(), 2); + clock.setSlots(15, 10); + EXPECT_EQ(clock.getSampleCount(), 0); +} + +TEST_F(ClockTest, ToleranceChangeDropsInflightBatch) { + clock.setEnabled(true); + feed(clock, 0, TRUE_NOW, WRONG_NOW); + ASSERT_EQ(clock.getSampleCount(), 1); + clock.setTolerance(300, 300); + EXPECT_EQ(clock.getSampleCount(), 0); +} + +TEST_F(ClockTest, LoweredCapFillsAndDecides) { + clock.setEnabled(true); + clock.setSlots(3, 2); + feed(clock, 0, TRUE_NOW, WRONG_NOW); + feed(clock, 1, TRUE_NOW, WRONG_NOW); + EXPECT_EQ(set_calls, 0u); // decides only when the lowered cap fills + + feed(clock, 2, TRUE_NOW, WRONG_NOW); + EXPECT_EQ(set_calls, 1u); + EXPECT_EQ(set_epoch, TRUE_NOW); + EXPECT_EQ(clock.getLastResult(), MeshClockSync::SET_CLOCK); +} + +TEST_F(ClockTest, ToleranceGatesInlierCount) { + clock.setEnabled(true); + clock.setSlots(5, 4); + clock.setTolerance(5, 0); + for (int i = 0; i < 2; i++) feed(clock, i, TRUE_NOW, WRONG_NOW); + for (int i = 2; i < 5; i++) feed(clock, i, TRUE_NOW + 100, WRONG_NOW); + // tight window: only the three T+100 sources count as inliers on the median T+100 + EXPECT_EQ(set_calls, 0u); + EXPECT_EQ(clock.getLastResult(), MeshClockSync::NO_CONSENSUS); + EXPECT_EQ(clock.getSampleCount(), 0); + + // loose window: all five count as inliers and the quorum is met + clock.setTolerance(200, 0); // also drops the batch; re-feed + for (int i = 0; i < 2; i++) feed(clock, i, TRUE_NOW, WRONG_NOW); + for (int i = 2; i < 5; i++) feed(clock, i, TRUE_NOW + 100, WRONG_NOW); + EXPECT_EQ(set_calls, 1u); + EXPECT_EQ(set_epoch, TRUE_NOW + 100); // the median of the five +} + +TEST_F(ClockTest, DeadbandZeroAlwaysSteps) { + clock.setEnabled(true); + clock.setTolerance(60, 0); // deadband 0: any difference is out of sync + for (int i = 0; i < MESHCLOCK_SLOTS; i++) feed(clock, i, TRUE_NOW + 5, TRUE_NOW); + EXPECT_EQ(set_calls, 1u); + EXPECT_EQ(set_epoch, TRUE_NOW + 5); +} + +// ---------------------------------------------------- v1 -> v2 migration + +TEST_F(ClockTest, V1ConfigMigrates) { + writeV1File(fs, /*enabled=*/1, MESHCLOCK_CFG_FILE); + clock.begin(&fs); + EXPECT_TRUE(clock.isEnabled()); + EXPECT_EQ(clock.getSlots(), MESHCLOCK_SLOTS); // knobs take the defaults + EXPECT_EQ(clock.getMinAgree(), MESHCLOCK_MIN_AGREE); + EXPECT_EQ(clock.getToleranceSecs(), MESHCLOCK_TOLERANCE_SECS); + EXPECT_EQ(clock.getMinDiffSecs(), MESHCLOCK_MIN_DIFF_SECS); + + flushSave(); // the migration save writes v2 + ASSERT_EQ(fs.files[MESHCLOCK_CFG_FILE].size(), 10u); + EXPECT_EQ(fs.files[MESHCLOCK_CFG_FILE][0], MESHCLOCK_CFG_VERSION); + + MeshClockSync loaded; + loaded.begin(&fs); + EXPECT_TRUE(loaded.isEnabled()); // the migrated record loads as v2 +} + +TEST_F(ClockTest, V1DisabledFlagCarries) { + writeV1File(fs, /*enabled=*/0, MESHCLOCK_CFG_FILE); + clock.begin(&fs); + EXPECT_FALSE(clock.isEnabled()); + flushSave(); + ASSERT_EQ(fs.files[MESHCLOCK_CFG_FILE].size(), 10u); + EXPECT_EQ(fs.files[MESHCLOCK_CFG_FILE][1], 0); +} + +TEST_F(ClockTest, CorruptV1CanonicalFallsBackToV1Backup) { + // the v1 path on its own: canonical v1 fails the CRC check, the backup is a + // good v1 — same recovery the v2 path gets, through the same machinery + std::vector bad = { 1, 1, 0, 0 }; + uint16_t crc = crc16_ccitt(bad.data(), 2); + memcpy(&bad[2], &crc, 2); + bad[3] ^= 0xFF; // break the CRC + fs.files[MESHCLOCK_CFG_FILE] = bad; + writeV1File(fs, /*enabled=*/1, MESHCLOCK_CFG_FILE ".bak"); + + MeshClockSync loaded; + loaded.begin(&fs); + EXPECT_TRUE(loaded.isEnabled()); // recovered from the v1 backup +} + +TEST_F(ClockTest, CorruptV2FallsBackToV1Backup) { + writeV1File(fs, /*enabled=*/1, MESHCLOCK_CFG_FILE); + clock.begin(&fs); // loads v1, marks dirty for the migration save + flushSave(); // v2 canonical promoted; the v1 bytes move to the backup + ASSERT_EQ(fs.files[MESHCLOCK_CFG_FILE].size(), 10u); + + // corrupt the canonical with a CRC-valid but impossible knob pair + std::vector& rec = fs.files[MESHCLOCK_CFG_FILE]; + rec[2] = 5; // slots + rec[3] = 9; // min_agree > slots + uint16_t crc = crc16_ccitt(rec.data(), 8); + memcpy(&rec[8], &crc, 2); + + MeshClockSync loaded; + loaded.begin(&fs); + EXPECT_TRUE(loaded.isEnabled()); // recovered from the v1 backup +} + +TEST_F(ClockTest, InvalidV2RecordRejected) { + clock.setEnabled(true); + clock.setSlots(5, 3); + flushSave(); // no backup existed before this first save + ASSERT_EQ(fs.files[MESHCLOCK_CFG_FILE].size(), 10u); + + std::vector& rec = fs.files[MESHCLOCK_CFG_FILE]; + rec[3] = 9; // min_agree 9 > slots 5, with a matching CRC + uint16_t crc = crc16_ccitt(rec.data(), 8); + memcpy(&rec[8], &crc, 2); + + MeshClockSync loaded; + loaded.begin(&fs); + EXPECT_FALSE(loaded.isEnabled()); // nothing usable: defaults + EXPECT_EQ(loaded.getSlots(), MESHCLOCK_SLOTS); +} + +// --------------------------------------------------------------- CLI knobs + +TEST_F(ClockTest, CliSlotsSetsAndPersists) { + char reply[CLI_REPLY_MAX]; + meshClockCLI(clock, NOW_TEXT, "slots 15 10", reply); + EXPECT_STREQ(reply, "OK - mesh clock slots 15/10"); + EXPECT_EQ(clock.getSlots(), 15); + EXPECT_EQ(clock.getMinAgree(), 10); + + flushSave(); + MeshClockSync loaded; + loaded.begin(&fs); + EXPECT_EQ(loaded.getSlots(), 15); + EXPECT_EQ(loaded.getMinAgree(), 10); + + // the status line shows the configured pair + meshClockCLI(loaded, NOW_TEXT, "on", reply); + meshClockCLI(loaded, NOW_TEXT, "", reply); + EXPECT_STREQ(reply, "on samples=0/15 last=idle slots=15/10 tol=60/60 now=2026-11-01T14:05:00Z"); +} + +TEST_F(ClockTest, CliSlotsValidation) { + char reply[CLI_REPLY_MAX]; + meshClockCLI(clock, NOW_TEXT, "slots", reply); + EXPECT_STREQ(reply, "Err - clock mesh takes on|off|slots|tolerance"); + meshClockCLI(clock, NOW_TEXT, "slots 15", reply); + EXPECT_STREQ(reply, "Err - clock mesh takes on|off|slots|tolerance"); + meshClockCLI(clock, NOW_TEXT, "slots 15 10 3", reply); + EXPECT_STREQ(reply, "Err - clock mesh takes on|off|slots|tolerance"); + meshClockCLI(clock, NOW_TEXT, "slots 2 2", reply); + EXPECT_STREQ(reply, "Err - slots must be 3..33"); + meshClockCLI(clock, NOW_TEXT, "slots 34 22", reply); + EXPECT_STREQ(reply, "Err - slots must be 3..33"); + meshClockCLI(clock, NOW_TEXT, "slots 15 16", reply); + EXPECT_STREQ(reply, "Err - min-agree must be 2..15"); + meshClockCLI(clock, NOW_TEXT, "slots 15 1", reply); + EXPECT_STREQ(reply, "Err - min-agree must be 2..15"); + meshClockCLI(clock, NOW_TEXT, "slots banana 10", reply); + EXPECT_STREQ(reply, "Err - clock mesh takes on|off|slots|tolerance"); + meshClockCLI(clock, NOW_TEXT, "slots 15 banana", reply); + EXPECT_STREQ(reply, "Err - clock mesh takes on|off|slots|tolerance"); + EXPECT_EQ(clock.getSlots(), MESHCLOCK_SLOTS); // nothing was applied +} + +TEST_F(ClockTest, CliToleranceSetsAndPersists) { + char reply[CLI_REPLY_MAX]; + meshClockCLI(clock, NOW_TEXT, "tolerance 300 0", reply); + EXPECT_STREQ(reply, "OK - mesh clock tolerance 300/0"); + EXPECT_EQ(clock.getToleranceSecs(), 300); + EXPECT_EQ(clock.getMinDiffSecs(), 0); + + flushSave(); + MeshClockSync loaded; + loaded.begin(&fs); + EXPECT_EQ(loaded.getToleranceSecs(), 300); + EXPECT_EQ(loaded.getMinDiffSecs(), 0); +} + +TEST_F(ClockTest, CliToleranceValidation) { + char reply[CLI_REPLY_MAX]; + meshClockCLI(clock, NOW_TEXT, "tolerance", reply); + EXPECT_STREQ(reply, "Err - clock mesh takes on|off|slots|tolerance"); + meshClockCLI(clock, NOW_TEXT, "tolerance 300", reply); + EXPECT_STREQ(reply, "Err - clock mesh takes on|off|slots|tolerance"); + meshClockCLI(clock, NOW_TEXT, "tolerance 0 60", reply); + EXPECT_STREQ(reply, "Err - tolerance must be 1..65535 seconds"); + meshClockCLI(clock, NOW_TEXT, "tolerance 65536 60", reply); + EXPECT_STREQ(reply, "Err - tolerance must be 1..65535 seconds"); + meshClockCLI(clock, NOW_TEXT, "tolerance 60 65536", reply); + EXPECT_STREQ(reply, "Err - min-diff must be 0..65535 seconds"); + meshClockCLI(clock, NOW_TEXT, "tolerance 300 300 1", reply); + EXPECT_STREQ(reply, "Err - clock mesh takes on|off|slots|tolerance"); + meshClockCLI(clock, NOW_TEXT, "tolerance banana 300", reply); + EXPECT_STREQ(reply, "Err - clock mesh takes on|off|slots|tolerance"); + EXPECT_EQ(clock.getToleranceSecs(), MESHCLOCK_TOLERANCE_SECS); // untouched +} + +TEST_F(ClockTest, CliStatusShowsKnobsWhenOff) { + char reply[CLI_REPLY_MAX]; + meshClockCLI(clock, NOW_TEXT, "slots 15 10", reply); + meshClockCLI(clock, NOW_TEXT, "", reply); + EXPECT_STREQ(reply, "off slots=15/10 tol=60/60 now=2026-11-01T14:05:00Z"); } int main(int argc, char **argv) {