#ifndef MACHINE_CLOCK_H_
#define MACHINE_CLOCK_H_

// Machine time: a nanosecond timeline shared by every board on the same USB
// host controller. All of them receive the same 1 kHz start-of-frame (SOF)
// packets and frame numbers, so machine time is defined as
//     frame_count * 1 ms
// interpolated between frames with the local crystal, which a PLL disciplines
// to the SOF edges (phase + rate). Frame counts are unwrapped locally from
// boot, so two boards' machine times differ by a multiple of 2048 ms; the host
// removes that offset.

#include <Arduino.h>

typedef struct clockStatus_t {
  uint64_t now_us;          // local time_us_64()
  uint16_t sof_raw;         // last USB frame number (11 bits)
  uint32_t sof_count;       // unwrapped frame count
  uint64_t sof_edge_us;     // estimated local time of that frame's start
  uint32_t sof_skips;       // frames whose number we never saw
  uint32_t max_poll_gap_us; // worst poll interval since last status read
  uint64_t machine_ns;      // machine time now
  uint8_t  ok;              // locked and SOF seen recently
  float    trim_ppm;        // rate correction applied to the local crystal
  float    phase_err_ns;    // last measured phase error
  uint32_t relocks;         // hard re-synchronisations (should stay 0)
  uint32_t rejected;        // edges ignored for imprecise timing
} clockStatus_t;

// call as often as possible from the main loop
void clock_poll(void);

// safe from ISR and main loop
uint64_t clock_machineTimeNs(void);

bool clock_ok(void);

void clock_getStatus(clockStatus_t* s);

#endif
