// The decoder's clock is the source of truth for timing and is never changed by RaceCore. It // is set by hand (it doesn't follow summer/winter time), and when it is off, everything that // compares a passing with "now" goes wrong: a heat's first lap from the start signal, a // practice pass on the phone, Even laps. Lap times themselves (two decoder times) stay right, // which is why it goes unnoticed. This only measures how far off it is, to warn about it. export const DECODER_CLOCK_WARNING_MS = 60 * 1000; const SAMPLES = 5; export function createDecoderClockCheck() { const samples = new Map(); return { // rawTs: the decoder's own time for a passing, receivedAt: the computer's clock on arrival. record(role, rawTs, receivedAt = Date.now()) { if (!Number.isFinite(rawTs)) return; const list = samples.get(role) || []; list.push(receivedAt - rawTs); if (list.length > SAMPLES) list.shift(); samples.set(role, list); }, // How far the decoder is behind the computer (ms; negative = ahead), or null before any // passing. The smallest recent sample: a passing delivered late (resent after a reconnect) // only makes the decoder look further behind than it is. skewMs(role) { const list = samples.get(role); return list?.length ? Math.min(...list) : null; }, }; } // null when the clocks agree; otherwise how far and which way the decoder is off. export function describeDecoderClockSkew(skewMs) { if (!Number.isFinite(skewMs) || Math.abs(skewMs) < DECODER_CLOCK_WARNING_MS) return null; const totalMinutes = Math.round(Math.abs(skewMs) / 60000); return { ahead: skewMs < 0, hours: Math.floor(totalMinutes / 60), minutes: totalMinutes % 60 }; } export const decoderClockCheck = createDecoderClockCheck();