File size: 11,927 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
#!/usr/bin/env python3
"""Bounded receive-only Piper CAN capture; never configures or transmits on CAN.

Requires an already-UP 1 Mbps interface in hardware LISTEN-ONLY mode. The
classification follows the local Piper SDK's double_piper.MD and can_id.py.
CAN identifiers describe message roles, not authenticated physical arm IDs.
"""

from __future__ import annotations

import argparse
from collections import Counter, defaultdict
from datetime import datetime
import json
from pathlib import Path
import struct
import subprocess
import sys
import time

import can

ROOT = Path(__file__).resolve().parents[1]


def link_info(interface: str) -> dict:
    result = subprocess.run(
        ["ip", "-json", "-details", "-statistics", "link", "show", "dev", interface],
        check=True, capture_output=True, text=True,
    )
    return json.loads(result.stdout)[0]


def require_listener(link: dict) -> None:
    info = link.get("linkinfo", {})
    if info.get("info_kind") != "can":
        raise ValueError("selected interface is not a CAN interface")
    if "UP" not in link.get("flags", []):
        raise ValueError("CAN interface is DOWN; enable it locally before capturing")
    details = info.get("info_data", {})
    if details.get("bittiming", {}).get("bitrate") != 1000000:
        raise ValueError("this Piper check requires the documented 1 Mbps bitrate")
    if "listen-only" not in json.dumps(details.get("ctrlmode", [])).lower():
        raise ValueError("hardware LISTEN-ONLY is required; capture was not started")


def decode(frame: can.Message) -> dict | None:
    if frame.is_error_frame or frame.is_extended_id or frame.is_remote_frame:
        return None
    ident = frame.arbitration_id
    data = bytes(frame.data)
    for offset in (0x00, 0x10, 0x20):
        for kind, base in (("target", 0x155), ("feedback", 0x2A5)):
            pair = ident - base - offset
            if 0 <= pair <= 2 and len(data) == 8:
                values = [v / 1000.0 for v in struct.unpack(">ii", data)]
                return {"kind": kind, "offset": offset, "pair": pair,
                        "joint_indices": [pair * 2 + 1, pair * 2 + 2],
                        "joint_deg": values}
        for kind, base in (("target_gripper", 0x159), ("feedback_gripper", 0x2A8)):
            if ident == base + offset and len(data) == 8:
                return {"kind": kind, "offset": offset,
                        "opening_mm": int.from_bytes(data[:4], "big", signed=True) / 1000.0,
                        "status_or_command_byte": data[6]}
        if ident == 0x2A1 + offset and len(data) == 8:
            return {"kind": "status", "offset": offset, "ctrl_mode": data[0],
                    "arm_status": data[1], "err_code": int.from_bytes(data[6:8], "big")}
    return None


class Analysis:
    def __init__(self) -> None:
        self.ids: Counter = Counter()
        self.last_times: dict[int, float] = {}
        self.first_times: dict[int, float] = {}
        self.max_gaps: dict[int, float] = defaultdict(float)
        self.error_frames = 0
        self.joint_ranges: dict[str, dict[int, list[float]]] = defaultdict(dict)
        self.pending: dict[str, dict] = defaultdict(dict)
        self.full_samples: Counter = Counter()
        self.other_decoded: dict[str, dict] = {}
        self.status_codes: dict[str, Counter] = defaultdict(Counter)

    def add(self, frame: can.Message, elapsed: float) -> tuple[dict | None, dict | None]:
        ident = frame.arbitration_id
        self.ids[ident] += 1
        self.first_times.setdefault(ident, elapsed)
        if ident in self.last_times:
            self.max_gaps[ident] = max(self.max_gaps[ident], elapsed - self.last_times[ident])
        self.last_times[ident] = elapsed
        self.error_frames += int(frame.is_error_frame)
        item = decode(frame)
        if item is None:
            return None, None
        group = f"{item['kind']}_offset_0x{item['offset']:02X}"
        if "joint_deg" not in item:
            self.other_decoded[group] = item
            if item["kind"] == "status":
                self.status_codes[group][f"arm_status={item['arm_status']},err_code={item['err_code']}"] += 1
            return item, None
        for joint, value in zip(item["joint_indices"], item["joint_deg"], strict=True):
            bounds = self.joint_ranges[group].setdefault(joint, [value, value])
            bounds[0], bounds[1] = min(bounds[0], value), max(bounds[1], value)
        pending = self.pending[group]
        pending[item["pair"]] = (elapsed, item["joint_deg"])
        if len(pending) != 3:
            return item, None
        times = [pending[i][0] for i in range(3)]
        if max(times) - min(times) > 0.05:
            oldest = min(pending, key=lambda i: pending[i][0])
            del pending[oldest]
            return item, None
        sample = {"time_sec": max(times), "kind": item["kind"], "offset": item["offset"],
                  "joint_deg": [v for i in range(3) for v in pending[i][1]],
                  "pair_arrival_times_sec": times, "pair_skew_sec": max(times) - min(times)}
        pending.clear()
        self.full_samples[group] += 1
        return item, sample

    def summary(self, duration: float) -> dict:
        target = any(k.startswith("target_") and v > 0 for k, v in self.full_samples.items())
        feedback = any(k.startswith("feedback_") and v > 0 for k, v in self.full_samples.items())
        result = "NO_COMPLETE_JOINT_FEEDBACK"
        if not self.ids:
            result = "NO_CAN_FRAMES"
        elif target and feedback:
            result = "TARGET_AND_FEEDBACK_PRESENT"
        elif target:
            result = "TARGET_ONLY_NO_COMPLETE_FEEDBACK"
        elif feedback:
            result = "FEEDBACK_PRESENT_NO_COMPLETE_TARGET"
        groups = {}
        for group, ranges in self.joint_ranges.items():
            groups[group] = {
                "complete_six_joint_samples": self.full_samples[group],
                "samples_per_second": self.full_samples[group] / max(duration, 1e-9),
                "joint_range_deg": {str(j): {"min": low, "max": high, "span": high-low}
                                    for j, (low, high) in ranges.items()},
            }
        return {
            "result": result, "duration_sec": duration, "received_frames": sum(self.ids.values()),
            "error_frames": self.error_frames,
            "can_ids": {f"0x{i:03X}": {"count": n, "max_interarrival_sec": self.max_gaps[i],
                                        "first_sec": self.first_times[i], "last_sec": self.last_times[i]}
                        for i, n in sorted(self.ids.items())},
            "joint_streams": groups, "last_gripper_and_status": self.other_decoded,
            "observed_status_codes": {key: dict(values) for key, values in self.status_codes.items()},
            "interpretation": "Presence is not a tracking-accuracy pass. Physical arm identity, "
                              "movement, gaps and command/feedback agreement require review.",
            "application_transmit_calls": 0,
        }


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--interface", default="can0")
    parser.add_argument("--seconds", type=float, default=30.0)
    parser.add_argument("--screen-cue", action="store_true")
    parser.add_argument("--prepare-seconds", type=float, default=15.0)
    parser.add_argument("--countdown-seconds", type=int, default=5)
    args = parser.parse_args()
    if not 0 < args.seconds <= 60 or not 0 <= args.prepare_seconds <= 120 or not 0 <= args.countdown_seconds <= 10:
        parser.error("capture must be <=60s, preparation <=120s and countdown <=10s")
    try:
        before = link_info(args.interface)
        require_listener(before)
    except (ValueError, subprocess.CalledProcessError) as exc:
        print(f"CAPTURE NOT STARTED: {exc}", file=sys.stderr)
        return 2
    cue = None
    if args.screen_cue:
        sys.path.insert(0, str(ROOT / "intent_rack_demo"))
        from src.camera.screen_cue import ScreenCue
        cue = ScreenCue()
    analysis = Analysis()
    output = ROOT / "data/piper_checks" / datetime.now().astimezone().strftime("%Y%m%dT%H%M%S_%f%z")
    output.mkdir(parents=True, exist_ok=False)
    (output / "link_before.json").write_text(json.dumps(before, indent=2) + "\n")
    started = None
    failure = None
    aborted = False
    try:
        if cue:
            cue.show("PREPARE", "Both arms clear; keep still until MOVE TEACHER")
            cue.wait(args.prepare_seconds)
            for number in range(args.countdown_seconds, 0, -1):
                cue.show(str(number), "Preparing receive-only capture")
                cue.wait(1.0)
        with can.Bus(interface="socketcan", channel=args.interface,
                     ignore_config=True, receive_own_messages=False) as bus:
            started = time.monotonic()
            started_ns = time.monotonic_ns()
            with (output / "frames.jsonl").open("w") as raw, (output / "joint_samples.jsonl").open("w") as joints:
                print(f"RECEIVING: move teaching arm gently now; output={output}", flush=True)
                next_screen = 0.0
                while (elapsed := time.monotonic() - started) < args.seconds:
                    if cue and elapsed >= next_screen:
                        cue.show("MOVE TEACHER", f"{elapsed:.0f}/{args.seconds:.0f}s | RX {sum(analysis.ids.values())} frames",
                                 background=(15, 70, 35))
                        next_screen = elapsed + 0.2
                    frame = bus.recv(timeout=min(0.05, max(0.001, args.seconds-elapsed)))
                    if frame is None:
                        continue
                    host_ns = time.monotonic_ns()
                    elapsed = (host_ns - started_ns) / 1e9
                    item, sample = analysis.add(frame, elapsed)
                    record = {"time_sec": elapsed, "host_monotonic_ns": host_ns,
                              "kernel_timestamp_sec": frame.timestamp, "can_id": f"0x{frame.arbitration_id:03X}",
                              "data_hex": frame.data.hex(), "is_rx": frame.is_rx,
                              "is_error": frame.is_error_frame, "is_extended": frame.is_extended_id,
                              "is_remote": frame.is_remote_frame, "decoded": item}
                    raw.write(json.dumps(record) + "\n")
                    if sample:
                        joints.write(json.dumps(sample) + "\n")
        if cue:
            cue.show("COMPLETE", "Stop moving; return to the computer")
            cue.wait(3.0)
    except KeyboardInterrupt:
        aborted = True
    except Exception as exc:
        failure = f"{type(exc).__name__}: {exc}"
    finally:
        duration = min(args.seconds, time.monotonic()-started) if started is not None else 0.0
        report = analysis.summary(duration)
        report.update({"interface": args.interface, "output": str(output), "error": failure,
                       "aborted": aborted, "hardware_listen_only_required": True})
        try:
            after = link_info(args.interface)
            (output / "link_after.json").write_text(json.dumps(after, indent=2) + "\n")
            stats_key = "stats64" if "stats64" in after else "stats"
            report["interface_tx_packets_delta"] = (after.get(stats_key, {}).get("tx", {}).get("packets", 0)
                                                     - before.get(stats_key, {}).get("tx", {}).get("packets", 0))
        except Exception as exc:
            report["link_after_error"] = str(exc)
        (output / "summary.json").write_text(json.dumps(report, indent=2) + "\n")
        if cue:
            cue.close()
        print(json.dumps(report, indent=2), flush=True)
    return 1 if failure or aborted or not analysis.ids else 0


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