File size: 17,387 Bytes
e302b11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
#!/usr/bin/env python3
"""Bounded Top RGB + receive-only Piper test, one trajectory row per real frame.

Software association uses host monotonic arrival times, NOT exposure hardware
sync. Native CAN rate is unchanged. No robot interface or send call is used.
"""
from __future__ import annotations

import argparse
import bisect
from collections import defaultdict
from dataclasses import asdict, replace
from datetime import datetime
import csv
import json
from pathlib import Path
import sys
import threading
import time

import can
import cv2
import numpy as np

from check_piper_input import Analysis, link_info, require_listener
from timestamp_sync_video import remux

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "intent_rack_demo"))
from src.camera.recording import load_camera_specs, prepare_camera, stop_camera
from src.camera.screen_cue import ScreenCue


def write_json(path, value):
    path.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8")


def select_sample(rows, times, stamp, tolerance_ns, causal=False):
    """Never bridge a long gap; return None instead of silently holding data."""
    index = bisect.bisect_right(times, stamp)
    choices = [i for i in (index - 1, index) if 0 <= i < len(times)
               and (not causal or times[i] <= stamp)]
    if not choices:
        return None
    best = min(choices, key=lambda i: abs(times[i] - stamp))
    return rows[best] if abs(times[best] - stamp) <= tolerance_ns else None


def distribution(values):
    return {"count": len(values), "median": float(np.median(values)),
            "p95": float(np.percentile(values, 95)), "max": float(np.max(values))} if values else None


def export_aligned(output, frames, streams, fps):
    keys = ("feedback", "target", "feedback_gripper", "target_gripper", "status")
    times = {k: [r["host_monotonic_ns"] for r in streams[k]] for k in keys}
    counts = {k: 0 for k in keys}
    deltas = {k: [] for k in keys}
    previous = {}
    reused = {k: 0 for k in keys}
    columns = ["video_frame_index", "camera_frame_index", "time_sec", "host_monotonic_ns",
               "device_timestamp_us", "device_system_timestamp_us"]
    for key in keys:
        columns += [f"{key}_valid", f"{key}_source_host_ns", f"{key}_source_kernel_sec",
                    f"{key}_signed_delta_ms", f"{key}_source_reused"]
        if key in ("feedback", "target"):
            columns += [f"{key}_j{j}_deg" for j in range(1, 7)] + [f"{key}_pair_skew_ms"]
        elif "gripper" in key:
            columns += [f"{key}_opening_mm", f"{key}_status_or_command_byte"]
        else:
            columns += ["ctrl_mode", "arm_status", "err_code"]
    with (output / "aligned_60hz.csv").open("x", newline="") as stream:
        writer = csv.DictWriter(stream, fieldnames=columns)
        writer.writeheader()
        for frame in frames:
            row = dict(frame)
            stamp = frame["host_monotonic_ns"]
            for key in keys:
                causal = key in ("target", "target_gripper", "status")
                sample = select_sample(streams[key], times[key], stamp,
                                       round(1e9 / fps * (1 if causal else 0.5)), causal)
                if sample and sample.get("pair_skew_sec", 0) > 0.005:
                    sample = None
                row[f"{key}_valid"] = int(sample is not None)
                if sample is None:
                    continue
                source = sample["host_monotonic_ns"]
                delta = (source - stamp) / 1e6
                repeat = previous.get(key) == source
                previous[key] = source
                counts[key] += 1
                reused[key] += int(repeat)
                deltas[key].append(abs(delta))
                row.update({f"{key}_source_host_ns": source,
                            f"{key}_source_kernel_sec": sample["kernel_timestamp_sec"],
                            f"{key}_signed_delta_ms": delta, f"{key}_source_reused": int(repeat)})
                if key in ("feedback", "target"):
                    row.update({f"{key}_j{j}_deg": q for j, q in enumerate(sample["joint_deg"], 1)})
                    row[f"{key}_pair_skew_ms"] = sample["pair_skew_sec"] * 1000
                elif "gripper" in key:
                    row[f"{key}_opening_mm"] = sample["opening_mm"]
                    row[f"{key}_status_or_command_byte"] = sample["status_or_command_byte"]
                else:
                    row.update({k: sample[k] for k in ("ctrl_mode", "arm_status", "err_code")})
            writer.writerow(row)
    return {k: {"source_samples_received": len(streams[k]), "matched_frames": counts[k],
                "missing_frames": len(frames) - counts[k], "reused_source_samples": reused[k],
                "absolute_host_alignment_ms": distribution(deltas[k])} for k in keys}


def camera_settings(handle):
    import pyorbbecsdk as ob
    device = handle.keepalive[1]
    result = {}
    properties = {"auto_exposure": ("OB_PROP_COLOR_AUTO_EXPOSURE_BOOL", True),
                  "exposure_raw": ("OB_PROP_COLOR_EXPOSURE_INT", False),
                  "gain_raw": ("OB_PROP_COLOR_GAIN_INT", False),
                  "auto_exposure_priority": ("OB_PROP_COLOR_AUTO_EXPOSURE_PRIORITY_INT", False),
                  "power_line_frequency_raw": ("OB_PROP_COLOR_POWER_LINE_FREQUENCY_INT", False)}
    for key, (name, boolean) in properties.items():
        try:
            getter = device.get_bool_property if boolean else device.get_int_property
            result[key] = getter(getattr(ob.OBPropertyID, name))
        except Exception as exc:
            result[key] = {"unavailable": str(exc)}
    try:
        config = device.get_multi_device_sync_config()
        result["sync_mode"] = str(config.mode)
        result["color_delay_us"] = config.color_delay_us
    except Exception as exc:
        result["sync_config_error"] = str(exc)
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--seconds", type=float, default=20)
    parser.add_argument("--prepare-seconds", type=float, default=15)
    parser.add_argument("--interface", default="can0")
    args = parser.parse_args()
    if not 0 < args.seconds <= 60 or not 5 <= args.prepare_seconds <= 60:
        parser.error("duration must be 0..60 seconds; preparation 5..60 seconds")
    cv2.setNumThreads(1)
    spec = next(s for s in load_camera_specs(ROOT / "intent_rack_demo/configs/cameras.yaml") if s.role == "top")
    spec = replace(spec, width=1280, height=720, fps=60)
    if spec.vendor != "orbbec":
        parser.error("this bounded test requires the configured Orbbec Top camera")
    before = link_info(args.interface)
    require_listener(before)
    output = ROOT / "data/piper_camera_sync" / datetime.now().astimezone().strftime("%Y%m%dT%H%M%S_%f%z")
    output.mkdir(parents=True, exist_ok=False)
    write_json(output / "link_before.json", before)
    state = {"start_ns": None, "end_ns": None}
    frames, errors, threads = [], [], []
    streams = defaultdict(list)
    analysis = Analysis()
    stop = threading.Event()
    camera_ready, can_ready = threading.Event(), threading.Event()
    handle = writer = cue = None
    settings = {}

    def camera_worker():
        last = None
        try:
            while not stop.is_set():
                frame_set = handle.pipeline.wait_for_frames(250)
                host_ns = time.monotonic_ns()  # Before MJPEG decoding or video encoding.
                if frame_set is None:
                    continue
                color = frame_set.get_color_frame()
                if color is None:
                    continue
                index = int(color.get_index())
                if index == last:
                    continue
                last = index
                camera_ready.set()
                start_ns, end_ns = state["start_ns"], state["end_ns"]
                if start_ns is None or host_ns < start_ns:
                    continue  # Drain throughout preparation: do not record stale startup frames.
                if host_ns >= end_ns:
                    break
                image = cv2.imdecode(np.asanyarray(color.get_data()).reshape(-1), cv2.IMREAD_COLOR)
                if image is None or image.shape[:2] != (spec.height, spec.width):
                    raise RuntimeError("invalid Top image")
                writer.write(image)
                frames.append({"video_frame_index": len(frames), "camera_frame_index": index,
                    "time_sec": (host_ns - start_ns) / 1e9, "host_monotonic_ns": host_ns,
                    "device_timestamp_us": int(color.get_timestamp_us()),
                    "device_system_timestamp_us": int(color.get_system_timestamp_us())})
        except Exception as exc:
            errors.append(f"camera: {type(exc).__name__}: {exc}")
            stop.set()

    def can_worker():
        ids = [0x155, 0x156, 0x157, 0x159, 0x2A1, 0x2A5, 0x2A6, 0x2A7, 0x2A8]
        try:
            with can.Bus(interface="socketcan", channel=args.interface, ignore_config=True,
                         receive_own_messages=False,
                         can_filters=[{"can_id": i, "can_mask": 0x7FF, "extended": False} for i in ids]) as bus:
                while not stop.is_set():
                    message = bus.recv(timeout=0.025)
                    host_ns = time.monotonic_ns()
                    if message is None:
                        continue
                    if message.arbitration_id in (0x2A5, 0x2A6, 0x2A7):
                        can_ready.set()
                    start_ns, end_ns = state["start_ns"], state["end_ns"]
                    if start_ns is None or host_ns < start_ns:
                        continue
                    if host_ns >= end_ns + 50_000_000:
                        break
                    item, sample = analysis.add(message, (host_ns - start_ns) / 1e9)
                    metadata = {"host_monotonic_ns": host_ns, "kernel_timestamp_sec": message.timestamp}
                    if sample:
                        streams[sample["kind"]].append({**sample, **metadata})
                    elif item and item["kind"] in ("target_gripper", "feedback_gripper", "status"):
                        streams[item["kind"]].append({**item, **metadata})
        except Exception as exc:
            errors.append(f"CAN: {type(exc).__name__}: {exc}")
            stop.set()

    try:
        cue = ScreenCue()
        cue.show("INITIALIZING", "Top 60 fps + passive CAN | No robot commands")
        handle = prepare_camera(spec)  # Exact 720p60 profile required; no silent fallback.
        settings = camera_settings(handle)
        writer = cv2.VideoWriter(str(output / "top.partial.mp4"), cv2.VideoWriter_fourcc(*"mp4v"),
                                 spec.fps, (spec.width, spec.height))
        if not writer.isOpened():
            raise RuntimeError("could not open video writer")
        for target in (camera_worker, can_worker):
            thread = threading.Thread(target=target)
            threads.append(thread)
            thread.start()
        deadline = time.monotonic() + 10
        while not (camera_ready.is_set() and can_ready.is_set()):
            if stop.is_set() or time.monotonic() >= deadline:
                raise RuntimeError("camera/CAN startup failed or no actual joint feedback")
            cue.wait(0.05)
        start_ns = time.monotonic_ns() + round((args.prepare_seconds + 5) * 1e9)
        state.update(start_ns=start_ns, end_ns=start_ns + round(args.seconds * 1e9))
        write_json(output / "session.json", {"camera": asdict(spec), "camera_settings": settings,
            "capture_window": state, "duration_sec": args.seconds,
            "clock_anchor": {"monotonic_ns": time.monotonic_ns(), "realtime_ns": time.time_ns()},
            "basis": "host monotonic arrival; no hardware exposure synchronization",
            "storage": "one row per native Top frame; native CAN samples buffered only in memory",
            "robot_commands_enabled": False, "application_transmit_calls": 0})
        print(f"PREPARE: {args.prepare_seconds}s then silent 5s countdown; output={output}", flush=True)
        last_label = None
        while time.monotonic_ns() < state["end_ns"] + 60_000_000:
            if stop.is_set():
                raise RuntimeError("a capture worker failed")
            now = time.monotonic_ns()
            remaining = (start_ns - now) / 1e9
            elapsed = (now - start_ns) / 1e9
            if remaining > 5:
                label, subtitle, color = "PREPARE", "Go to workbench; keep both arms clear", (20, 36, 64)
            elif remaining > 0:
                label, subtitle, color = str(int(np.ceil(remaining))), "Wait for green RECORDING", (20, 36, 64)
            elif elapsed < 3:
                label, subtitle, color = "RECORDING", "Keep still | Top + actual trajectory", (15, 70, 35)
            elif elapsed < args.seconds - 3:
                label, subtitle, color = "RECORDING", "Move teacher gently in a clear safe range", (15, 70, 35)
            else:
                label, subtitle, color = "RECORDING", "Stop moving; hold still", (15, 70, 35)
            current = (label, subtitle)
            if current != last_label:
                cue.show(label, subtitle, background=color)
                print(f"{label}: {subtitle}", flush=True)
                last_label = current
            cue.wait(0.025)
    except (Exception, KeyboardInterrupt) as exc:
        errors.append(f"main: {type(exc).__name__}: {exc}")
    finally:
        stop.set()
        for thread in threads:
            thread.join()
        if writer is not None:
            writer.release()
        if handle is not None:
            stop_camera(handle)
            if handle.error:
                errors.append(handle.error)
        if cue is not None:
            try:
                cue.show("STOPPED" if errors else "COMPLETE", "Return to computer; capture ended")
                cue.wait(2)
            except Exception:
                pass
            cue.close()

    alignment = export_aligned(output, frames, streams, spec.fps)
    write_json(output / "can_summary.json", analysis.summary(args.seconds))
    after = link_info(args.interface)
    write_json(output / "link_after.json", after)
    delta = {"tx_packets": after["stats64"]["tx"]["packets"] - before["stats64"]["tx"]["packets"],
             **{f"rx_{k}": after["stats64"]["rx"][k] - before["stats64"]["rx"][k] for k in ("errors", "dropped")}}
    hosts = [r["host_monotonic_ns"] for r in frames]
    devices = [r["device_timestamp_us"] for r in frames]
    fps = (len(hosts) - 1) * 1e9 / (hosts[-1] - hosts[0]) if len(hosts) > 1 else 0
    missing = sum(max(0, b["camera_frame_index"] - a["camera_frame_index"] - 1) for a, b in zip(frames, frames[1:]))
    host_monotonic = len(hosts) > 1 and bool(np.all(np.diff(hosts) > 0))
    device_monotonic = len(devices) > 1 and bool(np.all(np.diff(devices) > 0))
    valid_ratio = alignment["feedback"]["matched_frames"] / len(frames) if frames else 0
    technical_pass = (not errors and abs(fps - 60) < 3 and len(frames) >= args.seconds * 57
                      and valid_ratio >= 0.95 and missing <= max(1, len(frames) * 0.01)
                      and host_monotonic and device_monotonic and not any(delta.values()))
    summary = {"result": "SOFTWARE_ASSOCIATION_PASS" if technical_pass else "NEEDS_REVIEW",
        "output": str(output), "errors": errors, "video_frames": len(frames), "measured_host_fps": fps,
        "host_frame_interval_ms": distribution((np.diff(hosts) / 1e6).tolist()),
        "device_frame_interval_ms": distribution((np.diff(devices) / 1000).tolist()),
        "host_timestamps_monotonic": host_monotonic, "device_timestamps_monotonic": device_monotonic,
        "camera_sequence_gaps": missing, "alignment": alignment, "interface_counters_delta": delta,
        "limits": ["Not exposure-time or hardware synchronization; clocks are not assumed equal.",
                   "Feedback nearest <=8.333ms, targets causal age <=16.667ms; joint pair skew <=5ms.",
                   "Offline nearest feedback may occur after the image host-arrival timestamp.",
                   "Missing data stays blank with valid=0; no interpolation or frame duplication.",
                   "Native CAN feedback rate unchanged; its receive window includes a 50ms tail.",
                   "top.mp4 is nominal 60fps; top_timed.mp4 preserves CSV timing relative to the first frame.",
                   "Pass tests acquisition/timestamp association only, not robot safety or physical lag."]}
    partial = output / "top.partial.mp4"
    if frames and not errors and partial.exists():
        partial.rename(output / "top.mp4")
        try:
            summary["timestamped_video"] = remux(output / "top.mp4", output / "aligned_60hz.csv",
                                                output / "top_timed.mp4")
        except Exception as exc:
            errors.append(f"timestamped_video: {type(exc).__name__}: {exc}")
            summary["result"] = "NEEDS_REVIEW"
            technical_pass = False
    write_json(output / "summary.json", summary)
    print(json.dumps(summary, indent=2), flush=True)
    return 0 if technical_pass else 1


if __name__ == "__main__":
    raise SystemExit(main())