# Tactiverge Academy — companion code for "Communication inside a robot"
# Lesson: https://tactiverge.win/academy/robotics-foundations/robotic-system-architecture/communication-inside-a-robot/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
# Made-up data for illustration. The arm logs its gripper x position
# every 10 ms. A camera image was captured at t = 1234 ms but only
# reached the planner at t = 1300 ms.
arm_log = [(1220 + 10 * i, 412.0 + 2.0 * i) for i in range(9)]  # (ms, mm)

def x_at(t):
    """Linearly interpolate the arm's logged position at time t (ms)."""
    for (t0, x0), (t1, x1) in zip(arm_log, arm_log[1:]):
        if t0 <= t <= t1:
            return x0 + (x1 - x0) * (t - t0) / (t1 - t0)
    raise ValueError("time outside the log")

captured, arrived = 1234, 1300
print(f"gripper x when the image arrived:  {x_at(arrived):.1f} mm")
print(f"gripper x when the image was taken: {x_at(captured):.1f} mm")
print(f"error if we ignore the timestamp:   {x_at(arrived) - x_at(captured):.1f} mm")
