# Tactiverge Academy — companion code for "Timestamps and synchronising devices"
# Lesson: https://tactiverge.win/academy/embedded-systems/embedded-communication/timestamps-and-synchronisation/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
def clock_offset(t1, t2, t3, t4):
    """Offset of the remote clock and round-trip delay, from one exchange.
    t1: request sent (local clock)   t2: request received (remote clock)
    t3: reply sent (remote clock)    t4: reply received (local clock)"""
    delay = (t4 - t1) - (t3 - t2)
    offset = ((t2 - t1) + (t3 - t4)) / 2
    return offset, delay

print(clock_offset(1000, 1254, 1255, 1011))


# ── Example 2 ────────────────────────────────────────
# Made-up gyro angles (degrees), stamped every 10 ms by the same clock.
imu_t = [0, 10, 20, 30, 40, 50, 60, 70]
imu_angle = [0.0, 1.0, 2.1, 3.3, 4.6, 6.0, 7.5, 9.1]

def value_at(t, times, values):
    """Linearly interpolate a value at time t from sorted samples."""
    for i in range(len(times) - 1):
        t0, t1 = times[i], times[i + 1]
        if t0 <= t <= t1:
            fraction = (t - t0) / (t1 - t0)
            return values[i] + fraction * (values[i + 1] - values[i])
    raise ValueError("t is outside the recorded range")

# Camera frames: exposure time, already corrected for the camera's latency.
for frame_t in [13, 46, 63]:
    print(f"frame at {frame_t} ms: gyro angle {value_at(frame_t, imu_t, imu_angle):.2f} deg")
