Spaces:
Running
Running
stouchinglhh commited on
Commit ·
ef2250d
1
Parent(s): edae745
collector: 更新采集工程至 v1.3.4(新夹爪接入即自动生成运行标定并连接、不再需要人工两步:新增 core/gripper/calibration.py 移植厂商标定生成链,_ensure_calibration 就绪自动生成并复核落盘,失败抛带序列号的 GripperFaysError,设备面板新增「重新读取出厂标定」;并入 v1.3.3 的力矩阵/触觉力与 RGB 时间戳对齐:tactile_ready 加第 5 个载荷 capture_ns、新增 observation.gripper_{side}_force_ns / _force_matrix_ns 稀疏 int64 列、修 pyqtSignal(int) 把 time.monotonic_ns() 按 qint32 静默截断成负数、新增 scripts/align_modalities.py)
Browse files- collector/README.md +91 -1
- collector/config/__init__.py +1 -1
- collector/config/i18n.py +5 -0
- collector/core/egodata_writer.py +24 -4
- collector/core/gripper/bridge.py +38 -8
- collector/core/gripper/calibration.py +566 -0
- collector/core/gripper/fays_single.py +55 -3
- collector/core/pipeline.py +28 -4
- collector/docs/core.md +74 -1
- collector/docs/data.md +46 -0
- collector/docs/index.md +1 -1
- collector/docs/tools.md +1 -0
- collector/docs/ui.md +5 -2
- collector/scripts/align_modalities.py +267 -0
- collector/tools/import_gripper_calibration.py +101 -10
- collector/tools/tests/smoke_gripper_p2.py +1 -1
- collector/tools/tests/smoke_gripper_p3.py +1 -1
- collector/tools/tests/test_gripper_bridge.py +22 -4
- collector/tools/tests/test_gripper_calibration_autogen.py +927 -0
- collector/tools/tests/test_gripper_time_alignment.py +445 -0
- collector/ui/device_panel.py +37 -2
- collector/ui/main_window.py +103 -8
collector/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
# collector — Multimodal Data Acquisition SDK · 多模态数据采集 SDK
|
| 2 |
|
| 3 |
-

|
| 5 |

|
| 6 |
|
|
@@ -361,6 +361,60 @@ are documented in [docs/index.md](docs/index.md#开发约定).
|
|
| 361 |
|
| 362 |
### Changelog
|
| 363 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
- **v1.3.2** — stale SLAM frames (timestamp regression) are now rejected
|
| 365 |
before they reach the core library: the bridge counts *consecutive*
|
| 366 |
regressions, dropping single-frame glitches but rebasing after 30 — the
|
|
@@ -779,6 +833,42 @@ i18n 文案经 `tr()` 翻译、PyQt5 信号参数用 `object` 封送大整数、
|
|
| 779 |
|
| 780 |
### 更新记录
|
| 781 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 782 |
- **v1.3.2** — SLAM 陈旧帧(时间戳回退)改在入库前拦截:桥接按「连续回退
|
| 783 |
次数」判定——单帧脏读丢弃、连丢 30 帧才判定时钟真跳变并换基准放行(此前
|
| 784 |
每一帧回退都会让核心库清空 IMU 队并重建地图、位姿停发 0.2–1.34 s,静止时
|
|
|
|
| 1 |
# collector — Multimodal Data Acquisition SDK · 多模态数据采集 SDK
|
| 2 |
|
| 3 |
+

|
| 4 |

|
| 5 |

|
| 6 |
|
|
|
|
| 361 |
|
| 362 |
### Changelog
|
| 363 |
|
| 364 |
+
- **v1.3.4** — a newly plugged-in gripper now generates its own runtime
|
| 365 |
+
calibration and connects, with no manual step. Previously onboarding a new
|
| 366 |
+
Fays S80M took two manual steps — click `device_setup` on the gripper's host
|
| 367 |
+
PC, then run `tools/import_gripper_calibration.py` on the capture machine —
|
| 368 |
+
and missing either one made the app refuse to start ("current Fays is missing
|
| 369 |
+
runtime calibration files … please run device_setup on the gripper host PC").
|
| 370 |
+
Now `SingleFaysLease.acquire()` finds the per-serial YAMLs missing and, under
|
| 371 |
+
the device lock, runs the vendor exporter to read the factory calibration off
|
| 372 |
+
**this gripper itself**, producing both the SDK YAML (port fields rewritten)
|
| 373 |
+
and the ORB YAML (fisheye `stereoRectify` for P1/R1, IMU extrinsics
|
| 374 |
+
`T_b_c1`, plus the five noise/rate fields from the IMU probe), then re-checks
|
| 375 |
+
the on-disk paths and connects. Grippers that already have calibration take
|
| 376 |
+
an `isfile` fast path — zero extra startup cost, no device access. These two
|
| 377 |
+
files are **per-device** factory calibration and cannot be copied between
|
| 378 |
+
units (098 and 099 differ in all three groups), so they can only be read in
|
| 379 |
+
place. Also adds a right-click "re-read factory calibration" entry on gripper
|
| 380 |
+
rows in the device panel (disabled while recording; the gripper is closed
|
| 381 |
+
first and reopened afterwards), and a `--generate` mode for
|
| 382 |
+
`tools/import_gripper_calibration.py` (existing files are backed up to
|
| 383 |
+
`.bak_<timestamp>`) for forced regeneration from the command line. Along the
|
| 384 |
+
way, fixes the provenance comment on line 3 of the generated ORB YAML — the
|
| 385 |
+
vendor template hard-codes `3500000261870088`, so copying it would record
|
| 386 |
+
every new gripper's IMU extrinsics as "taken from another unit"; it now names
|
| 387 |
+
this unit's serial (existing artifacts left untouched). Follows v1.3.3's
|
| 388 |
+
force-matrix / tactile-force timestamp alignment.
|
| 389 |
+
- **v1.3.3** — force-matrix / tactile-force timestamps are now recorded and
|
| 390 |
+
aligned to the RGB video. **The force side never had a timestamp at all**:
|
| 391 |
+
within a row, the RGB frame and the force sample are not captured at the
|
| 392 |
+
same instant — RGB takes the *oldest* frame off an external source queue
|
| 393 |
+
while force/matrix take the *newest* sample from a latest-wins slot, so
|
| 394 |
+
"same row index" ≠ "same instant". Force always leads RGB, and the lead
|
| 395 |
+
grows with recording time (RGB source at 30.84 fps vs the 30 fps writer,
|
| 396 |
+
measured ≈1 frame/s — this is where the 3-frame lag seen downstream comes
|
| 397 |
+
from); the force matrix runs on its own pump thread and keeps its own
|
| 398 |
+
instant from the 3-vector force. The fix makes every row self-describing:
|
| 399 |
+
`tactile_ready` gains a fifth `capture_ns` payload taken at the SDK
|
| 400 |
+
callback entry, and `pipeline.write_tactile_force/_force_matrix` persist
|
| 401 |
+
it as separate `observation.gripper_{side}_force_ns` /
|
| 402 |
+
`_force_matrix_ns` sparse int64 columns (same host-monotonic clock as
|
| 403 |
+
`hardware_ns`, declared as `encoding: host_monotonic_ns`), so downstream
|
| 404 |
+
can recover the true pairing by nearest-in-time lookup with a precision
|
| 405 |
+
bound of half a force-sample interval. Also fixed
|
| 406 |
+
`rgb_frame_ready`/`stereo_frame_ready`, where `pyqtSignal(int)` marshalled
|
| 407 |
+
`time.monotonic_ns()` through C++ `qint32` and silently truncated it to a
|
| 408 |
+
negative number that flipped sign every 2.147 s — now marshalled as
|
| 409 |
+
`object`. That truncation is also why un-wrapping `hardware_ns` used to
|
| 410 |
+
invent hundreds of frames of phantom drift and report "median 5.8 frames /
|
| 411 |
+
max ±80 frames" as misalignment (the real figure is ~3 frames; the correct
|
| 412 |
+
rule is **unsigned**: a monotonic clock consumed FIFO means true steps are
|
| 413 |
+
never negative). New `scripts/align_modalities.py` provides the
|
| 414 |
+
nearest-in-time alignment on the processing side and explicitly reports
|
| 415 |
+
"cannot align (must re-record)" for episodes recorded before v1.3.3 rather
|
| 416 |
+
than guessing from a growth rate. Follows v1.3.2's pre-ingest rejection of
|
| 417 |
+
stale SLAM frames and the trajectory deep-copy fix.
|
| 418 |
- **v1.3.2** — stale SLAM frames (timestamp regression) are now rejected
|
| 419 |
before they reach the core library: the bridge counts *consecutive*
|
| 420 |
regressions, dropping single-frame glitches but rebasing after 30 — the
|
|
|
|
| 833 |
|
| 834 |
### 更新记录
|
| 835 |
|
| 836 |
+
- **v1.3.4** — 新夹爪接入即自动生成运行标定并连接,不再需要任何人工步骤。
|
| 837 |
+
此前接入一只新 Fays S80M 要人工两步——先在夹爪上位机点 `device_setup`、
|
| 838 |
+
再在采集机跑 `tools/import_gripper_calibration.py` 导入,漏掉任一步主程序
|
| 839 |
+
直接拒绝启动(「当前 Fays 缺少运行标定文件…请先在夹爪上位机中运行
|
| 840 |
+
device_setup」)。现在 `SingleFaysLease.acquire()` 发现 per-serial YAML
|
| 841 |
+
缺失时,就在设备锁内调厂商导出程序从**这只夹爪自身**读出厂标定,生成
|
| 842 |
+
SDK YAML(端口字段改写)与 ORB YAML(鱼眼 `stereoRectify` 求 P1/R1 +
|
| 843 |
+
IMU 外参 `T_b_c1` + 探针读五项噪声/频率),复核落盘路径后直接连上;已有
|
| 844 |
+
标定的夹爪走 `isfile` 快路径,启动零额外开销、不碰设备。这两个文件是
|
| 845 |
+
**逐设备**出厂标定,不可跨设备复用(实测 098/099 三组全不同),只能现场
|
| 846 |
+
读。同时给设备面板的夹爪条目加右键「重新读取出厂标定」(录制中禁用;
|
| 847 |
+
标定前自动关闭该夹爪、完成后开回),并给
|
| 848 |
+
`tools/import_gripper_calibration.py` 加 `--generate`(旧文件先备份
|
| 849 |
+
`.bak_<时间戳>`)供命令行强制重生成。顺带修掉生成产物 ORB YAML 第 3 行的
|
| 850 |
+
出处注释——厂商模板写死指向 `3500000261870088`,照抄会让每只新夹爪的 IMU
|
| 851 |
+
外参都被记成「取自另一台设备」,现改写成本机序列号(历史产物不动)。
|
| 852 |
+
承接 v1.3.3 的力矩阵/触觉力与 RGB 视频的时间戳对齐。
|
| 853 |
+
- **v1.3.3** — 力矩阵/触觉力与 RGB 视频的时间戳对齐。**力侧此前完全没有
|
| 854 |
+
时间戳**:同一行里的 RGB 帧和力样本不是同时刻采集的——RGB 走外部帧源队列
|
| 855 |
+
取**队头最旧帧**、力/矩阵走 latest-wins 单槽取**当下最新**样本,于是
|
| 856 |
+
「行号相同」≠「时刻相同」;力恒领先 RGB,领先量随录制时长增长(RGB 源
|
| 857 |
+
30.84fps vs 写线程 30fps,实测约 1 帧/秒,下游观测到的滞后 3 帧即由此而来),
|
| 858 |
+
力矩阵还走独立泵线程、与 3 向量力各记各的时刻。修法是让每行自描述:
|
| 859 |
+
`tactile_ready` 加第 5 个载荷 `capture_ns`(在 SDK 回调入口取),
|
| 860 |
+
`pipeline.write_tactile_force/_force_matrix` 落成独立的
|
| 861 |
+
`observation.gripper_{side}_force_ns` / `_force_matrix_ns` 稀疏 int64 列
|
| 862 |
+
(与 `hardware_ns` 同宿主单调钟时基,features 里声明
|
| 863 |
+
`encoding: host_monotonic_ns`),下游按时间取最近邻即可还原真实配对,
|
| 864 |
+
精度上界 = 半个力样本间隔。顺带修 `rgb_frame_ready`/`stereo_frame_ready`
|
| 865 |
+
的 `pyqtSignal(int)` 把 `time.monotonic_ns()` 按 C++ qint32 **静默截断成
|
| 866 |
+
负数**(每 2.147s 翻符号),改 `object` 封送——这也解释了此前用
|
| 867 |
+
`hardware_ns` 解回卷时凭空造出上百帧假漂移、把「中位 5.8 帧 / 最大 ±80 帧」
|
| 868 |
+
报成对齐误差(真值是 ~3 帧,正确规则是**无符号**:单调钟 + FIFO 消费 ⇒
|
| 869 |
+
真步长恒非负)。新增 `scripts/align_modalities.py` 处理端最近邻对齐工具,
|
| 870 |
+
对 v1.3.3 之前录的 episode 明确报「无法对齐(只能重录)」而不用增长率去猜。
|
| 871 |
+
承接 v1.3.2 的 SLAM 陈旧帧入库前拦截与轨迹显示深拷贝修复。
|
| 872 |
- **v1.3.2** — SLAM 陈旧帧(时间戳回退)改在入库前拦截:桥接按「连续回退
|
| 873 |
次数」判定——单帧脏读丢弃、连丢 30 帧才判定时钟真跳变并换基准放行(此前
|
| 874 |
每一帧回退都会让核心库清空 IMU 队并重建地图、位姿停发 0.2–1.34 s,静止时
|
collector/config/__init__.py
CHANGED
|
@@ -3,4 +3,4 @@
|
|
| 3 |
版本号集中定义于此:settings.APP_VERSION 及其他模块均从这里取值。
|
| 4 |
"""
|
| 5 |
|
| 6 |
-
__version__ = "1.3.
|
|
|
|
| 3 |
版本号集中定义于此:settings.APP_VERSION 及其他模块均从这里取值。
|
| 4 |
"""
|
| 5 |
|
| 6 |
+
__version__ = "1.3.4" # 新夹爪接入即自动生成运行标定并连接(Fays S80M):此前接入一只新夹爪要人工两步——先在夹爪上位机点 `device_setup`、再在采集机跑 `tools/import_gripper_calibration.py` 导入,漏掉任一步主程序直接拒绝启动(「当前 Fays 缺少运行标定文件…请先在夹爪上位机中运行 device_setup」);现在 `SingleFaysLease.acquire()` 发现 per-serial YAML 缺失时,就在设备锁内调厂商导出程序从**这只夹爪自身**读出厂标定、生成 SDK YAML 与 ORB YAML(鱼眼 `stereoRectify` 求 P1/R1 + IMU 外参 `T_b_c1` + 探针读五项噪声/频率),复核落盘路径后直接连上,已有标定走 `isfile` 快路径(启动零额外开销、不碰设备)——这两个文件是**逐设备**出厂标定不可跨设备复用(实测 098/099 三组全不同),只能现场读;设备面板夹爪条目右键加「重新读取出厂标定」(录制中禁用,标定前自动关该夹爪、完成后开回),`tools/import_gripper_calibration.py` 加 `--generate`(旧文件先备份 `.bak_<时间戳>`)供命令行强制重生成;顺带修掉生成产物第 3 行的出处注释——厂商模板写死指向 `3500000261870088`,照抄会让每只新夹爪的 IMU 外参都被记成「取自另一台设备」,现改写成本机序列号(历史产物不动)。承接 v1.3.3 的力矩阵/触觉力与 RGB 视频的时间戳对齐:**力侧此前完全没有时间戳**——同一行里的 RGB 帧和力样本不是同时刻采集的,RGB 走外部帧源队列取队头最旧帧、力/矩阵走 latest-wins 单槽取当下最新,于是「行号相同」≠「时刻相同」,力恒领先 RGB 且领先量随录制时长增长(RGB 源 30.84fps vs 写线程 30fps,实测约 1 帧/秒,下游观测到的滞后 3 帧就是这么来的),力矩阵走独立泵线程还与 3 向量力各记各的时刻。修法是让每行自描述:`tactile_ready` 加第 5 个载荷 `capture_ns`(在 SDK 回调入口取),`pipeline.write_tactile_force/_force_matrix` 落成独立的 `observation.gripper_{side}_force_ns` / `_force_matrix_ns` 稀疏 int64 列(与 `hardware_ns` 同宿主单��钟时基,features 里声明 `encoding: host_monotonic_ns`),下游按时间取最近邻即可还原真实配对,精度上界=半个力样本间隔;顺带修 `rgb_frame_ready`/`stereo_frame_ready` 的 `pyqtSignal(int)` 把 `time.monotonic_ns()` 按 C++ qint32 静默截断成负数(每 2.147s 翻符号),改 `object` 封送——这也解释了此前用 `hardware_ns` 解回卷时凭空造出上百帧假漂移、把"中位 5.8 帧 / 最大 ±80 帧"报成对齐误差(真值是 ~3 帧,正确规则是**无符号**:单调钟 + FIFO 消费 ⇒ 真步长恒非负);新增 `scripts/align_modalities.py` 处理端最近邻对齐工具,对 v1.3.3 之前录的 episode 明确报「无法对齐(只能重录)」而不用增长率去猜。承接 v1.3.2 的 SLAM 陈旧帧入库前拦截与轨迹显示深拷贝修复。:桥接按「连续回退次数」判定——单帧脏读丢弃、连丢 30 帧才判定时钟真跳变并换基准放行(此前每一帧回退都会让核心库清空 IMU 队并重建地图、位姿停发 0.2–1.34 s,静止时更久),新增 `[TIME_DROP]`/`[TIME_REBASE]` 现场行并**无条件**打进 GUI 日志(此前落进未匹配行被 50 条上限吃掉——实测原生日志 4 次回退、GUI 日志 0 条,真出事时反而看不见),且带 `seq`/`prev_seq` 对比结论以区分「SDK 乱序投递 / 重复投递同一帧 / 帧配了旧时间戳」三种成因(时间戳上三者长得一模一样,对策完全不同);逐秒遥测 `[FPS_DATA]` 改「只在异常时出声」(健康静默、进入异常与恢复各一行、持续异常每 30 s 重复,全量逐秒流仍在原生日志里),并修 `wait_sdk_ready` 就绪门被**粘滞** `state.error` 锁死——任何信息性输出(如 ld.so 的 `cannot be preloaded ... ignored.`)都会让标定明明已完成的这一次返回 False、报出误导的「未等到 [FAYS-CALIB] 标记」(2026-09-10 18:32 假超时事故,文案白名单 + 去掉粘滞判断双管修);原生日志在 runtime 目录 `rmtree` 之前留档到 `logs/slam_native/`(保留最近 20 份),修「一次干净退出的会话其原生日志不可恢复」——排查 SLAM 崩溃时唯一的证据曾随目录一起被删;轨迹显示去掉 Qt 主线程上的整条深拷贝(正是这次拷贝让 `_rendered_trajectory is traj` 判等恒为假、每个位姿都在主线程复制随会话线性增长的点列,即「画一段时间后帧率变低」的直接原因),显示上限 400→6000,并以向量化投影 + 一次 `drawPolyline` 绘制,修「十几秒后轨迹显出折角」(降采样按 stride 翻倍使顶点数恒落 [上限/2, 上限],上限 400 时每段跨 67 ms 且随 stride 每翻一倍继续变粗,观感像 SLAM 出点变慢而数据一直满 30 Hz,是绘制侧丢的);RGB 外部队列在录制开始/结束/中止三个边界排空,修「上一段残留 + 本段启动窗口累积被写成新视频开头」(实测每段开头约 28 帧与上一段 episode 末帧逐帧匹配,队列满时还占 ~110 MB/槽);任务进度只上报后端当前任务列表里存在的任务(本地自建任务平台没这个项目,上报必被拒 400),且后端该项目口径为 `"sessions"`(从没收到过任何上报)时首次送本机**全量**当基线——只送增量会把后端计数从 session 数砸成增量本身(现场:3/3/3 的项目再录一条变 1)。承接 v1.3.1 的力矩阵 5 档落盘与 SLAM 停落 slam_pose 列。
|
collector/config/i18n.py
CHANGED
|
@@ -199,6 +199,11 @@ _TRANSLATIONS = {
|
|
| 199 |
"蓝牙": {"en": "Bluetooth", "zh": "蓝牙"},
|
| 200 |
"开关设备以显示画面": {"en": "Toggle a device to show its feed", "zh": "开关设备以显示画面"},
|
| 201 |
"双击设备可重命名": {"en": "Double-click a device to rename", "zh": "双击设备可重命名"},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
"重命名设备": {"en": "Rename Device", "zh": "重命名设备"},
|
| 203 |
"设备名称:": {"en": "Device name:", "zh": "设备名称:"},
|
| 204 |
"录制中不可更改设备": {"en": "Devices cannot be changed while recording", "zh": "录制中不可更改设备"},
|
|
|
|
| 199 |
"蓝牙": {"en": "Bluetooth", "zh": "蓝牙"},
|
| 200 |
"开关设备以显示画面": {"en": "Toggle a device to show its feed", "zh": "开关设备以显示画面"},
|
| 201 |
"双击设备可重命名": {"en": "Double-click a device to rename", "zh": "双击设备可重命名"},
|
| 202 |
+
# 夹爪 UI 其余文案走中文回落(与既有夹爪弹窗一致);这一句是**追加**在
|
| 203 |
+
# 上面那条已翻译提示后面的,不译就会在英文界面里中英混排,故单独收录。
|
| 204 |
+
";右键夹爪可重读取出厂标定": {
|
| 205 |
+
"en": "; right-click a gripper to re-read its factory calibration",
|
| 206 |
+
"zh": ";右键夹爪可重读取出厂标定"},
|
| 207 |
"重命名设备": {"en": "Rename Device", "zh": "重命名设备"},
|
| 208 |
"设备名称:": {"en": "Device name:", "zh": "设备名称:"},
|
| 209 |
"录制中不可更改设备": {"en": "Devices cannot be changed while recording", "zh": "录制中不可更改设备"},
|
collector/core/egodata_writer.py
CHANGED
|
@@ -643,7 +643,12 @@ class EgoDataWriter(QObject):
|
|
| 643 |
gripper_state [open_pct, gripped, fz_mn]
|
| 644 |
gripper_{left,right}_force [fx,fy,fz] mN
|
| 645 |
gripper_{left,right}_force_matrix 力矩阵变长
|
| 646 |
-
列表(P4 泵线程预编码,无新样本不写键)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 647 |
类型只能区分「家族」,**倍率要另看 info.json
|
| 648 |
features.scale**:
|
| 649 |
int = int16 行差分量化(250×750 展平,cumsum
|
|
@@ -725,7 +730,12 @@ class EgoDataWriter(QObject):
|
|
| 725 |
for key, value in (gripper or {}).items():
|
| 726 |
if value is None:
|
| 727 |
continue
|
| 728 |
-
if key.endswith("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 729 |
row[f"observation.{key}"] = value
|
| 730 |
self._note_matrix_dtype(key, value)
|
| 731 |
elif key.endswith("slam_trajectory"):
|
|
@@ -909,7 +919,11 @@ class EgoDataWriter(QObject):
|
|
| 909 |
# 后者类型按本 episode 实际规格:int16 行差分 / float32 原值)
|
| 910 |
for key in sorted(self._present_gripper):
|
| 911 |
name = f"observation.{key}"
|
| 912 |
-
if key.endswith("
|
|
|
|
|
|
|
|
|
|
|
|
|
| 913 |
item = (pa.float32() if self._matrix_dtype.get(key) == "float32"
|
| 914 |
else pa.int16())
|
| 915 |
cols[name] = pa.array(
|
|
@@ -1041,7 +1055,13 @@ class EgoDataWriter(QObject):
|
|
| 1041 |
# 这里不重写一遍以免两处漂移)
|
| 1042 |
matrix_features = self._force_matrix_features()
|
| 1043 |
for key in sorted(self._present_gripper):
|
| 1044 |
-
if key.endswith("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1045 |
features[f"observation.{key}"] = matrix_features[
|
| 1046 |
f"observation.{key}"]
|
| 1047 |
elif key.endswith("slam_trajectory"):
|
|
|
|
| 643 |
gripper_state [open_pct, gripped, fz_mn]
|
| 644 |
gripper_{left,right}_force [fx,fy,fz] mN
|
| 645 |
gripper_{left,right}_force_matrix 力矩阵变长
|
| 646 |
+
列表(P4 泵线程预编码,无新样本不写键)
|
| 647 |
+
gripper_{left,right}_force_ns /
|
| 648 |
+
gripper_{left,right}_force_matrix_ns int64 采集
|
| 649 |
+
时刻(宿主单调钟纳秒,与 hardware_ns 同时基;
|
| 650 |
+
矩阵与 3 向量力来自不同落盘路径故各记各的)。
|
| 651 |
+
元素
|
| 652 |
类型只能区分「家族」,**倍率要另看 info.json
|
| 653 |
features.scale**:
|
| 654 |
int = int16 行差分量化(250×750 展平,cumsum
|
|
|
|
| 730 |
for key, value in (gripper or {}).items():
|
| 731 |
if value is None:
|
| 732 |
continue
|
| 733 |
+
if key.endswith("_ns"):
|
| 734 |
+
# 采集时刻列(int64 宿主单调钟纳秒,与 hardware_ns 同时基)。
|
| 735 |
+
# 后缀判定必须排在 _force_matrix/_force 之前:`_force_matrix_ns`
|
| 736 |
+
# 不以 `_force_matrix` 结尾只是巧合,靠顺序防止以后改后缀踩雷。
|
| 737 |
+
row[f"observation.{key}"] = int(value)
|
| 738 |
+
elif key.endswith("_force_matrix"):
|
| 739 |
row[f"observation.{key}"] = value
|
| 740 |
self._note_matrix_dtype(key, value)
|
| 741 |
elif key.endswith("slam_trajectory"):
|
|
|
|
| 919 |
# 后者类型按本 episode 实际规格:int16 行差分 / float32 原值)
|
| 920 |
for key in sorted(self._present_gripper):
|
| 921 |
name = f"observation.{key}"
|
| 922 |
+
if key.endswith("_ns"):
|
| 923 |
+
# 采集时刻(缺失帧填 0 = 未知,与 hardware_ns 的 0 约定一致)
|
| 924 |
+
cols[name] = pa.array(
|
| 925 |
+
[int(r.get(name, 0)) for r in rows], pa.int64())
|
| 926 |
+
elif key.endswith("_force_matrix"):
|
| 927 |
item = (pa.float32() if self._matrix_dtype.get(key) == "float32"
|
| 928 |
else pa.int16())
|
| 929 |
cols[name] = pa.array(
|
|
|
|
| 1055 |
# 这里不重写一遍以免两处漂移)
|
| 1056 |
matrix_features = self._force_matrix_features()
|
| 1057 |
for key in sorted(self._present_gripper):
|
| 1058 |
+
if key.endswith("_ns"):
|
| 1059 |
+
# 采集时刻:宿主单调钟纳秒,与 hardware_ns 同一时基。
|
| 1060 |
+
# 下游按此把力样本重采样到 RGB 帧时刻(见 docs/data.md)。
|
| 1061 |
+
features[f"observation.{key}"] = {
|
| 1062 |
+
"dtype": "int64", "shape": [1],
|
| 1063 |
+
"encoding": "host_monotonic_ns"}
|
| 1064 |
+
elif key.endswith("_force_matrix"):
|
| 1065 |
features[f"observation.{key}"] = matrix_features[
|
| 1066 |
f"observation.{key}"]
|
| 1067 |
elif key.endswith("slam_trajectory"):
|
collector/core/gripper/bridge.py
CHANGED
|
@@ -168,13 +168,21 @@ class _SerialLifecycleAdapter:
|
|
| 168 |
class GripperBridge(QObject):
|
| 169 |
"""One open gripper session; owns workers, emits events."""
|
| 170 |
|
| 171 |
-
stereo_frame_ready = pyqtSignal(str, object,
|
| 172 |
# slot("gripper_stereo_left"), bgr ndarray, host_monotonic_ns
|
| 173 |
-
rgb_frame_ready = pyqtSignal(object,
|
| 174 |
-
tactile_ready = pyqtSignal(str, object, object, object)
|
| 175 |
# side("left"|"right"), heatmap(320x240x3 RGB,worker 已 BGR→RGB),
|
| 176 |
# force(fx,fy,fz mN),
|
| 177 |
-
# force_matrix(250x250x3 float32) 或 None(矩阵回传关闭时)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
pose_ready = pyqtSignal(object, object, object, object)
|
| 179 |
# pos(x,y,z), quat(qx,qy,qz,qw), trajectory(位置点不可变元组,新点追加才重建),
|
| 180 |
# timestamp(SLAM 秒,与轨迹 txt 第一列同源——轨迹并入 episode parquet 后
|
|
@@ -515,6 +523,11 @@ class GripperBridge(QObject):
|
|
| 515 |
self._post_frame("rgb", frame, time.monotonic_ns())
|
| 516 |
|
| 517 |
def _on_tactile_result(self, side, heatmap, force, force_matrix):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 518 |
if side in ("left", "right"):
|
| 519 |
try:
|
| 520 |
self._latest_force[side] = tuple(
|
|
@@ -523,14 +536,17 @@ class GripperBridge(QObject):
|
|
| 523 |
pass
|
| 524 |
if force_matrix is not None:
|
| 525 |
with self._matrix_lock:
|
| 526 |
-
|
|
|
|
|
|
|
| 527 |
self._matrix_seq[side] += 1
|
| 528 |
if side not in self._matrix_first_logged:
|
| 529 |
self._matrix_first_logged.add(side)
|
| 530 |
self._log(
|
| 531 |
"[Gripper-Tactile] {} 侧力矩阵首帧回传 shape={}".format(
|
| 532 |
side, force_matrix.shape))
|
| 533 |
-
self._post_frame("tactile", side, heatmap, force, force_matrix
|
|
|
|
| 534 |
|
| 535 |
# ---- P4 串口/夹爪状态(heartbeat 与 grip 循环线程调用) ----
|
| 536 |
def _on_board_update(self, snapshot):
|
|
@@ -575,9 +591,23 @@ class GripperBridge(QObject):
|
|
| 575 |
with self._matrix_lock:
|
| 576 |
return self._matrix_seq.get(side, 0)
|
| 577 |
|
| 578 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 579 |
with self._matrix_lock:
|
| 580 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 581 |
|
| 582 |
def _on_slam_pose(self, pose):
|
| 583 |
"""SlamProcessController 工作线程回调:位姿进队列保序。
|
|
|
|
| 168 |
class GripperBridge(QObject):
|
| 169 |
"""One open gripper session; owns workers, emits events."""
|
| 170 |
|
| 171 |
+
stereo_frame_ready = pyqtSignal(str, object, object)
|
| 172 |
# slot("gripper_stereo_left"), bgr ndarray, host_monotonic_ns
|
| 173 |
+
rgb_frame_ready = pyqtSignal(object, object) # bgr ndarray, host_monotonic_ns
|
| 174 |
+
tactile_ready = pyqtSignal(str, object, object, object, object)
|
| 175 |
# side("left"|"right"), heatmap(320x240x3 RGB,worker 已 BGR→RGB),
|
| 176 |
# force(fx,fy,fz mN),
|
| 177 |
+
# force_matrix(250x250x3 float32) 或 None(矩阵回传关闭时),
|
| 178 |
+
# capture_ns(宿主单调钟纳秒,本样本的采集时刻)
|
| 179 |
+
#
|
| 180 |
+
# ★ 时间戳一律走 object:PyQt5 队列信号会把 Python int 按 C++ qint32
|
| 181 |
+
# 封送,超过 2^31(≈2.147s 的纳秒数)即**静默截断成负数**。曾经
|
| 182 |
+
# rgb/stereo 两处写 int,落盘的 hardware_ns 因此每 2.147s 翻一次
|
| 183 |
+
# 符号,下游拿它做不了任何对齐(且解回卷在 ±2.147s 歧义边界上
|
| 184 |
+
# 猜错会凭空造出上百帧的假漂移)。与 main_window 的
|
| 185 |
+
# stereo_frame_ready 用 object 同理。
|
| 186 |
pose_ready = pyqtSignal(object, object, object, object)
|
| 187 |
# pos(x,y,z), quat(qx,qy,qz,qw), trajectory(位置点不可变元组,新点追加才重建),
|
| 188 |
# timestamp(SLAM 秒,与轨迹 txt 第一列同源——轨迹并入 episode parquet 后
|
|
|
|
| 523 |
self._post_frame("rgb", frame, time.monotonic_ns())
|
| 524 |
|
| 525 |
def _on_tactile_result(self, side, heatmap, force, force_matrix):
|
| 526 |
+
# 采集时刻在回调入口取(最接近样本真实到达时刻),随信号一起送到
|
| 527 |
+
# 落盘侧:力/矩阵与 RGB 走的是两条互不相干的支路(力是 latest-wins
|
| 528 |
+
# 单槽、RGB 是 FIFO 队头最旧帧),两者在行内的先后完全由各自的队列
|
| 529 |
+
# 滞留决定。只有把各自的采集时刻都记下来,下游才能按时间重对齐。
|
| 530 |
+
capture_ns = time.monotonic_ns()
|
| 531 |
if side in ("left", "right"):
|
| 532 |
try:
|
| 533 |
self._latest_force[side] = tuple(
|
|
|
|
| 536 |
pass
|
| 537 |
if force_matrix is not None:
|
| 538 |
with self._matrix_lock:
|
| 539 |
+
# 与 matrix 同锁存:泵线程取出的 ns 恒与矩阵配对,
|
| 540 |
+
# 不会出现「新矩阵配了旧时刻」
|
| 541 |
+
self._latest_matrix[side] = (capture_ns, force_matrix)
|
| 542 |
self._matrix_seq[side] += 1
|
| 543 |
if side not in self._matrix_first_logged:
|
| 544 |
self._matrix_first_logged.add(side)
|
| 545 |
self._log(
|
| 546 |
"[Gripper-Tactile] {} 侧力矩阵首帧回传 shape={}".format(
|
| 547 |
side, force_matrix.shape))
|
| 548 |
+
self._post_frame("tactile", side, heatmap, force, force_matrix,
|
| 549 |
+
capture_ns)
|
| 550 |
|
| 551 |
# ---- P4 串口/夹爪状态(heartbeat 与 grip 循环线程调用) ----
|
| 552 |
def _on_board_update(self, snapshot):
|
|
|
|
| 591 |
with self._matrix_lock:
|
| 592 |
return self._matrix_seq.get(side, 0)
|
| 593 |
|
| 594 |
+
def latest_matrix_stamped(self, side):
|
| 595 |
+
"""最新力矩阵连同它的采集时刻 → (capture_ns, matrix),无则 None。
|
| 596 |
+
|
| 597 |
+
ns 与 matrix 在同一次加锁里取出,**恒配对**(分两次取会出现
|
| 598 |
+
「拿到新矩阵、配了旧时刻」)。泵线程用这个版本落盘。
|
| 599 |
+
"""
|
| 600 |
with self._matrix_lock:
|
| 601 |
+
entry = self._latest_matrix.get(side)
|
| 602 |
+
if entry is None:
|
| 603 |
+
return None
|
| 604 |
+
ns, matrix = entry
|
| 605 |
+
return int(ns), matrix
|
| 606 |
+
|
| 607 |
+
def latest_matrix(self, side):
|
| 608 |
+
"""最新力矩阵(不含时刻;需要时刻用 latest_matrix_stamped)。"""
|
| 609 |
+
stamped = self.latest_matrix_stamped(side)
|
| 610 |
+
return None if stamped is None else stamped[1]
|
| 611 |
|
| 612 |
def _on_slam_pose(self, pose):
|
| 613 |
"""SlamProcessController 工作线程回调:位姿进队列保序。
|
collector/core/gripper/calibration.py
ADDED
|
@@ -0,0 +1,566 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""现场读取一只 Fays 的出厂标定,生成它的 per-serial 运行文件。
|
| 2 |
+
|
| 3 |
+
厂商 ``dump_calib_opencv48`` 是唯一可信来源:``Camera1.fx/fy/cx/cy``、
|
| 4 |
+
``Stereo.b``、``IMU.T_b_c1`` 全是**逐设备**出厂标定,实测 098 与 099 三组
|
| 5 |
+
数值全不同,抄别人的会让 SLAM 初始化失败或位姿系统性跑偏。本模块从
|
| 6 |
+
``online/gripper_version1/fays_calibration.py`` 分叉而来(那份只在上位机
|
| 7 |
+
跑,且 ``online/`` 不入库),路径常量改指 ``core/gripper/native/``,两个
|
| 8 |
+
子进程补上 collector 的跨进程设备锁与 OpenCV 4.2 探针环境。
|
| 9 |
+
|
| 10 |
+
生成的三个产物(与原 device_setup 一致):
|
| 11 |
+
|
| 12 |
+
native/config/calibration/FS-VI80-<model>_<serial>_dump_calib.yaml
|
| 13 |
+
native/gripper_version1/fays_config/fays_vikit_<serial>.yaml
|
| 14 |
+
native/dist/fays_opencv48/s80m_<serial>_stereo_inertial.yaml
|
| 15 |
+
|
| 16 |
+
后两个正是 ``paths.per_device_fays_yamls()`` 要的文件,写齐即可开夹爪。
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import os
|
| 22 |
+
import re
|
| 23 |
+
import shutil
|
| 24 |
+
import subprocess
|
| 25 |
+
import tempfile
|
| 26 |
+
from typing import Mapping, Optional
|
| 27 |
+
|
| 28 |
+
from core.gripper import paths
|
| 29 |
+
from core.gripper.fays_runtime import FAYS_DEVICE_CONFIG, build_fays_probe_env
|
| 30 |
+
from core.gripper.fays_serial_probe import render_probe_config
|
| 31 |
+
from core.gripper.runtime.device_access import (
|
| 32 |
+
FAYS_SDK_INITIALIZATION_LOCK,
|
| 33 |
+
device_access_guard,
|
| 34 |
+
fays_device_guard,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
DUMP_BINARY = os.path.abspath(os.environ.get(
|
| 39 |
+
"KSQ_FAYS_CALIBRATION_DUMP",
|
| 40 |
+
os.path.join(
|
| 41 |
+
paths.DIST_ROOT, "fays_opencv48", "bin", "dump_calib_opencv48",
|
| 42 |
+
),
|
| 43 |
+
))
|
| 44 |
+
# 与序列号探针是同一个二进制(既打 device.serial= 也打 imu.*=),
|
| 45 |
+
# 因此直接复用 paths 里那份已随包交付的路径。
|
| 46 |
+
IMU_PROBE_BINARY = os.path.abspath(os.environ.get(
|
| 47 |
+
"KSQ_FAYS_IMU_CALIBRATION_PROBE", paths.FAYS_CALIBRATION_PROBE,
|
| 48 |
+
))
|
| 49 |
+
ORB_TEMPLATE = os.path.abspath(os.environ.get(
|
| 50 |
+
"KSQ_FAYS_ORB_TEMPLATE",
|
| 51 |
+
os.path.join(
|
| 52 |
+
paths.ORB_ROOT, "Examples", "fays", "s80m_stereo_inertial.yaml",
|
| 53 |
+
),
|
| 54 |
+
))
|
| 55 |
+
SDK_TEMPLATE = FAYS_DEVICE_CONFIG
|
| 56 |
+
# 原始 dump 交给 AIKit 服务路径(fays_runtime._factory_calibration_for_serial
|
| 57 |
+
# 按 `FS-VI80-*_{serial}_dump_calib.yaml` 唯一命中)。
|
| 58 |
+
DUMP_OUTPUT_DIR = os.path.join(paths.NATIVE_ROOT, "config", "calibration")
|
| 59 |
+
SDK_CONFIG_DIR = paths.FAYS_CONFIG_DIR
|
| 60 |
+
ORB_OUTPUT_DIR = paths.ORB_DEVICE_CONFIG_DIR
|
| 61 |
+
|
| 62 |
+
_SERIAL_PATTERN = re.compile(r"^[A-Za-z0-9._:-]+$")
|
| 63 |
+
_PORT_PATTERN = re.compile(r"/dev/video\d+")
|
| 64 |
+
_DUMP_NAME_PATTERN = re.compile(r"^FS-VI80-.+_dump_calib\.yaml$")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _log(logger, text):
|
| 68 |
+
if logger is not None:
|
| 69 |
+
try:
|
| 70 |
+
logger(text)
|
| 71 |
+
except Exception: # 日志永远不能拖垮标定流程
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _spawn(executable, config_path, ports, temp_dir, timeout):
|
| 76 |
+
"""在 SDK 初始化锁 + 本设备锁下跑一次厂商二进制。
|
| 77 |
+
|
| 78 |
+
两把锁缺一不可:初始化锁挡住与序列号探针/桥接并发初始化 SDK,设备锁挡住
|
| 79 |
+
与另一只夹爪同时开流。
|
| 80 |
+
"""
|
| 81 |
+
if not os.path.isfile(executable):
|
| 82 |
+
raise RuntimeError(f"厂商标定程序不存在: {executable}")
|
| 83 |
+
if not os.access(executable, os.X_OK):
|
| 84 |
+
raise RuntimeError(f"厂商标定程序不可执行: {executable}")
|
| 85 |
+
environment = build_fays_probe_env()
|
| 86 |
+
environment.setdefault("ASAN_OPTIONS", "detect_leaks=0")
|
| 87 |
+
with device_access_guard(FAYS_SDK_INITIALIZATION_LOCK, timeout=timeout), \
|
| 88 |
+
fays_device_guard(ports["stereo_dev_port"], timeout=timeout):
|
| 89 |
+
return subprocess.run(
|
| 90 |
+
[executable, config_path],
|
| 91 |
+
cwd=temp_dir,
|
| 92 |
+
capture_output=True,
|
| 93 |
+
text=True,
|
| 94 |
+
timeout=timeout,
|
| 95 |
+
env=environment,
|
| 96 |
+
check=False,
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _find_dump(output_root: str, product_serial: str) -> str:
|
| 101 |
+
candidates = []
|
| 102 |
+
for directory, _subdirectories, filenames in os.walk(output_root):
|
| 103 |
+
for filename in filenames:
|
| 104 |
+
if _DUMP_NAME_PATTERN.fullmatch(filename):
|
| 105 |
+
candidates.append(os.path.join(directory, filename))
|
| 106 |
+
matching = [
|
| 107 |
+
path for path in candidates
|
| 108 |
+
if product_serial in os.path.basename(path)
|
| 109 |
+
]
|
| 110 |
+
if len(matching) != 1:
|
| 111 |
+
if not matching and len(candidates) == 1:
|
| 112 |
+
raise RuntimeError(
|
| 113 |
+
"官方工具生成的标定文件序列号不匹配: "
|
| 114 |
+
f"expected={product_serial}, file={os.path.basename(candidates[0])}"
|
| 115 |
+
)
|
| 116 |
+
raise RuntimeError(
|
| 117 |
+
"官方工具未生成唯一的当前设备标定 YAML: "
|
| 118 |
+
f"expected={product_serial}, files="
|
| 119 |
+
f"{', '.join(os.path.basename(path) for path in candidates) or '<none>'}"
|
| 120 |
+
)
|
| 121 |
+
return matching[0]
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _copy_atomically(source: str, destination: str) -> str:
|
| 125 |
+
os.makedirs(os.path.dirname(destination), exist_ok=True)
|
| 126 |
+
temporary = f"{destination}.tmp.{os.getpid()}"
|
| 127 |
+
try:
|
| 128 |
+
with open(source, "rb") as source_stream, open(temporary, "wb") as target:
|
| 129 |
+
shutil.copyfileobj(source_stream, target)
|
| 130 |
+
target.flush()
|
| 131 |
+
os.fsync(target.fileno())
|
| 132 |
+
try:
|
| 133 |
+
os.chmod(temporary, 0o600)
|
| 134 |
+
except OSError:
|
| 135 |
+
pass
|
| 136 |
+
os.replace(temporary, destination)
|
| 137 |
+
except OSError as exc:
|
| 138 |
+
try:
|
| 139 |
+
os.unlink(temporary)
|
| 140 |
+
except OSError:
|
| 141 |
+
pass
|
| 142 |
+
raise RuntimeError(
|
| 143 |
+
f"保存 Fays 标定 YAML 失败: {destination}: {exc}"
|
| 144 |
+
) from exc
|
| 145 |
+
return destination
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _write_text_atomically(destination: str, content: str) -> str:
|
| 149 |
+
os.makedirs(os.path.dirname(destination), exist_ok=True)
|
| 150 |
+
temporary = f"{destination}.tmp.{os.getpid()}"
|
| 151 |
+
try:
|
| 152 |
+
with open(temporary, "w", encoding="utf-8") as stream:
|
| 153 |
+
stream.write(content)
|
| 154 |
+
stream.flush()
|
| 155 |
+
os.fsync(stream.fileno())
|
| 156 |
+
try:
|
| 157 |
+
os.chmod(temporary, 0o600)
|
| 158 |
+
except OSError:
|
| 159 |
+
pass
|
| 160 |
+
os.replace(temporary, destination)
|
| 161 |
+
except OSError as exc:
|
| 162 |
+
try:
|
| 163 |
+
os.unlink(temporary)
|
| 164 |
+
except OSError:
|
| 165 |
+
pass
|
| 166 |
+
raise RuntimeError(
|
| 167 |
+
f"保存 Fays ORB YAML 失败: {destination}: {exc}"
|
| 168 |
+
) from exc
|
| 169 |
+
return destination
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def write_fays_sdk_yaml(
|
| 173 |
+
product_serial: str,
|
| 174 |
+
ports: Mapping[str, str],
|
| 175 |
+
*,
|
| 176 |
+
template_path: Optional[str] = None,
|
| 177 |
+
config_dir: Optional[str] = None,
|
| 178 |
+
) -> str:
|
| 179 |
+
"""按 per-serial 模板写 ``fays_vikit_<serial>.yaml``(端口逐台不同)。"""
|
| 180 |
+
serial = str(product_serial or "").strip()
|
| 181 |
+
if not _SERIAL_PATTERN.fullmatch(serial):
|
| 182 |
+
raise ValueError(f"Fays 产品序列号无效: {product_serial!r}")
|
| 183 |
+
stereo = str(ports.get("stereo_dev_port", "")).strip()
|
| 184 |
+
imu = str(ports.get("imu_dev_port", "")).strip()
|
| 185 |
+
if not _PORT_PATTERN.fullmatch(stereo):
|
| 186 |
+
raise ValueError(f"stereo_dev_port 无效: {stereo!r}")
|
| 187 |
+
if not _PORT_PATTERN.fullmatch(imu):
|
| 188 |
+
raise ValueError(f"imu_dev_port 无效: {imu!r}")
|
| 189 |
+
template = os.path.abspath(template_path or SDK_TEMPLATE)
|
| 190 |
+
try:
|
| 191 |
+
with open(template, encoding="utf-8") as stream:
|
| 192 |
+
content = stream.read()
|
| 193 |
+
except OSError as exc:
|
| 194 |
+
raise RuntimeError(f"无法读取 Fays 模板: {template}: {exc}") from exc
|
| 195 |
+
for key, value in (("stereo_dev_port", stereo), ("imu_dev_port", imu)):
|
| 196 |
+
content, count = re.subn(
|
| 197 |
+
rf"^(\s*{re.escape(key)}\s*:)\s*[^\s#]+",
|
| 198 |
+
rf"\1 {value}",
|
| 199 |
+
content,
|
| 200 |
+
count=1,
|
| 201 |
+
flags=re.MULTILINE,
|
| 202 |
+
)
|
| 203 |
+
if count != 1:
|
| 204 |
+
raise RuntimeError(f"Fays 模板无法定位字段: {key}")
|
| 205 |
+
destination = os.path.join(
|
| 206 |
+
os.path.abspath(config_dir or SDK_CONFIG_DIR),
|
| 207 |
+
f"fays_vikit_{serial}.yaml",
|
| 208 |
+
)
|
| 209 |
+
return _write_text_atomically(destination, content)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def run_imu_probe(
|
| 213 |
+
ports: Mapping[str, str],
|
| 214 |
+
*,
|
| 215 |
+
probe_binary: Optional[str] = None,
|
| 216 |
+
template_path: Optional[str] = None,
|
| 217 |
+
timeout: float = 60.0,
|
| 218 |
+
) -> str:
|
| 219 |
+
"""跑一次官方探针,返回它的原始输出(IMU 噪声模型从中解析)。"""
|
| 220 |
+
executable = os.path.abspath(probe_binary or IMU_PROBE_BINARY)
|
| 221 |
+
with tempfile.TemporaryDirectory(prefix="ksq-fays-imu-probe-") as temp_dir:
|
| 222 |
+
config_path = render_probe_config(
|
| 223 |
+
ports,
|
| 224 |
+
os.path.join(temp_dir, "fays_vikit_imu_probe.yaml"),
|
| 225 |
+
template_path=template_path,
|
| 226 |
+
)
|
| 227 |
+
try:
|
| 228 |
+
completed = _spawn(executable, config_path, ports, temp_dir, timeout)
|
| 229 |
+
except subprocess.TimeoutExpired as exc:
|
| 230 |
+
raise RuntimeError(
|
| 231 |
+
f"Fays IMU 标定读取超时: timeout={exc.timeout}s"
|
| 232 |
+
) from exc
|
| 233 |
+
output = (completed.stdout or "") + "\n" + (completed.stderr or "")
|
| 234 |
+
if completed.returncode != 0:
|
| 235 |
+
tail = "\n".join(output.splitlines()[-20:])
|
| 236 |
+
raise RuntimeError(
|
| 237 |
+
"Fays IMU 标定读取失败: "
|
| 238 |
+
f"returncode={completed.returncode}\n{tail}"
|
| 239 |
+
)
|
| 240 |
+
return output
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def dump_fays_calibration(
|
| 244 |
+
product_serial: str,
|
| 245 |
+
ports: Mapping[str, str],
|
| 246 |
+
*,
|
| 247 |
+
output_dir: Optional[str] = None,
|
| 248 |
+
dump_binary: Optional[str] = None,
|
| 249 |
+
template_path: Optional[str] = None,
|
| 250 |
+
timeout: float = 60.0,
|
| 251 |
+
) -> str:
|
| 252 |
+
"""跑官方导出程序,把这只设备的出厂标定存成 ``FS-VI80-*_dump_calib.yaml``。"""
|
| 253 |
+
serial = str(product_serial or "").strip()
|
| 254 |
+
if not _SERIAL_PATTERN.fullmatch(serial):
|
| 255 |
+
raise ValueError(f"Fays 产品序列号无效: {product_serial!r}")
|
| 256 |
+
executable = os.path.abspath(dump_binary or DUMP_BINARY)
|
| 257 |
+
with tempfile.TemporaryDirectory(prefix="ksq-fays-calibration-") as temp_dir:
|
| 258 |
+
config_path = render_probe_config(
|
| 259 |
+
ports,
|
| 260 |
+
os.path.join(temp_dir, "fays_vikit_calibration.yaml"),
|
| 261 |
+
template_path=template_path,
|
| 262 |
+
)
|
| 263 |
+
try:
|
| 264 |
+
completed = _spawn(executable, config_path, ports, temp_dir, timeout)
|
| 265 |
+
except subprocess.TimeoutExpired as exc:
|
| 266 |
+
raise RuntimeError(
|
| 267 |
+
f"Fays 标定导出超时: serial={serial}, timeout={exc.timeout}s"
|
| 268 |
+
) from exc
|
| 269 |
+
output = (completed.stdout or "") + "\n" + (completed.stderr or "")
|
| 270 |
+
if completed.returncode != 0:
|
| 271 |
+
tail = "\n".join(output.splitlines()[-20:])
|
| 272 |
+
raise RuntimeError(
|
| 273 |
+
"Fays 官方标定导出失败: "
|
| 274 |
+
f"serial={serial}, returncode={completed.returncode}\n{tail}"
|
| 275 |
+
)
|
| 276 |
+
source = _find_dump(temp_dir, serial)
|
| 277 |
+
destination = os.path.join(
|
| 278 |
+
os.path.abspath(output_dir or DUMP_OUTPUT_DIR),
|
| 279 |
+
os.path.basename(source),
|
| 280 |
+
)
|
| 281 |
+
return _copy_atomically(source, destination)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _numbers(value: str):
|
| 285 |
+
return [float(item.strip()) for item in value.split(",") if item.strip()]
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def _parse_factory_dump(path: str):
|
| 289 |
+
"""Parse the small, fixed schema emitted by FAYS_VIK_DumpCalib."""
|
| 290 |
+
try:
|
| 291 |
+
with open(path, encoding="utf-8") as stream:
|
| 292 |
+
content = stream.read()
|
| 293 |
+
except OSError as exc:
|
| 294 |
+
raise RuntimeError(f"无法读取 Fays 工厂标定: {path}: {exc}") from exc
|
| 295 |
+
|
| 296 |
+
cameras = []
|
| 297 |
+
for index in range(2):
|
| 298 |
+
section_match = re.search(rf"(?m)^cam{index}:\s*$", content)
|
| 299 |
+
if section_match is None:
|
| 300 |
+
raise RuntimeError(f"Fays 标定缺少 cam{index}: {path}")
|
| 301 |
+
next_match = re.search(
|
| 302 |
+
rf"(?m)^cam{index + 1}:\s*$",
|
| 303 |
+
content[section_match.end():],
|
| 304 |
+
)
|
| 305 |
+
section_end = (
|
| 306 |
+
section_match.end() + next_match.start()
|
| 307 |
+
if next_match is not None else len(content)
|
| 308 |
+
)
|
| 309 |
+
section = content[section_match.end():section_end]
|
| 310 |
+
|
| 311 |
+
def vector(key, expected):
|
| 312 |
+
match = re.search(
|
| 313 |
+
rf"(?m)^\s*{re.escape(key)}:\s*\[([^\]]+)\]",
|
| 314 |
+
section,
|
| 315 |
+
)
|
| 316 |
+
if match is None:
|
| 317 |
+
raise RuntimeError(f"Fays cam{index} 缺少 {key}")
|
| 318 |
+
values = _numbers(match.group(1))
|
| 319 |
+
if len(values) != expected:
|
| 320 |
+
raise RuntimeError(f"Fays cam{index} 的 {key} 长度错误")
|
| 321 |
+
return values
|
| 322 |
+
|
| 323 |
+
def matrix(key):
|
| 324 |
+
match = re.search(
|
| 325 |
+
rf"(?ms)^\s*{re.escape(key)}:\s*\n"
|
| 326 |
+
rf"((?:^\s*-\s*\[[^\n]+\]\s*\n?){{4}})",
|
| 327 |
+
section,
|
| 328 |
+
)
|
| 329 |
+
if match is None:
|
| 330 |
+
raise RuntimeError(f"Fays cam{index} 缺少 {key}")
|
| 331 |
+
rows = re.findall(
|
| 332 |
+
r"^\s*-\s*\[([^\]]+)\]",
|
| 333 |
+
match.group(1),
|
| 334 |
+
re.MULTILINE,
|
| 335 |
+
)
|
| 336 |
+
values = [_numbers(row) for row in rows]
|
| 337 |
+
if len(values) != 4 or any(len(row) != 4 for row in values):
|
| 338 |
+
raise RuntimeError(f"Fays cam{index} 的 {key} 不是 4x4")
|
| 339 |
+
return values
|
| 340 |
+
|
| 341 |
+
cameras.append({
|
| 342 |
+
"intrinsics": vector("intrinsics", 4),
|
| 343 |
+
"distortion": vector("distortion_coeffs", 4),
|
| 344 |
+
"resolution": vector("resolution", 2),
|
| 345 |
+
"T_cam_imu": matrix("T_cam_imu"),
|
| 346 |
+
"T_cn_cnm1": (
|
| 347 |
+
matrix("T_cn_cnm1") if index == 1 else None
|
| 348 |
+
),
|
| 349 |
+
"timeshift": float(re.search(
|
| 350 |
+
rf"(?m)^\s*timeshift_cam_imu:\s*([^\s#]+)",
|
| 351 |
+
section,
|
| 352 |
+
).group(1)),
|
| 353 |
+
})
|
| 354 |
+
if cameras[0]["resolution"] != cameras[1]["resolution"]:
|
| 355 |
+
raise RuntimeError("Fays 双目分辨率不一致")
|
| 356 |
+
return cameras
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def _parse_imu_probe(output: str):
|
| 360 |
+
fields = {
|
| 361 |
+
"noise_acc": "accelerometer_noise_density",
|
| 362 |
+
"walk_acc": "accelerometer_random_walk",
|
| 363 |
+
"noise_gyro": "gyroscope_noise_density",
|
| 364 |
+
"walk_gyro": "gyroscope_random_walk",
|
| 365 |
+
"imu_hz": "update_rate",
|
| 366 |
+
}
|
| 367 |
+
values = {}
|
| 368 |
+
for target, source in fields.items():
|
| 369 |
+
match = re.search(
|
| 370 |
+
rf"(?m)^imu\.{re.escape(source)}=([^\s#]+)\s*$",
|
| 371 |
+
output,
|
| 372 |
+
)
|
| 373 |
+
if match is None:
|
| 374 |
+
raise RuntimeError(f"Fays IMU 标定输出缺少 imu.{source}")
|
| 375 |
+
value = float(match.group(1))
|
| 376 |
+
if value <= 0:
|
| 377 |
+
raise RuntimeError(f"Fays IMU 标定值无效: imu.{source}={value}")
|
| 378 |
+
values[target] = value
|
| 379 |
+
return values
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def _replace_yaml_scalar(content: str, key: str, value) -> str:
|
| 383 |
+
rendered = str(value)
|
| 384 |
+
if isinstance(value, float) and "." not in rendered:
|
| 385 |
+
rendered += ".0"
|
| 386 |
+
updated, count = re.subn(
|
| 387 |
+
rf"(?m)^{re.escape(key)}\s*:\s*[^\n]*$",
|
| 388 |
+
f"{key}: {rendered}",
|
| 389 |
+
content,
|
| 390 |
+
count=1,
|
| 391 |
+
)
|
| 392 |
+
if count != 1:
|
| 393 |
+
raise RuntimeError(f"ORB YAML 模板缺少字段: {key}")
|
| 394 |
+
return updated
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def generate_orb_yaml(
|
| 398 |
+
product_serial: str,
|
| 399 |
+
dump_path: str,
|
| 400 |
+
imu_output: str,
|
| 401 |
+
*,
|
| 402 |
+
template_path: Optional[str] = None,
|
| 403 |
+
output_dir: Optional[str] = None,
|
| 404 |
+
) -> str:
|
| 405 |
+
"""把设备 dump 换算成 ORB 的双目矫正内参 + IMU 外��� YAML。"""
|
| 406 |
+
try:
|
| 407 |
+
import cv2
|
| 408 |
+
import numpy as np
|
| 409 |
+
except ImportError as exc:
|
| 410 |
+
raise RuntimeError("生成 ORB YAML 需要 OpenCV/Numpy") from exc
|
| 411 |
+
|
| 412 |
+
cameras = _parse_factory_dump(dump_path)
|
| 413 |
+
imu = _parse_imu_probe(imu_output)
|
| 414 |
+
left, right = cameras
|
| 415 |
+
left_intrinsics = left["intrinsics"]
|
| 416 |
+
right_intrinsics = right["intrinsics"]
|
| 417 |
+
K1 = np.array([
|
| 418 |
+
[left_intrinsics[0], 0.0, left_intrinsics[2]],
|
| 419 |
+
[0.0, left_intrinsics[1], left_intrinsics[3]],
|
| 420 |
+
[0.0, 0.0, 1.0],
|
| 421 |
+
], dtype=float)
|
| 422 |
+
K2 = np.array([
|
| 423 |
+
[right_intrinsics[0], 0.0, right_intrinsics[2]],
|
| 424 |
+
[0.0, right_intrinsics[1], right_intrinsics[3]],
|
| 425 |
+
[0.0, 0.0, 1.0],
|
| 426 |
+
], dtype=float)
|
| 427 |
+
D1 = np.array(left["distortion"], dtype=float).reshape(1, 4)
|
| 428 |
+
D2 = np.array(right["distortion"], dtype=float).reshape(1, 4)
|
| 429 |
+
T_lr = np.array(right["T_cn_cnm1"], dtype=float)
|
| 430 |
+
T_cam_imu = np.array(left["T_cam_imu"], dtype=float)
|
| 431 |
+
resolution = tuple(int(value) for value in left["resolution"])
|
| 432 |
+
try:
|
| 433 |
+
R1, _R2, P1, _P2, _Q = cv2.fisheye.stereoRectify(
|
| 434 |
+
K1,
|
| 435 |
+
D1,
|
| 436 |
+
K2,
|
| 437 |
+
D2,
|
| 438 |
+
resolution,
|
| 439 |
+
T_lr[:3, :3],
|
| 440 |
+
T_lr[:3, 3],
|
| 441 |
+
flags=cv2.CALIB_ZERO_DISPARITY,
|
| 442 |
+
)
|
| 443 |
+
T_rectified_to_unrectified = np.eye(4, dtype=float)
|
| 444 |
+
T_rectified_to_unrectified[:3, :3] = R1.T
|
| 445 |
+
T_b_c1 = np.linalg.inv(T_cam_imu) @ T_rectified_to_unrectified
|
| 446 |
+
except Exception as exc:
|
| 447 |
+
raise RuntimeError(f"Fays 双目鱼眼校正失败: {exc}") from exc
|
| 448 |
+
|
| 449 |
+
try:
|
| 450 |
+
with open(
|
| 451 |
+
os.path.abspath(template_path or ORB_TEMPLATE),
|
| 452 |
+
encoding="utf-8",
|
| 453 |
+
) as stream:
|
| 454 |
+
content = stream.read()
|
| 455 |
+
except OSError as exc:
|
| 456 |
+
raise RuntimeError(
|
| 457 |
+
f"无法读取 ORB YAML 模板: {template_path or ORB_TEMPLATE}"
|
| 458 |
+
) from exc
|
| 459 |
+
|
| 460 |
+
model = os.path.basename(dump_path).split(f"_{product_serial}_", 1)[0]
|
| 461 |
+
# 模板历史上同时用过 ``FS-VI-S80M`` 与 ``FS-VI80-S80M`` 两种型号注释,
|
| 462 |
+
# 都只是标记,不能因为连字符差异挡住本次生成。
|
| 463 |
+
content, count = re.subn(
|
| 464 |
+
r"(?m)^# FS-VI(?:80-|-)?S80M.*$",
|
| 465 |
+
f"# {model} serial {product_serial}",
|
| 466 |
+
content,
|
| 467 |
+
count=1,
|
| 468 |
+
)
|
| 469 |
+
if count != 1:
|
| 470 |
+
raise RuntimeError("ORB YAML 模板缺少 Fays 序列号注释")
|
| 471 |
+
# 模板第 3 行是厂商模板自带的出处注释,写死指向 3500000261870088。照抄
|
| 472 |
+
# 下去,这台夹爪的 IMU 外参就被记成"取自另一台设备"——逐设备出厂标定最
|
| 473 |
+
# 怕这种看起来像抄来的出处,真出位姿问题时会把排查方向带偏。改写成这只
|
| 474 |
+
# 夹爪自己的序列号。模板里没这行也不报错:本改动只可能去掉假出处。
|
| 475 |
+
content, _ = re.subn(
|
| 476 |
+
r"(?m)^# IMU 外参来源:.*$",
|
| 477 |
+
f"# IMU 外参来源: 工厂标定 {model}_{product_serial}"
|
| 478 |
+
f" (dump_calib_opencv48 现场读取)",
|
| 479 |
+
content,
|
| 480 |
+
count=1,
|
| 481 |
+
)
|
| 482 |
+
content = _replace_yaml_scalar(content, "Camera1.fx", float(P1[0, 0]))
|
| 483 |
+
content = _replace_yaml_scalar(content, "Camera1.fy", float(P1[1, 1]))
|
| 484 |
+
content = _replace_yaml_scalar(content, "Camera1.cx", float(P1[0, 2]))
|
| 485 |
+
content = _replace_yaml_scalar(content, "Camera1.cy", float(P1[1, 2]))
|
| 486 |
+
content = _replace_yaml_scalar(
|
| 487 |
+
content,
|
| 488 |
+
"Stereo.b",
|
| 489 |
+
float(np.linalg.norm(T_lr[:3, 3])),
|
| 490 |
+
)
|
| 491 |
+
content = _replace_yaml_scalar(content, "IMU.NoiseGyro", imu["noise_gyro"])
|
| 492 |
+
content = _replace_yaml_scalar(content, "IMU.NoiseAcc", imu["noise_acc"])
|
| 493 |
+
content = _replace_yaml_scalar(content, "IMU.GyroWalk", imu["walk_gyro"])
|
| 494 |
+
content = _replace_yaml_scalar(content, "IMU.AccWalk", imu["walk_acc"])
|
| 495 |
+
content = _replace_yaml_scalar(content, "IMU.Frequency", imu["imu_hz"])
|
| 496 |
+
content = re.sub(
|
| 497 |
+
r"(?ms)^IMU\.T_b_c1:\s*!!opencv-matrix\s*\n"
|
| 498 |
+
r"\s*rows:\s*4\s*\n\s*cols:\s*4\s*\n"
|
| 499 |
+
r"\s*dt:\s*f\s*\n\s*data:\s*\[[^\]]*\]\s*$",
|
| 500 |
+
"IMU.T_b_c1: !!opencv-matrix\n"
|
| 501 |
+
" rows: 4\n cols: 4\n dt: f\n data: [ "
|
| 502 |
+
+ ", ".join(
|
| 503 |
+
f"{float(T_b_c1[row, col]):.15f}"
|
| 504 |
+
for row in range(4) for col in range(4)
|
| 505 |
+
)
|
| 506 |
+
+ " ]",
|
| 507 |
+
content,
|
| 508 |
+
count=1,
|
| 509 |
+
)
|
| 510 |
+
if "IMU.T_b_c1: !!opencv-matrix" not in content:
|
| 511 |
+
raise RuntimeError("ORB YAML 模板缺少 IMU.T_b_c1")
|
| 512 |
+
|
| 513 |
+
destination = os.path.join(
|
| 514 |
+
os.path.abspath(output_dir or ORB_OUTPUT_DIR),
|
| 515 |
+
f"s80m_{product_serial}_stereo_inertial.yaml",
|
| 516 |
+
)
|
| 517 |
+
return _write_text_atomically(destination, content)
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def generate_fays_calibration(
|
| 521 |
+
product_serial: str,
|
| 522 |
+
ports: Mapping[str, str],
|
| 523 |
+
*,
|
| 524 |
+
logger=None,
|
| 525 |
+
timeout: float = 60.0,
|
| 526 |
+
) -> dict:
|
| 527 |
+
"""读取这只夹爪的出厂标定并写齐三份产物(会打开设备)。"""
|
| 528 |
+
serial = str(product_serial or "").strip()
|
| 529 |
+
if not _SERIAL_PATTERN.fullmatch(serial):
|
| 530 |
+
raise ValueError(f"Fays 产品序���号无效: {product_serial!r}")
|
| 531 |
+
_log(logger, f"[Gripper-Fays] 新夹爪 {serial}:正在读取厂商出厂标定…")
|
| 532 |
+
dump_path = dump_fays_calibration(serial, ports, timeout=timeout)
|
| 533 |
+
sdk_yaml = write_fays_sdk_yaml(serial, ports)
|
| 534 |
+
_log(logger, f"[Gripper-Fays] {serial} SDK 配置已就位,正在读取 IMU 出厂参数…")
|
| 535 |
+
imu_output = run_imu_probe(ports, timeout=timeout)
|
| 536 |
+
orb_yaml = generate_orb_yaml(serial, dump_path, imu_output)
|
| 537 |
+
# 用 collector 自己的解析函数复核:这一步过了,插上就能开。
|
| 538 |
+
resolved_sdk, resolved_orb = paths.per_device_fays_yamls(serial)
|
| 539 |
+
_log(logger, f"[Gripper-Fays] {serial} 出厂标定已就位")
|
| 540 |
+
return {
|
| 541 |
+
"calibration_yaml": dump_path,
|
| 542 |
+
"sdk_yaml": resolved_sdk or sdk_yaml,
|
| 543 |
+
"orb_yaml": resolved_orb or orb_yaml,
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
def ensure_fays_calibration(
|
| 548 |
+
product_serial: str,
|
| 549 |
+
ports: Mapping[str, str],
|
| 550 |
+
*,
|
| 551 |
+
logger=None,
|
| 552 |
+
force: bool = False,
|
| 553 |
+
timeout: float = 60.0,
|
| 554 |
+
) -> tuple:
|
| 555 |
+
"""返回 ``(sdk_yaml, orb_yaml)``;缺失或 force 时先现场生成。
|
| 556 |
+
|
| 557 |
+
快路径只是一次 ``isfile``,已覆盖的夹爪启动时零额外开销、不碰设备。
|
| 558 |
+
"""
|
| 559 |
+
if not force:
|
| 560 |
+
try:
|
| 561 |
+
return paths.per_device_fays_yamls(product_serial)
|
| 562 |
+
except RuntimeError:
|
| 563 |
+
pass
|
| 564 |
+
generate_fays_calibration(
|
| 565 |
+
product_serial, ports, logger=logger, timeout=timeout)
|
| 566 |
+
return paths.per_device_fays_yamls(product_serial)
|
collector/core/gripper/fays_single.py
CHANGED
|
@@ -6,7 +6,9 @@
|
|
| 6 |
3. USB 链路速度 >= FAYS_MIN_USB_SPEED_MBPS,否则拒绝(提示换 USB3 口);
|
| 7 |
4. probe_product_serial() 通过官方 SDK 探针读取真实产品序列号;
|
| 8 |
5. 按序列号定位 fays_config/fays_vikit_{serial}.yaml 与
|
| 9 |
-
dist/fays_opencv48/s80m_{serial}_stereo_inertial.yaml;
|
|
|
|
|
|
|
| 10 |
6. flock 租约 /tmp/ksq-gripper-fays-locks/{serial}.lock 防多开;
|
| 11 |
7. materialize 当前端口的运行时 SDK yaml,并在 /dev/shm 建 IPC 目录。
|
| 12 |
|
|
@@ -26,7 +28,7 @@ import threading
|
|
| 26 |
import time
|
| 27 |
|
| 28 |
from config import settings
|
| 29 |
-
from core.gripper import paths
|
| 30 |
from core.gripper.fays_runtime import (
|
| 31 |
FAYS_MIN_USB_SPEED_MBPS,
|
| 32 |
build_fays_probe_env,
|
|
@@ -234,6 +236,56 @@ class SingleFaysLease:
|
|
| 234 |
) from exc
|
| 235 |
return serial, speed
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
def acquire(self, esp_serial):
|
| 238 |
"""锁定并返回 selected 字典;重复调用返回当前租约快照。"""
|
| 239 |
with self._lock:
|
|
@@ -243,7 +295,7 @@ class SingleFaysLease:
|
|
| 243 |
esp = self._match_esp(esp_serial)
|
| 244 |
group = self._discover_unique_fays_group(esp)
|
| 245 |
serial, speed = self._probe_serial(group)
|
| 246 |
-
sdk_yaml, orb_yaml =
|
| 247 |
|
| 248 |
os.makedirs(paths.FAYS_LOCK_DIR, mode=0o700, exist_ok=True)
|
| 249 |
lease_key = re.sub(r"[^A-Za-z0-9_.-]+", "-", serial)
|
|
|
|
| 6 |
3. USB 链路速度 >= FAYS_MIN_USB_SPEED_MBPS,否则拒绝(提示换 USB3 口);
|
| 7 |
4. probe_product_serial() 通过官方 SDK 探针读取真实产品序列号;
|
| 8 |
5. 按序列号定位 fays_config/fays_vikit_{serial}.yaml 与
|
| 9 |
+
dist/fays_opencv48/s80m_{serial}_stereo_inertial.yaml;缺任一个就**现场
|
| 10 |
+
用厂商导出程序从这只夹爪读出厂标定补齐**(见 calibration.py),不必再
|
| 11 |
+
人工跑上位机 device_setup + 导入;
|
| 12 |
6. flock 租约 /tmp/ksq-gripper-fays-locks/{serial}.lock 防多开;
|
| 13 |
7. materialize 当前端口的运行时 SDK yaml,并在 /dev/shm 建 IPC 目录。
|
| 14 |
|
|
|
|
| 28 |
import time
|
| 29 |
|
| 30 |
from config import settings
|
| 31 |
+
from core.gripper import calibration, paths
|
| 32 |
from core.gripper.fays_runtime import (
|
| 33 |
FAYS_MIN_USB_SPEED_MBPS,
|
| 34 |
build_fays_probe_env,
|
|
|
|
| 236 |
) from exc
|
| 237 |
return serial, speed
|
| 238 |
|
| 239 |
+
def _ensure_calibration(self, serial, group):
|
| 240 |
+
"""返回 (sdk_yaml, orb_yaml);缺文件就现场读这只夹爪的出厂标定。
|
| 241 |
+
|
| 242 |
+
快路径只 stat 两个文件,已覆盖的夹爪启动零额外开销、不碰设备。
|
| 243 |
+
"""
|
| 244 |
+
try:
|
| 245 |
+
return paths.per_device_fays_yamls(serial)
|
| 246 |
+
except RuntimeError:
|
| 247 |
+
pass # 缺标定,走下面现场生成
|
| 248 |
+
self._logger(
|
| 249 |
+
f"[Gripper-Fays] {serial} 尚无运行标定文件,"
|
| 250 |
+
f"正在从这只夹爪读取厂商出厂标定…"
|
| 251 |
+
)
|
| 252 |
+
try:
|
| 253 |
+
calibration.generate_fays_calibration(
|
| 254 |
+
serial, group["ports"], logger=self._logger,
|
| 255 |
+
)
|
| 256 |
+
# 复核也用 collector 自己的解析函数:生成"成功"却没落在
|
| 257 |
+
# paths 认得的路径上时,这里必须报出来,不能让下面那句裸
|
| 258 |
+
# RuntimeError 把「请先跑 device_setup」当成唯一解释。
|
| 259 |
+
return paths.per_device_fays_yamls(serial)
|
| 260 |
+
except Exception as exc:
|
| 261 |
+
raise GripperFaysError(
|
| 262 |
+
f"Fays {serial} 缺少运行标定文件,且现场读取出厂标定未成功:{exc}。"
|
| 263 |
+
f"可改用夹爪上位机运行 device_setup 后,执行 "
|
| 264 |
+
f"tools/import_gripper_calibration.py {serial} "
|
| 265 |
+
f"--source <上位机根目录> 手工导入。"
|
| 266 |
+
) from exc
|
| 267 |
+
|
| 268 |
+
def refresh_calibration(self, esp_serial):
|
| 269 |
+
"""强制重新读取这只夹爪的出厂标定(覆盖已有文件)。
|
| 270 |
+
|
| 271 |
+
与 acquire() 无关:不建租约、不占 IPC 目录,只是重新探一次设备身份
|
| 272 |
+
再跑一遍厂商导出。调用前应确保该夹爪未在录制(否则 SDK 正被占用)。
|
| 273 |
+
"""
|
| 274 |
+
with self._lock:
|
| 275 |
+
esp = self._match_esp(esp_serial)
|
| 276 |
+
group = self._discover_unique_fays_group(esp)
|
| 277 |
+
serial, _speed = self._probe_serial(group)
|
| 278 |
+
self._logger(
|
| 279 |
+
f"[Gripper-Fays] 正在重新读取 {serial} 的厂商出厂标定…"
|
| 280 |
+
)
|
| 281 |
+
result = calibration.generate_fays_calibration(
|
| 282 |
+
serial, group["ports"], logger=self._logger,
|
| 283 |
+
)
|
| 284 |
+
self._logger(
|
| 285 |
+
f"[Gripper-Fays] {serial} 出厂标定已重新生成"
|
| 286 |
+
)
|
| 287 |
+
return result
|
| 288 |
+
|
| 289 |
def acquire(self, esp_serial):
|
| 290 |
"""锁定并返回 selected 字典;重复调用返回当前租约快照。"""
|
| 291 |
with self._lock:
|
|
|
|
| 295 |
esp = self._match_esp(esp_serial)
|
| 296 |
group = self._discover_unique_fays_group(esp)
|
| 297 |
serial, speed = self._probe_serial(group)
|
| 298 |
+
sdk_yaml, orb_yaml = self._ensure_calibration(serial, group)
|
| 299 |
|
| 300 |
os.makedirs(paths.FAYS_LOCK_DIR, mode=0o700, exist_ok=True)
|
| 301 |
lease_key = re.sub(r"[^A-Za-z0-9_.-]+", "-", serial)
|
collector/core/pipeline.py
CHANGED
|
@@ -875,8 +875,20 @@ class CameraPipeline(QObject):
|
|
| 875 |
return
|
| 876 |
self._put_gripper_snapshot(f"{prefix}gripper_state", values)
|
| 877 |
|
| 878 |
-
def write_tactile_force(self, side: str, force3, prefix: str = ""
|
| 879 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 880 |
if force3 is None or side not in ("left", "right"):
|
| 881 |
return
|
| 882 |
values = [float(value) for value in force3[:3]]
|
|
@@ -884,14 +896,26 @@ class CameraPipeline(QObject):
|
|
| 884 |
return
|
| 885 |
self._put_gripper_snapshot(
|
| 886 |
f"{prefix}gripper_{side}_force", values)
|
|
|
|
|
|
|
|
|
|
| 887 |
|
| 888 |
def write_tactile_force_matrix(self, side: str, encoded,
|
| 889 |
-
prefix: str = ""):
|
| 890 |
-
"""触觉力矩阵快照(P4 泵线程预编码的行差分/原值列表)。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 891 |
if encoded is None or side not in ("left", "right"):
|
| 892 |
return
|
| 893 |
self._put_gripper_snapshot(
|
| 894 |
f"{prefix}gripper_{side}_force_matrix", encoded)
|
|
|
|
|
|
|
|
|
|
| 895 |
|
| 896 |
def set_force_matrix_spec(self, prefix: str, spec: str) -> None:
|
| 897 |
"""登记本段录制的力矩阵规格(录制开始时调一次,须在 start_episode 后)。
|
|
|
|
| 875 |
return
|
| 876 |
self._put_gripper_snapshot(f"{prefix}gripper_state", values)
|
| 877 |
|
| 878 |
+
def write_tactile_force(self, side: str, force3, prefix: str = "",
|
| 879 |
+
capture_ns: int = 0):
|
| 880 |
+
"""触觉力快照 [fx,fy,fz] mN(P2/P3;tactile_ready 回调)。
|
| 881 |
+
|
| 882 |
+
capture_ns:该样本在桥接回调入口取的宿主单调钟纳秒(与
|
| 883 |
+
`hardware_ns` 同一时基)。落成独立列
|
| 884 |
+
`observation.{prefix}gripper_{side}_force_ns`。
|
| 885 |
+
|
| 886 |
+
为什么要它:力走 latest-wins 单槽、RGB 走 FIFO 队头最旧帧,
|
| 887 |
+
两条支路的队列滞留不同且在段内持续变化,所以**行号配对本身
|
| 888 |
+
就带偏移**。记下各自真实采集时刻后,下游按时间重采样即可把
|
| 889 |
+
偏移压到半个行周期(≈0.5 帧)以内,而不是听任行号对齐。
|
| 890 |
+
0 表示该帧无时刻(旧调用方/无样本),下游按未知处理。
|
| 891 |
+
"""
|
| 892 |
if force3 is None or side not in ("left", "right"):
|
| 893 |
return
|
| 894 |
values = [float(value) for value in force3[:3]]
|
|
|
|
| 896 |
return
|
| 897 |
self._put_gripper_snapshot(
|
| 898 |
f"{prefix}gripper_{side}_force", values)
|
| 899 |
+
if capture_ns:
|
| 900 |
+
self._put_gripper_snapshot(
|
| 901 |
+
f"{prefix}gripper_{side}_force_ns", int(capture_ns))
|
| 902 |
|
| 903 |
def write_tactile_force_matrix(self, side: str, encoded,
|
| 904 |
+
prefix: str = "", capture_ns: int = 0):
|
| 905 |
+
"""触觉力矩阵快照(P4 泵线程预编码的行差分/原值列表)。
|
| 906 |
+
|
| 907 |
+
capture_ns 同 `write_tactile_force`,落成
|
| 908 |
+
`observation.{prefix}gripper_{side}_force_matrix_ns`。矩阵与
|
| 909 |
+
3 向量力来自同一次回调但落盘时刻不同(矩阵走独立泵线程),
|
| 910 |
+
所以两者**各记各的时刻**,不共用一列。
|
| 911 |
+
"""
|
| 912 |
if encoded is None or side not in ("left", "right"):
|
| 913 |
return
|
| 914 |
self._put_gripper_snapshot(
|
| 915 |
f"{prefix}gripper_{side}_force_matrix", encoded)
|
| 916 |
+
if capture_ns:
|
| 917 |
+
self._put_gripper_snapshot(
|
| 918 |
+
f"{prefix}gripper_{side}_force_matrix_ns", int(capture_ns))
|
| 919 |
|
| 920 |
def set_force_matrix_spec(self, prefix: str, spec: str) -> None:
|
| 921 |
"""登记本段录制的力矩阵规格(录制开始时调一次,须在 start_episode 后)。
|
collector/docs/core.md
CHANGED
|
@@ -51,8 +51,9 @@
|
|
| 51 |
| `core/sensor_config_dialogs.py` | PyQt5 传感器配置对话框(矩阵行列 / 仿生手掌逐部位) |
|
| 52 |
| `core/sensor_hand_config.py` | 仿生手掌配置加载/传感器列有效性过滤(纯函数,零 Qt) |
|
| 53 |
| `core/helpers.py` | 通用工具函数(约 47 个:ID/时间/格式化/路径/会话扫描) |
|
|
|
|
| 54 |
|
| 55 |
-
(`core/__init__.py` 为空包标记。)
|
| 56 |
|
| 57 |
## 采集与设备
|
| 58 |
|
|
@@ -950,6 +951,78 @@ rows/cols 映射,点击"选择"弹出子级 `MatrixConfigDialog` 逐部位编
|
|
| 950 |
|
| 951 |
**调用关系**:被 `ui/main_window.py`(`_on_s80m_depth` 用 `depth_to_heatmap` 渲染 S80C 深度格)、`core/d435_manager.py:24` 与 `core/egodata_writer.py:41`(`depth_to_heatmap`/`DepthHeatmapSmoother` 热力图生成/落盘)、`tools/tests/test_depth_heatmap.py:20` 引用。`StereoDepthComputer`(旧 S80M 视差路径)自 v1.0.11 起无调用方,仅为 demo 保留。
|
| 952 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 953 |
## 数据流
|
| 954 |
|
| 955 |
**采集链路**:`ui/main_window.py` 经 `core/device_detector.py`(复用
|
|
|
|
| 51 |
| `core/sensor_config_dialogs.py` | PyQt5 传感器配置对话框(矩阵行列 / 仿生手掌逐部位) |
|
| 52 |
| `core/sensor_hand_config.py` | 仿生手掌配置加载/传感器列有效性过滤(纯函数,零 Qt) |
|
| 53 |
| `core/helpers.py` | 通用工具函数(约 47 个:ID/时间/格式化/路径/会话扫描) |
|
| 54 |
+
| `core/gripper/` | UMI 夹爪 rig 自包含**子包**(Fays SLAM + Sightac 触觉 + 出厂标定生成),与上面平铺模块分开,见下文「夹爪」节 |
|
| 55 |
|
| 56 |
+
(`core/__init__.py` 为空包标记;`core/gripper/__init__.py` 为其子包标记。)
|
| 57 |
|
| 58 |
## 采集与设备
|
| 59 |
|
|
|
|
| 951 |
|
| 952 |
**调用关系**:被 `ui/main_window.py`(`_on_s80m_depth` 用 `depth_to_heatmap` 渲染 S80C 深度格)、`core/d435_manager.py:24` 与 `core/egodata_writer.py:41`(`depth_to_heatmap`/`DepthHeatmapSmoother` 热力图生成/落盘)、`tools/tests/test_depth_heatmap.py:20` 引用。`StereoDepthComputer`(旧 S80M 视差路径)自 v1.0.11 起无调用方,仅为 demo 保留。
|
| 953 |
|
| 954 |
+
## 夹爪(core/gripper/,v1.3.0 起)
|
| 955 |
+
|
| 956 |
+
`core/gripper/` 是 UMI 夹爪 rig 的**自包含子包**(从 `online/gripper_version1`
|
| 957 |
+
分叉,运行期不依赖 `online/`),与上面平铺的 `core/*.py` 由 `core/gripper/__init__.py`
|
| 958 |
+
分隔。子包内自带 `native/`(约 785 MB 厂商二进制与 ORB-SLAM 资源,gitignore,
|
| 959 |
+
换机器需重新部署)与 `sightac_sdk/`(pyarmor 加密随包入库)。
|
| 960 |
+
|
| 961 |
+
| 文件 | 一句话作用 |
|
| 962 |
+
|---|---|
|
| 963 |
+
| `core/gripper/paths.py` | 原生资源路径与运行时常量补丁;`per_device_fays_yamls(serial)` 是 per-serial 标定的唯一解析口径 |
|
| 964 |
+
| `core/gripper/calibration.py` | 现场读取一只 Fays 的出厂标定,生成它的 per-serial 运行文件 |
|
| 965 |
+
| `core/gripper/fays_single.py` | 单夹爪场景的 Fays 租约(`SingleFaysLease`:ESP 匹配 → 拓扑发现 → 序列号探测 → 标定 → flock → IPC 目录) |
|
| 966 |
+
| `core/gripper/fays_runtime.py` | FaysSense S80M 的单一运行时配置来源 + 探针/运行双 env(`build_fays_probe_env` / `build_fays_runtime_env`) |
|
| 967 |
+
| `core/gripper/fays_serial_probe.py` | 经官方 VI Kit SDK 读 S80M 产品序列号 |
|
| 968 |
+
| `core/gripper/bridge.py` | 夹爪 rig 与主程序的 Qt 桥(后台线程采集 → 队列信号回主线程) |
|
| 969 |
+
| `core/gripper/affinity.py` | 夹爪 CPU 预留(主进程掩码收窄 + raw 流接收线程专用核) |
|
| 970 |
+
| `core/gripper/tactile_process_worker.py` | Sightac 触觉计算子进程 |
|
| 971 |
+
| `core/gripper/slam/` | 桥接进程控制器与 stdout 协议解析(`process_controller.py` / `protocol.py`) |
|
| 972 |
+
| `core/gripper/runtime/` | 绑核、线程亲和与**跨进程设备互斥**(`device_access.py`、`cpu_policy.py`、`thread_affinity.py`、`interruptible_queue.py`) |
|
| 973 |
+
| `core/gripper/recording/` | raw 双目/IMU 流客户端(`fays_raw_client.py`) |
|
| 974 |
+
| `core/gripper/devices/` | ESP32 串口/控制板、Sightac 与 DECXIN 相机服务、USB 拓扑关联 |
|
| 975 |
+
| `core/gripper/control/` | 夹爪板状态、百分比与双路 Fz 锁存 |
|
| 976 |
+
|
| 977 |
+
### core/gripper/calibration.py
|
| 978 |
+
|
| 979 |
+
**作用**:**新夹爪接入即自动就位**(v1.3.4)。Fays 的运行标定是**逐设备出厂
|
| 980 |
+
标定**,不可跨设备复用(实测同型号不同机的 `Camera1.fx/fy/cx/cy`、`Stereo.b`、
|
| 981 |
+
`IMU.T_b_c1` 全不同),所以只能从这只夹爪自身读。本模块在设备锁内调厂商
|
| 982 |
+
导出程序,产出三份文件:
|
| 983 |
+
|
| 984 |
+
| 产物 | 路径 | 内容 |
|
| 985 |
+
|---|---|---|
|
| 986 |
+
| 原始 dump | `native/config/calibration/FS-VI80-<model>_<serial>_dump_calib.yaml` | `dump_calib_opencv48` 的原样输出(取证/回溯用) |
|
| 987 |
+
| SDK YAML | `native/gripper_version1/fays_config/fays_vikit_<serial>.yaml` | 由模板改写两个端口字段(`stereo_dev_port` / `imu_dev_port`) |
|
| 988 |
+
| ORB YAML | `native/dist/fays_opencv48/s80m_<serial>_stereo_inertial.yaml` | 由 ORB 模板改写出厂内参/IMU 外参 |
|
| 989 |
+
|
| 990 |
+
**关键接口**:
|
| 991 |
+
|
| 992 |
+
| 函数 | 签名 | 作用 |
|
| 993 |
+
|---|---|---|
|
| 994 |
+
| `ensure_fays_calibration` | `(product_serial, ports, *, logger=None, force=False, timeout=60.0)` | 缺则生成、`force=True` 强制重生成;返回 `(sdk_yaml, orb_yaml)` |
|
| 995 |
+
| `generate_fays_calibration` | `(product_serial, ports, *, logger=None, timeout=60.0)` | 完整生成链(dump → SDK YAML → IMU 探针 → ORB YAML) |
|
| 996 |
+
| `dump_fays_calibration` | `(product_serial, ports, *, output_dir=None, dump_binary=None, template_path=None, timeout=60.0)` | 只跑厂商 dump,返回原始 dump 路径 |
|
| 997 |
+
| `run_imu_probe` | `(ports, *, probe_binary=None, template_path=None, timeout=60.0)` | 只跑 IMU 探针,返回原始 stdout |
|
| 998 |
+
| `write_fays_sdk_yaml` | `(product_serial, ports, *, template_path=None, config_dir=None)` | 只由模板生成 SDK YAML |
|
| 999 |
+
| `generate_orb_yaml` | `(product_serial, dump_path, imu_output, *, template_path=None, output_dir=None)` | 只由 dump + 探针输出生成 ORB YAML |
|
| 1000 |
+
|
| 1001 |
+
**公开行为(v1.3.4)**:`SingleFaysLease.acquire()` 在探测到序列号后调
|
| 1002 |
+
`_ensure_calibration()` —— 已有标定走 `paths.per_device_fays_yamls(serial)`
|
| 1003 |
+
的 `isfile` 快路径(启动零额外开销、不碰设备);缺文件就地生成,**复核落盘
|
| 1004 |
+
路径**后才连上,失败抛带序列号与兜底办法的 `GripperFaysError`。生成"成功"
|
| 1005 |
+
却没落在 `paths` 认得的路径上必须当场报出来,否则会漏出 `paths.py` 那句误导
|
| 1006 |
+
人的「请先在夹爪上位机中运行 device_setup」。手工入口与一键重生成:
|
| 1007 |
+
`tools/import_gripper_calibration.py --generate`(旧文件先备份
|
| 1008 |
+
`.bak_<时间戳>`)、设备面板夹爪条目右键「重新读取出厂标定」(录制中禁用,
|
| 1009 |
+
标定前自动关该夹爪、完成后开回,见 `docs/ui.md`)。
|
| 1010 |
+
|
| 1011 |
+
**关键数据**:ORB 内参由 `cv2.fisheye.stereoRectify(..., CALIB_ZERO_DISPARITY)`
|
| 1012 |
+
的 `P1`/`R1` 得到,`T_b_c1 = inv(T_cam_imu) @ T_rectified_to_unrectified`;
|
| 1013 |
+
IMU 五项(`NoiseGyro`/`NoiseAcc`/`GyroWalk`/`AccWalk`/`Frequency`)由
|
| 1014 |
+
`fays_vikit_calibration_probe` 读。厂商二进制定位可用环境变量覆盖:
|
| 1015 |
+
`KSQ_FAYS_CALIBRATION_DUMP`、`KSQ_FAYS_IMU_CALIBRATION_PROBE`、`KSQ_FAYS_ORB_TEMPLATE`。
|
| 1016 |
+
所有接触 SDK 的子进程都套 `device_access_guard(FAYS_SDK_INITIALIZATION_LOCK)`
|
| 1017 |
+
+ `fays_device_guard(stereo_dev_port)` 两把跨进程锁,并在
|
| 1018 |
+
`build_fays_probe_env()`(OpenCV 4.2 + fays_atrak + ft602)下运行。
|
| 1019 |
+
|
| 1020 |
+
**调用关系**:由 `core/gripper/fays_single.py`(`acquire()` 内联生成、
|
| 1021 |
+
`refresh_calibration()` 强制重生成)、`tools/import_gripper_calibration.py`
|
| 1022 |
+
与 `ui/main_window.py`(后台线程跑 `refresh_calibration`)调用;离线回归见
|
| 1023 |
+
`tools/tests/test_gripper_calibration_autogen.py`(重定向全部产物目录 + 假厂商
|
| 1024 |
+
二进制,含真机产物逐字节回放)。
|
| 1025 |
+
|
| 1026 |
## 数据流
|
| 1027 |
|
| 1028 |
**采集链路**:`ui/main_window.py` 经 `core/device_detector.py`(复用
|
collector/docs/data.md
CHANGED
|
@@ -291,6 +291,52 @@ data/recordings/ # 录制根目录(settings.RECORDING
|
|
| 291 |
`episode_index`、`task_index`、`start_frame_index`、`end_frame_index`、
|
| 292 |
`length`(均为 int64)。
|
| 293 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
### 4.6 `meta/info.json` 字段概览(LeRobot v3 兼容,上传服务器严格依赖)
|
| 295 |
|
| 296 |
| 键 | 含义 |
|
|
|
|
| 291 |
`episode_index`、`task_index`、`start_frame_index`、`end_frame_index`、
|
| 292 |
`length`(均为 int64)。
|
| 293 |
|
| 294 |
+
### 4.5.1 UMI 夹爪列与跨模态时间对齐
|
| 295 |
+
|
| 296 |
+
启用夹爪时 episode parquet 增加下列稀疏列(无样本的行填 0/空):
|
| 297 |
+
|
| 298 |
+
| 列 | 类型 | 含义 |
|
| 299 |
+
|---|---|---|
|
| 300 |
+
| `observation.gripper_{left,right}_force` | list<float32, 3> | 3 向量力 `[fx,fy,fz]` mN |
|
| 301 |
+
| `observation.gripper_{left,right}_force_ns` | int64 | 该力样本的采集时刻 |
|
| 302 |
+
| `observation.gripper_{left,right}_force_matrix` | list<int16> / list<float32> | 250×250×3 力矩阵(档位见下) |
|
| 303 |
+
| `observation.gripper_{left,right}_force_matrix_ns` | int64 | 该力矩阵样本的采集时刻 |
|
| 304 |
+
| `observation.slam_trajectory` | list<double> | 轨迹点 `[t,x,y,z,qx,qy,qz,qw]`×N,变长 |
|
| 305 |
+
| `observation.gripper_state` | list<float32, 3> | `[open_pct, gripped, fz_mn]` |
|
| 306 |
+
|
| 307 |
+
力矩阵档位记在**每段一份**的 `meta/episodes` 行(`force_matrix_specs` 列),
|
| 308 |
+
不按面值猜——同一任务换档时前一段的倍率不会被后一段顶掉。
|
| 309 |
+
|
| 310 |
+
**为什么需要 `_ns` 列。** 同一行里的 RGB 帧和力样本**不是同时刻采集的**,
|
| 311 |
+
两条支路各走各的路:RGB 走外部帧源队列,写线程每 tick 取**队头最旧帧**;
|
| 312 |
+
力/矩阵走 latest-wins 单槽,写线程取到的是**当下最新**样本。于是「行号相同」
|
| 313 |
+
≠「时刻相同」——力恒领先 RGB,领先量等于那张 RGB 帧在队列里的滞留时间,
|
| 314 |
+
且随录制时长增长(RGB 源实测 30.84 fps vs 写线程 30 fps,约每秒多积 1 帧)。
|
| 315 |
+
力矩阵还走独立泵线程,与 3 向量力之间也各记各的时刻,所以两者不共用一列。
|
| 316 |
+
|
| 317 |
+
v1.3.3 起每行落盘两条支路各自的采集时刻(宿主单调钟纳秒,与 `hardware_ns`
|
| 318 |
+
同一时基),下游按时间取最近邻即可还原真实配对:
|
| 319 |
+
|
| 320 |
+
```bash
|
| 321 |
+
venv/bin/python scripts/align_modalities.py <episode.parquet> --residual
|
| 322 |
+
```
|
| 323 |
+
|
| 324 |
+
```python
|
| 325 |
+
from align_modalities import align_episode
|
| 326 |
+
mapping, residual_ns = align_episode("episode-000.parquet", side="left")
|
| 327 |
+
# mapping[k] = 视频第 k 帧应对应的 parquet 行号
|
| 328 |
+
```
|
| 329 |
+
|
| 330 |
+
- 对齐精度上界是**半个力样本间隔**,不是半个行周期。`force_ns == 0` 表示
|
| 331 |
+
「本行窗口内没有新样本」(**不是**时刻为 0,取最近邻时必须排除,否则会把
|
| 332 |
+
一批帧吸到第 0 行)。样本每 k 行才有一个时上界放宽到 k/2 个行周期。
|
| 333 |
+
- 早于第一个力样本的帧(段首陈旧帧,见 `rgb-prestart-frames`)与晚于最后
|
| 334 |
+
一个样本的帧在时间上没有对应样本,只能夹到端点——**这不是对齐结果**,
|
| 335 |
+
脚本单列「越界帧」计数,下游应丢弃。
|
| 336 |
+
- **v1.3.3 之前录的 episode 无法这样对齐**:那时力侧完全没有时间戳,RGB 侧
|
| 337 |
+
的 `hardware_ns` 还被 `pyqtSignal(int)` 截成 32 位(每 2.147 s 翻符号)。
|
| 338 |
+
脚本对这类 episode 明确报「无法对齐」而不是拿行号或增长率去猜。
|
| 339 |
+
|
| 340 |
### 4.6 `meta/info.json` 字段概览(LeRobot v3 兼容,上传服务器严格依赖)
|
| 341 |
|
| 342 |
| 键 | 含义 |
|
collector/docs/index.md
CHANGED
|
@@ -126,7 +126,7 @@ VENV_PY=/path/to/python ./tools/hand_3d_d435/run_live_d435.sh
|
|
| 126 |
| 目录 | 作用 | 文档 |
|
| 127 |
|---|---|---|
|
| 128 |
| `config/` | 全局配置:路径/相机/录制/上传常量(`settings.py`)、中英文文案(`i18n.py`)、S80M 标定副本与 `config/sensors/` 手套仿生手掌映射 | `docs/config.md` |
|
| 129 |
-
| `core/` | ★ SDK 核心(平铺,30 个模块):采集管线(`pipeline.py`/`camera.py`/`d435_camera.py`/`device_detector.py`)、设备管理器(`device_manager.py`/`s80m_manager.py`/`d435_manager.py`/`device_naming.py`/`exposure_controller.py`)、录制落盘(`egodata_writer.py`/`calibration.py`/`database.py`/`recording_record.py`/`recording_repository.py`/`task_record.py`)、上传后端(`api_client.py`/`task_service.py`/`uploader.py`)、回放会话(`session_timeline.py`/`session_catalog.py`/`session_loader.py`)、手部(`hand_tracking.py`/`hand_processor.py`/`auto_labeler.py`)、手套传感(`ble_engine.py`/`render_engine.py`/`sensor_config_dialogs.py`/`sensor_hand_config.py`)、通用(`helpers.py`/`stereo_depth.py`) | `docs/core.md` |
|
| 130 |
| `data/` | 本地配置(仓库提供 `*.example.json` 模板与出厂默认 `device_params.json`;其余配置、录制数据、SQLite 均 gitignore) | `docs/data.md`(本文档集) |
|
| 131 |
| `tools/demos/` | 交付版 demo:S80M 深度引擎 demo、双目 2D demo、手套关键点 demo、hdf5 演示、标定自检脚本 | `docs/demos.md` |
|
| 132 |
| `tools/hand_detection/` | 手部检测:YOLO 手套检测(`best.pt`、`world_detector.py`)、MediaPipe 裸手管线、`demo_stereo_hands.py` | `docs/hand_detection.md` |
|
|
|
|
| 126 |
| 目录 | 作用 | 文档 |
|
| 127 |
|---|---|---|
|
| 128 |
| `config/` | 全局配置:路径/相机/录制/上传常量(`settings.py`)、中英文文案(`i18n.py`)、S80M 标定副本与 `config/sensors/` 手套仿生手掌映射 | `docs/config.md` |
|
| 129 |
+
| `core/` | ★ SDK 核心(平铺,30 个模块):采集管线(`pipeline.py`/`camera.py`/`d435_camera.py`/`device_detector.py`)、设备管理器(`device_manager.py`/`s80m_manager.py`/`d435_manager.py`/`device_naming.py`/`exposure_controller.py`)、录制落盘(`egodata_writer.py`/`calibration.py`/`database.py`/`recording_record.py`/`recording_repository.py`/`task_record.py`)、上传后端(`api_client.py`/`task_service.py`/`uploader.py`)、回放会话(`session_timeline.py`/`session_catalog.py`/`session_loader.py`)、手部(`hand_tracking.py`/`hand_processor.py`/`auto_labeler.py`)、手套传感(`ble_engine.py`/`render_engine.py`/`sensor_config_dialogs.py`/`sensor_hand_config.py`)、通用(`helpers.py`/`stereo_depth.py`);另有自包含**子包** `core/gripper/`(UMI 夹爪 rig:Fays SLAM + Sightac 触觉 + 出厂标定生成) | `docs/core.md` |
|
| 130 |
| `data/` | 本地配置(仓库提供 `*.example.json` 模板与出厂默认 `device_params.json`;其余配置、录制数据、SQLite 均 gitignore) | `docs/data.md`(本文档集) |
|
| 131 |
| `tools/demos/` | 交付版 demo:S80M 深度引擎 demo、双目 2D demo、手套关键点 demo、hdf5 演示、标定自检脚本 | `docs/demos.md` |
|
| 132 |
| `tools/hand_detection/` | 手部检测:YOLO 手套检测(`best.pt`、`world_detector.py`)、MediaPipe 裸手管线、`demo_stereo_hands.py` | `docs/hand_detection.md` |
|
collector/docs/tools.md
CHANGED
|
@@ -29,6 +29,7 @@
|
|
| 29 |
| `tools/hand_3d_s80c/` | S80C 双目实时裸手/手套关键点 demo(含自包含 SDK `third_party/`、`build_dist.sh` 分发包) | 包内 `README.md` |
|
| 30 |
| `tools/fayssense_depth_sdk/` | FaysSense VI Kit 深度引擎 SDK(C++,专有;S80C demo 自包含用副本) | 包内 `README.md` |
|
| 31 |
| `tools/models/` | 模型权重:`hand_landmarker.task`(MediaPipe 裸手关键点) | — |
|
|
|
|
| 32 |
| `tools/tests/` | 16 个回归/冒烟测试(11 离线 + 5 真机,见文末) | `README.md` 测试节 |
|
| 33 |
| `tools/weights/clip/` | CLIP ViT-B-32 大权重(gitignore,不随仓库分发) | — |
|
| 34 |
|
|
|
|
| 29 |
| `tools/hand_3d_s80c/` | S80C 双目实时裸手/手套关键点 demo(含自包含 SDK `third_party/`、`build_dist.sh` 分发包) | 包内 `README.md` |
|
| 30 |
| `tools/fayssense_depth_sdk/` | FaysSense VI Kit 深度引擎 SDK(C++,专有;S80C demo 自包含用副本) | 包内 `README.md` |
|
| 31 |
| `tools/models/` | 模型权重:`hand_landmarker.task`(MediaPipe 裸手关键点) | — |
|
| 32 |
+
| `tools/import_gripper_calibration.py` | 夹爪出厂标定导入/生成:手工搬运上位机产物,或 `--generate` 就地读设备重生成(v1.3.4) | `docs/core.md` 夹爪节 |
|
| 33 |
| `tools/tests/` | 16 个回归/冒烟测试(11 离线 + 5 真机,见文末) | `README.md` 测试节 |
|
| 34 |
| `tools/weights/clip/` | CLIP ViT-B-32 大权重(gitignore,不随仓库分发) | — |
|
| 35 |
|
collector/docs/ui.md
CHANGED
|
@@ -259,14 +259,17 @@
|
|
| 259 |
| `_row_text` | `(dev) -> str` | 行文本 = 图标 + `label`(+ `— serial`) | — |
|
| 260 |
| `_on_item_changed` | `(item, column)` | 勾选状态真正变化(用 `_last_check` 挡文字类变化与组标题)才发射 `device_toggled` | — |
|
| 261 |
| `_on_item_double_clicked` | `(item, _column)` | 双击 → `QInputDialog` 命名 → `settings.save_device_name(dev.stable_key, name)` 持久化 → 更新行文本 + `device_renamed`;对话框打开期间列表可能已被 2s 轮询重建,必须用当前列表里的条目更新 | — |
|
|
|
|
|
|
|
|
|
|
| 262 |
|
| 263 |
**关键数据**:
|
| 264 |
|
| 265 |
- `_ICON = {"uvc": "📹", "d435": "🔭", "s80m": "👁", "data_ble": "🧤", "ble": "🎧"}`;`_GROUP_ORDER = ["camera", "glove", "other_ble"]`;`_GROUP_TITLE` 对应中文组标题。
|
| 266 |
-
- `_items`:device key → `QTreeWidgetItem`;`_last_check`:key → 上次勾选状态(防 `itemChanged` 误触发);`_group_expanded`:组展开状态(初始 camera/glove 展开、other_ble 折叠)。
|
| 267 |
- 命名持久化:`config.settings.save_device_name`(device_names.json)。
|
| 268 |
|
| 269 |
-
**调用关系**:由 `ui/main_window.py` 构造并连接 `device_toggled`/`device_renamed`;`tools/tests/device_panel_gui_smoke_test.py` 直接构造。依赖 `config.settings.save_device_name`、`config.i18n.tr`。
|
| 270 |
|
| 271 |
### ui/exposure_dialog.py
|
| 272 |
|
|
|
|
| 259 |
| `_row_text` | `(dev) -> str` | 行文本 = 图标 + `label`(+ `— serial`) | — |
|
| 260 |
| `_on_item_changed` | `(item, column)` | 勾选状态真正变化(用 `_last_check` 挡文字类变化与组标题)才发射 `device_toggled` | — |
|
| 261 |
| `_on_item_double_clicked` | `(item, _column)` | 双击 → `QInputDialog` 命名 → `settings.save_device_name(dev.stable_key, name)` 持久化 → 更新行文本 + `device_renamed`;对话框打开期间列表可能已被 2s 轮询重建,必须用当前列表里的条目更新 | — |
|
| 262 |
+
| `gripper_recalibration_requested`(信号) | `pyqtSignal(object)` | 夹爪条目右键选「重新读取出厂标定」(v1.3.4) | 由 `MainWindow` 连接 |
|
| 263 |
+
| `_on_context_menu` | `(pos)` | `Qt.CustomContextMenu` 回调:仅 `dev.group == "gripper"` 且非组标题/占位项才弹单项菜单;`_locked`(录制中)时菜单项置灰;按 `chosen is action` 判等,只弹不选不发信号 | — |
|
| 264 |
+
| `_refresh_hint_text` | `()` | 底部提示:有夹爪时追加「;右键夹爪可重读取出厂标定」 | 由 `refresh_texts` 调用 |
|
| 265 |
|
| 266 |
**关键数据**:
|
| 267 |
|
| 268 |
- `_ICON = {"uvc": "📹", "d435": "🔭", "s80m": "👁", "data_ble": "🧤", "ble": "🎧"}`;`_GROUP_ORDER = ["camera", "glove", "other_ble"]`;`_GROUP_TITLE` 对应中文组标题。
|
| 269 |
+
- `_items`:device key → `QTreeWidgetItem`;`_last_check`:key → 上次勾选状态(防 `itemChanged` 误触发);`_group_expanded`:组展开状态(初始 camera/glove 展开、other_ble 折叠);`_has_gripper`:列表里是否有夹爪(决定底部提示是否提右键入口,两个分支都要更新,空设备分支需重置)。
|
| 270 |
- 命名持久化:`config.settings.save_device_name`(device_names.json)。
|
| 271 |
|
| 272 |
+
**调用关系**:由 `ui/main_window.py` 构造并连接 `device_toggled`/`device_renamed`/`gripper_recalibration_requested`;`tools/tests/device_panel_gui_smoke_test.py` 直接构造。依赖 `config.settings.save_device_name`、`config.i18n.tr`。夹爪右键重标定的完整链路(关夹爪 → 后台线程 `refresh_calibration` → 完成后开回)见 `docs/core.md`「夹爪」节与 `ui/main_window.py` 的 `_on_gripper_recalibration`。
|
| 273 |
|
| 274 |
### ui/exposure_dialog.py
|
| 275 |
|
collector/scripts/align_modalities.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""按时间戳把力矩阵/触觉力对齐到 RGB 视频帧。
|
| 4 |
+
|
| 5 |
+
venv/bin/python scripts/align_modalities.py <episode.parquet> # 看统计
|
| 6 |
+
venv/bin/python scripts/align_modalities.py <episode.parquet> --residual # 逐帧残差
|
| 7 |
+
|
| 8 |
+
也可以当库用:
|
| 9 |
+
|
| 10 |
+
from align_modalities import align_episode
|
| 11 |
+
mapping, residual_ns = align_episode("episode-076.parquet", side="left")
|
| 12 |
+
|
| 13 |
+
`mapping[k]` = 视频第 k 帧应对应的 **parquet 行号**(该行的力矩阵即 k 帧
|
| 14 |
+
时刻的力);`residual_ns[k]` = 这次配对的残差(纳秒)。
|
| 15 |
+
|
| 16 |
+
为什么需要它
|
| 17 |
+
────────────
|
| 18 |
+
同一行里的 RGB 帧和力样本**不是同时刻采集的**,两者各走各的路:
|
| 19 |
+
|
| 20 |
+
· RGB 走外部帧源队列,写线程每 tick 取**队头最旧帧**(不排空);
|
| 21 |
+
· 力/矩阵走 latest-wins 单槽,写线程取到的是**当下最新**样本。
|
| 22 |
+
|
| 23 |
+
于是「行号相同」≠「时刻相同」:力恒领先 RGB,领先量等于那张 RGB 帧在
|
| 24 |
+
队列里的滞留时间,而滞留时间随录制时长增长(RGB 源实测 30.84fps、写线程
|
| 25 |
+
30fps,队列约每分钟涨 1 帧/秒 → 10 秒的段落末尾能差到 ~10 帧)。段首还
|
| 26 |
+
可能因为启动窗口的陈旧帧积压再叠一次跳变。
|
| 27 |
+
|
| 28 |
+
v1.3.3 起每行同时落盘两条支路各自的采集时刻(宿主单调钟纳秒,同一时基):
|
| 29 |
+
|
| 30 |
+
hardware_ns 该行 RGB 帧的采集时刻
|
| 31 |
+
observation.gripper_{side}_force_ns 3 向量力样本的采集时刻
|
| 32 |
+
observation.gripper_{side}_force_matrix_ns 力矩阵样本的采集时刻
|
| 33 |
+
|
| 34 |
+
有了它们,行号偏移就只是「可离线算出来的量」,按时间取最近邻即可还原
|
| 35 |
+
真实配对。
|
| 36 |
+
|
| 37 |
+
对齐精度的上界是**半个力样本间隔**,不是半个行周期。力样本并不保证每行
|
| 38 |
+
都有:`force_ns == 0` 表示「本行窗口内没有新样本」(不是时刻为 0),若某段
|
| 39 |
+
是每 k 行才落一个样本,上界就放宽到 k/2 个行周期。20 秒内没收到任何样本
|
| 40 |
+
时缺口更大,脚本会把中位样本间隔直接打出来,方便判断这段能不能用。
|
| 41 |
+
|
| 42 |
+
两头的帧(早于第一个力样本的段首陈旧帧、晚于最后一个样本的帧)在时间上
|
| 43 |
+
根本没有对应样本,只能夹到端点——这不是对齐结果,脚本单独报「越界帧」
|
| 44 |
+
数量,下游应当丢弃。
|
| 45 |
+
|
| 46 |
+
**2026-09-11 之前录的数据无法这样对齐**:那时力侧完全没有时间戳,RGB 侧
|
| 47 |
+
的 hardware_ns 还被 pyqtSignal(int) 截成了 32 位(每 2.147s 翻符号),
|
| 48 |
+
两条信息都不在,只能重录。本脚本对这类 episode 会明确报「无法对齐」,
|
| 49 |
+
不会拿行号或增长率去猜——那种近似在段首有大跳变的段上误差比不补还大。
|
| 50 |
+
"""
|
| 51 |
+
from __future__ import annotations
|
| 52 |
+
|
| 53 |
+
import argparse
|
| 54 |
+
import json
|
| 55 |
+
import os
|
| 56 |
+
import sys
|
| 57 |
+
|
| 58 |
+
import numpy as np
|
| 59 |
+
|
| 60 |
+
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 61 |
+
|
| 62 |
+
# 行周期(秒):残差折算成「帧」时的分母,也是对齐精度的理论下界
|
| 63 |
+
DEFAULT_FPS = 30.0
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _columns_for(side: str, which: str):
|
| 67 |
+
key = ("gripper_{}_force_matrix_ns" if which == "matrix"
|
| 68 |
+
else "gripper_{}_force_ns").format(side)
|
| 69 |
+
return f"observation.{key}"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def nearest_index(src_ns, dst_ns) -> np.ndarray:
|
| 73 |
+
"""对 dst_ns 的每个元素,返回它在 src_ns 中**时间最近**的下标。
|
| 74 |
+
|
| 75 |
+
两侧都必须是已排序的一维整型序列(时间戳天然有序)。用 searchsorted
|
| 76 |
+
做二分,O(n log m);不用线性扫描是因为一段 episode 有几百到几千行,
|
| 77 |
+
而调用方可能要对每一帧各查一次。
|
| 78 |
+
|
| 79 |
+
平局(左右等距)取左边(更早的样本)——对因果性友好:宁可配稍早的
|
| 80 |
+
力,也不要配到视频帧之后才发生的力。
|
| 81 |
+
"""
|
| 82 |
+
src = np.asarray(src_ns, dtype=np.int64)
|
| 83 |
+
dst = np.asarray(dst_ns, dtype=np.int64)
|
| 84 |
+
if src.size == 0:
|
| 85 |
+
raise ValueError("src_ns 为空,无法对齐")
|
| 86 |
+
if src.size == 1:
|
| 87 |
+
return np.zeros(dst.shape, dtype=np.int64)
|
| 88 |
+
# 夹到 [1, n-1] 后 src[i-1]/src[i] 恒存在,边界情形自然落回端点
|
| 89 |
+
i = np.clip(np.searchsorted(src, dst), 1, src.size - 1)
|
| 90 |
+
left = src[i - 1]
|
| 91 |
+
right = src[i]
|
| 92 |
+
return np.where(dst - left <= right - dst, i - 1, i)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def load_ns_columns(path: str, side: str = "left", which: str = "matrix"):
|
| 96 |
+
"""读出一段 episode 的对齐所需时间戳列。
|
| 97 |
+
|
| 98 |
+
返回 (rgb_ns, force_ns, diag):
|
| 99 |
+
rgb_ns —— 每行的 RGB 采集时刻(hardware_ns 列)
|
| 100 |
+
force_ns —— 每行的力样本采集时刻(0 = 该行无样本/未知)
|
| 101 |
+
diag —— {"reason": ...} 说明为什么不可对齐时 force_ns 为 None
|
| 102 |
+
"""
|
| 103 |
+
import pyarrow.parquet as pq
|
| 104 |
+
|
| 105 |
+
schema = pq.read_schema(path)
|
| 106 |
+
names = set(schema.names)
|
| 107 |
+
diag = {"path": path, "side": side, "which": which}
|
| 108 |
+
|
| 109 |
+
if "hardware_ns" not in names:
|
| 110 |
+
diag["reason"] = "缺少 hardware_ns 列"
|
| 111 |
+
return None, None, diag
|
| 112 |
+
|
| 113 |
+
force_col = _columns_for(side, which)
|
| 114 |
+
if force_col not in names:
|
| 115 |
+
diag["reason"] = (
|
| 116 |
+
f"缺少 {force_col} 列——该 episode 录于 v1.3.3 之前,力侧没有"
|
| 117 |
+
f"采集时刻,无法按时间对齐(只能重录)")
|
| 118 |
+
return None, None, diag
|
| 119 |
+
|
| 120 |
+
t = pq.read_table(path, columns=["hardware_ns", force_col])
|
| 121 |
+
rgb_ns = np.asarray(t.column("hardware_ns").to_pylist(), dtype=np.int64)
|
| 122 |
+
force_ns = np.asarray(t.column(force_col).to_pylist(), dtype=np.int64)
|
| 123 |
+
|
| 124 |
+
# 32 位截断的指纹:值域被压在 ±2^31 内。修好后 hardware_ns 是真实的
|
| 125 |
+
# 宿主单调钟(开机纳秒数,量级 1e14~1e16),必然远超 2^31。
|
| 126 |
+
if rgb_ns.size and np.abs(rgb_ns).max() < (1 << 31):
|
| 127 |
+
diag["reason"] = (
|
| 128 |
+
"hardware_ns 全在 ±2^31 内——这是 pyqtSignal(int) 的 32 位截断"
|
| 129 |
+
"指纹(每 2.147s 翻符号),该 episode 录于修复之前,时间戳不可用")
|
| 130 |
+
return None, None, diag
|
| 131 |
+
|
| 132 |
+
if not np.all(np.diff(rgb_ns) >= 0):
|
| 133 |
+
diag["reason"] = "hardware_ns 非单调,无法作为对齐基准"
|
| 134 |
+
return None, None, diag
|
| 135 |
+
|
| 136 |
+
return rgb_ns, force_ns, diag
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def align_episode(path: str, side: str = "left", which: str = "matrix"):
|
| 140 |
+
"""把一段 episode 的 RGB 帧对齐到力样本。
|
| 141 |
+
|
| 142 |
+
返回 (mapping, residual_ns):
|
| 143 |
+
mapping[k] —— 视频第 k 帧对应的 parquet 行号
|
| 144 |
+
residual_ns[k] —— 该配对的 |ΔT|(纳秒)
|
| 145 |
+
|
| 146 |
+
只在**有真实力样本**的行里找最近邻(force_ns == 0 的行是「本行没有
|
| 147 |
+
新样本」,不代表时刻为 0,必须排除,否则会把一堆帧吸到 0 上去)。
|
| 148 |
+
"""
|
| 149 |
+
rgb_ns, force_ns, diag = load_ns_columns(path, side=side, which=which)
|
| 150 |
+
if rgb_ns is None:
|
| 151 |
+
raise ValueError(diag["reason"])
|
| 152 |
+
|
| 153 |
+
valid = np.flatnonzero(force_ns > 0)
|
| 154 |
+
if valid.size == 0:
|
| 155 |
+
raise ValueError(f"{diag.get('path')} 没有任何有效的力采集时刻")
|
| 156 |
+
|
| 157 |
+
picked = valid[nearest_index(force_ns[valid], rgb_ns)]
|
| 158 |
+
return picked, np.abs(rgb_ns - force_ns[picked]).astype(np.int64)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _fmt_stats(mapping, residual_ns, rgb_ns, force_ns, fps):
|
| 162 |
+
res_ms = residual_ns / 1e6
|
| 163 |
+
res_frames = residual_ns / 1e9 * fps
|
| 164 |
+
# 行号偏移:不加时间戳时下游会默认的配对,用来对比"修了多少"
|
| 165 |
+
naive = np.arange(mapping.size, dtype=np.int64)
|
| 166 |
+
row_shift = mapping - naive
|
| 167 |
+
|
| 168 |
+
# 越界帧:RGB 时刻落在力样本时间范围之外,只能夹到最近端点,残差是
|
| 169 |
+
# "离端点多远"而非对齐误差。段首的陈旧帧(录到开机前的画面)就落在
|
| 170 |
+
# 这里——它们本来就没有对应的力样本,下游应当丢弃而不是当对齐结果用。
|
| 171 |
+
valid = force_ns[force_ns > 0]
|
| 172 |
+
outside = ((rgb_ns < valid.min()) | (rgb_ns > valid.max())) \
|
| 173 |
+
if valid.size else np.ones(rgb_ns.shape, dtype=bool)
|
| 174 |
+
inside = ~outside
|
| 175 |
+
|
| 176 |
+
# 对齐精度的上界由**力样本间隔**决定,不是行周期:样本每 k 行才有一个
|
| 177 |
+
# 时上界就放宽到 k/2 帧。
|
| 178 |
+
if valid.size > 1:
|
| 179 |
+
span_ns = float(np.median(np.diff(np.sort(valid))))
|
| 180 |
+
else:
|
| 181 |
+
span_ns = 1e9 / fps
|
| 182 |
+
bound_ns = span_ns / 2
|
| 183 |
+
|
| 184 |
+
out = [
|
| 185 |
+
f" 可对齐帧数 {mapping.size}",
|
| 186 |
+
f" 有效力样本行数 {int((force_ns > 0).sum())}",
|
| 187 |
+
f" 力样本间隔 中位 {span_ns / 1e6:.2f} ms"
|
| 188 |
+
f" → 对齐精度上界 {bound_ns / 1e9 * fps:.2f} 帧",
|
| 189 |
+
]
|
| 190 |
+
if inside.any():
|
| 191 |
+
out.append(
|
| 192 |
+
f" 残差 |ΔT| 中位 {np.median(res_ms[inside]):.2f} ms"
|
| 193 |
+
f" / 最大 {res_ms[inside].max():.2f} ms"
|
| 194 |
+
f" ← 只在范围内的 {int(inside.sum())} 帧上统计")
|
| 195 |
+
if outside.any():
|
| 196 |
+
idx = np.flatnonzero(outside)
|
| 197 |
+
out.append(
|
| 198 |
+
f" 越界帧 {int(outside.sum())} 帧"
|
| 199 |
+
f"({idx.min()}..{idx.max()})—— 早于第一个或晚于最后一个"
|
| 200 |
+
f"力样本,只能夹到端点,**不是对齐结果**,建议丢弃")
|
| 201 |
+
out.append(
|
| 202 |
+
f" 行号偏移 中位 {np.median(row_shift):+.0f}"
|
| 203 |
+
f" / 范围 {row_shift.min():+d}..{row_shift.max():+d}"
|
| 204 |
+
f" ← 不按时间戳、直接同行配对的误差")
|
| 205 |
+
return "\n".join(out)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def main(argv=None) -> int:
|
| 209 |
+
ap = argparse.ArgumentParser(
|
| 210 |
+
description="按时间戳把力矩阵/触觉力对齐到 RGB 视频帧")
|
| 211 |
+
ap.add_argument("episode", help="episode-NNN.parquet 路径")
|
| 212 |
+
ap.add_argument("--side", default="left", choices=("left", "right"))
|
| 213 |
+
ap.add_argument("--which", default="matrix", choices=("matrix", "force"),
|
| 214 |
+
help="matrix=力矩阵(默认),force=3 向量力")
|
| 215 |
+
ap.add_argument("--residual", action="store_true",
|
| 216 |
+
help="打印逐帧残差(最多 40 行)")
|
| 217 |
+
ap.add_argument("--json", action="store_true", help="以 JSON 输出")
|
| 218 |
+
args = ap.parse_args(argv)
|
| 219 |
+
|
| 220 |
+
if not os.path.isfile(args.episode):
|
| 221 |
+
print(f"找不到文件:{args.episode}", file=sys.stderr)
|
| 222 |
+
return 2
|
| 223 |
+
|
| 224 |
+
rgb_ns, force_ns, diag = load_ns_columns(
|
| 225 |
+
args.episode, side=args.side, which=args.which)
|
| 226 |
+
if rgb_ns is None:
|
| 227 |
+
print(f"无法对齐:{diag['reason']}", file=sys.stderr)
|
| 228 |
+
return 1
|
| 229 |
+
|
| 230 |
+
fps = DEFAULT_FPS
|
| 231 |
+
try:
|
| 232 |
+
import pyarrow.parquet as pq
|
| 233 |
+
info = os.path.join(os.path.dirname(os.path.dirname(
|
| 234 |
+
os.path.dirname(os.path.abspath(args.episode)))), "meta", "info.json")
|
| 235 |
+
if os.path.isfile(info):
|
| 236 |
+
with open(info, "r", encoding="utf-8") as f:
|
| 237 |
+
fps = float(json.load(f).get("fps") or DEFAULT_FPS)
|
| 238 |
+
except (OSError, ValueError, TypeError):
|
| 239 |
+
pass
|
| 240 |
+
|
| 241 |
+
try:
|
| 242 |
+
mapping, residual_ns = align_episode(
|
| 243 |
+
args.episode, side=args.side, which=args.which)
|
| 244 |
+
except ValueError as exc:
|
| 245 |
+
print(f"无法对齐:{exc}", file=sys.stderr)
|
| 246 |
+
return 1
|
| 247 |
+
|
| 248 |
+
if args.json:
|
| 249 |
+
print(json.dumps({
|
| 250 |
+
"mapping": mapping.tolist(),
|
| 251 |
+
"residual_ns": residual_ns.tolist(),
|
| 252 |
+
}))
|
| 253 |
+
return 0
|
| 254 |
+
|
| 255 |
+
print(f"{args.episode}\n 侧别={args.side} 模态={args.which}")
|
| 256 |
+
print(_fmt_stats(mapping, residual_ns, rgb_ns, force_ns, fps))
|
| 257 |
+
if args.residual:
|
| 258 |
+
print("\n 帧号 对应行 残差(ms)")
|
| 259 |
+
for k in range(min(40, mapping.size)):
|
| 260 |
+
print(f" {k:>4} {mapping[k]:>6} {residual_ns[k] / 1e6:>8.2f}")
|
| 261 |
+
if mapping.size > 40:
|
| 262 |
+
print(f" ...(其余 {mapping.size - 40} 帧略)")
|
| 263 |
+
return 0
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
if __name__ == "__main__":
|
| 267 |
+
sys.exit(main())
|
collector/tools/import_gripper_calibration.py
CHANGED
|
@@ -1,17 +1,24 @@
|
|
| 1 |
-
"""接入新夹爪:
|
| 2 |
|
| 3 |
-
collector
|
| 4 |
|
| 5 |
core/gripper/native/gripper_version1/fays_config/fays_vikit_<serial>.yaml
|
| 6 |
core/gripper/native/dist/fays_opencv48/s80m_<serial>_stereo_inertial.yaml
|
| 7 |
|
| 8 |
-
序
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
用法:
|
| 13 |
venv/bin/python tools/import_gripper_calibration.py --list
|
| 14 |
venv/bin/python tools/import_gripper_calibration.py --detect
|
|
|
|
| 15 |
venv/bin/python tools/import_gripper_calibration.py 3500000262300099
|
| 16 |
venv/bin/python tools/import_gripper_calibration.py 3500000262300099 \
|
| 17 |
--source /path/to/online [--force] [--dry-run]
|
|
@@ -20,8 +27,8 @@ collector 不生成夹爪标定,只按现场探到的产品序列号拼文件
|
|
| 20 |
上位机产物目录、或同时含两个 yaml 的任意目录。同名目标已存在且内容
|
| 21 |
不同时必须加 --force,旧文件先备份成 *.bak_<时间戳>。
|
| 22 |
|
| 23 |
-
注意:native/ 不入库(见 .gitignore),
|
| 24 |
-
|
| 25 |
"""
|
| 26 |
|
| 27 |
from __future__ import annotations
|
|
@@ -241,13 +248,87 @@ def _cmd_import(serial, source_root, *, force, dry_run):
|
|
| 241 |
return 0
|
| 242 |
|
| 243 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
def main(argv=None):
|
| 245 |
parser = argparse.ArgumentParser(
|
| 246 |
-
description="
|
| 247 |
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 248 |
)
|
| 249 |
parser.add_argument(
|
| 250 |
-
"serial", nargs="?",
|
|
|
|
|
|
|
| 251 |
parser.add_argument(
|
| 252 |
"--source", default=_DEFAULT_SOURCE,
|
| 253 |
help=f"上位机根目录(缺省 {_DEFAULT_SOURCE})")
|
|
@@ -256,6 +337,10 @@ def main(argv=None):
|
|
| 256 |
parser.add_argument(
|
| 257 |
"--detect", action="store_true",
|
| 258 |
help="现场探测插着的 Fays 序列号(需关闭主程序夹爪)")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
parser.add_argument(
|
| 260 |
"--force", action="store_true",
|
| 261 |
help="目标已存在且内容不同时覆盖(旧文件备份成 *.bak_<时间戳>)")
|
|
@@ -267,8 +352,14 @@ def main(argv=None):
|
|
| 267 |
return _cmd_list()
|
| 268 |
if args.detect:
|
| 269 |
return _cmd_detect()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
if not args.serial:
|
| 271 |
-
parser.error("需要序列号,或 --list / --detect")
|
| 272 |
try:
|
| 273 |
return _cmd_import(
|
| 274 |
args.serial, os.path.abspath(args.source),
|
|
|
|
| 1 |
+
"""接入新夹爪:备好 per-serial 标定文件。
|
| 2 |
|
| 3 |
+
collector 按现场探到的产品序列号拼文件名去找这两个文件:
|
| 4 |
|
| 5 |
core/gripper/native/gripper_version1/fays_config/fays_vikit_<serial>.yaml
|
| 6 |
core/gripper/native/dist/fays_opencv48/s80m_<serial>_stereo_inertial.yaml
|
| 7 |
|
| 8 |
+
主程序现在**自己会生成**(夹爪插上发现缺文件就地调厂商导出程序读出厂标定,
|
| 9 |
+
见 core/gripper/calibration.py),所以常规接入无需本脚本。本脚本留着用于:
|
| 10 |
+
|
| 11 |
+
* `--generate`:手工强制重新读取(换夹爪模组/怀疑标定被写坏时);
|
| 12 |
+
* 搬运:从别的机器(上位机)把已生成的标定拷进来(无设备在手时)。
|
| 13 |
+
|
| 14 |
+
出厂标定是**逐设备**的(`Camera1.fx/fy/cx/cy`、`Stereo.b`、`IMU.T_b_c1`
|
| 15 |
+
逐台不同),绝不能跨设备抄。序列号不用手填也能拿:--detect 现场读一次
|
| 16 |
+
(需先关闭主程序的夹爪,否则撞 SDK 初始化锁)。
|
| 17 |
|
| 18 |
用法:
|
| 19 |
venv/bin/python tools/import_gripper_calibration.py --list
|
| 20 |
venv/bin/python tools/import_gripper_calibration.py --detect
|
| 21 |
+
venv/bin/python tools/import_gripper_calibration.py --generate [序列号]
|
| 22 |
venv/bin/python tools/import_gripper_calibration.py 3500000262300099
|
| 23 |
venv/bin/python tools/import_gripper_calibration.py 3500000262300099 \
|
| 24 |
--source /path/to/online [--force] [--dry-run]
|
|
|
|
| 27 |
上位机产物目录、或同时含两个 yaml 的任意目录。同名目标已存在且内容
|
| 28 |
不同时必须加 --force,旧文件先备份成 *.bak_<时间戳>。
|
| 29 |
|
| 30 |
+
注意:native/ 不入库(见 .gitignore),标定只存在本机;换机器/重装要
|
| 31 |
+
重新生成或重新搬一次。
|
| 32 |
"""
|
| 33 |
|
| 34 |
from __future__ import annotations
|
|
|
|
| 248 |
return 0
|
| 249 |
|
| 250 |
|
| 251 |
+
def _backup_existing(serial):
|
| 252 |
+
"""重生成前把既有标定挪成 .bak_<时间戳>(生成失败也不至于毁掉可用的那份)。"""
|
| 253 |
+
stamp = time.strftime("%Y%m%dT%H%M%S")
|
| 254 |
+
for path in _target_paths(serial):
|
| 255 |
+
if os.path.isfile(path):
|
| 256 |
+
backup = f"{path}.bak_{stamp}"
|
| 257 |
+
shutil.copy2(path, backup)
|
| 258 |
+
print(f" 旧文件已备份 {backup}")
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _cmd_generate(serial, *, dry_run):
|
| 262 |
+
"""就地读这只夹爪的厂商出厂标定并写进 native/(不经过上位机)。"""
|
| 263 |
+
if serial is not None and not _SERIAL_PATTERN.match(serial):
|
| 264 |
+
print(f"序列号格式不合法: {serial!r}")
|
| 265 |
+
return 2
|
| 266 |
+
from core.gripper import calibration
|
| 267 |
+
from core.gripper.fays_runtime import (
|
| 268 |
+
build_fays_probe_env,
|
| 269 |
+
discover_fays_device_groups,
|
| 270 |
+
)
|
| 271 |
+
from core.gripper.fays_serial_probe import probe_product_serial
|
| 272 |
+
|
| 273 |
+
groups = discover_fays_device_groups()
|
| 274 |
+
if not groups:
|
| 275 |
+
print("未发现完整的 Fays S80M(检查 USB3 是否插好)")
|
| 276 |
+
return 1
|
| 277 |
+
print(f"发现 {len(groups)} 台完整 S80M,逐台读取产品序列号"
|
| 278 |
+
"(主程序的夹爪请先关闭,标定要独占设备):")
|
| 279 |
+
target = None
|
| 280 |
+
for group in groups:
|
| 281 |
+
ports = group["ports"]
|
| 282 |
+
try:
|
| 283 |
+
probed = probe_product_serial(
|
| 284 |
+
ports, environment=build_fays_probe_env())
|
| 285 |
+
except Exception as exc: # 探针失败不影响其他设备
|
| 286 |
+
print(f" {group['physical_usb_path']} {ports} 探测失败: {exc}")
|
| 287 |
+
continue
|
| 288 |
+
mark = ""
|
| 289 |
+
if serial is None or probed == serial:
|
| 290 |
+
mark = " ← 选中"
|
| 291 |
+
target = target or (probed, ports)
|
| 292 |
+
print(f" {group['physical_usb_path']} {ports} serial={probed}{mark}")
|
| 293 |
+
|
| 294 |
+
if target is None:
|
| 295 |
+
if serial is None:
|
| 296 |
+
print("未能读到任何一台夹爪的产品序列号")
|
| 297 |
+
else:
|
| 298 |
+
print(f"没找到序列号 {serial} 的夹爪")
|
| 299 |
+
return 1
|
| 300 |
+
|
| 301 |
+
probed, ports = target
|
| 302 |
+
print(f"\n序列号 {probed}")
|
| 303 |
+
print(f" stereo: {ports['stereo_dev_port']}")
|
| 304 |
+
print(f" imu : {ports['imu_dev_port']}")
|
| 305 |
+
if dry_run:
|
| 306 |
+
print("\n[dry-run] 将读取该设备的出厂标定并写入 native/,未执行")
|
| 307 |
+
return 0
|
| 308 |
+
|
| 309 |
+
_backup_existing(probed)
|
| 310 |
+
print("正在读取厂商出厂标定(独占设备,约需数秒)…")
|
| 311 |
+
result = calibration.generate_fays_calibration(
|
| 312 |
+
probed, ports, logger=lambda text: print(f" {text}"))
|
| 313 |
+
|
| 314 |
+
resolved_sdk, resolved_orb = paths.per_device_fays_yamls(probed)
|
| 315 |
+
print("\n已生成:")
|
| 316 |
+
print(f" 原始 dump: {result['calibration_yaml']}")
|
| 317 |
+
print(f" SDK YAML : {resolved_sdk}")
|
| 318 |
+
print(f" ORB YAML : {resolved_orb}")
|
| 319 |
+
print("提醒: native/ 不入库,这些标定只存在本机;换机器要重新生成。")
|
| 320 |
+
return 0
|
| 321 |
+
|
| 322 |
+
|
| 323 |
def main(argv=None):
|
| 324 |
parser = argparse.ArgumentParser(
|
| 325 |
+
description="备好 Fays per-serial 标定(就地生成 或 从别处搬运)",
|
| 326 |
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 327 |
)
|
| 328 |
parser.add_argument(
|
| 329 |
+
"serial", nargs="?",
|
| 330 |
+
help="Fays 产品序列号(如 3500000262300099);"
|
| 331 |
+
"--generate 时可省略,省略则用现场唯一那台")
|
| 332 |
parser.add_argument(
|
| 333 |
"--source", default=_DEFAULT_SOURCE,
|
| 334 |
help=f"上位机根目录(缺省 {_DEFAULT_SOURCE})")
|
|
|
|
| 337 |
parser.add_argument(
|
| 338 |
"--detect", action="store_true",
|
| 339 |
help="现场探测插着的 Fays 序列号(需关闭主程序夹爪)")
|
| 340 |
+
parser.add_argument(
|
| 341 |
+
"--generate", action="store_true",
|
| 342 |
+
help="就地读取这只夹爪的厂商出厂标定并写入 native/"
|
| 343 |
+
"(需关闭主程序夹爪;会先备份既有标定)")
|
| 344 |
parser.add_argument(
|
| 345 |
"--force", action="store_true",
|
| 346 |
help="目标已存在且内容不同时覆盖(旧文件备份成 *.bak_<时间戳>)")
|
|
|
|
| 352 |
return _cmd_list()
|
| 353 |
if args.detect:
|
| 354 |
return _cmd_detect()
|
| 355 |
+
if args.generate:
|
| 356 |
+
try:
|
| 357 |
+
return _cmd_generate(args.serial, dry_run=args.dry_run)
|
| 358 |
+
except RuntimeError as exc:
|
| 359 |
+
print(f"失败: {exc}")
|
| 360 |
+
return 1
|
| 361 |
if not args.serial:
|
| 362 |
+
parser.error("需要序列号,或 --list / --detect / --generate")
|
| 363 |
try:
|
| 364 |
return _cmd_import(
|
| 365 |
args.serial, os.path.abspath(args.source),
|
collector/tools/tests/smoke_gripper_p2.py
CHANGED
|
@@ -33,7 +33,7 @@ def main():
|
|
| 33 |
print(f"[RGB] #{stats['rgb']} {frame.shape} hw={hw_ns}",
|
| 34 |
flush=True)
|
| 35 |
|
| 36 |
-
def on_tactile(side, heatmap, force, matrix):
|
| 37 |
key = "tactile_l" if side == "left" else "tactile_r"
|
| 38 |
stats[key] += 1
|
| 39 |
stats[f"last_force_{side[0]}"] = force
|
|
|
|
| 33 |
print(f"[RGB] #{stats['rgb']} {frame.shape} hw={hw_ns}",
|
| 34 |
flush=True)
|
| 35 |
|
| 36 |
+
def on_tactile(side, heatmap, force, matrix, capture_ns):
|
| 37 |
key = "tactile_l" if side == "left" else "tactile_r"
|
| 38 |
stats[key] += 1
|
| 39 |
stats[f"last_force_{side[0]}"] = force
|
collector/tools/tests/smoke_gripper_p3.py
CHANGED
|
@@ -44,7 +44,7 @@ def main():
|
|
| 44 |
print(f"[STEREO] {slot} #{stats['stereo_l']} {frame.shape} "
|
| 45 |
f"hw={hw_ns}", flush=True)
|
| 46 |
|
| 47 |
-
def on_tactile(side, heatmap, force, matrix):
|
| 48 |
key = "tactile_l" if side == "left" else "tactile_r"
|
| 49 |
stats[key] += 1
|
| 50 |
stats[f"last_force_{side[0]}"] = force
|
|
|
|
| 44 |
print(f"[STEREO] {slot} #{stats['stereo_l']} {frame.shape} "
|
| 45 |
f"hw={hw_ns}", flush=True)
|
| 46 |
|
| 47 |
+
def on_tactile(side, heatmap, force, matrix, capture_ns):
|
| 48 |
key = "tactile_l" if side == "left" else "tactile_r"
|
| 49 |
stats[key] += 1
|
| 50 |
stats[f"last_force_{side[0]}"] = force
|
collector/tools/tests/test_gripper_bridge.py
CHANGED
|
@@ -134,7 +134,7 @@ def _run_open_flow(fail_select=None, wait_ready=True, ready_errors=(),
|
|
| 134 |
"""跑一次 open 流程,返回 (bridge, fakes)。"""
|
| 135 |
app = APP
|
| 136 |
bridge = GripperBridge()
|
| 137 |
-
stats = {"rgb": 0, "stereo": [], "tactile": [], "pose": [],
|
| 138 |
"state": [], "opened": 0, "error": None}
|
| 139 |
fakes = {}
|
| 140 |
|
|
@@ -182,11 +182,13 @@ def _run_open_flow(fail_select=None, wait_ready=True, ready_errors=(),
|
|
| 182 |
fakes["discovery"] = discovery
|
| 183 |
|
| 184 |
bridge.rgb_frame_ready.connect(
|
| 185 |
-
lambda _f, _t: stats.__setitem__("rgb", stats["rgb"] + 1)
|
|
|
|
| 186 |
bridge.stereo_frame_ready.connect(
|
| 187 |
lambda slot, _f, _t: stats["stereo"].append(slot))
|
| 188 |
bridge.tactile_ready.connect(
|
| 189 |
-
lambda s, h, f, m: stats["tactile"].append(
|
|
|
|
| 190 |
bridge.pose_ready.connect(
|
| 191 |
lambda p, q, t, ts: stats["pose"].append(
|
| 192 |
(tuple(p), tuple(q), tuple(t), ts)))
|
|
@@ -241,6 +243,12 @@ def main():
|
|
| 241 |
check(stats["opened"] == 1 and stats["error"] is None,
|
| 242 |
f"opened 且无 error: opened={stats['opened']} error={stats['error']}")
|
| 243 |
check(stats["rgb"] >= 1, f"RGB 首帧送达 (rgb={stats['rgb']})")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
check(fakes["tactile"].start_connected.called,
|
| 245 |
"触觉 start_connected 已调用")
|
| 246 |
left_arg = fakes["tactile"].start_connected.call_args
|
|
@@ -269,8 +277,12 @@ def main():
|
|
| 269 |
bridge._on_tactile_result("left", heatmap, (12.5, -3.0, 88.0), matrix)
|
| 270 |
_pump_until(lambda: len(stats["tactile"]) == result_count + 1)
|
| 271 |
check(len(stats["tactile"]) == result_count + 1
|
| 272 |
-
and stats["tactile"][-1] == ("left", (12.5, -3.0, 88.0), matrix),
|
| 273 |
"tactile_ready 信号携带 side/force/matrix")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
|
| 275 |
# 双目 side_by_side:单包 1280×400 只取左半投左目(右目/IMU 不外送)
|
| 276 |
stereo_base = len(stats["stereo"])
|
|
@@ -366,6 +378,12 @@ def main():
|
|
| 366 |
"矩阵最新值/序号递增(右侧)")
|
| 367 |
check(bridge.matrix_seq("left") == left_seq_before,
|
| 368 |
"未收到的侧别序号不动")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 369 |
|
| 370 |
# close 逆序回收:串口 → raw → slam → RGB 线程 → 触觉 → 租约 → 服务
|
| 371 |
bridge.close()
|
|
|
|
| 134 |
"""跑一次 open 流程,返回 (bridge, fakes)。"""
|
| 135 |
app = APP
|
| 136 |
bridge = GripperBridge()
|
| 137 |
+
stats = {"rgb": 0, "rgb_ns": [], "stereo": [], "tactile": [], "pose": [],
|
| 138 |
"state": [], "opened": 0, "error": None}
|
| 139 |
fakes = {}
|
| 140 |
|
|
|
|
| 182 |
fakes["discovery"] = discovery
|
| 183 |
|
| 184 |
bridge.rgb_frame_ready.connect(
|
| 185 |
+
lambda _f, _t: (stats.__setitem__("rgb", stats["rgb"] + 1),
|
| 186 |
+
stats["rgb_ns"].append(_t)))
|
| 187 |
bridge.stereo_frame_ready.connect(
|
| 188 |
lambda slot, _f, _t: stats["stereo"].append(slot))
|
| 189 |
bridge.tactile_ready.connect(
|
| 190 |
+
lambda s, h, f, m, ns: stats["tactile"].append(
|
| 191 |
+
(s, tuple(f), m, ns)))
|
| 192 |
bridge.pose_ready.connect(
|
| 193 |
lambda p, q, t, ts: stats["pose"].append(
|
| 194 |
(tuple(p), tuple(q), tuple(t), ts)))
|
|
|
|
| 243 |
check(stats["opened"] == 1 and stats["error"] is None,
|
| 244 |
f"opened 且无 error: opened={stats['opened']} error={stats['error']}")
|
| 245 |
check(stats["rgb"] >= 1, f"RGB 首帧送达 (rgb={stats['rgb']})")
|
| 246 |
+
# hardware_ns 必须是**未截断**的 64 位宿主单调钟。曾经 rgb_frame_ready
|
| 247 |
+
# 声明为 pyqtSignal(object, int),PyQt5 按 C++ qint32 封送 → 每 2.147s
|
| 248 |
+
# 翻符号变负、落盘后下游无法做任何时间对齐。断言 >2^31 才验得出这个坑
|
| 249 |
+
# (等于 2^31 以下的值截断与否看不出来)。
|
| 250 |
+
check(stats["rgb_ns"] and all(ns > (1 << 31) for ns in stats["rgb_ns"]),
|
| 251 |
+
f"RGB hardware_ns 未被 int32 截断 (首帧={stats['rgb_ns'][:1]})")
|
| 252 |
check(fakes["tactile"].start_connected.called,
|
| 253 |
"触觉 start_connected 已调用")
|
| 254 |
left_arg = fakes["tactile"].start_connected.call_args
|
|
|
|
| 277 |
bridge._on_tactile_result("left", heatmap, (12.5, -3.0, 88.0), matrix)
|
| 278 |
_pump_until(lambda: len(stats["tactile"]) == result_count + 1)
|
| 279 |
check(len(stats["tactile"]) == result_count + 1
|
| 280 |
+
and stats["tactile"][-1][:3] == ("left", (12.5, -3.0, 88.0), matrix),
|
| 281 |
"tactile_ready 信号携带 side/force/matrix")
|
| 282 |
+
# 第 4 个载荷是本样本的采集时刻,同样必须未被 int32 截断。
|
| 283 |
+
tactile_ns = stats["tactile"][-1][3]
|
| 284 |
+
check(isinstance(tactile_ns, int) and tactile_ns > (1 << 31),
|
| 285 |
+
f"tactile_ready 携带 64 位采集时刻 ({tactile_ns})")
|
| 286 |
|
| 287 |
# 双目 side_by_side:单包 1280×400 只取左半投左目(右目/IMU 不外送)
|
| 288 |
stereo_base = len(stats["stereo"])
|
|
|
|
| 378 |
"矩阵最新值/序号递增(右侧)")
|
| 379 |
check(bridge.matrix_seq("left") == left_seq_before,
|
| 380 |
"未收到的侧别序号不动")
|
| 381 |
+
# 带时刻的版本(泵线程按此落盘):ns 与矩阵在同一次加锁里取出、恒配对,
|
| 382 |
+
# 且 ns 同样不得被 int32 截断。
|
| 383 |
+
stamped = bridge.latest_matrix_stamped("right")
|
| 384 |
+
check(stamped is not None and stamped[1] is matrix
|
| 385 |
+
and stamped[0] > (1 << 31),
|
| 386 |
+
f"latest_matrix_stamped 返回 (采集时刻, 矩阵) ({stamped and stamped[0]})")
|
| 387 |
|
| 388 |
# close 逆序回收:串口 → raw → slam → RGB 线程 → 触觉 → 租约 → 服务
|
| 389 |
bridge.close()
|
collector/tools/tests/test_gripper_calibration_autogen.py
ADDED
|
@@ -0,0 +1,927 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""新夹爪接入即自动生成标定 —— 离线自检(不碰真设备/真实 native 目录)。
|
| 4 |
+
|
| 5 |
+
QT_QPA_PLATFORM=offscreen venv/bin/python \
|
| 6 |
+
tools/tests/test_gripper_calibration_autogen.py
|
| 7 |
+
|
| 8 |
+
背景:接入没见过的夹爪(序列号没被覆盖)时主程序直接拒绝启动,报
|
| 9 |
+
「当前 Fays 缺少运行标定文件…请先在夹爪上位机中运行 device_setup」——
|
| 10 |
+
要人工去上位机跑一遍 GUI 再把两个 YAML 搬过来。现在改成:`acquire()` 发现
|
| 11 |
+
缺文件就地调厂商导出程序从**这只夹爪自身**读出厂标定,写完直接连上。
|
| 12 |
+
|
| 13 |
+
出厂标定是逐设备的(`Camera1.fx/fy/cx/cy`、`Stereo.b`、`IMU.T_b_c1` 实测
|
| 14 |
+
098/099 三组全不同),所以本测试用**合成**的 dump 与模板,不用真机数据。
|
| 15 |
+
|
| 16 |
+
覆盖:
|
| 17 |
+
1. _find_dump:唯一命中 / 多设备取对号 / 无命中 / 序列号不符 四种判定
|
| 18 |
+
2. write_fays_sdk_yaml 只换两个端口字段,其余逐字节不动;非法输入拒绝
|
| 19 |
+
3. dump_fays_calibration:假厂商二进制(sh 脚本)→ 产物落盘且逐字节一致
|
| 20 |
+
4. **两个子进程都套了 SDK 初始化锁 + 本设备锁**(参数逐项核对)
|
| 21 |
+
5. **两个子进程拿到的都是 build_fays_probe_env() 的环境**(OpenCV 4.2 必需)
|
| 22 |
+
6. 假二进制的**非零退出码 / 超时**都要变成可读的 RuntimeError
|
| 23 |
+
7. _parse_factory_dump 逐字段解析 + 双目分辨率不一致要报错
|
| 24 |
+
8. _parse_imu_probe 五个字段映射;缺字段 / 非正值要报错
|
| 25 |
+
9. generate_orb_yaml:Stereo.b = |T_cn_cnm1 平移|(独立算的期望值)、
|
| 26 |
+
IMU 噪声五项等于探针读数、T_b_c1 结构合法、尺寸字段不被改写
|
| 27 |
+
10. ensure_fays_calibration 快路径:两个文件都在时不生成、不碰设备
|
| 28 |
+
11. ensure_fays_calibration 端到端:缺失 → 生成 → per_device_fays_yamls 通过
|
| 29 |
+
12. fays_single._ensure_calibration:已覆盖走快路径;缺文件触发生成;
|
| 30 |
+
生成失败抛 GripperFaysError 且**同时**给出底层原因与手工兜底办法
|
| 31 |
+
13. 真机产物回放(native/ 在时):真实 dump + 真实 ORB YAML 逐字节复现
|
| 32 |
+
14. 设备面板右键菜单:只对夹爪行出现、录制中禁用、非夹爪行不发信号
|
| 33 |
+
退出码 0 = 全部通过。
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
from __future__ import annotations
|
| 37 |
+
|
| 38 |
+
import math
|
| 39 |
+
import os
|
| 40 |
+
import re
|
| 41 |
+
import shutil
|
| 42 |
+
import sys
|
| 43 |
+
import tempfile
|
| 44 |
+
|
| 45 |
+
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
|
| 46 |
+
os.path.abspath(__file__))))
|
| 47 |
+
sys.path.insert(0, REPO_ROOT)
|
| 48 |
+
|
| 49 |
+
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
| 50 |
+
|
| 51 |
+
from unittest import mock # noqa: E402
|
| 52 |
+
|
| 53 |
+
from core.gripper import calibration, fays_serial_probe, paths # noqa: E402
|
| 54 |
+
from core.gripper.fays_single import ( # noqa: E402
|
| 55 |
+
GripperFaysError, SingleFaysLease,
|
| 56 |
+
)
|
| 57 |
+
from core.gripper.runtime.device_access import ( # noqa: E402
|
| 58 |
+
FAYS_SDK_INITIALIZATION_LOCK,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
FAILS = []
|
| 62 |
+
SERIAL = "3500000999990001"
|
| 63 |
+
OTHER_SERIAL = "3500000999990002"
|
| 64 |
+
|
| 65 |
+
# ── 合成的出厂 dump(结构照真机,数值是编的但自洽:鱼眼双目 + 8cm 基线)──
|
| 66 |
+
DUMP_NAME = f"FS-VI80-S80M_{SERIAL}_dump_calib.yaml"
|
| 67 |
+
LEFT_FX = 235.5
|
| 68 |
+
_T_CAM_IMU = """ T_cam_imu:
|
| 69 |
+
- [-0.9998, -0.0177, -0.0053, -0.0046]
|
| 70 |
+
- [0.0176, -0.9996, 0.0238, 0.0088]
|
| 71 |
+
- [-0.0058, 0.0237, 0.9997, -0.0088]
|
| 72 |
+
- [0.0, 0.0, 0.0, 1.0]
|
| 73 |
+
"""
|
| 74 |
+
_T_CN_CNM1 = """ T_cn_cnm1:
|
| 75 |
+
- [0.9999, -0.0073, 0.0093, -0.07985]
|
| 76 |
+
- [0.0075, 0.9998, -0.0211, -0.00021]
|
| 77 |
+
- [-0.0091, 0.0211, 0.9997, 0.00011]
|
| 78 |
+
- [0.0, 0.0, 0.0, 1.0]
|
| 79 |
+
"""
|
| 80 |
+
DUMP_BODY = (
|
| 81 |
+
"cam0:\n" + _T_CAM_IMU
|
| 82 |
+
+ " camera_model: pinhole\n"
|
| 83 |
+
+ " distortion_coeffs: [0.031, 0.062, -0.048, 0.013]\n"
|
| 84 |
+
+ " distortion_model: equidistant\n"
|
| 85 |
+
+ f" intrinsics: [{LEFT_FX}, 235.2, 318.7, 205.4]\n"
|
| 86 |
+
+ " resolution: [640, 400]\n"
|
| 87 |
+
+ " timeshift_cam_imu: 0.001\n"
|
| 88 |
+
+ "cam1:\n" + _T_CAM_IMU + _T_CN_CNM1
|
| 89 |
+
+ " camera_model: pinhole\n"
|
| 90 |
+
+ " distortion_coeffs: [0.033, 0.060, -0.047, 0.0129]\n"
|
| 91 |
+
+ " distortion_model: equidistant\n"
|
| 92 |
+
+ " intrinsics: [235.1, 235.0, 326.3, 203.9]\n"
|
| 93 |
+
+ " resolution: [640, 400]\n"
|
| 94 |
+
+ " timeshift_cam_imu: 0.0011\n"
|
| 95 |
+
)
|
| 96 |
+
# 基线应等于 T_cn_cnm1 平移的模(测试里独立算,不看实现)
|
| 97 |
+
EXPECTED_BASELINE = math.sqrt(0.07985 ** 2 + 0.00021 ** 2 + 0.00011 ** 2)
|
| 98 |
+
|
| 99 |
+
# ── 合成的 SDK 模板(两个端口字段 + 若干无关字段)────────────────────────
|
| 100 |
+
SDK_TEMPLATE_BODY = """%YAML:1.0
|
| 101 |
+
# FS-VI-S80M test template
|
| 102 |
+
stereo_dev_port: /dev/video0
|
| 103 |
+
stereo_single_cam_width: 640
|
| 104 |
+
stereo_single_cam_height: 400
|
| 105 |
+
stereo_fps: 50
|
| 106 |
+
imu_dev_port: /dev/video2
|
| 107 |
+
gravity: 9.7946
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
# ── 合成的 ORB 模板(含所有会被改写的键)───────────────────────────────
|
| 111 |
+
ORB_TEMPLATE_BODY = """%YAML:1.0
|
| 112 |
+
# FS-VI-S80M → ORB-SLAM3 test template
|
| 113 |
+
|
| 114 |
+
File.version: "1.0"
|
| 115 |
+
Camera.type: "Rectified"
|
| 116 |
+
|
| 117 |
+
Camera1.fx: 182.542
|
| 118 |
+
Camera1.fy: 182.542
|
| 119 |
+
Camera1.cx: 329.164
|
| 120 |
+
Camera1.cy: 185.844
|
| 121 |
+
|
| 122 |
+
Stereo.b: 0.0801
|
| 123 |
+
Stereo.ThDepth: 40.0
|
| 124 |
+
|
| 125 |
+
IMU.T_b_c1: !!opencv-matrix
|
| 126 |
+
rows: 4
|
| 127 |
+
cols: 4
|
| 128 |
+
dt: f
|
| 129 |
+
data: [ 1.0, 0.0, 0.0, 0.0,
|
| 130 |
+
0.0, 1.0, 0.0, 0.0,
|
| 131 |
+
0.0, 0.0, 1.0, 0.0,
|
| 132 |
+
0.0, 0.0, 0.0, 1.0 ]
|
| 133 |
+
IMU.NoiseGyro: 0.00017
|
| 134 |
+
IMU.NoiseAcc: 0.002
|
| 135 |
+
IMU.GyroWalk: 0.000022
|
| 136 |
+
IMU.AccWalk: 0.00086
|
| 137 |
+
IMU.Frequency: 1000.0
|
| 138 |
+
IMU.InsertKFsWhenLost: 1
|
| 139 |
+
|
| 140 |
+
Camera.width: 640
|
| 141 |
+
Camera.height: 400
|
| 142 |
+
Camera.fps: 25
|
| 143 |
+
"""
|
| 144 |
+
IMU_VALUES = {
|
| 145 |
+
"gyroscope_noise_density": "0.0008001",
|
| 146 |
+
"accelerometer_noise_density": "0.0071002",
|
| 147 |
+
"gyroscope_random_walk": "0.0000082003",
|
| 148 |
+
"accelerometer_random_walk": "0.000071004",
|
| 149 |
+
"update_rate": "1035.5",
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def check(cond, msg):
|
| 154 |
+
if cond:
|
| 155 |
+
print(f" PASS: {msg}")
|
| 156 |
+
else:
|
| 157 |
+
print(f" FAIL: {msg}")
|
| 158 |
+
FAILS.append(msg)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _write(path, text, mode=None):
|
| 162 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
| 163 |
+
with open(path, "w", encoding="utf-8") as handle:
|
| 164 |
+
handle.write(text)
|
| 165 |
+
if mode is not None:
|
| 166 |
+
os.chmod(path, mode)
|
| 167 |
+
return path
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _make_script(path, body):
|
| 171 |
+
"""假厂商二进制:sh 脚本,0700。"""
|
| 172 |
+
return _write(path, "#!/bin/sh\n" + body + "\n", mode=0o700)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class GuardRecorder:
|
| 176 |
+
"""替身锁:记录调用参数,不做真实 flock(测试不该碰 /tmp 的真实锁文件)。"""
|
| 177 |
+
|
| 178 |
+
def __init__(self, label, calls):
|
| 179 |
+
self._label = label
|
| 180 |
+
self._calls = calls
|
| 181 |
+
|
| 182 |
+
def __call__(self, target, **kwargs):
|
| 183 |
+
self._calls.append((self._label, target, kwargs.get("timeout")))
|
| 184 |
+
return mock.MagicMock()
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class Sandbox:
|
| 188 |
+
"""把三个产物目录 + 两个模板 + 两把设备锁全重定向到临时目录。"""
|
| 189 |
+
|
| 190 |
+
def __init__(self):
|
| 191 |
+
self.root = tempfile.mkdtemp(prefix="ksq-calib-test-")
|
| 192 |
+
self.sdk_dir = os.path.join(self.root, "fays_config")
|
| 193 |
+
self.orb_dir = os.path.join(self.root, "orb_cfg")
|
| 194 |
+
self.dump_dir = os.path.join(self.root, "dumps")
|
| 195 |
+
self.sdk_template = _write(
|
| 196 |
+
os.path.join(self.root, "sdk_template.yaml"), SDK_TEMPLATE_BODY)
|
| 197 |
+
self.orb_template = _write(
|
| 198 |
+
os.path.join(self.root, "orb_template.yaml"), ORB_TEMPLATE_BODY)
|
| 199 |
+
self.guard_calls = []
|
| 200 |
+
self.env_calls = []
|
| 201 |
+
self.probe_env = dict(os.environ, KSQ_TEST_PROBE_ENV="1")
|
| 202 |
+
|
| 203 |
+
def _env():
|
| 204 |
+
self.env_calls.append(True)
|
| 205 |
+
return dict(self.probe_env)
|
| 206 |
+
|
| 207 |
+
self._patches = [
|
| 208 |
+
mock.patch.object(paths, "FAYS_CONFIG_DIR", self.sdk_dir),
|
| 209 |
+
mock.patch.object(paths, "ORB_DEVICE_CONFIG_DIR", self.orb_dir),
|
| 210 |
+
mock.patch.object(calibration, "DUMP_OUTPUT_DIR", self.dump_dir),
|
| 211 |
+
mock.patch.object(calibration, "SDK_CONFIG_DIR", self.sdk_dir),
|
| 212 |
+
mock.patch.object(calibration, "ORB_OUTPUT_DIR", self.orb_dir),
|
| 213 |
+
mock.patch.object(calibration, "SDK_TEMPLATE", self.sdk_template),
|
| 214 |
+
mock.patch.object(calibration, "ORB_TEMPLATE", self.orb_template),
|
| 215 |
+
mock.patch.object(fays_serial_probe, "DEFAULT_TEMPLATE",
|
| 216 |
+
self.sdk_template),
|
| 217 |
+
mock.patch.object(calibration, "build_fays_probe_env", _env),
|
| 218 |
+
mock.patch.object(calibration, "device_access_guard",
|
| 219 |
+
GuardRecorder("init", self.guard_calls)),
|
| 220 |
+
mock.patch.object(calibration, "fays_device_guard",
|
| 221 |
+
GuardRecorder("device", self.guard_calls)),
|
| 222 |
+
]
|
| 223 |
+
for patch in self._patches:
|
| 224 |
+
patch.start()
|
| 225 |
+
|
| 226 |
+
def ports(self, stereo="/dev/video9", imu="/dev/video11"):
|
| 227 |
+
return {"stereo_dev_port": stereo, "imu_dev_port": imu}
|
| 228 |
+
|
| 229 |
+
def dump_exporter(self, *, body=None, serial=SERIAL, name=None):
|
| 230 |
+
"""假 dump 二进制:把 dump 内容写到 cwd(= 厂商程序的工作目录)。"""
|
| 231 |
+
name = name or f"FS-VI80-S80M_{serial}_dump_calib.yaml"
|
| 232 |
+
if body is None:
|
| 233 |
+
body = f"cat > {name} <<'KQS_EOF'\n{DUMP_BODY}KQS_EOF"
|
| 234 |
+
return _make_script(os.path.join(self.root, "dump_calib_opencv48"), body)
|
| 235 |
+
|
| 236 |
+
def imu_probe(self, *, values=None, extra=""):
|
| 237 |
+
"""假 IMU 探针:打出 imu.* 行。"""
|
| 238 |
+
values = IMU_VALUES if values is None else values
|
| 239 |
+
lines = "".join(
|
| 240 |
+
f"printf 'imu.{key}=%s\\n' '{value}'\n"
|
| 241 |
+
for key, value in values.items())
|
| 242 |
+
return _make_script(
|
| 243 |
+
os.path.join(self.root, "fays_vikit_calibration_probe"),
|
| 244 |
+
"printf 'device.serial=%s\\n' " + f"'{SERIAL}'\n" + lines + extra)
|
| 245 |
+
|
| 246 |
+
def close(self):
|
| 247 |
+
for patch in reversed(self._patches):
|
| 248 |
+
patch.stop()
|
| 249 |
+
shutil.rmtree(self.root, ignore_errors=True)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def section(title):
|
| 253 |
+
print(f"\n[{title}]")
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
# ═══════════════════════════════════════════════════════════════════
|
| 257 |
+
# 1. _find_dump
|
| 258 |
+
# ═══════════════════════════════════════════════════════════════════
|
| 259 |
+
|
| 260 |
+
def test_find_dump(box):
|
| 261 |
+
section("1. _find_dump 四种判定")
|
| 262 |
+
found = {}
|
| 263 |
+
for serial in (SERIAL, OTHER_SERIAL):
|
| 264 |
+
_write(os.path.join(box.dump_dir,
|
| 265 |
+
f"FS-VI80-S80M_{serial}_dump_calib.yaml"), DUMP_BODY)
|
| 266 |
+
got = calibration._find_dump(box.dump_dir, SERIAL)
|
| 267 |
+
check(os.path.basename(got) == DUMP_NAME,
|
| 268 |
+
f"三份 dump 里按序列号取对:{os.path.basename(got)}")
|
| 269 |
+
|
| 270 |
+
empty = os.path.join(box.root, "empty")
|
| 271 |
+
os.makedirs(empty, exist_ok=True)
|
| 272 |
+
try:
|
| 273 |
+
calibration._find_dump(empty, SERIAL)
|
| 274 |
+
check(False, "空目录应报错")
|
| 275 |
+
except RuntimeError as exc:
|
| 276 |
+
check("未生成唯一的当前设备标定 YAML" in str(exc),
|
| 277 |
+
f"空目录报可读错误:{exc}")
|
| 278 |
+
|
| 279 |
+
mismatch = os.path.join(box.root, "mismatch")
|
| 280 |
+
_write(os.path.join(mismatch,
|
| 281 |
+
f"FS-VI80-S80M_{OTHER_SERIAL}_dump_calib.yaml"), DUMP_BODY)
|
| 282 |
+
try:
|
| 283 |
+
calibration._find_dump(mismatch, SERIAL)
|
| 284 |
+
check(False, "序列号不符应报错")
|
| 285 |
+
except RuntimeError as exc:
|
| 286 |
+
check("序列号不匹配" in str(exc),
|
| 287 |
+
f"序列号不符单独报错(不误报成『没有』):{exc}")
|
| 288 |
+
|
| 289 |
+
# 文件名只含模糊子串不算命中(防 001 命中 0001)
|
| 290 |
+
partial = os.path.join(box.root, "partial")
|
| 291 |
+
_write(os.path.join(partial,
|
| 292 |
+
f"FS-VI80-S80M_1{SERIAL}_dump_calib.yaml"), DUMP_BODY)
|
| 293 |
+
_write(os.path.join(partial,
|
| 294 |
+
f"FS-VI80-S80M_{SERIAL}_dump_calib.yaml"), DUMP_BODY)
|
| 295 |
+
try:
|
| 296 |
+
calibration._find_dump(partial, SERIAL)
|
| 297 |
+
check(False, "两份同时含该序列号片段应报『不唯一』")
|
| 298 |
+
except RuntimeError as exc:
|
| 299 |
+
check("未生成唯一的当前设备标定 YAML" in str(exc),
|
| 300 |
+
"含序列号片段的两份 dump → 判为不唯一,不瞎挑")
|
| 301 |
+
del found
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
# ═══════════════════════════════════════════════════════════════════
|
| 305 |
+
# 2/3/4/5/6. 两个子进程
|
| 306 |
+
# ═══════════════════════════════════════════════════════════════════
|
| 307 |
+
|
| 308 |
+
def test_sdk_yaml(box):
|
| 309 |
+
section("2. write_fays_sdk_yaml")
|
| 310 |
+
target = calibration.write_fays_sdk_yaml(
|
| 311 |
+
SERIAL, box.ports("/dev/video7", "/dev/video13"))
|
| 312 |
+
text = open(target, encoding="utf-8").read()
|
| 313 |
+
check(target == os.path.join(box.sdk_dir, f"fays_vikit_{SERIAL}.yaml"),
|
| 314 |
+
f"落点符合 paths.per_device_fays_yamls 的约定:{target}")
|
| 315 |
+
check("stereo_dev_port: /dev/video7" in text, "stereo 端口已写入")
|
| 316 |
+
check("imu_dev_port: /dev/video13" in text, "imu 端口已写入")
|
| 317 |
+
check("stereo_fps: 50" in text and "gravity: 9.7946" in text,
|
| 318 |
+
"无关字段逐字节不动")
|
| 319 |
+
check(oct(os.stat(target).st_mode & 0o777) == "0o600", "权限 0600")
|
| 320 |
+
check(not [n for n in os.listdir(box.sdk_dir) if ".tmp." in n],
|
| 321 |
+
"无残留 .tmp 文件")
|
| 322 |
+
|
| 323 |
+
for label, bad in [("非法序列号", "../../etc/passwd"),
|
| 324 |
+
("空序列号", "")]:
|
| 325 |
+
try:
|
| 326 |
+
calibration.write_fays_sdk_yaml(bad, box.ports())
|
| 327 |
+
check(False, f"{label} 应被拒绝")
|
| 328 |
+
except ValueError:
|
| 329 |
+
check(True, f"{label} 被拒绝(不写文件)")
|
| 330 |
+
for label, port in [("非法 stereo 端口", "video7"),
|
| 331 |
+
("非法 imu 端口", "/dev/ttyUSB0")]:
|
| 332 |
+
try:
|
| 333 |
+
calibration.write_fays_sdk_yaml(
|
| 334 |
+
SERIAL, {"stereo_dev_port": port, "imu_dev_port": "/dev/video2"})
|
| 335 |
+
check(False, f"{label} 应被拒绝")
|
| 336 |
+
except ValueError:
|
| 337 |
+
check(True, f"{label} 被拒绝")
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def test_dump_subprocess(box):
|
| 341 |
+
section("3/4/5. dump_fays_calibration 子进程")
|
| 342 |
+
box.guard_calls.clear()
|
| 343 |
+
box.env_calls.clear()
|
| 344 |
+
exporter = box.dump_exporter()
|
| 345 |
+
result = calibration.dump_fays_calibration(
|
| 346 |
+
SERIAL, box.ports(), dump_binary=exporter, timeout=30)
|
| 347 |
+
check(result == os.path.join(box.dump_dir, DUMP_NAME),
|
| 348 |
+
f"dump 已原子落到 config/calibration:{os.path.basename(result)}")
|
| 349 |
+
check(open(result, encoding="utf-8").read() == DUMP_BODY,
|
| 350 |
+
"dump 内容逐字节一致")
|
| 351 |
+
check(oct(os.stat(result).st_mode & 0o777) == "0o600", "dump 权限 0600")
|
| 352 |
+
|
| 353 |
+
check(box.env_calls != [], "子进程用的是 build_fays_probe_env()(不是裸 os.environ)")
|
| 354 |
+
marks = {label for label, _t, _to in box.guard_calls}
|
| 355 |
+
check(marks == {"init", "device"},
|
| 356 |
+
f"SDK 初始化锁 + 本设备锁都取了:{sorted(marks)}")
|
| 357 |
+
init = [c for c in box.guard_calls if c[0] == "init"]
|
| 358 |
+
device = [c for c in box.guard_calls if c[0] == "device"]
|
| 359 |
+
check(init and init[0][1] == FAYS_SDK_INITIALIZATION_LOCK,
|
| 360 |
+
f"初始化锁路径正确:{init[0][1] if init else '-'}")
|
| 361 |
+
check(device and device[0][1] == "/dev/video9",
|
| 362 |
+
f"设备锁按本次的 stereo 节点取:{device[0][1] if device else '-'}")
|
| 363 |
+
|
| 364 |
+
# 假二进制把探到的探针环境记号也写出来 → 证明确实传进去了
|
| 365 |
+
marker = box.root + "/marker.txt"
|
| 366 |
+
exporter2 = box.dump_exporter(body=(
|
| 367 |
+
f"printf '%s' \"$KSQ_TEST_PROBE_ENV\" > {marker}\n"
|
| 368 |
+
f"cat > {DUMP_NAME} <<'KQS_EOF'\n{DUMP_BODY}KQS_EOF"))
|
| 369 |
+
calibration.dump_fays_calibration(
|
| 370 |
+
SERIAL, box.ports(), dump_binary=exporter2, timeout=30)
|
| 371 |
+
check(open(marker, encoding="utf-8").read() == "1",
|
| 372 |
+
"子进程真实拿到了探针环境变量(OpenCV 4.2 依赖这条链)")
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def test_subprocess_failures(box):
|
| 376 |
+
section("6. 子进程失败路径")
|
| 377 |
+
failing = box.dump_exporter(body="echo 'boom: usb stalled' >&2\nexit 3")
|
| 378 |
+
try:
|
| 379 |
+
calibration.dump_fays_calibration(
|
| 380 |
+
SERIAL, box.ports(), dump_binary=failing, timeout=30)
|
| 381 |
+
check(False, "非零退出码应报错")
|
| 382 |
+
except RuntimeError as exc:
|
| 383 |
+
text = str(exc)
|
| 384 |
+
check("returncode=3" in text and "boom: usb stalled" in text,
|
| 385 |
+
"非零退出码报错并带上厂商输出尾部")
|
| 386 |
+
|
| 387 |
+
sleeping = box.dump_exporter(body="sleep 5")
|
| 388 |
+
try:
|
| 389 |
+
calibration.dump_fays_calibration(
|
| 390 |
+
SERIAL, box.ports(), dump_binary=sleeping, timeout=0.4)
|
| 391 |
+
check(False, "超时应报错")
|
| 392 |
+
except RuntimeError as exc:
|
| 393 |
+
check("超时" in str(exc), f"超时报可读错误:{exc}")
|
| 394 |
+
|
| 395 |
+
# 导出成功但没写出任何 dump → 走 _find_dump 的『未生成』分支
|
| 396 |
+
silent = box.dump_exporter(body="exit 0")
|
| 397 |
+
try:
|
| 398 |
+
calibration.dump_fays_calibration(
|
| 399 |
+
SERIAL, box.ports(), dump_binary=silent, timeout=30)
|
| 400 |
+
check(False, "没产出文件应报错")
|
| 401 |
+
except RuntimeError as exc:
|
| 402 |
+
check("未生成唯一" in str(exc), "厂商程序没写文件 → 报『未生成』")
|
| 403 |
+
|
| 404 |
+
missing = os.path.join(box.root, "not_there")
|
| 405 |
+
try:
|
| 406 |
+
calibration.dump_fays_calibration(
|
| 407 |
+
SERIAL, box.ports(), dump_binary=missing, timeout=30)
|
| 408 |
+
check(False, "二进制不存在应报错")
|
| 409 |
+
except RuntimeError as exc:
|
| 410 |
+
check("不存在" in str(exc), f"二进制缺失报可读错误:{exc}")
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def test_imu_probe(box):
|
| 414 |
+
section("7/8. IMU 探针与解析")
|
| 415 |
+
box.guard_calls.clear()
|
| 416 |
+
probe = box.imu_probe()
|
| 417 |
+
output = calibration.run_imu_probe(
|
| 418 |
+
box.ports("/dev/video7", "/dev/video13"), probe_binary=probe, timeout=30)
|
| 419 |
+
check("imu.update_rate=1035.5" in output, "探针原始输出被完整带回")
|
| 420 |
+
parsed = calibration._parse_imu_probe(output)
|
| 421 |
+
check(parsed["imu_hz"] == 1035.5, "imu_hz → update_rate")
|
| 422 |
+
check(parsed["noise_gyro"] == float(IMU_VALUES["gyroscope_noise_density"]),
|
| 423 |
+
"noise_gyro → gyroscope_noise_density")
|
| 424 |
+
check(parsed["walk_acc"] == float(IMU_VALUES["accelerometer_random_walk"]),
|
| 425 |
+
"walk_acc → accelerometer_random_walk")
|
| 426 |
+
device = [c for c in box.guard_calls if c[0] == "device"]
|
| 427 |
+
check(device and device[0][1] == "/dev/video7",
|
| 428 |
+
f"IMU 探针也按 stereo 节点取设备锁:{device[0][1] if device else '-'}")
|
| 429 |
+
|
| 430 |
+
# run_imu_probe 只管跑并带回原始输出;字段解析在 _parse_imu_probe。
|
| 431 |
+
# 两处的失败都要能拦住生成,所以两条路径都测。
|
| 432 |
+
for label, bad in [
|
| 433 |
+
("缺字段", {k: v for k, v in IMU_VALUES.items()
|
| 434 |
+
if k != "update_rate"}),
|
| 435 |
+
("非正值", dict(IMU_VALUES, gyroscope_noise_density="0"))]:
|
| 436 |
+
broken = box.imu_probe(values=bad)
|
| 437 |
+
raw = calibration.run_imu_probe(box.ports(), probe_binary=broken,
|
| 438 |
+
timeout=30)
|
| 439 |
+
try:
|
| 440 |
+
calibration._parse_imu_probe(raw)
|
| 441 |
+
check(False, f"IMU 探针{label}应报错")
|
| 442 |
+
except RuntimeError as exc:
|
| 443 |
+
check(True, f"IMU 探针{label}被拒:{exc}")
|
| 444 |
+
# 端到端:同一个坏探针喂给整条生成链,也必须失败
|
| 445 |
+
with mock.patch.object(calibration, "IMU_PROBE_BINARY", broken), \
|
| 446 |
+
mock.patch.object(calibration, "DUMP_BINARY",
|
| 447 |
+
box.dump_exporter()):
|
| 448 |
+
try:
|
| 449 |
+
calibration.generate_fays_calibration(SERIAL, box.ports(),
|
| 450 |
+
timeout=30)
|
| 451 |
+
check(False, f"坏 IMU 探针({label})不该生成出可用标定")
|
| 452 |
+
except RuntimeError:
|
| 453 |
+
check(True, f"坏 IMU 探针({label})在整链上被拒")
|
| 454 |
+
failing = _make_script(os.path.join(box.root, "imu_fail"), "exit 4")
|
| 455 |
+
try:
|
| 456 |
+
calibration.run_imu_probe(box.ports(), probe_binary=failing, timeout=30)
|
| 457 |
+
check(False, "IMU 探针非零退出应报错")
|
| 458 |
+
except RuntimeError as exc:
|
| 459 |
+
check("returncode=4" in str(exc), "IMU 探针非零退出码带上返回码")
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def test_parse_dump(box):
|
| 463 |
+
section("7b. _parse_factory_dump")
|
| 464 |
+
path = _write(os.path.join(box.root, "p.yaml"), DUMP_BODY)
|
| 465 |
+
cameras = calibration._parse_factory_dump(path)
|
| 466 |
+
check(cameras[0]["intrinsics"] == [LEFT_FX, 235.2, 318.7, 205.4],
|
| 467 |
+
f"cam0 内参:{cameras[0]['intrinsics']}")
|
| 468 |
+
check(cameras[1]["intrinsics"] == [235.1, 235.0, 326.3, 203.9],
|
| 469 |
+
f"cam1 内参:{cameras[1]['intrinsics']}")
|
| 470 |
+
check(cameras[0]["distortion"] == [0.031, 0.062, -0.048, 0.013],
|
| 471 |
+
"cam0 畸变系数")
|
| 472 |
+
check(cameras[0]["resolution"] == [640.0, 400.0], "分辨率")
|
| 473 |
+
check(cameras[0]["timeshift"] == 0.001, "cam0 时间偏移")
|
| 474 |
+
check(cameras[0]["T_cn_cnm1"] is None, "cam0 无 T_cn_cnm1")
|
| 475 |
+
check(cameras[1]["T_cn_cnm1"][0][3] == -0.07985, "cam1 的 T_cn_cnm1 解析")
|
| 476 |
+
check(len(cameras[0]["T_cam_imu"]) == 4
|
| 477 |
+
and len(cameras[0]["T_cam_imu"][0]) == 4, "T_cam_imu 是 4x4")
|
| 478 |
+
|
| 479 |
+
# 只改 cam0 的分辨率(count=1),制造"双目不一致"
|
| 480 |
+
bad = _write(os.path.join(box.root, "bad.yaml"),
|
| 481 |
+
DUMP_BODY.replace("resolution: [640, 400]\n timeshift",
|
| 482 |
+
"resolution: [1280, 800]\n timeshift", 1))
|
| 483 |
+
try:
|
| 484 |
+
calibration._parse_factory_dump(bad)
|
| 485 |
+
check(False, "双目分辨率不一致应报错")
|
| 486 |
+
except RuntimeError as exc:
|
| 487 |
+
check("分辨率不一致" in str(exc), "双目分辨率不一致被拒")
|
| 488 |
+
try:
|
| 489 |
+
calibration._parse_factory_dump(_write(
|
| 490 |
+
os.path.join(box.root, "nocam.yaml"), "cam0:\n intrinsics: [1,2,3,4]\n"))
|
| 491 |
+
check(False, "缺字段应报错")
|
| 492 |
+
except RuntimeError:
|
| 493 |
+
check(True, "dump 缺字段被拒")
|
| 494 |
+
try:
|
| 495 |
+
calibration._parse_factory_dump(os.path.join(box.root, "nope.yaml"))
|
| 496 |
+
check(False, "文件不存在应报错")
|
| 497 |
+
except RuntimeError:
|
| 498 |
+
check(True, "dump 文件缺失被拒")
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def test_orb_yaml(box):
|
| 502 |
+
section("9. generate_orb_yaml")
|
| 503 |
+
dump_path = _write(os.path.join(box.root, DUMP_NAME), DUMP_BODY)
|
| 504 |
+
probe = box.imu_probe()
|
| 505 |
+
output = calibration.run_imu_probe(
|
| 506 |
+
box.ports(), probe_binary=probe, timeout=30)
|
| 507 |
+
target = calibration.generate_orb_yaml(
|
| 508 |
+
SERIAL, dump_path, output, output_dir=box.orb_dir)
|
| 509 |
+
text = open(target, encoding="utf-8").read()
|
| 510 |
+
check(target == os.path.join(
|
| 511 |
+
box.orb_dir, f"s80m_{SERIAL}_stereo_inertial.yaml"),
|
| 512 |
+
f"落点符合 paths.per_device_fays_yamls 的约定:{target}")
|
| 513 |
+
|
| 514 |
+
def scalar(key):
|
| 515 |
+
for line in text.splitlines():
|
| 516 |
+
if line.startswith(key + ":"):
|
| 517 |
+
return float(line.split(":", 1)[1].strip())
|
| 518 |
+
return None
|
| 519 |
+
|
| 520 |
+
baseline = scalar("Stereo.b")
|
| 521 |
+
check(abs(baseline - EXPECTED_BASELINE) < 1e-12,
|
| 522 |
+
f"Stereo.b = |T_cn_cnm1 平移| = {EXPECTED_BASELINE}(实得 {baseline})")
|
| 523 |
+
for key in ("Camera1.fx", "Camera1.fy", "Camera1.cx", "Camera1.cy"):
|
| 524 |
+
value = scalar(key)
|
| 525 |
+
check(value is not None and value > 0 and value == value,
|
| 526 |
+
f"{key} 已改写成有效正数:{value}")
|
| 527 |
+
check(scalar("IMU.NoiseGyro") == float(IMU_VALUES["gyroscope_noise_density"]),
|
| 528 |
+
"IMU.NoiseGyro 等于探针读数")
|
| 529 |
+
check(scalar("IMU.NoiseAcc") == float(IMU_VALUES["accelerometer_noise_density"]),
|
| 530 |
+
"IMU.NoiseAcc 等于探针读数")
|
| 531 |
+
check(scalar("IMU.GyroWalk") == float(IMU_VALUES["gyroscope_random_walk"]),
|
| 532 |
+
"IMU.GyroWalk 等于探针读数")
|
| 533 |
+
check(scalar("IMU.AccWalk") == float(IMU_VALUES["accelerometer_random_walk"]),
|
| 534 |
+
"IMU.AccWalk 等于探针读数")
|
| 535 |
+
check(scalar("IMU.Frequency") == float(IMU_VALUES["update_rate"]),
|
| 536 |
+
"IMU.Frequency 等于探针读数")
|
| 537 |
+
check("Camera.width: 640" in text and "Camera.height: 400" in text,
|
| 538 |
+
"尺寸字段不被改写")
|
| 539 |
+
check("Camera.fps: 25" in text, "模板里我们不碰的字段原样保留")
|
| 540 |
+
check(f"# FS-VI80-S80M serial {SERIAL}" in text, "型号注释反映本设备的 dump")
|
| 541 |
+
check("IMU.InsertKFsWhenLost: 1" in text, "T_b_c1 之后的字段没被吞掉")
|
| 542 |
+
|
| 543 |
+
rows = [line for line in text.splitlines() if line.startswith(" data:")]
|
| 544 |
+
check(len(rows) == 1, "T_b_c1 的 data 只有一块(count=1,不会重复改写)")
|
| 545 |
+
values = rows[0].split("[", 1)[1].rsplit("]", 1)[0].split(",")
|
| 546 |
+
numbers = [float(v) for v in values]
|
| 547 |
+
check(len(numbers) == 16, f"T_b_c1 是 16 个值(实得 {len(numbers)})")
|
| 548 |
+
check(all(n == n and abs(n) != float("inf") for n in numbers), "T_b_c1 全为有限值")
|
| 549 |
+
check(numbers[12:] == [0.0, 0.0, 0.0, 1.0], "T_b_c1 末行是 [0,0,0,1]")
|
| 550 |
+
|
| 551 |
+
no_comment = _write(os.path.join(box.root, "orb_nc.yaml"),
|
| 552 |
+
ORB_TEMPLATE_BODY.replace("# FS-VI-S80M → ORB-SLAM3 test template\n", ""))
|
| 553 |
+
try:
|
| 554 |
+
calibration.generate_orb_yaml(SERIAL, dump_path, output,
|
| 555 |
+
template_path=no_comment,
|
| 556 |
+
output_dir=box.orb_dir)
|
| 557 |
+
check(False, "模板���型号注释应报错")
|
| 558 |
+
except RuntimeError as exc:
|
| 559 |
+
check("序列号注释" in str(exc), "模板缺 Fays 注释被拒")
|
| 560 |
+
missing_key = _write(os.path.join(box.root, "orb_mk.yaml"),
|
| 561 |
+
ORB_TEMPLATE_BODY.replace("Stereo.b: 0.0801\n", ""))
|
| 562 |
+
try:
|
| 563 |
+
calibration.generate_orb_yaml(SERIAL, dump_path, output,
|
| 564 |
+
template_path=missing_key,
|
| 565 |
+
output_dir=box.orb_dir)
|
| 566 |
+
check(False, "模板缺字段应报错")
|
| 567 |
+
except RuntimeError as exc:
|
| 568 |
+
check("缺少字段" in str(exc), "模板缺 Stereo.b 被拒")
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
# ═══════════════════════════════════════════════════════════════════
|
| 572 |
+
# 10/11. ensure_fays_calibration
|
| 573 |
+
# ═══════════════════════════════════════════════════════════════════
|
| 574 |
+
|
| 575 |
+
def _populate(box, serial):
|
| 576 |
+
"""就地把该序列号的两个产物文件造出来(走真实的生成链)。"""
|
| 577 |
+
with mock.patch.object(calibration, "DUMP_BINARY",
|
| 578 |
+
box.dump_exporter(serial=serial)), \
|
| 579 |
+
mock.patch.object(calibration, "IMU_PROBE_BINARY", box.imu_probe()):
|
| 580 |
+
return calibration.ensure_fays_calibration(serial, box.ports())
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def test_ensure(box):
|
| 584 |
+
section("10/11. ensure_fays_calibration 快路径与端到端")
|
| 585 |
+
# 独占一个序列号:上面的用例已经往 sandbox 里写过 SERIAL 的文件了
|
| 586 |
+
serial = "3500000999990005"
|
| 587 |
+
try:
|
| 588 |
+
paths.per_device_fays_yamls(serial)
|
| 589 |
+
check(False, "先决条件:sandbox 里此刻不该已有该序列号的标定文件")
|
| 590 |
+
except RuntimeError:
|
| 591 |
+
check(True, "先决条件成立:sandbox 里还没有标定文件")
|
| 592 |
+
|
| 593 |
+
sdk_yaml, orb_yaml = _populate(box, serial)
|
| 594 |
+
check(os.path.isfile(sdk_yaml) and os.path.isfile(orb_yaml),
|
| 595 |
+
"端到端生成后 per_device_fays_yamls 通过(两个文件都在)")
|
| 596 |
+
check(sdk_yaml.startswith(box.sdk_dir) and orb_yaml.startswith(box.orb_dir),
|
| 597 |
+
"产物落在 path 约定目录内")
|
| 598 |
+
|
| 599 |
+
with mock.patch.object(calibration, "generate_fays_calibration",
|
| 600 |
+
side_effect=AssertionError("已覆盖不该再生成")), \
|
| 601 |
+
mock.patch.object(calibration, "build_fays_probe_env",
|
| 602 |
+
side_effect=AssertionError("快路径不该碰设备环境")):
|
| 603 |
+
again = calibration.ensure_fays_calibration(serial, box.ports())
|
| 604 |
+
check(again == (sdk_yaml, orb_yaml),
|
| 605 |
+
"已覆盖时走 isfile 快路径:不生成、不碰设备、零开销")
|
| 606 |
+
|
| 607 |
+
with mock.patch.object(calibration, "generate_fays_calibration") as forced:
|
| 608 |
+
forced.return_value = {"sdk_yaml": sdk_yaml, "orb_yaml": orb_yaml}
|
| 609 |
+
calibration.ensure_fays_calibration(serial, box.ports(), force=True)
|
| 610 |
+
check(forced.call_count == 1, "force=True 时不走快路径,强制重新读取")
|
| 611 |
+
|
| 612 |
+
try:
|
| 613 |
+
calibration.ensure_fays_calibration(OTHER_SERIAL, box.ports())
|
| 614 |
+
check(False, "没有设备时生成应失败而不是假装成功")
|
| 615 |
+
except RuntimeError:
|
| 616 |
+
check(True, "缺设备/二进制时 ensure 抛错,不静默返回不存在的路径")
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
def test_fays_single_hook(box):
|
| 620 |
+
section("12. SingleFaysLease._ensure_calibration")
|
| 621 |
+
lease = SingleFaysLease(logger=lambda _text: None)
|
| 622 |
+
group = {"ports": box.ports()}
|
| 623 |
+
|
| 624 |
+
sdk_yaml, orb_yaml = lease._ensure_calibration(SERIAL, group)
|
| 625 |
+
check(os.path.isfile(sdk_yaml) and os.path.isfile(orb_yaml),
|
| 626 |
+
"已覆盖 → 直接返回两个路径(不生成)")
|
| 627 |
+
|
| 628 |
+
def _fake_generate(serial, ports, **_kwargs):
|
| 629 |
+
"""假生成:真的把该序列号的两个文件写出来(否则复核必然失败)。"""
|
| 630 |
+
sdk = calibration.write_fays_sdk_yaml(serial, ports)
|
| 631 |
+
orb = _write(os.path.join(
|
| 632 |
+
box.orb_dir, f"s80m_{serial}_stereo_inertial.yaml"), ORB_TEMPLATE_BODY)
|
| 633 |
+
return {"sdk_yaml": sdk, "orb_yaml": orb}
|
| 634 |
+
|
| 635 |
+
with mock.patch.object(calibration, "generate_fays_calibration",
|
| 636 |
+
side_effect=_fake_generate) as gen:
|
| 637 |
+
got = lease._ensure_calibration(OTHER_SERIAL, group)
|
| 638 |
+
check(gen.call_count == 1,
|
| 639 |
+
"缺文件 → 触发一次现场生成(用户要的『插上就能用』)")
|
| 640 |
+
check(got == paths.per_device_fays_yamls(OTHER_SERIAL),
|
| 641 |
+
"生成后按 paths 复核并返回该序列号的真实路径")
|
| 642 |
+
check(got[0].endswith(f"fays_vikit_{OTHER_SERIAL}.yaml"),
|
| 643 |
+
"返回的是这台夹爪自己的标定,不是别人的")
|
| 644 |
+
|
| 645 |
+
with mock.patch.object(calibration, "generate_fays_calibration",
|
| 646 |
+
side_effect=RuntimeError("厂商导出程序不存在")):
|
| 647 |
+
try:
|
| 648 |
+
lease._ensure_calibration("3500000999990003", group)
|
| 649 |
+
check(False, "生成失败应抛 GripperFaysError")
|
| 650 |
+
except GripperFaysError as exc:
|
| 651 |
+
text = str(exc)
|
| 652 |
+
check("厂商导出程序不存在" in text, "带上底层原因")
|
| 653 |
+
check("device_setup" in text, "给出上位机手工兜底办法")
|
| 654 |
+
check("import_gripper_calibration.py" in text, "给出导入脚本兜底办法")
|
| 655 |
+
check("3500000999990003" in text, "带上序列号")
|
| 656 |
+
|
| 657 |
+
# 生成"成功"但产物没落在 paths 认得的路径上 → 也必须带上生成上下文,
|
| 658 |
+
# 不能让 paths 那句「请先跑 device_setup」成为唯一解释
|
| 659 |
+
with mock.patch.object(calibration, "generate_fays_calibration",
|
| 660 |
+
side_effect=lambda *a, **k: {"sdk_yaml": "", "orb_yaml": ""}):
|
| 661 |
+
try:
|
| 662 |
+
lease._ensure_calibration("3500000999990004", group)
|
| 663 |
+
check(False, "产物落错位置应报错")
|
| 664 |
+
except GripperFaysError as exc:
|
| 665 |
+
check("3500000999990004" in str(exc),
|
| 666 |
+
"产物落错位置时报的是 GripperFaysError 且带序列号")
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
# ═══════════════════════════════════════════════════════════════════
|
| 670 |
+
# 13. 真机产物回放
|
| 671 |
+
# ═══════════════════════════════════════════════════════════════════
|
| 672 |
+
|
| 673 |
+
def test_real_artifacts_replay():
|
| 674 |
+
section("13. 真实产物逐字节回放(native/ 缺失则跳过)")
|
| 675 |
+
serial = "3500000262300098"
|
| 676 |
+
dump = os.path.join(paths.NATIVE_ROOT, "config", "calibration",
|
| 677 |
+
f"FS-VI80-S80M_{serial}_dump_calib.yaml")
|
| 678 |
+
orb = os.path.join(paths.ORB_DEVICE_CONFIG_DIR,
|
| 679 |
+
f"s80m_{serial}_stereo_inertial.yaml")
|
| 680 |
+
sdk = os.path.join(paths.FAYS_CONFIG_DIR, f"fays_vikit_{serial}.yaml")
|
| 681 |
+
if not (os.path.isfile(dump) and os.path.isfile(orb) and os.path.isfile(sdk)):
|
| 682 |
+
print(" SKIP: 本机没有该序列号的真机产物")
|
| 683 |
+
return
|
| 684 |
+
|
| 685 |
+
expected = open(orb, encoding="utf-8").read()
|
| 686 |
+
fake_probe = "\n".join(
|
| 687 |
+
"imu.{src}={value}".format(src=src, value=_scalar_of(expected, dst))
|
| 688 |
+
for src, dst in (("accelerometer_noise_density", "IMU.NoiseAcc"),
|
| 689 |
+
("accelerometer_random_walk", "IMU.AccWalk"),
|
| 690 |
+
("gyroscope_noise_density", "IMU.NoiseGyro"),
|
| 691 |
+
("gyroscope_random_walk", "IMU.GyroWalk"),
|
| 692 |
+
("update_rate", "IMU.Frequency"))) + "\n"
|
| 693 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 694 |
+
got = calibration.generate_orb_yaml(
|
| 695 |
+
serial, dump, fake_probe, output_dir=tmp)
|
| 696 |
+
generated = open(got, encoding="utf-8").read()
|
| 697 |
+
# 出处注释要单独校验:这台真机产物(098)带的是模板遗留的 1870088——
|
| 698 |
+
# 它自己就是"照抄模板出处"的实例,而生成器现在必须改写成本机序列号。
|
| 699 |
+
# 把这一行摘出去再比对,逐字节那条断言才仍然是"除 Camera.fps 外全等",
|
| 700 |
+
# 而不是给注释开一个能吞掉错值的口子。
|
| 701 |
+
def _provenance(text):
|
| 702 |
+
return [ln for ln in text.splitlines() if ln.startswith("# IMU 外参来源:")]
|
| 703 |
+
|
| 704 |
+
def _strip_provenance(text):
|
| 705 |
+
return [ln for ln in text.splitlines()
|
| 706 |
+
if not ln.startswith("# IMU 外参来源:")]
|
| 707 |
+
|
| 708 |
+
got_prov, exp_prov = _provenance(generated), _provenance(expected)
|
| 709 |
+
check(len(got_prov) == 1 and len(exp_prov) == 1,
|
| 710 |
+
f"两侧各有且仅有一条出处注释(生成 {got_prov} / 真机 {exp_prov})")
|
| 711 |
+
if got_prov and exp_prov:
|
| 712 |
+
check(serial in got_prov[0], f"出处注释写明本机序列号:{got_prov[0]}")
|
| 713 |
+
check("1870088" in exp_prov[0] and got_prov[0] != exp_prov[0],
|
| 714 |
+
f"真机产物带的是模板遗留的 1870088(历史产物本次不动):{exp_prov[0]}")
|
| 715 |
+
# 顺手堵住"别的序列号漏进产物":生成物里出现的 16 位序列号只许是这一台
|
| 716 |
+
found = set(re.findall(r"\b3\d{15}\b", generated))
|
| 717 |
+
check(found <= {serial}, f"生成物只提到本机序列号(出现 {sorted(found)})")
|
| 718 |
+
|
| 719 |
+
gen_lines, exp_lines = _strip_provenance(generated), _strip_provenance(expected)
|
| 720 |
+
diffs = [
|
| 721 |
+
(index + 1, left, right)
|
| 722 |
+
for index, (left, right) in enumerate(zip(gen_lines, exp_lines))
|
| 723 |
+
if left != right
|
| 724 |
+
]
|
| 725 |
+
check(len(gen_lines) == len(exp_lines), "行数与真机产物一致")
|
| 726 |
+
# 唯一允许的差异是模板漂移的 Camera.fps(模板 25 / 旧产物 30,产线两种
|
| 727 |
+
# 值并存,与本次改动无关)
|
| 728 |
+
unexpected = [d for d in diffs if not d[1].startswith("Camera.fps:")]
|
| 729 |
+
check(not unexpected, f"逐字节复现真机 ORB YAML(差异仅 {diffs})")
|
| 730 |
+
check(all(d[1].startswith("Camera.fps:") for d in diffs),
|
| 731 |
+
f"唯一差异是模板的 Camera.fps:{diffs}")
|
| 732 |
+
|
| 733 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 734 |
+
ports = _ports_of(sdk)
|
| 735 |
+
got = calibration.write_fays_sdk_yaml(serial, ports, config_dir=tmp)
|
| 736 |
+
check(open(got, encoding="utf-8").read() == open(sdk, encoding="utf-8").read(),
|
| 737 |
+
"逐字节复现真机 SDK YAML(只换两个端口字段)")
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
def _scalar_of(text, key):
|
| 741 |
+
for line in text.splitlines():
|
| 742 |
+
if line.startswith(key + ":"):
|
| 743 |
+
return line.split(":", 1)[1].strip()
|
| 744 |
+
raise AssertionError(f"真机产物里没有 {key}")
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
def _ports_of(sdk_yaml):
|
| 748 |
+
import re
|
| 749 |
+
text = open(sdk_yaml, encoding="utf-8").read()
|
| 750 |
+
ports = {}
|
| 751 |
+
for key in ("stereo_dev_port", "imu_dev_port"):
|
| 752 |
+
ports[key] = re.search(
|
| 753 |
+
rf"(?m)^\s*{key}\s*:\s*(/dev/video\d+)", text).group(1)
|
| 754 |
+
return ports
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
# ═══════════════════════════════════════════════════════════════════
|
| 758 |
+
# 14. 设备面板右键菜单
|
| 759 |
+
# ═══════════════════════════════════════════════════════════════════
|
| 760 |
+
|
| 761 |
+
def test_device_panel_menu():
|
| 762 |
+
section("14. 设备面板右键菜单")
|
| 763 |
+
from PyQt5.QtWidgets import QApplication
|
| 764 |
+
from config.i18n import tr
|
| 765 |
+
from core.device_detector import DeviceInfo
|
| 766 |
+
from ui.device_panel import DevicePanel
|
| 767 |
+
|
| 768 |
+
app = QApplication.instance() or QApplication([])
|
| 769 |
+
panel = DevicePanel()
|
| 770 |
+
# group 是 kind 的派生属性(不是构造参数)
|
| 771 |
+
gripper = DeviceInfo(key="gripper:3500000999990001", kind="gripper",
|
| 772 |
+
display_name="UMI", serial="3500000999990001")
|
| 773 |
+
camera = DeviceInfo(key="uvc:cam0", kind="uvc",
|
| 774 |
+
display_name="CAM", serial="")
|
| 775 |
+
check(gripper.group == "gripper" and camera.group == "camera",
|
| 776 |
+
"先决条件:DeviceInfo.group 按 kind 派生正确")
|
| 777 |
+
panel.set_devices([gripper, camera])
|
| 778 |
+
|
| 779 |
+
check(hasattr(panel, "gripper_recalibration_requested"),
|
| 780 |
+
"面板暴露重标定信号")
|
| 781 |
+
# 与实现同一口径取自翻译表,语言切换下都成立(英文界面断言中文会误判)
|
| 782 |
+
hint_with = tr("双击设备可重命名") + tr(";右键夹爪可重读取出厂标定")
|
| 783 |
+
hint_without = tr("双击设备可重命名")
|
| 784 |
+
check(panel._refresh_hint.text() == hint_with,
|
| 785 |
+
f"有夹爪时底部提示右键入口:{panel._refresh_hint.text()!r}")
|
| 786 |
+
panel.set_devices([camera])
|
| 787 |
+
check(panel._refresh_hint.text() == hint_without,
|
| 788 |
+
"没有夹爪时不提右键入口")
|
| 789 |
+
|
| 790 |
+
emitted = []
|
| 791 |
+
panel.gripper_recalibration_requested.connect(emitted.append)
|
| 792 |
+
|
| 793 |
+
class _FakeAction:
|
| 794 |
+
def __init__(self, text):
|
| 795 |
+
self.text = text
|
| 796 |
+
self.enabled = True
|
| 797 |
+
|
| 798 |
+
def setEnabled(self, on):
|
| 799 |
+
self.enabled = bool(on)
|
| 800 |
+
|
| 801 |
+
class _FakeMenu:
|
| 802 |
+
last = None
|
| 803 |
+
accept = False # True → exec_ 返回本次刚建的那一项(模拟用户点选)
|
| 804 |
+
|
| 805 |
+
def __init__(self, _parent):
|
| 806 |
+
_FakeMenu.last = self
|
| 807 |
+
self.actions = []
|
| 808 |
+
|
| 809 |
+
def addAction(self, text):
|
| 810 |
+
action = _FakeAction(text)
|
| 811 |
+
self.actions.append(action)
|
| 812 |
+
return action
|
| 813 |
+
|
| 814 |
+
def exec_(self, _pos):
|
| 815 |
+
# 必须回传自己 addAction 造的那个对象(实现按 `chosen is action` 判等)
|
| 816 |
+
return self.actions[0] if _FakeMenu.accept and self.actions else None
|
| 817 |
+
|
| 818 |
+
panel.set_devices([gripper, camera])
|
| 819 |
+
gpos = panel._tree.visualItemRect(panel._items[gripper.key]).center()
|
| 820 |
+
cpos = panel._tree.visualItemRect(panel._items[camera.key]).center()
|
| 821 |
+
|
| 822 |
+
with mock.patch("ui.device_panel.QMenu", _FakeMenu):
|
| 823 |
+
_FakeMenu.accept = False
|
| 824 |
+
_FakeMenu.last = None
|
| 825 |
+
panel._on_context_menu(cpos)
|
| 826 |
+
check(_FakeMenu.last is None, "相机行右键不弹夹爪菜单(无菜单对象)")
|
| 827 |
+
check(emitted == [], "相机行不发重标定信号")
|
| 828 |
+
|
| 829 |
+
_FakeMenu.last = None
|
| 830 |
+
panel._on_context_menu(gpos)
|
| 831 |
+
menu = _FakeMenu.last
|
| 832 |
+
check(menu is not None and len(menu.actions) == 1,
|
| 833 |
+
"夹爪行右键弹出菜单,且只一项")
|
| 834 |
+
check(menu.actions[0].text == tr("重新读取出厂标定"),
|
| 835 |
+
f"菜单文案:{menu.actions[0].text!r}")
|
| 836 |
+
check(emitted == [], "只弹菜单不选 → 不发信号")
|
| 837 |
+
|
| 838 |
+
_FakeMenu.accept = True
|
| 839 |
+
panel._on_context_menu(gpos)
|
| 840 |
+
check(emitted and emitted[-1].key == gripper.key,
|
| 841 |
+
f"选中菜单项 → 发信号带该夹爪:{emitted[-1].key if emitted else '-'}")
|
| 842 |
+
|
| 843 |
+
panel.set_locked(True)
|
| 844 |
+
before = len(emitted)
|
| 845 |
+
panel._on_context_menu(gpos)
|
| 846 |
+
check(len(emitted) == before, "录制中不触发重标定(设备要独占)")
|
| 847 |
+
panel.set_locked(False)
|
| 848 |
+
|
| 849 |
+
panel.deleteLater()
|
| 850 |
+
del app
|
| 851 |
+
|
| 852 |
+
|
| 853 |
+
def test_main_window_reopen_bookkeeping():
|
| 854 |
+
section("15. 主窗口标定完成后的开回逻辑")
|
| 855 |
+
import ui.main_window as main_window
|
| 856 |
+
|
| 857 |
+
# MainWindow.__new__ 绕过 Qt 基类初始化,不能当 QMessageBox 的父窗口,
|
| 858 |
+
# 所以弹窗整体换成替身(本用例只关心开回与日志,不关心弹窗长什么样)
|
| 859 |
+
boxes = []
|
| 860 |
+
|
| 861 |
+
class _FakeBox:
|
| 862 |
+
@staticmethod
|
| 863 |
+
def critical(_parent, title, text):
|
| 864 |
+
boxes.append(("critical", title, text))
|
| 865 |
+
|
| 866 |
+
window = main_window.MainWindow.__new__(main_window.MainWindow)
|
| 867 |
+
logs = []
|
| 868 |
+
window._log = logs.append
|
| 869 |
+
window._gripper_recalib_reopen = {"g:1"}
|
| 870 |
+
reopened = []
|
| 871 |
+
window._on_device_toggled = lambda dev, on: reopened.append((dev.key, on))
|
| 872 |
+
window._device_panel = mock.MagicMock()
|
| 873 |
+
fake_dev = mock.MagicMock(key="g:1")
|
| 874 |
+
window._device_panel.device_for_key.return_value = fake_dev
|
| 875 |
+
|
| 876 |
+
with mock.patch.object(main_window, "QMessageBox", _FakeBox):
|
| 877 |
+
window._on_gripper_recalibration_done("g:1", "UMI", "")
|
| 878 |
+
check(reopened == [("g:1", True)], "成功且原先开着 → 自动开回来")
|
| 879 |
+
check(not window._gripper_recalib_reopen, "开回后清掉待开回记录")
|
| 880 |
+
check(any("已更新" in line for line in logs), f"记一行成功日志:{logs}")
|
| 881 |
+
check(boxes == [], "成功不弹窗")
|
| 882 |
+
|
| 883 |
+
reopened.clear()
|
| 884 |
+
window._gripper_recalib_reopen = {"g:1"}
|
| 885 |
+
window._on_gripper_recalibration_done("g:1", "UMI", "设备被占用")
|
| 886 |
+
check(reopened == [], "失败不自动开回(避免二次弹错)")
|
| 887 |
+
check(not window._gripper_recalib_reopen, "失败也清掉待开回记录")
|
| 888 |
+
check(any("设备被占用" in line for line in logs), "失败写日志带上原因")
|
| 889 |
+
check(len(boxes) == 1 and "设备被占用" in boxes[0][2],
|
| 890 |
+
"失败弹窗带上底层原因")
|
| 891 |
+
|
| 892 |
+
reopened.clear()
|
| 893 |
+
window._gripper_recalib_reopen = set()
|
| 894 |
+
window._on_gripper_recalibration_done("g:2", "UMI2", "")
|
| 895 |
+
check(reopened == [], "本来就没开 → 不擅自打开")
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
def main():
|
| 899 |
+
box = Sandbox()
|
| 900 |
+
try:
|
| 901 |
+
test_find_dump(box)
|
| 902 |
+
test_sdk_yaml(box)
|
| 903 |
+
test_dump_subprocess(box)
|
| 904 |
+
test_subprocess_failures(box)
|
| 905 |
+
test_imu_probe(box)
|
| 906 |
+
test_parse_dump(box)
|
| 907 |
+
test_orb_yaml(box)
|
| 908 |
+
test_ensure(box)
|
| 909 |
+
test_fays_single_hook(box)
|
| 910 |
+
finally:
|
| 911 |
+
box.close()
|
| 912 |
+
test_real_artifacts_replay()
|
| 913 |
+
test_device_panel_menu()
|
| 914 |
+
test_main_window_reopen_bookkeeping()
|
| 915 |
+
|
| 916 |
+
print()
|
| 917 |
+
if FAILS:
|
| 918 |
+
print(f"❌ {len(FAILS)} 项失败:")
|
| 919 |
+
for item in FAILS:
|
| 920 |
+
print(f" - {item}")
|
| 921 |
+
return 1
|
| 922 |
+
print("✅ 全部通过")
|
| 923 |
+
return 0
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
if __name__ == "__main__":
|
| 927 |
+
sys.exit(main())
|
collector/tools/tests/test_gripper_time_alignment.py
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""跨模态时间戳对齐回归:力/RGB 各自的采集时刻落盘 + 按时间取最近邻。
|
| 4 |
+
|
| 5 |
+
QT_QPA_PLATFORM=offscreen venv/bin/python \
|
| 6 |
+
tools/tests/test_gripper_time_alignment.py
|
| 7 |
+
|
| 8 |
+
背景:同一行里的 RGB 帧与力样本不是同时刻采集的——RGB 走外部队列取
|
| 9 |
+
**队头最旧帧**、力走 latest-wins 单槽取**当下最新**样本,所以「行号相同」
|
| 10 |
+
≠「时刻相同」,力恒领先 RGB 且领先量随录制时长增长。修法是让每一行自描述:
|
| 11 |
+
两条支路各自落盘采集时刻(宿主单调钟纳秒),下游按时间重采样。
|
| 12 |
+
|
| 13 |
+
覆盖:
|
| 14 |
+
1. hardware_ns 是 64 位(>2^31)——32 位截断是这条链路上的头号坑
|
| 15 |
+
2. 力/矩阵的 _ns 列落盘,值与写入时逐位相同(int64,不被截断)
|
| 16 |
+
3. 缺失 _ns 时不建列(稀疏契约;老调用方不传 capture_ns 仍可用)
|
| 17 |
+
4. features 里声明 encoding=host_monotonic_ns,下游知道怎么解读
|
| 18 |
+
5. Pipeline 两个 write_tactile_* 把 ns 放进对应快照键
|
| 19 |
+
6. nearest_index 边界:空/单点/精确命中/等距取左
|
| 20 |
+
7. 稳态漂移:力领先 3 帧且逐秒增长 → 范围内残差 ≤ 半个行周期
|
| 21 |
+
8. 段首陈旧帧:早于任何力样本的帧必须被判越界(下游据此丢弃)
|
| 22 |
+
9. 稀疏力样本:force_ns==0 的行不得参与配对(0 是"本行无样本"不是时刻)
|
| 23 |
+
10. 修复前的旧 episode 被明确拒绝,不拿行号硬凑
|
| 24 |
+
退出码 0 = 全部通过。
|
| 25 |
+
"""
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import glob
|
| 29 |
+
import json
|
| 30 |
+
import os
|
| 31 |
+
import shutil
|
| 32 |
+
import sys
|
| 33 |
+
|
| 34 |
+
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
| 35 |
+
|
| 36 |
+
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
|
| 37 |
+
os.path.abspath(__file__))))
|
| 38 |
+
sys.path.insert(0, REPO_ROOT)
|
| 39 |
+
|
| 40 |
+
import numpy as np # noqa: E402
|
| 41 |
+
|
| 42 |
+
from core.egodata_writer import EgoDataWriter # noqa: E402
|
| 43 |
+
from scripts.align_modalities import ( # noqa: E402
|
| 44 |
+
align_episode,
|
| 45 |
+
load_ns_columns,
|
| 46 |
+
nearest_index,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
OUT_ROOT = "/tmp/gripper_time_alignment_test"
|
| 50 |
+
NS_BASE = 287_000_000_000_000 # 开机纳秒量级:远超 2^31,验得出截断
|
| 51 |
+
_PERIOD = 1.0 / 30.0
|
| 52 |
+
_HALF = _PERIOD * 1e9 / 2 # 半个行周期 ≈ 16.67 ms ≈ 0.5 帧
|
| 53 |
+
|
| 54 |
+
_FAILS: list[str] = []
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def check(name: str, cond: bool, detail: str = ""):
|
| 58 |
+
tag = "PASS" if cond else "FAIL"
|
| 59 |
+
print(f" [{tag}] {name}" + (f" — {detail}" if detail else ""))
|
| 60 |
+
if not cond:
|
| 61 |
+
_FAILS.append(name)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _find_episode(root: str) -> str:
|
| 65 |
+
"""定位录制落盘的 data parquet(writer 会在 root 下建 session/ 层)。"""
|
| 66 |
+
found = glob.glob(os.path.join(root, "**", "data", "chunk-*",
|
| 67 |
+
"episode-*.parquet"), recursive=True)
|
| 68 |
+
return found[0] if found else ""
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _start(root: str, writer: EgoDataWriter) -> bool:
|
| 72 |
+
return writer.start_episode(
|
| 73 |
+
root, {"gripper_rgb": (960, 1280)}, 30.0, sensors=[],
|
| 74 |
+
device_ids=["gripper:1"],
|
| 75 |
+
devices=[{"key": "gripper:1", "kind": "gripper", "name": "夹爪",
|
| 76 |
+
"slots": ["gripper_rgb"]}],
|
| 77 |
+
calibrations={})
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# ── 1-4. 落盘链路 ────────────────────────────────────────────
|
| 81 |
+
|
| 82 |
+
def test_writer_columns():
|
| 83 |
+
shutil.rmtree(OUT_ROOT, ignore_errors=True)
|
| 84 |
+
os.makedirs(OUT_ROOT, exist_ok=True)
|
| 85 |
+
|
| 86 |
+
w = EgoDataWriter()
|
| 87 |
+
check("start_episode 成功", _start(OUT_ROOT, w),
|
| 88 |
+
f"episode_index={w.episode_index}")
|
| 89 |
+
|
| 90 |
+
# 三条支路各记各的时刻:RGB 落后力 3 帧(队列滞留),矩阵走独立泵线程
|
| 91 |
+
# 另有约 1ms 偏差——真实链路里它们本来就不等,落盘必须逐位保真。
|
| 92 |
+
rows = 6
|
| 93 |
+
rgb_ns, force_ns, matrix_ns = [], [], []
|
| 94 |
+
for i in range(rows):
|
| 95 |
+
f_ns = NS_BASE + i * 33_333_333
|
| 96 |
+
r_ns = f_ns - 3 * 33_333_333
|
| 97 |
+
m_ns = f_ns + 1_000_000
|
| 98 |
+
rgb_ns.append(r_ns)
|
| 99 |
+
force_ns.append(f_ns)
|
| 100 |
+
matrix_ns.append(m_ns)
|
| 101 |
+
w.write_frame_row(
|
| 102 |
+
i, i / 30.0,
|
| 103 |
+
hardware_ns=r_ns,
|
| 104 |
+
gripper={
|
| 105 |
+
"gripper_left_force": [1.0, 2.0, 3.0],
|
| 106 |
+
"gripper_left_force_ns": f_ns,
|
| 107 |
+
"gripper_left_force_matrix": [0] * (250 * 750),
|
| 108 |
+
"gripper_left_force_matrix_ns": m_ns,
|
| 109 |
+
})
|
| 110 |
+
w.end_episode()
|
| 111 |
+
task_dir = w.task_dir
|
| 112 |
+
|
| 113 |
+
import pyarrow
|
| 114 |
+
import pyarrow.parquet as pq
|
| 115 |
+
path = _find_episode(OUT_ROOT)
|
| 116 |
+
check("data parquet 落盘", bool(path), path)
|
| 117 |
+
if not path:
|
| 118 |
+
return None
|
| 119 |
+
t = pq.read_table(path)
|
| 120 |
+
|
| 121 |
+
# hardware_ns 必须是 64 位。修复前它是 pyqtSignal(int) 截断后的 int32,
|
| 122 |
+
# 值域压在 ±2^31 内——这条断言就是那个 bug 的检测器(低于 2^31 的值
|
| 123 |
+
# 截断与否看不出来,所以基时刻特意选在开机纳秒量级)。
|
| 124 |
+
hw = np.asarray(t.column("hardware_ns").to_pylist(), dtype=np.int64)
|
| 125 |
+
check("hardware_ns 未被 int32 截断(>2^31)",
|
| 126 |
+
bool(np.all(hw > (1 << 31))), f"首值={hw[0]}")
|
| 127 |
+
|
| 128 |
+
for col, want in (("observation.gripper_left_force_ns", force_ns),
|
| 129 |
+
("observation.gripper_left_force_matrix_ns", matrix_ns)):
|
| 130 |
+
check(f"{col} 列存在", col in t.schema.names)
|
| 131 |
+
if col not in t.schema.names:
|
| 132 |
+
continue
|
| 133 |
+
got = np.asarray(t.column(col).to_pylist(), dtype=np.int64)
|
| 134 |
+
check(f"{col} 值逐位相同且为 int64",
|
| 135 |
+
bool(np.array_equal(got, np.asarray(want, dtype=np.int64)))
|
| 136 |
+
and t.schema.field(col).type.equals(pyarrow.int64()),
|
| 137 |
+
f"{got[:3].tolist()}")
|
| 138 |
+
|
| 139 |
+
with open(os.path.join(task_dir, "meta", "info.json"),
|
| 140 |
+
"r", encoding="utf-8") as f:
|
| 141 |
+
info = json.load(f)
|
| 142 |
+
feat = info.get("features", {})
|
| 143 |
+
for col in ("observation.gripper_left_force_ns",
|
| 144 |
+
"observation.gripper_left_force_matrix_ns"):
|
| 145 |
+
spec = feat.get(col) or {}
|
| 146 |
+
check(f"features 声明 {col}",
|
| 147 |
+
spec.get("dtype") == "int64"
|
| 148 |
+
and spec.get("shape") == [1]
|
| 149 |
+
and spec.get("encoding") == "host_monotonic_ns",
|
| 150 |
+
repr(spec))
|
| 151 |
+
|
| 152 |
+
return path
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def test_sparse_contract():
|
| 156 |
+
"""不传 capture_ns 时不建列——老调用方与稀疏契约都不能破。"""
|
| 157 |
+
root = OUT_ROOT + "_sparse"
|
| 158 |
+
shutil.rmtree(root, ignore_errors=True)
|
| 159 |
+
os.makedirs(root, exist_ok=True)
|
| 160 |
+
|
| 161 |
+
w = EgoDataWriter()
|
| 162 |
+
w.start_episode(root, {"gripper_rgb": (960, 1280)}, 30.0, sensors=[],
|
| 163 |
+
device_ids=[], devices=[], calibrations={})
|
| 164 |
+
for i in range(3):
|
| 165 |
+
w.write_frame_row(i, i / 30.0, hardware_ns=NS_BASE + i * 33_333_333,
|
| 166 |
+
gripper={"gripper_left_force": [1.0, 2.0, 3.0]})
|
| 167 |
+
w.end_episode()
|
| 168 |
+
|
| 169 |
+
import pyarrow.parquet as pq
|
| 170 |
+
path = _find_episode(root)
|
| 171 |
+
check("data parquet 落盘", bool(path), path)
|
| 172 |
+
if not path:
|
| 173 |
+
return
|
| 174 |
+
# 只看 observation.gripper 段:顶层 hardware_ns 本身就以 _ns 结尾,
|
| 175 |
+
# 不能拿它当"建了 _ns 列"的证据
|
| 176 |
+
names = [n for n in pq.read_schema(path).names
|
| 177 |
+
if n.startswith("observation.gripper")]
|
| 178 |
+
check("用力列仍在", "observation.gripper_left_force" in names, str(names))
|
| 179 |
+
check("无 capture_ns 时不建 _ns 列",
|
| 180 |
+
not any(n.endswith("_ns") for n in names), str(sorted(names)))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def test_pipeline_snapshot_keys():
|
| 184 |
+
"""Pipeline 的两个 write_tactile_* 要把 ns 放进对应的快照键。"""
|
| 185 |
+
from core.pipeline import CameraPipeline
|
| 186 |
+
|
| 187 |
+
pip = CameraPipeline(OUT_ROOT + "_pip")
|
| 188 |
+
pip._writer = object() # 只为过 _put_gripper_snapshot 的非空判断
|
| 189 |
+
pip._recording = True
|
| 190 |
+
|
| 191 |
+
pip.write_tactile_force("left", [1.0, 2.0, 3.0], capture_ns=NS_BASE + 7)
|
| 192 |
+
pip.write_tactile_force_matrix("left", [0, 1], capture_ns=NS_BASE + 9)
|
| 193 |
+
pip.write_tactile_force("right", [4.0, 5.0, 6.0]) # 不传 ns
|
| 194 |
+
snap = pip._pop_gripper_snapshots()
|
| 195 |
+
|
| 196 |
+
check("force_ns 键与值正确",
|
| 197 |
+
snap.get("gripper_left_force_ns") == NS_BASE + 7,
|
| 198 |
+
repr(snap.get("gripper_left_force_ns")))
|
| 199 |
+
check("force_matrix_ns 键与值正确",
|
| 200 |
+
snap.get("gripper_left_force_matrix_ns") == NS_BASE + 9,
|
| 201 |
+
repr(snap.get("gripper_left_force_matrix_ns")))
|
| 202 |
+
check("不传 capture_ns 时不写该键(老调用方兼容)",
|
| 203 |
+
"gripper_right_force_ns" not in snap,
|
| 204 |
+
str(sorted(snap)))
|
| 205 |
+
|
| 206 |
+
pip._writer = None
|
| 207 |
+
pip._recording = False
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
# ── 6-9. 对齐数学 ────────────────────────────────────────────
|
| 211 |
+
|
| 212 |
+
def test_nearest_index_edges():
|
| 213 |
+
check("空 src 报错", _raises(ValueError, lambda: nearest_index([], [1])),
|
| 214 |
+
"nearest_index([], [1])")
|
| 215 |
+
check("单点 src → 全 0",
|
| 216 |
+
nearest_index([5], [0, 4, 9]).tolist() == [0, 0, 0])
|
| 217 |
+
check("精确命中取自身",
|
| 218 |
+
nearest_index([10, 20, 30], [20]).tolist() == [1])
|
| 219 |
+
# 15 与 10/20 等距 → 取左(更早的样本,对因果友好)
|
| 220 |
+
check("等距取左", nearest_index([10, 20], [15]).tolist() == [0])
|
| 221 |
+
check("超出右端夹到末点",
|
| 222 |
+
nearest_index([10, 20], [99]).tolist() == [1])
|
| 223 |
+
check("超出左端夹到首点",
|
| 224 |
+
nearest_index([10, 20], [-99]).tolist() == [0])
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def _raises(exc, fn):
|
| 228 |
+
try:
|
| 229 |
+
fn()
|
| 230 |
+
except exc:
|
| 231 |
+
return True
|
| 232 |
+
except Exception:
|
| 233 |
+
return False
|
| 234 |
+
return False
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def _scenario(rows, lag_frames_at):
|
| 238 |
+
"""合成一段:力在写行时刻采集,RGB 是 lag 帧前的画面。
|
| 239 |
+
|
| 240 |
+
lag_frames_at(k) 给出第 k 行的滞后帧数。真实链路里它随录制时长增长
|
| 241 |
+
(RGB 源实测 30.84 fps vs 写线程 30 fps,队列每秒多积 ~0.84 帧,行内
|
| 242 |
+
看就是滞后每秒多 ~1 帧),段首还可能叠一次启动窗口的陈旧帧积压。
|
| 243 |
+
"""
|
| 244 |
+
force_ns, rgb_ns = [], []
|
| 245 |
+
for k in range(rows):
|
| 246 |
+
f = NS_BASE + int(k * _PERIOD * 1e9)
|
| 247 |
+
force_ns.append(f)
|
| 248 |
+
rgb_ns.append(f - int(lag_frames_at(k) * _PERIOD * 1e9))
|
| 249 |
+
return (np.asarray(rgb_ns, dtype=np.int64),
|
| 250 |
+
np.asarray(force_ns, dtype=np.int64))
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def _align(rgb_ns, force_ns):
|
| 254 |
+
"""返回 (配到的力行号, 残差, "在力样本时间范围内"掩码)。
|
| 255 |
+
|
| 256 |
+
落在范围外的帧(段首早于第一个力样本的陈旧帧、段尾晚于最后一个样本的
|
| 257 |
+
帧)只能夹到端点,残差天然是"离端点多远",不受半个行周期约束——必须
|
| 258 |
+
分开统计,否则一个段首陈旧帧就能把整段残差的最大值带偏。
|
| 259 |
+
"""
|
| 260 |
+
picked = nearest_index(force_ns, rgb_ns)
|
| 261 |
+
residual = np.abs(rgb_ns - force_ns[picked])
|
| 262 |
+
inside = (rgb_ns >= force_ns[0]) & (rgb_ns <= force_ns[-1])
|
| 263 |
+
return picked, residual, inside
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def test_alignment_steady_state():
|
| 267 |
+
"""力领先 3 帧起、每 30 行多滞后 1 帧(≈1 帧/秒)→ 残差 ≤ 半周期。"""
|
| 268 |
+
rows = 300
|
| 269 |
+
rgb_ns, force_ns = _scenario(rows, lambda k: 3.0 + k / 30.0)
|
| 270 |
+
picked, residual, inside = _align(rgb_ns, force_ns)
|
| 271 |
+
|
| 272 |
+
check("范围内的帧占绝大多数", int(inside.sum()) >= rows - 10,
|
| 273 |
+
f"{int(inside.sum())}/{rows}")
|
| 274 |
+
check("范围内残差 ≤ 半个行周期(≈0.5 帧)",
|
| 275 |
+
bool(residual[inside].max() <= _HALF + 1),
|
| 276 |
+
f"中位 {np.median(residual[inside]) / 1e6:.2f} ms / 最大 "
|
| 277 |
+
f"{residual[inside].max() / 1e6:.2f} ms(上界 {_HALF / 1e6:.2f} ms)")
|
| 278 |
+
|
| 279 |
+
shift = picked - np.arange(rows)
|
| 280 |
+
check("行号偏移确实在增长(说明按行号配对是错的)",
|
| 281 |
+
shift[-1] < shift[0] - 5,
|
| 282 |
+
f"首行 {shift[0]:+d} → 末行 {shift[-1]:+d}")
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def test_alignment_start_stale_frames():
|
| 286 |
+
"""段首陈旧帧:启动窗口积压的旧帧早于任何力样本,必须被判越界。
|
| 287 |
+
|
| 288 |
+
这些帧录的是开机之前(上一段残留)的画面,力侧根本不存在对应时刻的
|
| 289 |
+
样本——夹到第 0 行是唯一可行的动作,但下游必须知道那是编排不是对齐。
|
| 290 |
+
"""
|
| 291 |
+
rows = 300
|
| 292 |
+
stale = 5
|
| 293 |
+
rgb_ns, force_ns = _scenario(
|
| 294 |
+
rows, lambda k: 60.0 if k < stale else 3.0)
|
| 295 |
+
picked, residual, inside = _align(rgb_ns, force_ns)
|
| 296 |
+
outside = np.flatnonzero(~inside)
|
| 297 |
+
|
| 298 |
+
check("越界帧数正好等于陈旧帧数", outside.size == stale,
|
| 299 |
+
f"越界行号 {outside.tolist()}")
|
| 300 |
+
check("越界帧全部夹在第 0 行(不越界则真去配了别的行)",
|
| 301 |
+
bool(np.all(picked[outside] == 0)) if outside.size else False,
|
| 302 |
+
f"配到 {picked[outside].tolist() if outside.size else []}")
|
| 303 |
+
check("排空后残差回到 ≤ 半个行周期",
|
| 304 |
+
bool(residual[inside].max() <= _HALF + 1),
|
| 305 |
+
f"范围内 {int(inside.sum())}/{rows} 帧,最大 "
|
| 306 |
+
f"{residual[inside].max() / 1e6:.2f} ms")
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def test_alignment_sparse_force_samples():
|
| 310 |
+
"""力样本稀疏时(多数行 force_ns==0)0 值行不得参与配对。
|
| 311 |
+
|
| 312 |
+
0 的含义是"本行窗口内没有新力样本",不是"时刻为 0"。拿它当时间戳会
|
| 313 |
+
把一大批视频帧吸到第 0 行上去——这是本工具最容易被误用的地方。
|
| 314 |
+
"""
|
| 315 |
+
rows, stride = 60, 3
|
| 316 |
+
rgb_ns, force_ns = _scenario(rows, lambda k: 3.0 + k / 60.0)
|
| 317 |
+
sparse = np.where(np.arange(rows) % stride == 0, force_ns, 0)
|
| 318 |
+
|
| 319 |
+
valid = np.flatnonzero(sparse > 0)
|
| 320 |
+
picked = valid[nearest_index(sparse[valid], rgb_ns)]
|
| 321 |
+
residual = np.abs(rgb_ns - force_ns[picked])
|
| 322 |
+
inside = (rgb_ns >= force_ns[0]) & (rgb_ns <= force_ns[-1])
|
| 323 |
+
# 上界随**样本间隔**走,不是行周期:样本每 3 行才有一个 → 50 ms
|
| 324 |
+
half_sample = stride * _PERIOD * 1e9 / 2
|
| 325 |
+
|
| 326 |
+
check("配到的行全部是真实样本行",
|
| 327 |
+
bool(np.all(sparse[picked] > 0)),
|
| 328 |
+
f"行号 {picked[:6].tolist()}…")
|
| 329 |
+
check("稀疏下残差 ≤ 半个样本间隔(间隔 ×3 → 上界也 ×3)",
|
| 330 |
+
bool(residual[inside].max() <= half_sample + 1),
|
| 331 |
+
f"范围内最大 {residual[inside].max() / 1e6:.2f} ms"
|
| 332 |
+
f"(上界 {half_sample / 1e6:.2f} ms);越界 "
|
| 333 |
+
f"{int((~inside).sum())} 帧全在段首")
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
# ── 10. 旧数据必须被明确拒绝 ─────────────────────────────────
|
| 337 |
+
|
| 338 |
+
def test_rejects_pre_fix_episode():
|
| 339 |
+
legacy = os.path.join(
|
| 340 |
+
REPO_ROOT, "data", "recordings", "UMIGripper_Action_AI",
|
| 341 |
+
"data", "chunk-000", "episode-076.parquet")
|
| 342 |
+
if not os.path.isfile(legacy):
|
| 343 |
+
print(" [SKIP] 旧 episode 不在本机,跳过")
|
| 344 |
+
return
|
| 345 |
+
rgb_ns, force_ns, diag = load_ns_columns(legacy)
|
| 346 |
+
check("修复前的 episode 被判为不可对齐", rgb_ns is None,
|
| 347 |
+
diag.get("reason", ""))
|
| 348 |
+
check("拒绝理由点明是录于修复之前(或 32 位截断)",
|
| 349 |
+
"v1.3.3 之前" in (diag.get("reason") or "")
|
| 350 |
+
or "截断" in (diag.get("reason") or ""),
|
| 351 |
+
diag.get("reason", ""))
|
| 352 |
+
check("align_episode 同样拒绝而不是硬凑",
|
| 353 |
+
_raises(ValueError, lambda: align_episode(legacy)),
|
| 354 |
+
"align_episode(legacy)")
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
# ── 11. 真落盘的 episode 走一遍 align_episode(端到端) ──────
|
| 358 |
+
|
| 359 |
+
def test_align_episode_end_to_end():
|
| 360 |
+
"""自建一段「力稀疏 + RGB 滞后」的 episode,整个 align_episode 跑通。"""
|
| 361 |
+
root = OUT_ROOT + "_e2e"
|
| 362 |
+
shutil.rmtree(root, ignore_errors=True)
|
| 363 |
+
os.makedirs(root, exist_ok=True)
|
| 364 |
+
|
| 365 |
+
rows, stride = 90, 3
|
| 366 |
+
rgb_all = []
|
| 367 |
+
w = EgoDataWriter()
|
| 368 |
+
w.start_episode(root, {"gripper_rgb": (960, 1280)}, 30.0, sensors=[],
|
| 369 |
+
device_ids=[], devices=[], calibrations={})
|
| 370 |
+
for k in range(rows):
|
| 371 |
+
lag = 3.0 + k / 30.0
|
| 372 |
+
rgb = NS_BASE + int(k * _PERIOD * 1e9) - int(lag * _PERIOD * 1e9)
|
| 373 |
+
rgb_all.append(rgb)
|
| 374 |
+
gripper = {}
|
| 375 |
+
if k % stride == 0: # 每 3 行才有一次力样本
|
| 376 |
+
gripper = {
|
| 377 |
+
"gripper_left_force": [1.0, 2.0, 3.0],
|
| 378 |
+
"gripper_left_force_ns": NS_BASE + int(k * _PERIOD * 1e9),
|
| 379 |
+
"gripper_left_force_matrix": [0] * (250 * 750),
|
| 380 |
+
"gripper_left_force_matrix_ns":
|
| 381 |
+
NS_BASE + int(k * _PERIOD * 1e9) + 1_000_000,
|
| 382 |
+
}
|
| 383 |
+
w.write_frame_row(k, k / 30.0, hardware_ns=rgb, gripper=gripper)
|
| 384 |
+
w.end_episode()
|
| 385 |
+
|
| 386 |
+
path = _find_episode(root)
|
| 387 |
+
check("e2e parquet 落盘", bool(path), path)
|
| 388 |
+
if not path:
|
| 389 |
+
return
|
| 390 |
+
|
| 391 |
+
mapping, residual = align_episode(path, side="left", which="matrix")
|
| 392 |
+
check("align_episode 返回的行号全是真实样本行",
|
| 393 |
+
bool(np.all(mapping % stride == 0)),
|
| 394 |
+
f"{mapping[:8].tolist()}…")
|
| 395 |
+
|
| 396 |
+
# "越界"按**时间范围**判定,与脚本 `_fmt_stats` 报给下游的口径一致:
|
| 397 |
+
# 帧早于第一个力样本(或晚于最后一个)就是没有对应样本,只能夹端点。
|
| 398 |
+
# 这和"残差超过半个样本间隔"不是一回事——后者里还有只是离得远的帧。
|
| 399 |
+
valid_ns = np.array([NS_BASE + int(k * _PERIOD * 1e9)
|
| 400 |
+
for k in range(0, rows, stride)], dtype=np.int64)
|
| 401 |
+
rgb_ns = np.asarray(rgb_all, dtype=np.int64)
|
| 402 |
+
outside = (rgb_ns < valid_ns[0]) | (rgb_ns > valid_ns[-1])
|
| 403 |
+
|
| 404 |
+
check("越界帧只在段首(早于第一个力样本,只能夹到它)",
|
| 405 |
+
bool(np.all(np.flatnonzero(outside) < 5))
|
| 406 |
+
and bool(np.all(mapping[outside] == 0)),
|
| 407 |
+
f"越界 {int(outside.sum())} 帧:行号 "
|
| 408 |
+
f"{np.flatnonzero(outside).tolist()} → 配到行 "
|
| 409 |
+
f"{mapping[outside].tolist()}")
|
| 410 |
+
check("范围内残差 ≤ 半个样本间隔(每 3 行一个样本 → 50 ms)",
|
| 411 |
+
bool(np.all(residual[~outside] <= stride * _PERIOD * 1e9 / 2 + 1)),
|
| 412 |
+
f"范围内 {int((~outside).sum())}/{rows} 帧,最大 "
|
| 413 |
+
f"{residual[~outside].max() / 1e6:.2f} ms")
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def main() -> int:
|
| 417 |
+
print("[1-4] 落盘链路:力/矩阵采集时刻列")
|
| 418 |
+
test_writer_columns()
|
| 419 |
+
print("[3b] 稀疏契约:不传 capture_ns 不建列")
|
| 420 |
+
test_sparse_contract()
|
| 421 |
+
print("[5] Pipeline 快照键")
|
| 422 |
+
test_pipeline_snapshot_keys()
|
| 423 |
+
print("[6] nearest_index 边界")
|
| 424 |
+
test_nearest_index_edges()
|
| 425 |
+
print("[7] 稳态漂移对齐")
|
| 426 |
+
test_alignment_steady_state()
|
| 427 |
+
print("[8] 段首陈旧帧越界")
|
| 428 |
+
test_alignment_start_stale_frames()
|
| 429 |
+
print("[9] 稀疏力样本")
|
| 430 |
+
test_alignment_sparse_force_samples()
|
| 431 |
+
print("[10] 旧数据拒绝")
|
| 432 |
+
test_rejects_pre_fix_episode()
|
| 433 |
+
print("[11] align_episode 端到端")
|
| 434 |
+
test_align_episode_end_to_end()
|
| 435 |
+
|
| 436 |
+
print()
|
| 437 |
+
if _FAILS:
|
| 438 |
+
print(f"FAILED: {len(_FAILS)} 项 — {_FAILS}")
|
| 439 |
+
return 1
|
| 440 |
+
print("ALL PASS")
|
| 441 |
+
return 0
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
if __name__ == "__main__":
|
| 445 |
+
sys.exit(main())
|
collector/ui/device_panel.py
CHANGED
|
@@ -15,7 +15,7 @@ from PyQt5.QtCore import Qt, pyqtSignal
|
|
| 15 |
from PyQt5.QtGui import QColor
|
| 16 |
from PyQt5.QtWidgets import (
|
| 17 |
QWidget, QVBoxLayout, QLabel, QTreeWidget, QTreeWidgetItem,
|
| 18 |
-
QInputDialog, QAbstractItemView,
|
| 19 |
)
|
| 20 |
|
| 21 |
from config import settings
|
|
@@ -36,6 +36,8 @@ class DevicePanel(QWidget):
|
|
| 36 |
|
| 37 |
device_toggled = pyqtSignal(object, bool) # (DeviceInfo, checked)
|
| 38 |
device_renamed = pyqtSignal(object, str) # (DeviceInfo, new_name)
|
|
|
|
|
|
|
| 39 |
|
| 40 |
def __init__(self, parent=None):
|
| 41 |
super().__init__(parent)
|
|
@@ -59,6 +61,8 @@ class DevicePanel(QWidget):
|
|
| 59 |
lambda item: self._record_expansion(item, True))
|
| 60 |
self._tree.itemCollapsed.connect(
|
| 61 |
lambda item: self._record_expansion(item, False))
|
|
|
|
|
|
|
| 62 |
layout.addWidget(self._tree, 1)
|
| 63 |
|
| 64 |
self._refresh_hint = QLabel(tr("双击设备可重命名"))
|
|
@@ -72,6 +76,8 @@ class DevicePanel(QWidget):
|
|
| 72 |
"gripper": True,
|
| 73 |
"other_ble": False} # 组展开状态(重建保留)
|
| 74 |
self._locked = False # 录制中锁死开关
|
|
|
|
|
|
|
| 75 |
|
| 76 |
# ── 对外接口 ─────────────────────────────────────
|
| 77 |
|
|
@@ -87,11 +93,15 @@ class DevicePanel(QWidget):
|
|
| 87 |
placeholder.setFlags(Qt.NoItemFlags)
|
| 88 |
self._tree.addTopLevelItem(placeholder)
|
| 89 |
self._tree.blockSignals(False)
|
|
|
|
|
|
|
| 90 |
return
|
| 91 |
|
| 92 |
by_group: dict = {}
|
| 93 |
for dev in devices:
|
| 94 |
by_group.setdefault(dev.group, []).append(dev)
|
|
|
|
|
|
|
| 95 |
|
| 96 |
for group in _GROUP_ORDER:
|
| 97 |
devs = by_group.get(group, [])
|
|
@@ -192,7 +202,7 @@ class DevicePanel(QWidget):
|
|
| 192 |
def refresh_texts(self):
|
| 193 |
"""语言切换刷新提示文字、组标题与占位项。"""
|
| 194 |
self._hint.setText(tr("开关设备以显示画面"))
|
| 195 |
-
self.
|
| 196 |
self._tree.blockSignals(True)
|
| 197 |
for i in range(self._tree.topLevelItemCount()):
|
| 198 |
item = self._tree.topLevelItem(i)
|
|
@@ -205,6 +215,31 @@ class DevicePanel(QWidget):
|
|
| 205 |
|
| 206 |
# ── 内部 ─────────────────────────────────────────
|
| 207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
def _row_text(self, dev) -> str:
|
| 209 |
icon = _ICON.get(dev.kind, "📹")
|
| 210 |
text = f"{icon} {dev.label}"
|
|
|
|
| 15 |
from PyQt5.QtGui import QColor
|
| 16 |
from PyQt5.QtWidgets import (
|
| 17 |
QWidget, QVBoxLayout, QLabel, QTreeWidget, QTreeWidgetItem,
|
| 18 |
+
QInputDialog, QAbstractItemView, QMenu,
|
| 19 |
)
|
| 20 |
|
| 21 |
from config import settings
|
|
|
|
| 36 |
|
| 37 |
device_toggled = pyqtSignal(object, bool) # (DeviceInfo, checked)
|
| 38 |
device_renamed = pyqtSignal(object, str) # (DeviceInfo, new_name)
|
| 39 |
+
# 右键菜单:重新读取这只夹爪的厂商出厂标定(DeviceInfo)
|
| 40 |
+
gripper_recalibration_requested = pyqtSignal(object)
|
| 41 |
|
| 42 |
def __init__(self, parent=None):
|
| 43 |
super().__init__(parent)
|
|
|
|
| 61 |
lambda item: self._record_expansion(item, True))
|
| 62 |
self._tree.itemCollapsed.connect(
|
| 63 |
lambda item: self._record_expansion(item, False))
|
| 64 |
+
self._tree.setContextMenuPolicy(Qt.CustomContextMenu)
|
| 65 |
+
self._tree.customContextMenuRequested.connect(self._on_context_menu)
|
| 66 |
layout.addWidget(self._tree, 1)
|
| 67 |
|
| 68 |
self._refresh_hint = QLabel(tr("双击设备可重命名"))
|
|
|
|
| 76 |
"gripper": True,
|
| 77 |
"other_ble": False} # 组展开状态(重建保留)
|
| 78 |
self._locked = False # 录制中锁死开关
|
| 79 |
+
self._has_gripper = False # 有夹爪时才提示右键菜单
|
| 80 |
+
self._refresh_hint_text()
|
| 81 |
|
| 82 |
# ── 对外接口 ─────────────────────────────────────
|
| 83 |
|
|
|
|
| 93 |
placeholder.setFlags(Qt.NoItemFlags)
|
| 94 |
self._tree.addTopLevelItem(placeholder)
|
| 95 |
self._tree.blockSignals(False)
|
| 96 |
+
self._has_gripper = False
|
| 97 |
+
self._refresh_hint_text()
|
| 98 |
return
|
| 99 |
|
| 100 |
by_group: dict = {}
|
| 101 |
for dev in devices:
|
| 102 |
by_group.setdefault(dev.group, []).append(dev)
|
| 103 |
+
self._has_gripper = bool(by_group.get("gripper"))
|
| 104 |
+
self._refresh_hint_text()
|
| 105 |
|
| 106 |
for group in _GROUP_ORDER:
|
| 107 |
devs = by_group.get(group, [])
|
|
|
|
| 202 |
def refresh_texts(self):
|
| 203 |
"""语言切换刷新提示文字、组标题与占位项。"""
|
| 204 |
self._hint.setText(tr("开关设备以显示画面"))
|
| 205 |
+
self._refresh_hint_text()
|
| 206 |
self._tree.blockSignals(True)
|
| 207 |
for i in range(self._tree.topLevelItemCount()):
|
| 208 |
item = self._tree.topLevelItem(i)
|
|
|
|
| 215 |
|
| 216 |
# ── 内部 ─────────────────────────────────────────
|
| 217 |
|
| 218 |
+
def _refresh_hint_text(self):
|
| 219 |
+
"""底部提示:夹爪在场时才提右键菜单(别的设备没有这个菜单)。"""
|
| 220 |
+
text = tr("双击设备可重命名")
|
| 221 |
+
if self._has_gripper:
|
| 222 |
+
text += tr(";右键夹爪可重读取出厂标定")
|
| 223 |
+
self._refresh_hint.setText(text)
|
| 224 |
+
|
| 225 |
+
def _on_context_menu(self, pos):
|
| 226 |
+
"""夹爪条目右键 → 「重新读取出厂标定」。"""
|
| 227 |
+
item = self._tree.itemAt(pos)
|
| 228 |
+
if item is None:
|
| 229 |
+
return
|
| 230 |
+
dev = item.data(0, Qt.UserRole)
|
| 231 |
+
if dev is None or isinstance(dev, tuple):
|
| 232 |
+
return # 组标题 / 占位项
|
| 233 |
+
if dev.group != "gripper":
|
| 234 |
+
return
|
| 235 |
+
# 标定要独占设备,录制中不给入口(与 set_locked 的灰显口径一致)
|
| 236 |
+
menu = QMenu(self)
|
| 237 |
+
action = menu.addAction(tr("重新读取出厂标定"))
|
| 238 |
+
action.setEnabled(not self._locked)
|
| 239 |
+
chosen = menu.exec_(self._tree.viewport().mapToGlobal(pos))
|
| 240 |
+
if chosen is action and not self._locked:
|
| 241 |
+
self.gripper_recalibration_requested.emit(dev)
|
| 242 |
+
|
| 243 |
def _row_text(self, dev) -> str:
|
| 244 |
icon = _ICON.get(dev.kind, "📹")
|
| 245 |
text = f"{icon} {dev.label}"
|
collector/ui/main_window.py
CHANGED
|
@@ -198,6 +198,9 @@ class MainWindow(QMainWindow):
|
|
| 198 |
# 上传后自动删除结果信号(删除线程 → 主线程):
|
| 199 |
# (session_path, error_msg, episode_index)——episode_index 用 int 且恒 < 2^31
|
| 200 |
_upload_session_deleted = pyqtSignal(str, str, int)
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
def __init__(self):
|
| 203 |
super().__init__()
|
|
@@ -221,6 +224,8 @@ class MainWindow(QMainWindow):
|
|
| 221 |
# 引用同一 dict,离线测试注入假条目沿用同一形状)
|
| 222 |
self._device_manager = DeviceManager()
|
| 223 |
self._workers = self._device_manager.entries
|
|
|
|
|
|
|
| 224 |
# ── 面板开关分派表(kind → 具体开启/关闭动作;路由口径在
|
| 225 |
# core.device_manager.dispatch_toggle)──
|
| 226 |
self._open_fns = {"uvc": self._open_uvc, "d435": self._open_d435,
|
|
@@ -407,6 +412,10 @@ class MainWindow(QMainWindow):
|
|
| 407 |
self._device_panel = DevicePanel()
|
| 408 |
self._device_panel.device_toggled.connect(self._on_device_toggled)
|
| 409 |
self._device_panel.device_renamed.connect(self._on_device_renamed)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
self._device_dock = QDockWidget(tr("📷 设备检测"), self)
|
| 411 |
self._device_dock.setWidget(self._device_panel)
|
| 412 |
self._device_dock.setFeatures(
|
|
@@ -838,6 +847,7 @@ class MainWindow(QMainWindow):
|
|
| 838 |
# 清设备面板激活状态(防止下次进入采集页误高亮)
|
| 839 |
self._active_device_keys = set()
|
| 840 |
self._lost_device_keys = set()
|
|
|
|
| 841 |
self._last_device_keys = {}
|
| 842 |
self._last_device_kinds = {}
|
| 843 |
self._device_panel.set_checked_keys(set())
|
|
@@ -1647,8 +1657,9 @@ class MainWindow(QMainWindow):
|
|
| 1647 |
lambda slot, frame, hw_ns, key=key:
|
| 1648 |
self._on_gripper_stereo(key, slot, frame, hw_ns))
|
| 1649 |
bridge.tactile_ready.connect(
|
| 1650 |
-
lambda side, heatmap, force, matrix, key=key:
|
| 1651 |
-
self._on_gripper_tactile(key, side, heatmap, force, matrix
|
|
|
|
| 1652 |
bridge.pose_ready.connect(
|
| 1653 |
lambda position, quat, trajectory=(), timestamp=None, key=key:
|
| 1654 |
self._on_gripper_pose(key, position, quat, trajectory,
|
|
@@ -1816,9 +1827,10 @@ class MainWindow(QMainWindow):
|
|
| 1816 |
prefix=entry["snapshot_prefix"], timestamp=timestamp)
|
| 1817 |
|
| 1818 |
def _on_gripper_tactile(self, dev_key: str, side, heatmap, force,
|
| 1819 |
-
force_matrix):
|
| 1820 |
"""触觉结果(左/右):热力图 + 力曲线显示 + 力值落盘;
|
| 1821 |
-
力矩阵落盘 P4 泵线程。
|
|
|
|
| 1822 |
entry = self._gripper_entry(dev_key)
|
| 1823 |
if entry is None:
|
| 1824 |
return
|
|
@@ -1833,7 +1845,8 @@ class MainWindow(QMainWindow):
|
|
| 1833 |
widget.update_tactile(display_heatmap, force)
|
| 1834 |
if force is not None and len(force) == 3:
|
| 1835 |
self._pipeline.write_tactile_force(
|
| 1836 |
-
side, force, prefix=entry["snapshot_prefix"]
|
|
|
|
| 1837 |
|
| 1838 |
def _on_gripper_state(self, dev_key: str, payload):
|
| 1839 |
"""串口夹爪状态 {pct,gripped,fz,event,board}:PoseView 开合板 +
|
|
@@ -1911,9 +1924,12 @@ class MainWindow(QMainWindow):
|
|
| 1911 |
if seq == last_seq[side]:
|
| 1912 |
continue
|
| 1913 |
last_seq[side] = seq
|
| 1914 |
-
|
| 1915 |
-
|
|
|
|
|
|
|
| 1916 |
continue
|
|
|
|
| 1917 |
try:
|
| 1918 |
encoded = encode_gripper_force_matrix(matrix, spec)
|
| 1919 |
except Exception as exc:
|
|
@@ -1921,7 +1937,8 @@ class MainWindow(QMainWindow):
|
|
| 1921 |
side, exc))
|
| 1922 |
continue
|
| 1923 |
self._pipeline.write_tactile_force_matrix(
|
| 1924 |
-
side, encoded, prefix=entry["snapshot_prefix"]
|
|
|
|
| 1925 |
wrote[side] += 1
|
| 1926 |
if not first_logged[side]:
|
| 1927 |
first_logged[side] = True
|
|
@@ -1961,6 +1978,84 @@ class MainWindow(QMainWindow):
|
|
| 1961 |
self._device_panel.set_active_keys(self._active_device_keys)
|
| 1962 |
self._update_status()
|
| 1963 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1964 |
def _on_device_toggled(self, dev, on: bool):
|
| 1965 |
"""面板开关 → 打开/关闭设备(多路并发:只动自己,不互拆)。
|
| 1966 |
|
|
|
|
| 198 |
# 上传后自动删除结果信号(删除线程 → 主线程):
|
| 199 |
# (session_path, error_msg, episode_index)——episode_index 用 int 且恒 < 2^31
|
| 200 |
_upload_session_deleted = pyqtSignal(str, str, int)
|
| 201 |
+
# 重读夹爪出厂标定完成(标定线程 → 主线程):(dev_key, label, 错误文案)
|
| 202 |
+
# 错误文案空串 = 成功。用 str 而非 Exception:跨线程只传可显示文本。
|
| 203 |
+
_gripper_recalibration_done = pyqtSignal(str, str, str)
|
| 204 |
|
| 205 |
def __init__(self):
|
| 206 |
super().__init__()
|
|
|
|
| 224 |
# 引用同一 dict,离线测试注入假条目沿用同一形状)
|
| 225 |
self._device_manager = DeviceManager()
|
| 226 |
self._workers = self._device_manager.entries
|
| 227 |
+
# 重读标定前这台夹爪是否开着(标定独占设备,完了要开回原来的状态)
|
| 228 |
+
self._gripper_recalib_reopen = set()
|
| 229 |
# ── 面板开关分派表(kind → 具体开启/关闭动作;路由口径在
|
| 230 |
# core.device_manager.dispatch_toggle)──
|
| 231 |
self._open_fns = {"uvc": self._open_uvc, "d435": self._open_d435,
|
|
|
|
| 412 |
self._device_panel = DevicePanel()
|
| 413 |
self._device_panel.device_toggled.connect(self._on_device_toggled)
|
| 414 |
self._device_panel.device_renamed.connect(self._on_device_renamed)
|
| 415 |
+
self._device_panel.gripper_recalibration_requested.connect(
|
| 416 |
+
self._on_gripper_recalibration)
|
| 417 |
+
self._gripper_recalibration_done.connect(
|
| 418 |
+
self._on_gripper_recalibration_done)
|
| 419 |
self._device_dock = QDockWidget(tr("📷 设备检测"), self)
|
| 420 |
self._device_dock.setWidget(self._device_panel)
|
| 421 |
self._device_dock.setFeatures(
|
|
|
|
| 847 |
# 清设备面板激活状态(防止下次进入采集页误高亮)
|
| 848 |
self._active_device_keys = set()
|
| 849 |
self._lost_device_keys = set()
|
| 850 |
+
self._gripper_recalib_reopen = set()
|
| 851 |
self._last_device_keys = {}
|
| 852 |
self._last_device_kinds = {}
|
| 853 |
self._device_panel.set_checked_keys(set())
|
|
|
|
| 1657 |
lambda slot, frame, hw_ns, key=key:
|
| 1658 |
self._on_gripper_stereo(key, slot, frame, hw_ns))
|
| 1659 |
bridge.tactile_ready.connect(
|
| 1660 |
+
lambda side, heatmap, force, matrix, capture_ns, key=key:
|
| 1661 |
+
self._on_gripper_tactile(key, side, heatmap, force, matrix,
|
| 1662 |
+
capture_ns))
|
| 1663 |
bridge.pose_ready.connect(
|
| 1664 |
lambda position, quat, trajectory=(), timestamp=None, key=key:
|
| 1665 |
self._on_gripper_pose(key, position, quat, trajectory,
|
|
|
|
| 1827 |
prefix=entry["snapshot_prefix"], timestamp=timestamp)
|
| 1828 |
|
| 1829 |
def _on_gripper_tactile(self, dev_key: str, side, heatmap, force,
|
| 1830 |
+
force_matrix, capture_ns=0):
|
| 1831 |
"""触觉结果(左/右):热力图 + 力曲线显示 + 力值落盘;
|
| 1832 |
+
力矩阵落盘 P4 泵线程。capture_ns 为该样本的采集时刻,随力值
|
| 1833 |
+
一起落盘(力矩阵由其泵线程各自带上自己的时刻)。"""
|
| 1834 |
entry = self._gripper_entry(dev_key)
|
| 1835 |
if entry is None:
|
| 1836 |
return
|
|
|
|
| 1845 |
widget.update_tactile(display_heatmap, force)
|
| 1846 |
if force is not None and len(force) == 3:
|
| 1847 |
self._pipeline.write_tactile_force(
|
| 1848 |
+
side, force, prefix=entry["snapshot_prefix"],
|
| 1849 |
+
capture_ns=capture_ns)
|
| 1850 |
|
| 1851 |
def _on_gripper_state(self, dev_key: str, payload):
|
| 1852 |
"""串口夹爪状态 {pct,gripped,fz,event,board}:PoseView 开合板 +
|
|
|
|
| 1924 |
if seq == last_seq[side]:
|
| 1925 |
continue
|
| 1926 |
last_seq[side] = seq
|
| 1927 |
+
# 时刻与矩阵同锁取出(latest_matrix_stamped),保证配对;
|
| 1928 |
+
# 泵线程与主线程各自落各自模态,所以矩阵的时刻单独记
|
| 1929 |
+
stamped = bridge.latest_matrix_stamped(side)
|
| 1930 |
+
if stamped is None:
|
| 1931 |
continue
|
| 1932 |
+
capture_ns, matrix = stamped
|
| 1933 |
try:
|
| 1934 |
encoded = encode_gripper_force_matrix(matrix, spec)
|
| 1935 |
except Exception as exc:
|
|
|
|
| 1937 |
side, exc))
|
| 1938 |
continue
|
| 1939 |
self._pipeline.write_tactile_force_matrix(
|
| 1940 |
+
side, encoded, prefix=entry["snapshot_prefix"],
|
| 1941 |
+
capture_ns=capture_ns)
|
| 1942 |
wrote[side] += 1
|
| 1943 |
if not first_logged[side]:
|
| 1944 |
first_logged[side] = True
|
|
|
|
| 1978 |
self._device_panel.set_active_keys(self._active_device_keys)
|
| 1979 |
self._update_status()
|
| 1980 |
|
| 1981 |
+
def _on_gripper_recalibration(self, dev):
|
| 1982 |
+
"""右键夹爪 → 重新读取这只夹爪的厂商出厂标定。
|
| 1983 |
+
|
| 1984 |
+
出厂标定是**逐设备**的(内参/基线/IMU 外参逐台不同),所以只能从这
|
| 1985 |
+
只夹爪自身读,不能抄别的;读错设备会让 SLAM 位姿系统性跑偏。标定要
|
| 1986 |
+
独占设备,因此先关掉这台夹爪(若已开),完成后再自动开回来。
|
| 1987 |
+
"""
|
| 1988 |
+
label = self._device_label(dev)
|
| 1989 |
+
if not dev.serial:
|
| 1990 |
+
QMessageBox.warning(
|
| 1991 |
+
self, tr("夹爪无序列号"),
|
| 1992 |
+
tr("未读取到夹爪 ESP32 序列号,无法定位控制板。"))
|
| 1993 |
+
return
|
| 1994 |
+
if self._pipeline.is_recording:
|
| 1995 |
+
QMessageBox.warning(
|
| 1996 |
+
self, tr("录制中"),
|
| 1997 |
+
tr("录制中不可重读标定,请先停止录制。"))
|
| 1998 |
+
return
|
| 1999 |
+
answer = QMessageBox.question(
|
| 2000 |
+
self, tr("重新读取出厂标定"),
|
| 2001 |
+
tr("将从「{}」这只夹爪重新读取厂商出厂标定,并覆盖本机已有的"
|
| 2002 |
+
"标定文件。\n\n标定期间该夹爪被独占:已开启的话会先关闭,"
|
| 2003 |
+
"完成后自动开回来。\n\n继续?", label),
|
| 2004 |
+
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
|
| 2005 |
+
if answer != QMessageBox.Yes:
|
| 2006 |
+
return
|
| 2007 |
+
|
| 2008 |
+
was_open = dev.key in self._workers
|
| 2009 |
+
if was_open:
|
| 2010 |
+
self._gripper_recalib_reopen.add(dev.key)
|
| 2011 |
+
self._close_gripper(dev.key)
|
| 2012 |
+
self._active_device_keys.discard(dev.key)
|
| 2013 |
+
self._device_panel.set_checked(dev.key, False)
|
| 2014 |
+
self._device_panel.set_active_keys(self._active_device_keys)
|
| 2015 |
+
self._update_status()
|
| 2016 |
+
self._log(tr("[夹爪] {} 正在重新读取厂商出厂标定…", label))
|
| 2017 |
+
|
| 2018 |
+
thread = threading.Thread(
|
| 2019 |
+
target=self._gripper_recalibration_worker,
|
| 2020 |
+
args=(dev, label),
|
| 2021 |
+
name="gripper-recalibration",
|
| 2022 |
+
daemon=True,
|
| 2023 |
+
)
|
| 2024 |
+
thread.start()
|
| 2025 |
+
|
| 2026 |
+
def _gripper_recalibration_worker(self, dev, label: str):
|
| 2027 |
+
"""标定线程:读设备 → 写 YAML。结果经信号回主线程弹窗。"""
|
| 2028 |
+
reason = ""
|
| 2029 |
+
try:
|
| 2030 |
+
from core.gripper.fays_single import SingleFaysLease
|
| 2031 |
+
lease = SingleFaysLease(logger=self._log)
|
| 2032 |
+
lease.refresh_calibration(dev.serial)
|
| 2033 |
+
except Exception as exc: # 设备被占用/未插好/二进制缺失都走这里
|
| 2034 |
+
reason = str(exc)
|
| 2035 |
+
self._gripper_recalibration_done.emit(dev.key, label, reason)
|
| 2036 |
+
|
| 2037 |
+
def _on_gripper_recalibration_done(self, dev_key: str, label: str,
|
| 2038 |
+
reason: str):
|
| 2039 |
+
"""标定结果回主线程:失败弹窗,成功把原先开着的夹爪开回来。"""
|
| 2040 |
+
reopen = dev_key in self._gripper_recalib_reopen
|
| 2041 |
+
self._gripper_recalib_reopen.discard(dev_key)
|
| 2042 |
+
if reason:
|
| 2043 |
+
self._log(tr("[夹爪] {} 重读标定失败: {}", label, reason))
|
| 2044 |
+
QMessageBox.critical(
|
| 2045 |
+
self, tr("重读标定失败"),
|
| 2046 |
+
tr("「{}」的出厂标定未能重新读取。\n\n{}\n\n"
|
| 2047 |
+
"夹爪仍在设备列表中,可重新勾选开启。", label, reason))
|
| 2048 |
+
return
|
| 2049 |
+
self._log(tr("[夹爪] {} 出厂标定已更新", label))
|
| 2050 |
+
if not reopen:
|
| 2051 |
+
return # 本来就没开,不擅自打开
|
| 2052 |
+
dev = self._device_panel.device_for_key(dev_key)
|
| 2053 |
+
if dev is None:
|
| 2054 |
+
return # 标定期间设备拔了/列表重建过,不自动开
|
| 2055 |
+
# 自动开回来 = 用户点开关那条路,勾选状态与 _active_device_keys 一致
|
| 2056 |
+
self._device_panel.set_checked(dev_key, True)
|
| 2057 |
+
self._on_device_toggled(dev, True)
|
| 2058 |
+
|
| 2059 |
def _on_device_toggled(self, dev, on: bool):
|
| 2060 |
"""面板开关 → 打开/关闭设备(多路并发:只动自己,不互拆)。
|
| 2061 |
|