stouchinglhh Claude Code commited on
Commit
2f78cc5
·
1 Parent(s): 0901daa

collector: 更新采集工程至 v1.3.12(夹爪配对/串口诊断进主 GUI、触觉就绪门不再谎报、IMU 预积分判空修复;并整体回退 SLAM SDK 接入)

Browse files

同步 master 的 collector/ 子树至 e270ce3f,含两个提交:
- 6282955b revert: SLAM SDK 接入整体回退(2026-09-23)—— 双引擎切换与
slam_sdk 只读适配接口一并撤回,桥接回到 legacy;System.h /
RuntimeMapDiagnostics.h 的只读接口刻意保留(现役核心库编自那份源码)
- e270ce3f feat: v1.3.12 —— 触觉就绪门不再把「事件置位」当「可用」、
IMU 预积分 5 处判空(SIGSEGV 根因)、夹爪配对与 ESP32 串口诊断进主 GUI

collector/ 文件集合与 master 树逐条一致(2474 条目)。本分支 .gitattributes
把 collector/**/*.so、*.rknn、*.jpg 及通用模型后缀划给 LFS,匹配文件已由
git-lfs 转成指针。

Co-Authored-By: Claude Code <noreply@anthropic.com>

Files changed (46) hide show
  1. collector/.gitignore +11 -0
  2. collector/README.md +74 -1
  3. collector/config/__init__.py +1 -1
  4. collector/config/i18n.py +4 -3
  5. collector/core/gripper/bridge.py +15 -1
  6. collector/core/gripper/devices/gripper_serial.py +108 -39
  7. collector/core/gripper/devices/tactile_process_manager.py +22 -2
  8. collector/core/gripper/devices/uvc_camera_service.py +12 -3
  9. collector/core/gripper/fays_serial_probe.py +5 -1
  10. collector/core/gripper/fays_single.py +175 -13
  11. collector/core/gripper/orb_slam_src/ORB-SLAM/Examples/fays/offline/run_suite.py +24 -4
  12. collector/core/gripper/orb_slam_src/ORB-SLAM/include/RuntimeMapDiagnostics.h +13 -0
  13. collector/core/gripper/orb_slam_src/ORB-SLAM/include/System.h +45 -0
  14. collector/core/gripper/orb_slam_src/ORB-SLAM/src/LocalMapping.cc +7 -2
  15. collector/core/gripper/orb_slam_src/ORB-SLAM/src/Optimizer.cc +23 -1
  16. collector/core/gripper/orb_slam_src/ORB-SLAM/src/System.cc +138 -47
  17. collector/core/gripper/orb_slam_src/ORB-SLAM/src/Tracking.cc +6 -1
  18. collector/core/gripper/orb_slam_src/build.sh +27 -1
  19. collector/core/gripper/orb_slam_src/tests/baselines/README.md +285 -0
  20. collector/core/gripper/orb_slam_src/tests/baselines/bridge.readelf-d.txt +43 -0
  21. collector/core/gripper/orb_slam_src/tests/baselines/bridge.symbols.txt.gz +3 -0
  22. collector/core/gripper/orb_slam_src/tests/baselines/libORB_SLAM3.readelf-d.txt +46 -0
  23. collector/core/gripper/orb_slam_src/tests/baselines/libORB_SLAM3.symbols.txt.gz +3 -0
  24. collector/core/gripper/orb_slam_src/tests/baselines/pre_sdk_swap_lines.json +56 -0
  25. collector/core/gripper/orb_slam_src/tests/run_contract_tests.py +8 -4
  26. collector/core/gripper/orb_slam_src/tests/test_orb_preintegration_guard_contract.py +490 -0
  27. collector/core/gripper/runtime/device_access.py +102 -31
  28. collector/core/gripper/sightac_sdk/api_new/__init__.py +2 -2
  29. collector/core/gripper/sightac_sdk/api_new/platform_utils.py +2 -2
  30. collector/core/gripper/sightac_sdk/api_new/sensor_function.py +0 -0
  31. collector/core/gripper/sightac_sdk/api_new/sensor_gripper.py +0 -0
  32. collector/core/gripper/sightac_sdk/api_new/touch_sensor.py +0 -0
  33. collector/core/gripper/sightac_sdk/api_new/touch_sensor_base.py +0 -0
  34. collector/core/gripper/sightac_sdk/api_new/xu_camera.py +0 -0
  35. collector/core/gripper/sightac_sdk/pyarmor_runtime_000000/__init__.py +1 -1
  36. collector/core/gripper/sightac_sdk/pyarmor_runtime_000000/pyarmor_runtime.so +2 -2
  37. collector/docs/core.md +58 -0
  38. collector/docs/tools.md +3 -1
  39. collector/docs/ui.md +6 -4
  40. collector/tools/audit_slam_line_classes.py +197 -0
  41. collector/tools/tests/test_device_access_selflock.py +258 -0
  42. collector/tools/tests/test_gripper_calibration_autogen.py +39 -16
  43. collector/tools/tests/test_gripper_esp_binding.py +1147 -0
  44. collector/tools/tests/test_tactile_ready_gate.py +98 -0
  45. collector/ui/device_panel.py +23 -8
  46. collector/ui/main_window.py +429 -37
collector/.gitignore CHANGED
@@ -88,6 +88,11 @@ online/
88
  # 触觉 Sightac SDK 例外:core/gripper/sightac_sdk/ 已 pyarmor 加密,随包入库
89
  core/gripper/native/
90
 
 
 
 
 
 
91
  # ORB-SLAM 核心源码树(core/gripper/orb_slam_src/):**源码入库,产物不入库**。
92
  # 它必须排在 dist/ 那条全局规则(第 5 行)后面:那条规则会把整棵 dist 排掉,
93
  # 而 dist/fays_opencv48/ 里放的是桥接的 CMakeLists 与 7 份出厂标定,是源码。
@@ -117,5 +122,11 @@ core/gripper/orb_slam_src/FaysSense_VI_Kit_Release/config
117
  # 已随之删除,否则每次重打包都会留下未跟踪副本。
118
  lite_package/*
119
 
 
 
 
 
 
 
120
  # 对外接口文档等 Word 产物:随包发送,不入代码库
121
  *.docx
 
88
  # 触觉 Sightac SDK 例外:core/gripper/sightac_sdk/ 已 pyarmor 加密,随包入库
89
  core/gripper/native/
90
 
91
+ # (2026-09-23 已删除)SLAM SDK 厂商交付包 tools/SLAM_SDK_upload/ 与入库的
92
+ # core/gripper/orb_slam_src/slam_sdk/ 源码树:SDK 接入已整体回退,见
93
+ # core/gripper/orb_slam_src/tests/baselines/README.md「SLAM SDK 接入已回退」那节。
94
+ # 留档 ~/SLAM_SDK_upload_20260923.tgz(已排除与 native/ORBvoc.txt 相同的词典)。
95
+
96
  # ORB-SLAM 核心源码树(core/gripper/orb_slam_src/):**源码入库,产物不入库**。
97
  # 它必须排在 dist/ 那条全局规则(第 5 行)后面:那条规则会把整棵 dist 排掉,
98
  # 而 dist/fays_opencv48/ 里放的是桥接的 CMakeLists 与 7 份出厂标定,是源码。
 
122
  # 已随之删除,否则每次重打包都会留下未跟踪副本。
123
  lite_package/*
124
 
125
+ # 换包时的就地备份(如 2026-09-23 sightac 的 PyArmor runtime 3.12→3.10 那份)。
126
+ # 里面是**厂商加密件**,与 native/、glove_sdk/ 同策略:绝不入库、绝不推公开仓。
127
+ # 仓库跟踪的那些回退点走 git 自己(`git checkout HEAD -- <路径>`),这里放的是
128
+ # 「git 里那份也已经被覆盖掉」时的兜底。
129
+ backups/
130
+
131
  # 对外接口文档等 Word 产物:随包发送,不入代码库
132
  *.docx
collector/README.md CHANGED
@@ -1,6 +1,6 @@
1
  # collector — Multimodal Data Acquisition SDK · 多模态数据采集 SDK
2
 
3
- ![Version](https://img.shields.io/badge/version-1.3.11-blue)
4
  ![Python](https://img.shields.io/badge/python-3.10-blue)
5
  ![License](https://img.shields.io/badge/license-TBD-lightgrey)
6
 
@@ -336,6 +336,9 @@ venv/bin/python tools/tests/test_glove_registry.py
336
  venv/bin/python tools/tests/test_glove_backend_parity.py
337
  venv/bin/python tools/tests/test_glove_engine_sdk_guards.py
338
  venv/bin/python tools/tests/test_sdk_python_version.py
 
 
 
339
  # hardware tests require the corresponding device attached: d405_worker_test,
340
  # d435_e2e_test, d435_gui_smoke_test, mono_regression, d435_playback_test, etc.
341
  ```
@@ -397,6 +400,47 @@ are documented in [docs/index.md](docs/index.md#开发约定).
397
 
398
  ### Changelog
399
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
400
  - **v1.3.11** — the glove path moves to the vendor SDK v2.1.0 (`tools/glove_sdk/`,
401
  replacing the forked `core/glove_usb`), which pins the whole stack to **Python
402
  3.10**: the SDK's `algorithm/` is PyArmor-encrypted for the 3.10 ABI, so on
@@ -1159,6 +1203,9 @@ venv/bin/python tools/tests/test_glove_registry.py
1159
  venv/bin/python tools/tests/test_glove_backend_parity.py
1160
  venv/bin/python tools/tests/test_glove_engine_sdk_guards.py
1161
  venv/bin/python tools/tests/test_sdk_python_version.py
 
 
 
1162
  # 真机相关测试需连接对应设备:d405_worker_test、d435_e2e_test、
1163
  # d435_gui_smoke_test、mono_regression、d435_playback_test 等
1164
  ```
@@ -1210,6 +1257,32 @@ i18n 文案�� `tr()` 翻译、PyQt5 信号参数用 `object` 封送大整数、
1210
 
1211
  ### 更新记录
1212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1213
  - **v1.3.11** — 手套链路整体换厂商 SDK v2.1.0(`tools/glove_sdk/`,取代 fork 的
1214
  `core/glove_usb`),全栈因此锁到 **Python 3.10**:SDK 的 `algorithm/` 是 PyArmor
1215
  按 3.10 ABI 加密的,3.11+ 下 `import sdk.api` 直接失败 ⇒ 丢的是**整条手套链路**,
 
1
  # collector — Multimodal Data Acquisition SDK · 多模态数据采集 SDK
2
 
3
+ ![Version](https://img.shields.io/badge/version-1.3.12-blue)
4
  ![Python](https://img.shields.io/badge/python-3.10-blue)
5
  ![License](https://img.shields.io/badge/license-TBD-lightgrey)
6
 
 
336
  venv/bin/python tools/tests/test_glove_backend_parity.py
337
  venv/bin/python tools/tests/test_glove_engine_sdk_guards.py
338
  venv/bin/python tools/tests/test_sdk_python_version.py
339
+ # gripper pairing / ESP32 port diagnostics in the main GUI (v1.3.12)
340
+ venv/bin/python tools/tests/test_gripper_fays_pairing.py
341
+ venv/bin/python tools/tests/test_gripper_esp_binding.py
342
  # hardware tests require the corresponding device attached: d405_worker_test,
343
  # d435_e2e_test, d435_gui_smoke_test, mono_regression, d435_playback_test, etc.
344
  ```
 
400
 
401
  ### Changelog
402
 
403
+ - **v1.3.12** — pairing a new gripper no longer needs the vendor toolkit GUI.
404
+ When the app refused to connect a fresh gripper
405
+ (`串口连接失败,无法查询绑定的 Fays 序列号: serial open/handshake failed: Write
406
+ timeout`), nothing in the app answered the one question that matters: *is the
407
+ board talking at all?* The gripper context menu now has two more entries — an
408
+ **ESP32 serial diagnostics** pass (read-only: opens the port, prints the
409
+ board's raw output, and treats "not a single line in 3 s" as a first-class
410
+ verdict, since the USB node exists even when the firmware does not) and
411
+ **read/write the bound Fays serial**. The write path is probe → pick a target
412
+ → confirm → `WF:<serial>` → immediate `QF` read-back: the target list is the
413
+ *online* Fays serials only (no free-text entry — a wrong serial makes the
414
+ gripper silently point at another Fays, whose symptom is exactly "cannot
415
+ connect"), and a read-back that disagrees is reported as a warning rather than
416
+ a success. All three offline actions share one skeleton: refuse while
417
+ recording or without a board serial, hand the port over by closing the gripper
418
+ if it was open, and restore it afterwards — read-only diagnostics always,
419
+ failed probes/writes never (board state unknown, the user decides). The
420
+ diagnostics also fix a place that asked for evidence and never collected it:
421
+ `connect()` returned on a failed handshake, so "3 s, not a single line" — the
422
+ single most discriminating fact — was never actually measured. `connect()` is
423
+ now `open_readonly()` + `handshake()`, and a failed handshake re-opens the
424
+ port **read-only** (not one byte written) for 3 s: a board whose writes block
425
+ still reads, so "board is mute" (0 lines) separates cleanly from "board is
426
+ talking and just won't take writes" (lines shown). The four serial-failure
427
+ dialogs (open, recalibrate, read binding, write binding) — previously just
428
+ "still in the device list" or nothing at all — now all append the same
429
+ cheapest-first ladder: power-cycle the board's own supply for 5 s (the USB
430
+ node is enumerated by the chip's own USB peripheral, so unplugging USB is not
431
+ a chip power cycle), then use the toolkit's "test connection" to read the MAC
432
+ once (same download path as flashing, so it separates "host cannot reach the
433
+ board" from "the board's firmware is at fault"), and only then reflash — plus
434
+ a note that `--erase` wipes the whole chip including the Fays binding in NVS,
435
+ which must be written back afterwards. The ladder is attached only to the two
436
+ symptoms of "the board is not serving its USB port" (`Write timeout` and
437
+ `serial handshake timeout after N attempts`): a busy port (`Errno 16`) or a
438
+ permission error (`Errno 13`) also arrive wrapped in `serial open/handshake
439
+ failed:`, and matching on that prefix would point a host-side problem at a
440
+ reflash. One last blind spot: when the first `?` blocks, the log carries no
441
+ `connect attempt` line at all, so reading it later suggests the handshake was
442
+ never tried — the exception path now also logs which write attempt died and
443
+ what had been read back before it.
444
  - **v1.3.11** — the glove path moves to the vendor SDK v2.1.0 (`tools/glove_sdk/`,
445
  replacing the forked `core/glove_usb`), which pins the whole stack to **Python
446
  3.10**: the SDK's `algorithm/` is PyArmor-encrypted for the 3.10 ABI, so on
 
1203
  venv/bin/python tools/tests/test_glove_backend_parity.py
1204
  venv/bin/python tools/tests/test_glove_engine_sdk_guards.py
1205
  venv/bin/python tools/tests/test_sdk_python_version.py
1206
+ # 主程序内的夹爪配对与 ESP32 串口诊断(v1.3.12)
1207
+ venv/bin/python tools/tests/test_gripper_fays_pairing.py
1208
+ venv/bin/python tools/tests/test_gripper_esp_binding.py
1209
  # 真机相关测试需连接对应设备:d405_worker_test、d435_e2e_test、
1210
  # d435_gui_smoke_test、mono_regression、d435_playback_test 等
1211
  ```
 
1257
 
1258
  ### 更新记录
1259
 
1260
+ - **v1.3.12** — 接新夹爪不再需要开厂商工具包 GUI。新板子连不上时报的那句
1261
+ `串口连接失败,无法查询绑定的 Fays 序列号: serial open/handshake failed: Write
1262
+ timeout` 里,最要紧的问题是「板子到底在不在说话」,而主程序原本答不了。夹爪
1263
+ 右键菜单因此多了两个入口:**ESP32 串口诊断**(只读:打开串口把板上原样输出打
1264
+ 出来 —— USB 节点是硬件枚举出来的,固件死了节点照样在)与**读取/写入 Fays
1265
+ 绑定序列号**。写入走「探板 → 挑目标 → 确认 → `WF:<serial>` → 立刻 `QF` 回读」:
1266
+ 候选只列**当前在线**的 Fays 序列号、不给手输(写错会让这只夹爪静默指向另一台,
1267
+ 症状恰好就是「连不上」),回读对不上一律报警告而不是成功。三条离线操作共用一套
1268
+ 骨架:录制中或缺板子序列号不给进,执行前先把开着的夹爪关掉让出串口,完成后按
1269
+ 原样开回 —— 只读诊断一律开回,探板/写入失败不开回(板子状态未知,交回用户决定)。
1270
+ 诊断本身修掉一处「要证据的地方恰恰没取证」:`connect()` 握不上手就直接返回,
1271
+ 于是「收 3 秒一行都没有」这条最有分辨力的证据**从来没被采集过**。现在
1272
+ `connect()` 拆成 `open_readonly()` + `handshake()` 两半,握不上手时会**再只读
1273
+ 打开一次**(一个字节都不写)收 3 秒:写阻塞的板子读这条路仍然通,于是能分清
1274
+ 「板子哑了」(0 行)与「板子在说话、只是不收主机写入」(有行)。另外四条串口
1275
+ 失败弹窗(启动失败 / 重读标定 / 读绑定 / 写绑定)原本只有一句「夹爪仍在设备
1276
+ 列表中」或干脆没有,现在统一追加从低到高的处置梯子:先断控制板自身的电 5 秒
1277
+ (USB 节点由芯片的 USB 外设枚举,拔插 USB ≠ 芯片断电),再用工具包「测试连接」
1278
+ 读一次 MAC 判断主机能不能连上板子(走的是和刷写同一条下载通路),最后才重烧
1279
+ 固件;并提醒 `--erase` 是整片擦除、会把 NVS 里的 Fays 绑定一并清掉、烧完必须
1280
+ 重新写入序列号。梯子只挂在「板子没在服务串口」的两种报法(`Write timeout` 与
1281
+ `serial handshake timeout after N attempts`)上 —— 口被别的进程占(`Errno 16`)
1282
+ 或没权限(`Errno 13`)也都被包在 `serial open/handshake failed:` 这句里,按前缀
1283
+ 判定会把主机侧问题误引到重烧固件上去。还有一处盲点:第一笔 `?` 就阻塞时日志里
1284
+ 一条 `connect attempt` 都不会有,事后翻日志会读成「根本没试过握手」,所以异常
1285
+ 路径现在额外打一行「中断于第几次写、之前读回过什么」。
1286
  - **v1.3.11** — 手套链路整体换厂商 SDK v2.1.0(`tools/glove_sdk/`,取代 fork 的
1287
  `core/glove_usb`),全栈因此锁到 **Python 3.10**:SDK 的 `algorithm/` 是 PyArmor
1288
  按 3.10 ABI 加密的,3.11+ 下 `import sdk.api` 直接失败 ⇒ 丢的是**整条手套链路**,
collector/config/__init__.py CHANGED
@@ -3,7 +3,7 @@
3
  版本号集中定义于此:settings.APP_VERSION 及其他模块均从这里取值。
4
  """
5
 
6
- __version__ = "1.3.11"
7
 
8
  # v1.3.11 —— 手套链路整体换厂商 SDK v2.1.0(`tools/glove_sdk/`,取代 fork 的
9
  # `core/glove_usb`),全栈因此锁到 **Python 3.10**:SDK 的 `algorithm/` 是
 
3
  版本号集中定义于此:settings.APP_VERSION 及其他模块均从这里取值。
4
  """
5
 
6
+ __version__ = "1.3.12"
7
 
8
  # v1.3.11 —— 手套链路整体换厂商 SDK v2.1.0(`tools/glove_sdk/`,取代 fork 的
9
  # `core/glove_usb`),全栈因此锁到 **Python 3.10**:SDK 的 `algorithm/` 是
collector/config/i18n.py CHANGED
@@ -201,9 +201,10 @@ _TRANSLATIONS = {
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": "录制中不可更改设备"},
 
201
  "双击设备可重命名": {"en": "Double-click a device to rename", "zh": "双击设备可重命名"},
202
  # 夹爪 UI 其余文案走中文回落(与既有夹爪弹窗一致);这一句是**追加**在
203
  # 上面那条已翻译提示后面的,不译就会在英文界面里中英混排,故单独收录。
204
+ ";右键夹爪可重读标定 / 配对序列号 / 串口诊断": {
205
+ "en": "; right-click a gripper to re-read its calibration, "
206
+ "pair its Fays serial, or diagnose the ESP32 port",
207
+ "zh": ";右键夹爪可重读标定 / 配对序列号 / 串口诊断"},
208
  "重命名设备": {"en": "Rename Device", "zh": "重命名设备"},
209
  "设备名称:": {"en": "Device name:", "zh": "设备名称:"},
210
  "录制中不可更改设备": {"en": "Devices cannot be changed while recording", "zh": "录制中不可更改设备"},
collector/core/gripper/bridge.py CHANGED
@@ -543,7 +543,21 @@ class GripperBridge(QObject):
543
  self._teardown()
544
  return
545
  self._opened = True
546
- self._log("[Gripper] 相机 + 触觉 + SLAM 链路就绪")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
547
  self._post("opened")
548
  except Exception as exc:
549
  if self._stop.is_set():
 
543
  self._teardown()
544
  return
545
  self._opened = True
546
+ # 上面那句 wait_ready 只在**两路都失败**时返回 False;只灭一路
547
+ # 仍然放行(半边触觉也比没有强)。所以这里的文案得自己把话说准:
548
+ # 半边坏了就别讲「触觉就绪」,否则这条日志会掩护着一块空白的
549
+ # 触觉面板——2026-09-23 那次两路全灭还报就绪就是栽在这上面。
550
+ tactile_snapshot = self._tactile.snapshot()
551
+ broken = [
552
+ side for side in ("left", "right")
553
+ if getattr(tactile_snapshot, side).error
554
+ ]
555
+ if broken:
556
+ self._log(
557
+ "[Gripper] 相机 + SLAM 链路就绪;触觉未就绪({})"
558
+ .format("、".join(broken)))
559
+ else:
560
+ self._log("[Gripper] 相机 + 触觉 + SLAM 链路就绪")
561
  self._post("opened")
562
  except Exception as exc:
563
  if self._stop.is_set():
collector/core/gripper/devices/gripper_serial.py CHANGED
@@ -68,52 +68,121 @@ class GripperSerial:
68
  return self._last_error
69
 
70
  def connect(self, port: str, baud: int = CONNECT_BAUD) -> bool:
71
- """独占打开串口,在有限窗口内用 ``?`` 握手确认主控在线。"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  with self._io_lock:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  self._disconnect_locked()
74
- self._last_error = None
75
- try:
76
- # 独占模式:串口被其他进程占用时立刻失败,而不是两个进程
77
- # 各自读走半条响应,把「被占用」伪装成「握手超时」。
78
- opened = self._serial_factory(
79
- port,
80
- baud,
81
- timeout=self.CONNECT_TIMEOUT,
82
- write_timeout=self.CONNECT_WRITE_TIMEOUT,
83
- exclusive=True,
84
- )
85
- self._serial = opened
86
- opened.reset_input_buffer()
87
- deadline = self._clock() + self.CONNECT_BOOT_TIMEOUT
88
- attempts_made = 0
89
- for attempt in range(self.CONNECT_ATTEMPTS):
90
- if attempt and self._clock() >= deadline:
91
- break
92
- attempts_made = attempt + 1
93
- opened.write(b"?\r\n")
94
- line = opened.readline().decode(
95
- errors="ignore").strip()
96
- self._logger(
97
- f"[Serial] connect attempt {attempt + 1}/"
98
- f"{self.CONNECT_ATTEMPTS}: [{line[:60]}]"
99
- )
100
- if line.startswith("STATE"):
101
- return True
102
- if self._clock() < deadline:
103
- self._sleep(self.CONNECT_RETRY_DELAY)
104
- except Exception as exc:
105
- self._last_error = (
106
- f"serial open/handshake failed: {exc}"
107
  )
108
- self._disconnect_locked()
109
- return False
110
- # 报实际尝试次数,不报上限:被抢占/占用时上限是误导
 
 
 
 
 
 
 
 
111
  self._last_error = (
112
- "serial handshake timeout after "
113
- f"{attempts_made} attempts"
114
  )
115
  self._disconnect_locked()
116
  return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
  def disconnect(self) -> None:
119
  """幂等关闭串口;即使底层已关闭也清除 owner 引用。"""
 
68
  return self._last_error
69
 
70
  def connect(self, port: str, baud: int = CONNECT_BAUD) -> bool:
71
+ """独占打开串口,在有限窗口内用 ``?`` 握手确认主控在线。
72
+
73
+ 等于 :meth:`open_readonly` + :meth:`handshake`(打开后先丢弃陈旧
74
+ 输入再握手)。诊断路径要在「握手不上」时仍然拿到板子 TX 侧的
75
+ 证据,所以两半可以分开单独调。
76
+ """
77
+ with self._io_lock:
78
+ if not self._open_locked(port, baud):
79
+ return False
80
+ return self._handshake_locked()
81
+
82
+ def open_readonly(self, port: str, baud: int = CONNECT_BAUD) -> bool:
83
+ """只打开串口、一个字节都不写(只读诊断的第一步)。
84
+
85
+ 打开参数与 :meth:`connect` 完全一致(独占、同样的读/写超时),
86
+ 区别是不发握手 ``?``:板子收 FIFO 满导致写阻塞时,**写**这条路
87
+ 走不通,**打开+读**这条路仍然走得通 —— 这是把「板子哑了」与
88
+ 「板子会说话但不收主机写入」分开的唯一手段。
89
+ """
90
+ with self._io_lock:
91
+ return self._open_locked(port, baud)
92
+
93
+ def handshake(self) -> bool:
94
+ """在已打开的串口上补做握手(:meth:`connect` 的后半段)。"""
95
  with self._io_lock:
96
+ return self._handshake_locked()
97
+
98
+ def _open_locked(self, port: str, baud: int) -> bool:
99
+ self._disconnect_locked()
100
+ self._last_error = None
101
+ try:
102
+ # 独占模式:串口被其他进程占用时立刻失败,而不是两个进程
103
+ # 各自读走半条响应,把「被占用」伪装成「握手超时」。
104
+ opened = self._serial_factory(
105
+ port,
106
+ baud,
107
+ timeout=self.CONNECT_TIMEOUT,
108
+ write_timeout=self.CONNECT_WRITE_TIMEOUT,
109
+ exclusive=True,
110
+ )
111
+ self._serial = opened
112
+ opened.reset_input_buffer()
113
+ except Exception as exc:
114
+ self._last_error = f"serial open/handshake failed: {exc}"
115
  self._disconnect_locked()
116
+ return False
117
+ return True
118
+
119
+ def _handshake_locked(self) -> bool:
120
+ opened = self._serial
121
+ if opened is None or not getattr(opened, "is_open", False):
122
+ self._last_error = "serial handshake skipped: port not open"
123
+ return False
124
+ attempts_made = 0
125
+ last_line = ""
126
+ try:
127
+ deadline = self._clock() + self.CONNECT_BOOT_TIMEOUT
128
+ for attempt in range(self.CONNECT_ATTEMPTS):
129
+ if attempt and self._clock() >= deadline:
130
+ break
131
+ attempts_made = attempt + 1
132
+ opened.write(b"?\r\n")
133
+ last_line = opened.readline().decode(
134
+ errors="ignore").strip()
135
+ self._logger(
136
+ f"[Serial] connect attempt {attempt + 1}/"
137
+ f"{self.CONNECT_ATTEMPTS}: [{last_line[:60]}]"
 
 
 
 
 
 
 
 
 
 
 
138
  )
139
+ if last_line.startswith("STATE"):
140
+ return True
141
+ if self._clock() < deadline:
142
+ self._sleep(self.CONNECT_RETRY_DELAY)
143
+ except Exception as exc:
144
+ # 中断在哪一次写、最后一次读回什么,都要留痕:板子收 FIFO 没人
145
+ # 排空时第一笔写就阻塞,日志里一条 `connect attempt` 都不会有,
146
+ # 光看上面那行会以为「没试过」。这一行把两者区分开。
147
+ self._logger(
148
+ f"[Serial] 握手中断于第 {attempts_made} 次写"
149
+ f"(最后一次读回 {last_line!r}): {exc}")
150
  self._last_error = (
151
+ f"serial open/handshake failed: {exc}"
 
152
  )
153
  self._disconnect_locked()
154
  return False
155
+ # 报实际尝试次数,不报上限:被抢占/占用时上限是误导
156
+ self._last_error = (
157
+ "serial handshake timeout after "
158
+ f"{attempts_made} attempts"
159
+ )
160
+ self._disconnect_locked()
161
+ return False
162
+
163
+ def read_lines(self, duration: float, *, limit: int = 200):
164
+ """在 ``duration`` 秒内收集板上主动到达的整行(只读诊断)。
165
+
166
+ 不发任何命令:健康的 ESP32 空闲时也会周期性输出 ``STATE ...``,
167
+ 一行都收不到就说明没有程序在写这个口。超时那次 ``readline`` 返回
168
+ 空串,继续等到达时间上限;串口没打开时返回空列表。
169
+ """
170
+ with self._io_lock:
171
+ opened = self._serial
172
+ if opened is None or not getattr(opened, "is_open", False):
173
+ return []
174
+ lines = []
175
+ deadline = self._clock() + max(0.0, float(duration))
176
+ while len(lines) < limit and self._clock() < deadline:
177
+ try:
178
+ line = opened.readline().decode(
179
+ errors="ignore").strip()
180
+ except Exception:
181
+ # 板子掉线/句柄失效:已收到的行仍然有效,如实返回
182
+ break
183
+ if line:
184
+ lines.append(line)
185
+ return lines
186
 
187
  def disconnect(self) -> None:
188
  """幂等关闭串口;即使底层已关闭也清除 owner 引用。"""
collector/core/gripper/devices/tactile_process_manager.py CHANGED
@@ -2330,7 +2330,23 @@ class TactileProcessManager:
2330
  self._notify()
2331
 
2332
  def wait_ready(self, timeout: Optional[float] = None):
2333
- """等待左右两路各自 ready 或独立失败。"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2334
  timeout = (
2335
  self.PROCESS_READY_TIMEOUT
2336
  if timeout is None
@@ -2346,7 +2362,11 @@ class TactileProcessManager:
2346
  remaining = max(0.0, deadline - self.clock())
2347
  if not event.wait(timeout=remaining):
2348
  return False
2349
- return True
 
 
 
 
2350
 
2351
  def calibrate(
2352
  self, timeout: float = TACTILE_CALIBRATION_TIMEOUT,
 
2330
  self._notify()
2331
 
2332
  def wait_ready(self, timeout: Optional[float] = None):
2333
+ """等待左右两路各自 ready 或独立失败。
2334
+
2335
+ 返回 False 覆盖两种「没就绪」:等超时了,或**两路都失败**了。
2336
+
2337
+ 为什么必须判后者:`_initialize_all_input()` 的失败路径上也调
2338
+ `ready_event.set()`——那是为了让调用方不必干等满超时。于是
2339
+ 「事件全置位」**不等于**「触觉可用」。这个区别在 2026-09-23 咬过
2340
+ 一次:sightac 的 PyArmor runtime 是按 3.12 编的、而 venv 是 3.10,
2341
+ 输入子进程一 spawn 就 `undefined symbol: _PyCode_Validate`,两路
2342
+ 全灭,wait_ready 却照样返回 True ⇒ 主程序打「相机 + 触觉 + SLAM
2343
+ 链路就绪」、触觉面板空白,日志里那两条 `[Tactile:*] ERROR:` 没人
2344
+ 看得到,整整两天。真机取证见 logs/main.log 2026-09-21 16:22(最后
2345
+ 一次正常)与 09-23 11:50(两路全灭却报就绪)。
2346
+
2347
+ 只失败一路时仍算就绪:半边触觉也比没有强,调用方按 snapshot()
2348
+ 里的 error 自行决定怎么说。
2349
+ """
2350
  timeout = (
2351
  self.PROCESS_READY_TIMEOUT
2352
  if timeout is None
 
2362
  remaining = max(0.0, deadline - self.clock())
2363
  if not event.wait(timeout=remaining):
2364
  return False
2365
+ with self.state.lock:
2366
+ return not all(
2367
+ self.state.sides[side].error is not None
2368
+ for side in ("left", "right")
2369
+ )
2370
 
2371
  def calibrate(
2372
  self, timeout: float = TACTILE_CALIBRATION_TIMEOUT,
collector/core/gripper/devices/uvc_camera_service.py CHANGED
@@ -699,18 +699,27 @@ class UvcCameraServiceManager:
699
  bus, port = self._discovery_scope(assignment, live_esp)
700
  groups = self._run_discovery(usb_bus=bus, port_prefix=port)
701
  matches = []
702
- for group in groups:
 
703
  try:
704
  matches.append(self._associate_group(
705
  group, assignment, live_esp))
706
- except UvcCameraServiceError:
 
 
 
 
 
707
  continue
708
  if len(matches) != 1:
709
  esp_serial, fays_serial = self._assignment_identity(assignment)
 
 
 
710
  raise UvcCameraServiceError(
711
  "当前设备清单身份与动态 UVC 拓扑无法唯一配对: "
712
  f"esp32={esp_serial} fays={fays_serial} "
713
- f"matches={len(matches)} groups={len(groups)}"
714
  )
715
  return matches[0]
716
 
 
699
  bus, port = self._discovery_scope(assignment, live_esp)
700
  groups = self._run_discovery(usb_bus=bus, port_prefix=port)
701
  matches = []
702
+ rejections = []
703
+ for index, group in enumerate(groups):
704
  try:
705
  matches.append(self._associate_group(
706
  group, assignment, live_esp))
707
+ except UvcCameraServiceError as exc:
708
+ # 逐组记下拒绝原因:这里吞掉的往往才是真因(触觉相机
709
+ # mode 探测失败、Flash 身份缺失…),只报 matches/groups
710
+ # 计数会让人去猜拓扑,等于把现场丢掉一次。
711
+ label = group.get("physical_usb_path") or "group#{}".format(index)
712
+ rejections.append("{}: {}".format(label, exc))
713
  continue
714
  if len(matches) != 1:
715
  esp_serial, fays_serial = self._assignment_identity(assignment)
716
+ detail = ""
717
+ if rejections:
718
+ detail = ";逐组拒绝原因: [{}]".format("; ".join(rejections))
719
  raise UvcCameraServiceError(
720
  "当前设备清单身份与动态 UVC 拓扑无法唯一配对: "
721
  f"esp32={esp_serial} fays={fays_serial} "
722
+ f"matches={len(matches)} groups={len(groups)}{detail}"
723
  )
724
  return matches[0]
725
 
collector/core/gripper/fays_serial_probe.py CHANGED
@@ -116,8 +116,12 @@ def probe_product_serial(
116
  # the same vendor SDK at the same time. This is synchronization
117
  # only: identity still comes exclusively from the live SDK result
118
  # and the device_setup manifest below.
 
 
 
 
119
  with device_access_guard(FAYS_SDK_INITIALIZATION_LOCK, timeout=timeout), \
120
- fays_device_guard(ports["stereo_dev_port"]):
121
  command = [executable]
122
  if serial_only_fast:
123
  command.append("--serial-only-fast")
 
116
  # the same vendor SDK at the same time. This is synchronization
117
  # only: identity still comes exclusively from the live SDK result
118
  # and the device_setup manifest below.
119
+ # 设备锁这里必须带上 timeout:不传就是默认 0.0,而读出厂标定
120
+ # (calibration.py)会在同一把锁上停留十几秒 —— 2026-09-24 现场
121
+ # 日志里「启动的身份探测被自己进程正在跑的标定挡掉」就是这条
122
+ # 缺省值造成的。带上 timeout 变成排队等,而不是立刻失败。
123
  with device_access_guard(FAYS_SDK_INITIALIZATION_LOCK, timeout=timeout), \
124
+ fays_device_guard(ports["stereo_dev_port"], timeout=timeout):
125
  command = [executable]
126
  if serial_only_fast:
127
  command.append("--serial-only-fast")
collector/core/gripper/fays_single.py CHANGED
@@ -46,7 +46,11 @@ from core.gripper.fays_runtime import (
46
  validate_fays_superspeed,
47
  )
48
  from core.gripper.fays_serial_probe import probe_product_serial
49
- from core.gripper.runtime.device_access import fays_device_guard
 
 
 
 
50
 
51
  _INSTANCE_IPC_FILES = (
52
  "orb_pose.json.tmp", "orb_pose.json", "orb_meta.json",
@@ -166,6 +170,23 @@ class SingleFaysLease:
166
  )
167
  return matches[0]
168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  def _query_esp_bound_fays_serial(self, esp):
170
  """读 ESP32 NVS 里绑定的 Fays 产品序列号(串口命令 ``QF``)。
171
 
@@ -184,17 +205,7 @@ class SingleFaysLease:
184
  "ESP32 {} 串口连接失败,无法查询绑定的 Fays 序列号: {}".format(
185
  esp_serial, bridge.last_error or "unknown error"))
186
  try:
187
- response = ""
188
- for attempt in range(3):
189
- response = bridge.send("QF")
190
- if response.startswith(("FAYS_SERIAL:", "ERR FAYS_SERIAL")):
191
- break
192
- if response.startswith("STATE") and attempt < 2:
193
- # 固件周期性状态行插在命令响应前面:重试,别把串口
194
- # 收发竞态误判成「没有绑定」。
195
- time.sleep(0.05)
196
- continue
197
- break
198
  finally:
199
  bridge.disconnect()
200
  prefix = "FAYS_SERIAL:"
@@ -212,14 +223,21 @@ class SingleFaysLease:
212
 
213
  @staticmethod
214
  def _device_in_use(group):
215
- """这台 Fays 是否已被运行中的会话独占(另一套 rig 的 SLAM)。
216
 
217
  双夹爪时另一套 rig 的 SLAM 会把本设备锁一直持有到会话结束,
218
  它按定义不可能是本次要打开的夹爪,但探测不了就得如实记下来。
 
 
 
 
 
219
  """
220
  port = str((group.get("ports") or {}).get("stereo_dev_port") or "")
221
  if re.fullmatch(r"/dev/video[0-9]+", port) is None:
222
  return False # 节点无效留给后面的 SDK 预检去报错
 
 
223
  try:
224
  with fays_device_guard(port, timeout=0.0):
225
  return False
@@ -392,6 +410,150 @@ class SingleFaysLease:
392
  )
393
  return result
394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395
  def acquire(self, esp_serial):
396
  """锁定并返回 selected 字典;重复调用返回当前租约快照。"""
397
  with self._lock:
 
46
  validate_fays_superspeed,
47
  )
48
  from core.gripper.fays_serial_probe import probe_product_serial
49
+ from core.gripper.runtime.device_access import (
50
+ device_guard_held_by_process,
51
+ fays_device_guard,
52
+ fays_device_guard_path,
53
+ )
54
 
55
  _INSTANCE_IPC_FILES = (
56
  "orb_pose.json.tmp", "orb_pose.json", "orb_meta.json",
 
170
  )
171
  return matches[0]
172
 
173
+ def _send_qf(self, bridge):
174
+ """在已打开的串口上问一次 ``QF``,返回板上响应原文。
175
+
176
+ 固件周期性状态行会插在命令响应前面:拿不到 ``FAYS_SERIAL:`` /
177
+ ``ERR FAYS_SERIAL`` 就重试两次,别把串口收发竞态误判成「没有绑定」。
178
+ """
179
+ response = ""
180
+ for attempt in range(3):
181
+ response = bridge.send("QF")
182
+ if response.startswith(("FAYS_SERIAL:", "ERR FAYS_SERIAL")):
183
+ break
184
+ if response.startswith("STATE") and attempt < 2:
185
+ time.sleep(0.05)
186
+ continue
187
+ break
188
+ return response
189
+
190
  def _query_esp_bound_fays_serial(self, esp):
191
  """读 ESP32 NVS 里绑定的 Fays 产品序列号(串口命令 ``QF``)。
192
 
 
205
  "ESP32 {} 串口连接失败,无法查询绑定的 Fays 序列号: {}".format(
206
  esp_serial, bridge.last_error or "unknown error"))
207
  try:
208
+ response = self._send_qf(bridge)
 
 
 
 
 
 
 
 
 
 
209
  finally:
210
  bridge.disconnect()
211
  prefix = "FAYS_SERIAL:"
 
223
 
224
  @staticmethod
225
  def _device_in_use(group):
226
+ """这台 Fays 是否已被**别的**会话独占(另一套 rig 的 SLAM)。
227
 
228
  双夹爪时另一套 rig 的 SLAM 会把本设备锁一直持有到会话结束,
229
  它按定义不可能是本次要打开的夹爪,但探测不了就得如实记下来。
230
+
231
+ 必须先查进程内登记表:flock 绑在 open file description 上,本进程
232
+ 自己正持有(例如正在读出厂标定时)时,这里再开一次 fd 也一样
233
+ EWOULDBLOCK。只看「加锁失败」会把本机唯一那台 Fays 判成别人占用,
234
+ 于是跳过它、报出「在线 serial=[<无>]」并拒绝配对——自己挡自己。
235
  """
236
  port = str((group.get("ports") or {}).get("stereo_dev_port") or "")
237
  if re.fullmatch(r"/dev/video[0-9]+", port) is None:
238
  return False # 节点无效留给后面的 SDK 预检去报错
239
+ if device_guard_held_by_process(fays_device_guard_path(port)):
240
+ return False # 本进程自己持有,不是别的会话
241
  try:
242
  with fays_device_guard(port, timeout=0.0):
243
  return False
 
410
  )
411
  return result
412
 
413
+ # ── 配对(读/写 ESP32 NVS 里绑定的 Fays 序列号):GUI 入口 ──────
414
+ # 这四个都**不建租约、不占 IPC 目录**,与 refresh_calibration 同一口径:
415
+ # 串口与 Fays SDK 都是独占资源,调用方负责先确认这台夹爪没在用。
416
+
417
+ def esp_binding_status(self, esp_serial):
418
+ """这只 ESP32 的连接与绑定现状(「未绑定」不算失败)。
419
+
420
+ 返回 ``{"esp_serial", "device", "bound", "response", "reason"}``:
421
+ ``reason`` 为空=读通了,此时 ``bound`` 为空串表示板上没写绑定 ——
422
+ 新板的正常状态,界面可以直接往下走写入;``reason`` 非空=读不通,
423
+ 带上底层原文(例如 ``串口连接失败: serial open/handshake failed:
424
+ Write timeout``),由界面如实显示,不猜。除握手那条 ``?`` 与一条
425
+ ``QF`` 外不发任何命令。
426
+ """
427
+ with self._lock:
428
+ esp = self._match_esp(esp_serial)
429
+ status = {
430
+ "esp_serial": str(esp.get("serial") or ""),
431
+ "device": str(esp.get("device") or ""),
432
+ "bound": "",
433
+ "response": "",
434
+ "reason": "",
435
+ }
436
+ device = status["device"]
437
+ if not device:
438
+ status["reason"] = "缺少串口节点,无法查询绑���序列号"
439
+ return status
440
+ bridge = GripperSerial(logger=self._logger)
441
+ if not bridge.connect(device):
442
+ status["reason"] = "串口连接失败: {}".format(
443
+ bridge.last_error or "unknown error")
444
+ return status
445
+ try:
446
+ response = self._send_qf(bridge)
447
+ finally:
448
+ bridge.disconnect()
449
+ status["response"] = response
450
+ prefix = "FAYS_SERIAL:"
451
+ if response.startswith(prefix):
452
+ status["bound"] = response[len(prefix):].strip()
453
+ elif not response.startswith("ERR FAYS_SERIAL_NOT_SET"):
454
+ # 未绑定是正常状态;其它一律当读不通(含固件不认识 QF 的 ERR)
455
+ status["reason"] = "查询绑定序列号失败: {}".format(
456
+ response or "<empty>")
457
+ return status
458
+
459
+ def online_fays_serials(self):
460
+ """枚举当前在线的 Fays 产品序列号 → ``(by_serial, skipped)``。
461
+
462
+ ``by_serial`` 是 ``{产品序列号: 设备组}``,``skipped`` 是被其他会话
463
+ 独占而跳过的组(不能当写入目标)。探测口径与 ``acquire`` 完全一致
464
+ (超速预检 + ``--serial-only-fast``),所以列出来的就是配对会认的。
465
+ """
466
+ with self._lock:
467
+ groups = tuple(discover_fays_device_groups())
468
+ if not groups:
469
+ raise GripperFaysError(
470
+ "未发现完整的 Fays S80M"
471
+ "(stereo + IMU 两个节点必须同时在线)")
472
+ return self._probe_fays_groups_by_serial(groups)
473
+
474
+ def write_bound_serial(self, esp_serial, fays_serial):
475
+ """把 Fays 产品序列号写进这只 ESP32 的 NVS(``WF:``),返回回读值。
476
+
477
+ 校验与板上回执判定都交给 :meth:`GripperSerial.set_fays_serial`(它
478
+ 拥有字符集规则与三种终态);写完立刻 ``QF`` 回读确认,回读为空串
479
+ 表示板子没把新值读回来 —— 不猜成功,由调用方如实显示。
480
+ """
481
+ with self._lock:
482
+ esp = self._match_esp(esp_serial)
483
+ device = str(esp.get("device") or "").strip()
484
+ board = str(esp.get("serial") or "<unknown>").strip()
485
+ if not device:
486
+ raise GripperFaysError(
487
+ "ESP32 {} 缺少串口节点,无法写入 Fays 序列号".format(
488
+ board))
489
+ bridge = GripperSerial(logger=self._logger)
490
+ if not bridge.connect(device):
491
+ raise GripperFaysError(
492
+ "ESP32 {} 串口连接失败,无法写入 Fays 序列号: {}".format(
493
+ board, bridge.last_error or "unknown error"))
494
+ try:
495
+ bridge.set_fays_serial(fays_serial)
496
+ return bridge.query_fays_serial()
497
+ finally:
498
+ bridge.disconnect()
499
+
500
+ def esp_console_report(self, esp_serial, seconds: float = 3.0):
501
+ """只读诊断:定位这只夹爪的 ESP32,把板上原样输出带回给界面。
502
+
503
+ 除握手那一条 ``?`` 外不发任何命令,也不改板子状态。返回字典:
504
+ ``esp_serial``/``device``/``physical_usb_path`` 是身份,``connected``
505
+ 为假时 ``last_error`` 就是串口层原文(例如
506
+ ``serial open/handshake failed: Write timeout``),``state`` 与
507
+ ``bound`` 是 ``?`` 与 ``QF`` 的响应,``lines`` 是随后 ``seconds``
508
+ 秒内板上主动吐出的整行。
509
+
510
+ 握手失败不是「没有证据」:此时会再**只读**打开一次(一个字节都
511
+ 不写),把 ``seconds`` 秒内板子 TX 侧的原样输出收进
512
+ ``read_only_lines``。写阻塞时这条只读路径依然走得通,于是能分清
513
+ 两件处置完全不同的事 —— 一行都没有=板上没有程序在写这个口,
514
+ 有输出=板子在说话、只是不收主机写入。
515
+ """
516
+ with self._lock:
517
+ esp = self._match_esp(esp_serial)
518
+ report = {
519
+ "esp_serial": str(esp.get("serial") or ""),
520
+ "device": str(esp.get("device") or ""),
521
+ "physical_usb_path": str(
522
+ esp.get("physical_usb_path") or ""),
523
+ "connected": False,
524
+ "last_error": "",
525
+ "state": "",
526
+ "bound": "",
527
+ "lines": [],
528
+ "read_only_lines": [],
529
+ "read_only_error": "",
530
+ "seconds": float(seconds),
531
+ }
532
+ device = report["device"]
533
+ if not device:
534
+ report["last_error"] = "缺少串口节点,无法打开"
535
+ return report
536
+ bridge = GripperSerial(logger=self._logger)
537
+ try:
538
+ if not bridge.connect(device):
539
+ report["last_error"] = (
540
+ bridge.last_error or "unknown error")
541
+ # 握手失败时 connect 已经把口关掉了,重新只读打开:
542
+ # 写不进去的板子照样可能在说话,这一条不能省。
543
+ if bridge.open_readonly(device):
544
+ report["read_only_lines"] = bridge.read_lines(seconds)
545
+ else:
546
+ report["read_only_error"] = (
547
+ bridge.last_error or "unknown error")
548
+ return report
549
+ report["connected"] = True
550
+ report["state"] = bridge.send("?")
551
+ report["bound"] = bridge.send("QF")
552
+ report["lines"] = bridge.read_lines(seconds)
553
+ finally:
554
+ bridge.disconnect()
555
+ return report
556
+
557
  def acquire(self, esp_serial):
558
  """锁定并返回 selected 字典;重复调用返回当前租约快照。"""
559
  with self._lock:
collector/core/gripper/orb_slam_src/ORB-SLAM/Examples/fays/offline/run_suite.py CHANGED
@@ -10,10 +10,30 @@ import subprocess
10
  import sys
11
  import time
12
 
13
- PROJECT = Path(__file__).resolve().parents[4]
14
- sys.path.insert(0, str(PROJECT / 'gripper_version1'))
15
- from runtime.cpu_policy import detect_cpu_policy
16
- from fays_runtime import build_fays_runtime_env, ORB_LIBRARY, ORB_VOCABULARY
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  CASES = {
19
  'normal_1': ('normal', 0., 0.),
 
10
  import sys
11
  import time
12
 
13
+ def _find_repo_root(start):
14
+ """向上探测 collector 根(含 ``core/gripper/fays_runtime.py`` 的那一层)。
15
+
16
+ 这里原来写死 ``parents[4] / 'gripper_version1'`` —— 那是本树还活在
17
+ ``online/`` 布局下的路径。搬进 ``core/gripper/orb_slam_src/`` 之后它
18
+ **静默失效**:sys.path 指向一个不存在的目录,紧接着的 import 直接
19
+ ImportError,本套件整套跑不起来。病根是硬编码深度,所以改成向上探测,
20
+ 并留一个环境变量覆盖口(沿用 ``KSQ_GRIPPER_NATIVE_ROOT`` 那套做法)。
21
+ """
22
+ override = os.environ.get('KSQ_COLLECTOR_ROOT')
23
+ if override:
24
+ return Path(override).resolve()
25
+ for candidate in (start, *start.parents):
26
+ if (candidate / 'core' / 'gripper' / 'fays_runtime.py').is_file():
27
+ return candidate
28
+ raise SystemExit(
29
+ '找不到 collector 根(含 core/gripper/fays_runtime.py);'
30
+ '可用 KSQ_COLLECTOR_ROOT 显式指定')
31
+
32
+
33
+ REPO_ROOT = _find_repo_root(Path(__file__).resolve().parent)
34
+ sys.path.insert(0, str(REPO_ROOT))
35
+ from core.gripper.runtime.cpu_policy import detect_cpu_policy
36
+ from core.gripper.fays_runtime import build_fays_runtime_env, ORB_LIBRARY, ORB_VOCABULARY
37
 
38
  CASES = {
39
  'normal_1': ('normal', 0., 0.),
collector/core/gripper/orb_slam_src/ORB-SLAM/include/RuntimeMapDiagnostics.h CHANGED
@@ -22,6 +22,19 @@ struct RuntimeMapDiagnostics
22
  // retire or delete any SLAM object.
23
  unsigned long long GetCreatedKeyFrameCount();
24
  unsigned long long GetCreatedMapPointCount();
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  void UpdateRuntimeTrackingLocalCounts(
26
  unsigned long long localKf, unsigned long long localMp);
27
  RuntimeMapDiagnostics GetRuntimeMapDiagnostics();
 
22
  // retire or delete any SLAM object.
23
  unsigned long long GetCreatedKeyFrameCount();
24
  unsigned long long GetCreatedMapPointCount();
25
+
26
+ // 地图「大改动」计数器,取值等同 System::MapChanged() 内部的
27
+ // mpAtlas->GetLastBigChangeIdx()。每帧刷新(不受下面诊断快照的 1 秒节流影响)。
28
+ //
29
+ // 为什么要有它:桥接的 SDK 引擎路径(KSQ_FAYS_SLAM_ENGINE=sdk)走
30
+ // slam_sdk::Slam,而 SDK 不提供 MapChanged()。这个计数器让桥接能在
31
+ // **同一颗 libORB_SLAM3.so** 上复刻 System::MapChanged() 的轮询语义,
32
+ // 从而保住 output.map_changed 这个位姿重锚触发源。
33
+ //
34
+ // 2026-09-23:SDK 接入已整体回退,回退后的桥接重新直接调
35
+ // System::MapChanged(),本计数器暂无调用方(保留:它在现役核心库导出符号里,
36
+ // 与 System.h 的只读接口同理 —— 删要重编核心库)。
37
+ int GetRuntimeMapChangeIndex();
38
  void UpdateRuntimeTrackingLocalCounts(
39
  unsigned long long localKf, unsigned long long localMp);
40
  RuntimeMapDiagnostics GetRuntimeMapDiagnostics();
collector/core/gripper/orb_slam_src/ORB-SLAM/include/System.h CHANGED
@@ -192,6 +192,51 @@ public:
192
 
193
  float GetImageScale();
194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  #ifdef REGISTER_TIMES
196
  void InsertRectTime(double& time);
197
  void InsertResizeTime(double& time);
 
192
 
193
  float GetImageScale();
194
 
195
+ // ------------------------------------------------------------------
196
+ // slam_sdk 只读地图适配接口(新增)
197
+ //
198
+ // 2026-09-23:SDK 接入已整体回退(见 tests/baselines/README.md 同名那节),
199
+ // 调用方已删除;这些接口**保留**,因为现役核心库 libORB_SLAM3.so(f3446320)
200
+ // 就是编自这份源码 —— 删它们要重编核心库,而回退只需换桥接。
201
+ //
202
+ // 背景:slam_sdk 需要对外提供「地图快照」和「地图保存/加载」能力,但不能
203
+ // 把 Map / KeyFrame / MapPoint 的内部指针或引用暴露给调用方。
204
+ //
205
+ // 约束:以下接口只做值语义搬运,输出全部由调用方拥有;不改变跟踪算法、
206
+ // 线程模型或地图所有权。读取活动地图时依赖 Atlas 内部互斥量
207
+ // (Atlas::GetAllKeyFrames / GetAllMapPoints 自带锁),因此可在跟踪线程
208
+ // 之外调用;单个 KeyFrame 的位姿读取沿用其自身互斥量。
209
+ //
210
+ // 验证:slam_sdk 的 tests/map_test.cpp 覆盖「空地图 / 跟踪后快照 /
211
+ // 保存-加载往返」;算法侧无行为变化,不需要新的数据集基线。
212
+ // ------------------------------------------------------------------
213
+ struct ReadOnlyKeyFrame {
214
+ unsigned long int id = 0; // 上游 KeyFrame::mnId
215
+ double timestamp_seconds = 0.0; // 关键帧时间戳(秒)
216
+ Sophus::SE3f T_wc; // T_world_camera,平移单位为米
217
+ };
218
+
219
+ struct ReadOnlyMapPoint {
220
+ unsigned long int id = 0; // 上游 MapPoint::mnId
221
+ Eigen::Vector3f position_w; // 世界坐标系位置(米)
222
+ };
223
+
224
+ // 活动地图的只读快照(深拷贝,返回后与内部对象解耦)。
225
+ std::vector<ReadOnlyKeyFrame> GetReadOnlyKeyFrames();
226
+ std::vector<ReadOnlyMapPoint> GetReadOnlyMapPoints();
227
+ // 活动地图的规模(内部加锁,代价与地图大小无关)。
228
+ unsigned long int GetReadOnlyKeyFrameCount();
229
+ unsigned long int GetReadOnlyMapPointCount();
230
+
231
+ // 显式路径的 Atlas 持久化(二进制格式)。与 Settings 中的
232
+ // System.SaveAtlasToFile / System.LoadAtlasFromFile 共用同一实现:
233
+ // - Save 把当前 Atlas(含活动地图与备份地图)写入 filename;
234
+ // - Load 读取 filename 并替换当前 Atlas,必须在任何跟踪调用之前执行,
235
+ // 否则会替换掉跟踪线程正在使用的 Atlas。
236
+ // 返回 false 表示文件不可写/不可读或词典校验和不匹配。
237
+ bool SaveAtlasToFile(const string &filename, int type = BINARY_FILE);
238
+ bool LoadAtlasFromFile(const string &filename, int type = BINARY_FILE);
239
+
240
  #ifdef REGISTER_TIMES
241
  void InsertRectTime(double& time);
242
  void InsertResizeTime(double& time);
collector/core/gripper/orb_slam_src/ORB-SLAM/src/LocalMapping.cc CHANGED
@@ -700,8 +700,13 @@ void LocalMapping::PeriodicTimeWindowCleanup()
700
  if(keyFrame->isBad())
701
  {
702
  ++deletedKeyFrames;
703
- runDiscardedMeasurements +=
704
- keyFrame->mpImuPreintegrated->DiscardMeasurements();
 
 
 
 
 
705
  }
706
  else
707
  {
 
700
  if(keyFrame->isBad())
701
  {
702
  ++deletedKeyFrames;
703
+ // Nullable by design: a keyframe built during an
704
+ // IMU gap keeps mpImuPreintegrated==NULL. There is
705
+ // then nothing to discard, so contribute 0 rather
706
+ // than dereference NULL.
707
+ if(keyFrame->mpImuPreintegrated)
708
+ runDiscardedMeasurements +=
709
+ keyFrame->mpImuPreintegrated->DiscardMeasurements();
710
  }
711
  else
712
  {
collector/core/gripper/orb_slam_src/ORB-SLAM/src/Optimizer.cc CHANGED
@@ -487,7 +487,11 @@ void Optimizer::FullInertialBA(Map *pMap, int its, const bool bFixLocal, const l
487
  {
488
  if(pKFi->isBad() || pKFi->mPrevKF->mnId>maxKFid)
489
  continue;
490
- if(pKFi->bImu && pKFi->mPrevKF->bImu)
 
 
 
 
491
  {
492
  pKFi->mpImuPreintegrated->SetNewBias(pKFi->mPrevKF->GetImuBias());
493
  g2o::HyperGraph::Vertex* VP1 = optimizer.vertex(pKFi->mPrevKF->mnId);
@@ -3169,8 +3173,16 @@ void Optimizer::InertialOptimization(Map *pMap, Eigen::Matrix3d &Rwg, double &sc
3169
  {
3170
  if(pKFi->isBad() || pKFi->mPrevKF->mnId>maxKFid)
3171
  continue;
 
 
 
 
 
3172
  if(!pKFi->mpImuPreintegrated)
 
3173
  std::cout << "Not preintegrated measurement" << std::endl;
 
 
3174
 
3175
  pKFi->mpImuPreintegrated->SetNewBias(pKFi->mPrevKF->GetImuBias());
3176
  g2o::HyperGraph::Vertex* VP1 = optimizer.vertex(pKFi->mPrevKF->mnId);
@@ -3343,6 +3355,16 @@ void Optimizer::InertialOptimization(Map *pMap, Eigen::Vector3d &bg, Eigen::Vect
3343
  if(pKFi->isBad() || pKFi->mPrevKF->mnId>maxKFid)
3344
  continue;
3345
 
 
 
 
 
 
 
 
 
 
 
3346
  pKFi->mpImuPreintegrated->SetNewBias(pKFi->mPrevKF->GetImuBias());
3347
  g2o::HyperGraph::Vertex* VP1 = optimizer.vertex(pKFi->mPrevKF->mnId);
3348
  g2o::HyperGraph::Vertex* VV1 = optimizer.vertex(maxKFid+(pKFi->mPrevKF->mnId)+1);
 
487
  {
488
  if(pKFi->isBad() || pKFi->mPrevKF->mnId>maxKFid)
489
  continue;
490
+ // bImu records that the keyframe HAS inertial samples, not that a
491
+ // preintegration was built: a keyframe can carry bImu and still
492
+ // hold mpImuPreintegrated==NULL. Same condition as LocalInertialBA
493
+ // and MergeInertialBA, which already test it.
494
+ if(pKFi->bImu && pKFi->mPrevKF->bImu && pKFi->mpImuPreintegrated)
495
  {
496
  pKFi->mpImuPreintegrated->SetNewBias(pKFi->mPrevKF->GetImuBias());
497
  g2o::HyperGraph::Vertex* VP1 = optimizer.vertex(pKFi->mPrevKF->mnId);
 
3173
  {
3174
  if(pKFi->isBad() || pKFi->mPrevKF->mnId>maxKFid)
3175
  continue;
3176
+ // An empty preintegration is a designed state, not a corruption:
3177
+ // Tracking.cc seeds keyframes with mpImuPreintegrated=NULL when the
3178
+ // IMU window is too short, and that keyframe simply has no inertial
3179
+ // edge to contribute. Print and SKIP the whole keyframe -- printing
3180
+ // without skipping dereferences NULL at SetNewBias below.
3181
  if(!pKFi->mpImuPreintegrated)
3182
+ {
3183
  std::cout << "Not preintegrated measurement" << std::endl;
3184
+ continue;
3185
+ }
3186
 
3187
  pKFi->mpImuPreintegrated->SetNewBias(pKFi->mPrevKF->GetImuBias());
3188
  g2o::HyperGraph::Vertex* VP1 = optimizer.vertex(pKFi->mPrevKF->mnId);
 
3355
  if(pKFi->isBad() || pKFi->mPrevKF->mnId>maxKFid)
3356
  continue;
3357
 
3358
+ // Same designed-state guard as the 11-argument overload above: a
3359
+ // keyframe without preintegration contributes no inertial edge.
3360
+ // This overload had no guard at all, so it crashed silently -- no
3361
+ // message, just SIGSEGV at SetNewBias.
3362
+ if(!pKFi->mpImuPreintegrated)
3363
+ {
3364
+ std::cout << "Not preintegrated measurement" << std::endl;
3365
+ continue;
3366
+ }
3367
+
3368
  pKFi->mpImuPreintegrated->SetNewBias(pKFi->mPrevKF->GetImuBias());
3369
  g2o::HyperGraph::Vertex* VP1 = optimizer.vertex(pKFi->mPrevKF->mnId);
3370
  g2o::HyperGraph::Vertex* VV1 = optimizer.vertex(maxKFid+(pKFi->mPrevKF->mnId)+1);
collector/core/gripper/orb_slam_src/ORB-SLAM/src/System.cc CHANGED
@@ -50,6 +50,11 @@ std::mutex gRuntimeMapDiagnosticsMutex;
50
  RuntimeMapDiagnostics gRuntimeMapDiagnostics;
51
  std::chrono::steady_clock::time_point gLastRuntimeMapDiagnostics;
52
  std::atomic<unsigned long long> gRuntimeLocalKf{0};
 
 
 
 
 
53
  std::atomic<unsigned long long> gRuntimeLocalMp{0};
54
 
55
  enum KsqOrbStageIndex
@@ -172,6 +177,10 @@ void ReportKsqOrbStages(KsqOrbStageValues sample,
172
  void UpdateRuntimeMapDiagnostics(
173
  Tracking* tracker, Atlas* atlas, LocalMapping* localMapper)
174
  {
 
 
 
 
175
  const auto now = std::chrono::steady_clock::now();
176
  if(gLastRuntimeMapDiagnostics.time_since_epoch().count() != 0 &&
177
  now - gLastRuntimeMapDiagnostics < std::chrono::seconds(1))
@@ -211,6 +220,11 @@ RuntimeMapDiagnostics GetRuntimeMapDiagnostics()
211
  return gRuntimeMapDiagnostics;
212
  }
213
 
 
 
 
 
 
214
  System::System(const string &strVocFile, const string &strSettingsFile, const eSensor sensor,
215
  const bool bUseViewer, const int initFr, const string &strSequence):
216
  mSensor(sensor), mpViewer(static_cast<Viewer*>(NULL)),
@@ -1621,86 +1635,109 @@ void System::InsertTrackTime(double& time)
1621
  #endif
1622
 
1623
  void System::SaveAtlas(int type){
1624
- if(!mStrSaveAtlasToFile.empty())
1625
- {
1626
- //clock_t start = clock();
 
1627
 
1628
- // Save the current session
1629
- mpAtlas->PreSave();
1630
 
1631
- string pathSaveFileName = "./";
1632
- pathSaveFileName = pathSaveFileName.append(mStrSaveAtlasToFile);
1633
- pathSaveFileName = pathSaveFileName.append(".osa");
 
1634
 
1635
- string strVocabularyChecksum = CalculateCheckSum(mStrVocabularyFilePath,TEXT_FILE);
1636
- std::size_t found = mStrVocabularyFilePath.find_last_of("/\\");
1637
- string strVocabularyName = mStrVocabularyFilePath.substr(found+1);
1638
 
1639
- if(type == TEXT_FILE) // File text
1640
- {
1641
- cout << "Starting to write the save text file " << endl;
1642
- std::remove(pathSaveFileName.c_str());
1643
- std::ofstream ofs(pathSaveFileName, std::ios::binary);
1644
- boost::archive::text_oarchive oa(ofs);
1645
-
1646
- oa << strVocabularyName;
1647
- oa << strVocabularyChecksum;
1648
- oa << mpAtlas;
1649
- cout << "End to write the save text file" << endl;
1650
- }
1651
- else if(type == BINARY_FILE) // File binary
1652
- {
1653
- cout << "Starting to write the save binary file" << endl;
1654
- std::remove(pathSaveFileName.c_str());
1655
- std::ofstream ofs(pathSaveFileName, std::ios::binary);
1656
- boost::archive::binary_oarchive oa(ofs);
1657
- oa << strVocabularyName;
1658
- oa << strVocabularyChecksum;
1659
- oa << mpAtlas;
1660
- cout << "End to write save binary file" << endl;
1661
- }
1662
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1663
  }
1664
 
1665
  bool System::LoadAtlas(int type)
 
 
 
 
 
 
 
 
 
 
1666
  {
1667
  string strFileVoc, strVocChecksum;
1668
  bool isRead = false;
1669
 
1670
- string pathLoadFileName = "./";
1671
- pathLoadFileName = pathLoadFileName.append(mStrLoadAtlasFromFile);
1672
- pathLoadFileName = pathLoadFileName.append(".osa");
1673
 
1674
  if(type == TEXT_FILE) // File text
1675
  {
1676
- cout << "Starting to read the save text file " << endl;
1677
- std::ifstream ifs(pathLoadFileName, std::ios::binary);
1678
  if(!ifs.good())
1679
  {
1680
- cout << "Load file not found" << endl;
1681
  return false;
1682
  }
1683
  boost::archive::text_iarchive ia(ifs);
1684
  ia >> strFileVoc;
1685
  ia >> strVocChecksum;
1686
  ia >> mpAtlas;
1687
- cout << "End to load the save text file " << endl;
1688
  isRead = true;
1689
  }
1690
  else if(type == BINARY_FILE) // File binary
1691
  {
1692
- cout << "Starting to read the save binary file" << endl;
1693
- std::ifstream ifs(pathLoadFileName, std::ios::binary);
1694
  if(!ifs.good())
1695
  {
1696
- cout << "Load file not found" << endl;
1697
  return false;
1698
  }
1699
  boost::archive::binary_iarchive ia(ifs);
1700
  ia >> strFileVoc;
1701
  ia >> strVocChecksum;
1702
  ia >> mpAtlas;
1703
- cout << "End to load the save binary file" << endl;
1704
  isRead = true;
1705
  }
1706
 
@@ -1711,8 +1748,8 @@ bool System::LoadAtlas(int type)
1711
 
1712
  if(strInputVocabularyChecksum.compare(strVocChecksum) != 0)
1713
  {
1714
- cout << "The vocabulary load isn't the same which the load session was created " << endl;
1715
- cout << "-Vocabulary name: " << strFileVoc << endl;
1716
  return false; // Both are differents
1717
  }
1718
 
@@ -1725,6 +1762,60 @@ bool System::LoadAtlas(int type)
1725
  return false;
1726
  }
1727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1728
  string System::CalculateCheckSum(string filename, int type)
1729
  {
1730
  string checksum = "";
 
50
  RuntimeMapDiagnostics gRuntimeMapDiagnostics;
51
  std::chrono::steady_clock::time_point gLastRuntimeMapDiagnostics;
52
  std::atomic<unsigned long long> gRuntimeLocalKf{0};
53
+
54
+ // System::MapChanged() 的读数镜像,见 RuntimeMapDiagnostics.h 的说明。
55
+ // 刻意放在 UpdateRuntimeMapDiagnostics 的 1 秒节流**之前**刷新:地图大改动
56
+ // 会让世界坐标系跳变,晚发现 1 秒就赶不上当次位姿重锚了。
57
+ std::atomic<int> gRuntimeMapChangeIndex{0};
58
  std::atomic<unsigned long long> gRuntimeLocalMp{0};
59
 
60
  enum KsqOrbStageIndex
 
177
  void UpdateRuntimeMapDiagnostics(
178
  Tracking* tracker, Atlas* atlas, LocalMapping* localMapper)
179
  {
180
+ // 必须在节流之前:这一项是逐帧语义,其余字段是趋势观测。
181
+ gRuntimeMapChangeIndex.store(
182
+ atlas->GetLastBigChangeIdx(), std::memory_order_relaxed);
183
+
184
  const auto now = std::chrono::steady_clock::now();
185
  if(gLastRuntimeMapDiagnostics.time_since_epoch().count() != 0 &&
186
  now - gLastRuntimeMapDiagnostics < std::chrono::seconds(1))
 
220
  return gRuntimeMapDiagnostics;
221
  }
222
 
223
+ int GetRuntimeMapChangeIndex()
224
+ {
225
+ return gRuntimeMapChangeIndex.load(std::memory_order_relaxed);
226
+ }
227
+
228
  System::System(const string &strVocFile, const string &strSettingsFile, const eSensor sensor,
229
  const bool bUseViewer, const int initFr, const string &strSequence):
230
  mSensor(sensor), mpViewer(static_cast<Viewer*>(NULL)),
 
1635
  #endif
1636
 
1637
  void System::SaveAtlas(int type){
1638
+ // 兼容原有行为:Settings 里给了 SaveAtlasToFile 才写,写的是
1639
+ // "./<名字>.osa";显式路径版本见 SaveAtlasToFile()。
1640
+ if(mStrSaveAtlasToFile.empty())
1641
+ return;
1642
 
1643
+ SaveAtlasToFile("./" + mStrSaveAtlasToFile + ".osa", type);
1644
+ }
1645
 
1646
+ bool System::SaveAtlasToFile(const string &filename, int type)
1647
+ {
1648
+ if(filename.empty())
1649
+ return false;
1650
 
1651
+ // Save the current session
1652
+ mpAtlas->PreSave();
 
1653
 
1654
+ string strVocabularyChecksum = CalculateCheckSum(mStrVocabularyFilePath,TEXT_FILE);
1655
+ std::size_t found = mStrVocabularyFilePath.find_last_of("/\\");
1656
+ string strVocabularyName = mStrVocabularyFilePath.substr(found+1);
1657
+
1658
+ std::remove(filename.c_str());
1659
+ std::ofstream ofs(filename, std::ios::binary);
1660
+ if(!ofs.good())
1661
+ {
1662
+ cerr << "无法写入地图文件:" << filename << endl;
1663
+ return false;
1664
+ }
1665
+
1666
+ if(type == TEXT_FILE) // File text
1667
+ {
1668
+ cout << "开始写出文本格式地图文件" << endl;
1669
+ boost::archive::text_oarchive oa(ofs);
1670
+
1671
+ oa << strVocabularyName;
1672
+ oa << strVocabularyChecksum;
1673
+ oa << mpAtlas;
1674
+ cout << "文本格式地图文件写出完成" << endl;
 
 
1675
  }
1676
+ else if(type == BINARY_FILE) // File binary
1677
+ {
1678
+ cout << "开始写出二进制地图文件" << endl;
1679
+ boost::archive::binary_oarchive oa(ofs);
1680
+ oa << strVocabularyName;
1681
+ oa << strVocabularyChecksum;
1682
+ oa << mpAtlas;
1683
+ cout << "二进制地图文件写出完成" << endl;
1684
+ }
1685
+ else
1686
+ {
1687
+ return false;
1688
+ }
1689
+
1690
+ return ofs.good();
1691
  }
1692
 
1693
  bool System::LoadAtlas(int type)
1694
+ {
1695
+ // 兼容原有行为:Settings 里给了 LoadAtlasFromFile 才读,
1696
+ // 读的是 "./<名字>.osa";显式路径版本见 LoadAtlasFromFile()。
1697
+ if(mStrLoadAtlasFromFile.empty())
1698
+ return false;
1699
+
1700
+ return LoadAtlasFromFile("./" + mStrLoadAtlasFromFile + ".osa", type);
1701
+ }
1702
+
1703
+ bool System::LoadAtlasFromFile(const string &filename, int type)
1704
  {
1705
  string strFileVoc, strVocChecksum;
1706
  bool isRead = false;
1707
 
1708
+ if(filename.empty())
1709
+ return false;
 
1710
 
1711
  if(type == TEXT_FILE) // File text
1712
  {
1713
+ cout << "开始读取文本格式地图文件" << endl;
1714
+ std::ifstream ifs(filename, std::ios::binary);
1715
  if(!ifs.good())
1716
  {
1717
+ cout << "地图文件不存在或不可读" << endl;
1718
  return false;
1719
  }
1720
  boost::archive::text_iarchive ia(ifs);
1721
  ia >> strFileVoc;
1722
  ia >> strVocChecksum;
1723
  ia >> mpAtlas;
1724
+ cout << "文本格式地图文件读取完成" << endl;
1725
  isRead = true;
1726
  }
1727
  else if(type == BINARY_FILE) // File binary
1728
  {
1729
+ cout << "开始读取二进制地图文件" << endl;
1730
+ std::ifstream ifs(filename, std::ios::binary);
1731
  if(!ifs.good())
1732
  {
1733
+ cout << "地图文件不存在或不可读" << endl;
1734
  return false;
1735
  }
1736
  boost::archive::binary_iarchive ia(ifs);
1737
  ia >> strFileVoc;
1738
  ia >> strVocChecksum;
1739
  ia >> mpAtlas;
1740
+ cout << "二进制地图文件读取完成" << endl;
1741
  isRead = true;
1742
  }
1743
 
 
1748
 
1749
  if(strInputVocabularyChecksum.compare(strVocChecksum) != 0)
1750
  {
1751
+ cout << "地图文件与当前词典不匹配:地图创建时使用的词典与当前词典不同" << endl;
1752
+ cout << "-地图记录的词典名:" << strFileVoc << endl;
1753
  return false; // Both are differents
1754
  }
1755
 
 
1762
  return false;
1763
  }
1764
 
1765
+ std::vector<System::ReadOnlyKeyFrame> System::GetReadOnlyKeyFrames()
1766
+ {
1767
+ std::vector<ReadOnlyKeyFrame> output;
1768
+
1769
+ // Atlas::GetAllKeyFrames() 内部持有 Atlas 互斥量,返回的是活动地图指针
1770
+ // 的一份副本;这里立刻转换成本 map 拥有的值语义结构,调用方拿不到内部指针。
1771
+ const std::vector<KeyFrame*> keyframes = mpAtlas->GetAllKeyFrames();
1772
+ output.reserve(keyframes.size());
1773
+ for(KeyFrame* pKF : keyframes)
1774
+ {
1775
+ if(!pKF)
1776
+ continue;
1777
+
1778
+ ReadOnlyKeyFrame entry;
1779
+ entry.id = pKF->mnId;
1780
+ entry.timestamp_seconds = pKF->mTimeStamp;
1781
+ entry.T_wc = pKF->GetPoseInverse();
1782
+ output.push_back(entry);
1783
+ }
1784
+
1785
+ return output;
1786
+ }
1787
+
1788
+ std::vector<System::ReadOnlyMapPoint> System::GetReadOnlyMapPoints()
1789
+ {
1790
+ std::vector<ReadOnlyMapPoint> output;
1791
+
1792
+ // 与 GetReadOnlyKeyFrames() 同理:加锁取指针副本,再深拷贝成值语义。
1793
+ const std::vector<MapPoint*> map_points = mpAtlas->GetAllMapPoints();
1794
+ output.reserve(map_points.size());
1795
+ for(MapPoint* pMP : map_points)
1796
+ {
1797
+ if(!pMP)
1798
+ continue;
1799
+
1800
+ ReadOnlyMapPoint entry;
1801
+ entry.id = pMP->mnId;
1802
+ entry.position_w = pMP->GetWorldPos();
1803
+ output.push_back(entry);
1804
+ }
1805
+
1806
+ return output;
1807
+ }
1808
+
1809
+ unsigned long int System::GetReadOnlyKeyFrameCount()
1810
+ {
1811
+ return mpAtlas->KeyFramesInMap();
1812
+ }
1813
+
1814
+ unsigned long int System::GetReadOnlyMapPointCount()
1815
+ {
1816
+ return mpAtlas->MapPointsInMap();
1817
+ }
1818
+
1819
  string System::CalculateCheckSum(string filename, int type)
1820
  {
1821
  string checksum = "";
collector/core/gripper/orb_slam_src/ORB-SLAM/src/Tracking.cc CHANGED
@@ -2818,7 +2818,12 @@ void Tracking::CreateInitialMapMonocular()
2818
  pKFini->mNextKF = pKFcur;
2819
  pKFcur->mpImuPreintegrated = mpImuPreintegratedFromLastKF;
2820
 
2821
- mpImuPreintegratedFromLastKF = new IMU::Preintegrated(pKFcur->mpImuPreintegrated->GetUpdatedBias(),pKFcur->mImuCalib);
 
 
 
 
 
2822
  }
2823
 
2824
 
 
2818
  pKFini->mNextKF = pKFcur;
2819
  pKFcur->mpImuPreintegrated = mpImuPreintegratedFromLastKF;
2820
 
2821
+ // mpImuPreintegratedFromLastKF is nullable -- PreintegrateIMU() and
2822
+ // ResetActiveMap() both test it before use -- so the seed above can be
2823
+ // NULL. Re-seeding from its bias would then dereference NULL; leaving
2824
+ // it unset is safe because every other reader already tests it.
2825
+ if(pKFcur->mpImuPreintegrated)
2826
+ mpImuPreintegratedFromLastKF = new IMU::Preintegrated(pKFcur->mpImuPreintegrated->GetUpdatedBias(),pKFcur->mImuCalib);
2827
  }
2828
 
2829
 
collector/core/gripper/orb_slam_src/build.sh CHANGED
@@ -316,6 +316,15 @@ fi
316
  # 解析 DSO 传递依赖的搜索路径:**不进 RUNPATH、不进 NEEDED**(现役二进制的 NEEDED
317
  # 里没有 jasper,实测),运行时照旧由 orb48_env/lib 那份 libjasper.so.7 兜。两处
318
  # 取值照抄现役的构建缓存(/tmp/ksq-bridge-build/CMakeCache.txt)。
 
 
 
 
 
 
 
 
 
319
 
320
  ORB48_ENV="$NATIVE/FaysSense_VI_Kit_Release/thirdparty/orb48_env"
321
  OPENCV_PKG_LIB="$(cd "$OPENCV_DIR_48/../.." && pwd)" # <pkg>/lib/cmake/opencv4 → <pkg>/lib
@@ -332,7 +341,7 @@ cmake -S "$BRIDGE_SRC" -B "$BRIDGE_BUILD" \
332
  -DFAYS_BRIDGE_SOURCE="$ORB_SRC/Examples/fays/fayssense_orb_slam.cc" \
333
  -DKSQ_ORB_LIBRARY_PATH="$ORB_LIB_DEST/libORB_SLAM3.so" \
334
  -DKSQ_FAYS_BINARY_SUFFIX="$BRIDGE_SUFFIX" \
335
- -DCMAKE_EXE_LINKER_FLAGS="-Wl,-rpath-link,$ORB48_ENV/lib -Wl,-rpath-link,$OPENCV_PKG_LIB"
336
  mark_cache_local "$BRIDGE_BUILD"
337
  if [ "$ALL_TARGETS" = 1 ]; then
338
  cmake --build "$BRIDGE_BUILD" -j"$JOBS"
@@ -354,6 +363,23 @@ if command -v readelf >/dev/null 2>&1; then
354
  echo "RPATH 与现役一致 ✓"
355
  fi
356
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357
  # ---------------------------------------------------------------- ctest
358
 
359
  if [ "$DO_TEST" = 1 ]; then
 
316
  # 解析 DSO 传递依赖的搜索路径:**不进 RUNPATH、不进 NEEDED**(现役二进制的 NEEDED
317
  # 里没有 jasper,实测),运行时照旧由 orb48_env/lib 那份 libjasper.so.7 兜。两处
318
  # 取值照抄现役的构建缓存(/tmp/ksq-bridge-build/CMakeCache.txt)。
319
+ #
320
+ # -Wl,--allow-shlib-undefined 同样是**必需**的,而且是为了同一类「只记 NEEDED、
321
+ # 不列 IMPORTED」的 DSO:orb48_env/lib/libtiff.so.6 自己带着四个未定义的
322
+ # `jpeg12_*@LIBJPEG_8.0`(由同目录 libjpeg.so.8 提供,靠它自己的 RPATH $ORIGIN
323
+ # 兜)。ld 在**产出可执行文件**时默认把 DSO 的未定义符号当错误报(产出 .so 时才
324
+ # 默认放行),而 -ljpeg 从来不在我们的链接行上,于是 collect2 直接退出。
325
+ # 这个旗标只关掉链接期那道检查:不改 NEEDED、不改 RPATH(现役二进制里没有
326
+ # libjpeg,实测),运行时照旧由 orb48_env/lib 那份 libjpeg.so.8 解析。
327
+ # 代价是以后真漏链符号这里也不报 —— 所以紧接着补了 ldd -r 的装载期判据。
328
 
329
  ORB48_ENV="$NATIVE/FaysSense_VI_Kit_Release/thirdparty/orb48_env"
330
  OPENCV_PKG_LIB="$(cd "$OPENCV_DIR_48/../.." && pwd)" # <pkg>/lib/cmake/opencv4 → <pkg>/lib
 
341
  -DFAYS_BRIDGE_SOURCE="$ORB_SRC/Examples/fays/fayssense_orb_slam.cc" \
342
  -DKSQ_ORB_LIBRARY_PATH="$ORB_LIB_DEST/libORB_SLAM3.so" \
343
  -DKSQ_FAYS_BINARY_SUFFIX="$BRIDGE_SUFFIX" \
344
+ -DCMAKE_EXE_LINKER_FLAGS="-Wl,-rpath-link,$ORB48_ENV/lib -Wl,-rpath-link,$OPENCV_PKG_LIB -Wl,--allow-shlib-undefined"
345
  mark_cache_local "$BRIDGE_BUILD"
346
  if [ "$ALL_TARGETS" = 1 ]; then
347
  cmake --build "$BRIDGE_BUILD" -j"$JOBS"
 
363
  echo "RPATH 与现役一致 ✓"
364
  fi
365
 
366
+ # 成败判据 2:装载期必须干净。--allow-shlib-undefined 放开了链接期那道检查,
367
+ # 这里就得自己顶上 —— `ldd -r` 会把桥接与它的整棵依赖(含 libORB_SLAM3.so)
368
+ # 的未定义符号都解析一遍,缺一个就说明进程里也解析不到。顺带看住核心库与
369
+ # Pangolin 的代际配对:核心库那个 `pangolin::Handler3D` 构造函数只由本地单体
370
+ # libpangolin.so 导出,换成 vendor 的 pango_display 拆分库这里立刻报出来。
371
+ if command -v ldd >/dev/null 2>&1; then
372
+ BRIDGE_RUNTIME_LDPATH="$ORB48_ENV/lib:$ORB_LIB_DEST:$NATIVE/FaysSense_VI_Kit_Release/lib/fays_atrak/$ARCH/Release"
373
+ # `|| true` 不是保险:grep -c 数到 0 个时退出码是 1,配上 set -euo pipefail
374
+ # 会把整个脚本在「一切正常」的那一次静默带走(装不上,也不报错)。
375
+ not_found="$(LD_LIBRARY_PATH="$BRIDGE_RUNTIME_LDPATH" ldd "$BRIDGE_BIN" 2>&1 | grep -c 'not found' || true)"
376
+ unresolved="$(LD_LIBRARY_PATH="$BRIDGE_RUNTIME_LDPATH" ldd -r "$BRIDGE_BIN" 2>&1 | grep -c 'undefined symbol' || true)"
377
+ [ "$not_found" = 0 ] && [ "$unresolved" = 0 ] \
378
+ || die "$BRIDGE_TARGET$BRIDGE_SUFFIX 装载期不干净: not found=$not_found undefined=$unresolved
379
+ 用 LD_LIBRARY_PATH=$BRIDGE_RUNTIME_LDPATH ldd -r $BRIDGE_BIN 看细节"
380
+ echo "装载期 ldd not found=0、ldd -r undefined=0 ✓"
381
+ fi
382
+
383
  # ---------------------------------------------------------------- ctest
384
 
385
  if [ "$DO_TEST" = 1 ]; then
collector/core/gripper/orb_slam_src/tests/baselines/README.md ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 换 SLAM 核心前的基线(2026-09-23 冻结)
2
+
3
+ 用途:把主程序 SLAM 核心替换成 `SLAM_SDK_upload`(v0.2.0)时,证明
4
+ 「改动只增不减、没悄悄丢掉符号、没改行为」。本目录是 P0 阶段冻结的
5
+ **四项基线**,换核心之后的每一项改动都要能对着它对账。
6
+
7
+ | 项 | 资产 | 状态 |
8
+ |---|---|---|
9
+ | P0.1 产物指纹 | `*.symbols.txt.gz`、`*.readelf-d.txt`、下表 | 已冻结 |
10
+ | P0.2 行分类 | `pre_sdk_swap_lines.json` | 已冻结(20 份日志 / 227646 行) |
11
+ | P0.3 轨迹 | — | **未冻结**,见下节「P0.3 为什么没做」 |
12
+ | P0.4 契约测试 | 本节记录 | 已跑(见下节) |
13
+
14
+ 产物指纹部分方法沿用主 README 的「复现性:重编出来的和现役差在哪」小节。
15
+
16
+ ## 冻结时的现役产物
17
+
18
+ | | 大小 | md5 | BuildID | 导出符号数 |
19
+ |---|---|---|---|---|
20
+ | 核心库 `libORB_SLAM3.so` | 5432608 | `c21808e2…` | `efd49c48…` | 6936 行 / **5847 去重** |
21
+ | 桥接 `fayssense_orb_slam_sn219_opencv48_mark_only` | 234840 | `a76a602c…` | `6fa2ac54…` | 70 |
22
+
23
+ ★ **两个数别混**:`nm -DC --defined-only | wc -l` 是 **6936 行**(同名符号在多个
24
+ TU 里各出现一次),`… | sed 's/^[0-9a-f]* //' | sort -u` 才是 **5847** 个唯一符号。
25
+ `libORB_SLAM3.symbols.txt.gz` 存的是**去重后的 5847**,`comm` 对账必须两边同法。
26
+
27
+ 路径(`core/gripper/native/` 下,该目录不入库):
28
+
29
+ - `dist/orb_mark_only/lib/libORB_SLAM3.so`
30
+ - `dist/fays_opencv48/bin/fayssense_orb_slam_sn219_opencv48_mark_only`
31
+
32
+ md5 / BuildID 与主 README 第 158/160 行记录逐位吻合 ⇒ 冻结的就是 README 描述的那两件。
33
+
34
+ ## 文件
35
+
36
+ | 文件 | 内容 |
37
+ |---|---|
38
+ | `libORB_SLAM3.symbols.txt.gz` | 核心库全部 6936 个导出符号(`nm -DC --defined-only` 去地址后排序去重) |
39
+ | `bridge.symbols.txt.gz` | 桥接 70 个导出符号,同法 |
40
+ | `libORB_SLAM3.readelf-d.txt` / `bridge.readelf-d.txt` | `readelf -d` 全量,用于核对 RPATH/NEEDED/FLAGS **逐字符**相同 |
41
+
42
+ 符号表用 gzip 存(908 KB → 45 KB);`readelf -d` 体积小,直接存原文。
43
+
44
+ ## 怎么用(改动后的门)
45
+
46
+ ```bash
47
+ # 1) 符号集「只增不减」
48
+ # 重新构建后,对新产物跑同样的 nm,与基线做差:
49
+ nm -DC --defined-only <新产物> | sed 's/^[0-9a-f]* //' | sort -u > /tmp/new.symbols.txt
50
+ zcat tests/baselines/libORB_SLAM3.symbols.txt.gz > /tmp/base.symbols.txt
51
+ comm -23 /tmp/base.symbols.txt /tmp/new.symbols.txt # 期望:空(没有任何符号消失)
52
+
53
+ # 2) readelf -d 逐字符
54
+ diff <(readelf -d <新产物>) tests/baselines/libORB_SLAM3.readelf-d.txt
55
+ # 注意:BuildID 不会出现在 -d 输出里;期望只有 NEEDED 增删是有意的改动
56
+
57
+ # 3) 同形状部署树里 ldd -r
58
+ ldd -r <新产物> | { command grep 'not found' || echo 'not found=0'; }
59
+ ```
60
+
61
+ `comm` 那一步是本基线的主要价值:核心库有 6936 个符号,肉眼看不出少没少。
62
+
63
+ ## P0.2 行分类基线(`pre_sdk_swap_lines.json`)
64
+
65
+ 用 `tools/audit_slam_line_classes.py --capture` 生成;换核心后用 `--compare` 对账。
66
+ 20 份 `logs/slam_native/*_slam_stdout.log`、227646 行:
67
+
68
+ | kind | 条数 | | kind | 条数 |
69
+ |---|---:|---|---|---:|
70
+ | pose | 154828 | | mp_cleanup | 5255 |
71
+ | log | 44161 | | fays_rates | 5326 |
72
+ | orb_stage | 5401 | | error | **1110** |
73
+ | orb_diagnostic | 5361 | | status | 716 |
74
+ | affinity | 5379 | | time_drop | 75 |
75
+ | origin | 17 | | ready | 17 |
76
+
77
+ **★ 关键发现:现役生产本来就有 1110 条 error 分类行**,其中
78
+ `ERROR building inertial edge` ×1106 独占(另 4 条是 2026-09-20 某次的
79
+ `StereoOnlineCapture(): get img failed` 等一次性文案)。这条来自上游 ORB-SLAM3
80
+ 的 `Optimizer.cc`(本树 `:2692/:4277`,SDK 树 `:2663/:4248` **两棵树都有**),
81
+ **不是换核心引入的**。换核心后的对账要拿它当既有基线,不能当成回归。
82
+
83
+ `_ERROR_RE` 裸命中 6 种 > error 分类 5 种,多出来的是
84
+ `[FAYS-CALIB] WARN SetStereoFPS(50) failed` ×19 —— 它命中正则但被
85
+ `protocol.py` 的 `_IGNORED_NON_FATAL_RE` 白名单提前挡掉,**证明白名单确实在生效**,
86
+ 也说明「只看裸命中会高估风险」。
87
+
88
+ **⚠️ 纠正一条我方案里写错的契约**:`_ERROR_RE` 命中**不再锁死就绪门**。
89
+ `process_controller.py:332-345 wait_sdk_ready()` 的判据已经改成
90
+ `_sdk_ready_event.is_set() and snapshot.running`,注释里显式写明「不能再挂
91
+ `not snapshot.error`」(2026-09-10 18:32 假超时事故的修复)。`state.error` 今天
92
+ 唯一的消费者是 `:993-999`,只做「记一行 `[SLAM] ⚠` + 把 `status` 写成
93
+ `Error: …`」——**纯显示字段,没有任何控制流读它**(`status.startswith("error")`
94
+ 只有 `core/usb_glove_engine.py:237` 一处,那是手套引擎)。所以新增 error 文案的
95
+ 后果是「UI 状态栏可能闪一下」,不是「就绪门超时」。
96
+
97
+ ## P0.4 契约测试
98
+
99
+ ```sh
100
+ venv/bin/python core/gripper/orb_slam_src/tests/run_contract_tests.py # rc=0
101
+ QT_QPA_PLATFORM=offscreen venv/bin/python tools/tests/test_slam_ready_gate.py # ALL PASS
102
+ ```
103
+
104
+ 本机实测 **6 OK / 2 RED / 4 SKIP**(合计 12;`slam_engine_switch_contract`
105
+ 是第二步 2.1 时加的,见下文那节):
106
+
107
+ - OK:`fays_calibration_container(2/2)`、`fays_input_trace(4/4)`、
108
+ `orb_frame_lastkf_contract(4/4)`、`orb_stereo_baseline(3/3)`、`slam_offline_evaluation(6/6)`、
109
+ `slam_engine_switch_contract(11/11)`
110
+ - RED:`orb_mp_cleanup_contract(2F)`、`fays_historical_orb_contract(3F)`
111
+ - SKIP:`codec_benchmark`(缺 `yaml`)、`connect_debug` / `fays_sdk_shutdown` /
112
+ `fays_factory_calibration_contract`(都要 `online/` 上位机源码,本机没有)
113
+
114
+ ★ **必须用 `venv/bin/python`**,用 PATH 上的 conda(3.13 + 新 scipy)跑会多出 6 个
115
+ 假 RED:`slam_offline_evaluation` 的 `trajectory()` 用
116
+ `Rotation.from_euler('z', <1 维数组>)` 造合成轨迹,新 scipy 拒绝 1 维角度数组
117
+ (要求 `(N,1)`),6 个用例全 ERROR。`venv/bin/python` 是 3.10.20 + scipy 1.15.3,
118
+ 实测 OK 6/6 —— **是解释器差异,不是回归**。
119
+
120
+ **与主 README 那节的两处出入**(主 README 记的是「7 绿 4 红」):
121
+
122
+ 1. 主 README 记 7 绿含 `connect_debug`、`fays_sdk_shutdown`、
123
+ `fays_factory_calibration_contract` —— 它们标了 `*`,脚注写明「纯 clone 上没有
124
+ online 时整体 SkipTest(带原因,不算失败)」。本机 `online/` 不存在,所以是
125
+ SKIP 而非绿,**符合脚注,不算出入**。
126
+ 2. **真出入:`slam_offline_evaluation`**。主 README 红榜写 `slam_offline_evaluation(6)`,
127
+ 本机实测 **OK 6/6**。该文件 6 个用例全部加载本树的
128
+ `ORB-SLAM/Examples/fays/offline/evaluate.py` 喂**合成**轨迹,只依赖 numpy/scipy,
129
+ 没有任何 skip 逻辑;而这份 `evaluate.py` 与本树逐字节等同、SDK 树根本没有这份
130
+ 测试。⇒ 主 README 那条红是从 `online/tests/` 抄来的陈旧判决(online 那份
131
+ `evaluate.py` 是旧版本),**本树实测绿才是对的**。主 README 的表格把
132
+ `fays_factory_calibration_contract` 同时列进绿榜和红榜、又漏掉 `codec_benchmark`,
133
+ 一并记在此处以免下次再对不上。
134
+
135
+ ## P0.3 不能照原方案做(数据已备,跑法待定)
136
+
137
+ 原方案写的是「用 `run_suite.py` **跑一段录制**出 TUM+ATE/RPE」。查实后这句不成立:
138
+
139
+ 1. **`replay.cc` 吃的是 mav0 数据集,不是我们的 episode。** 生产桥接
140
+ `fayssense_orb_slam.cc:2259` 只收 `<vocab> <orb.yaml> <cam.yaml> [traj.txt]`,
141
+ 是实时采集二进制,**没有离线回放入口**;离线只有 `replay.cc` 这一条路,
142
+ 它要 `cam{0,1}/data.csv` + `imu0/data.csv`。
143
+ 2. **我们的录制里没有可转 mav0 的数据。** `data/recordings/<proj>/data/chunk-000/episode-*.parquet`
144
+ 的 23 列里只有 `observation.slam_trajectory{,_ns}`(SLAM 的**输出**);
145
+ `meta/info.json` 声明的 28 个特征里 `observation.imu`、`observation.slam_pose`
146
+ **没有落盘**。`videos/chunk-000/gripper_rgb/` 是 DECXIN **单目 RGB**
147
+ (一条一段),不是 SLAM 的双目对。⇒ SLAM 的双目+IMU 是实时消费、**从不持久化**,
148
+ 录完就没了。
149
+ 3. 所以离线 A/B 的数据只能来自公网:`fetch_dataset.py` 下 TUM-VI room1。
150
+ **2026-09-23 11:15 已下并解包完成**(当时根分区 98%,余 24 G):
151
+
152
+ | | 路径 | 实测量 |
153
+ |---|---|---|
154
+ | 解包后 | `/home/stouch/tumvi/dataset-room1_512_16/mav0/` | 3.2 G |
155
+ | 压缩包 | `/home/stouch/tumvi/dataset-room1_512_16.tar` | 1.6 G(**解包后可删,删了省 1.6 G**) |
156
+ | 校验记录 | `/home/stouch/tumvi/dataset_integrity.json` | `sha256=20354392…398f`,另记了 2 条跳过的 dso 软链 |
157
+
158
+ 内容:`cam0`/`cam1` 各 **2821** 帧、`imu0` **28123** 行、`mocap0` **16542** 行
159
+ (mocap 是真值,出 ATE 用得上;`dso/` 那部分没解,SLAM 不需要)。
160
+ 4. 另有两处待处理:`replay.cc` 需要构建(`offline/CMakeLists.txt` 在,未见产物);
161
+ `replay.cc:37,48` 对时间戳**要求严格单调**(非单调直接 `throw`),而本树基线里
162
+ 就有 75 次 `[TIME_DROP]` —— 用真机数据时得先决定怎么处理。
163
+
164
+ 已顺手修掉 `run_suite.py` 的**死路径**(原 `parents[4]/'gripper_version1'` 是
165
+ `online/` 时代写的,搬树后 sys.path 指向不存在的目录、整套 ImportError):
166
+ 改成向上探测 `core/gripper/fays_runtime.py` + `KSQ_COLLECTOR_ROOT` 覆盖口,
167
+ **不再硬编码深度**。`--help` 实测可跑。
168
+
169
+ **对 L3 判据的影响**:`s80m_stereo_inertial.yaml` 是**夹爪 rig 专用标定**,拿 TUM-VI
170
+ 喂它,绝对 ATE 数字没有意义;两引擎同数据集同配置跑的**相对**差异才有效
171
+ (rig 不匹配的劣势两边一样,会抵消)。L3 的判据应当据此表述。
172
+
173
+ ## SLAM SDK 接入已整体回退(2026-09-23)
174
+
175
+ 厂商 SLAM SDK v0.2.0(`tools/SLAM_SDK_upload`)的接入**全部撤销**:��轮真机会话
176
+ (13:52 / 14:10 / 14:21,都跑在 `engine=sdk`)反复出现 IMU 饥饿
177
+ (`Insufficient IMU measurements samples=1 coverage_s≈-0.020`)、惯性边丢失
178
+ (`ERROR building inertial edge` 1021 / 2373 / 6733)、跟踪器整段丢失、轨迹游走
179
+ ——结论是这条路不可用。回退到 SDK 接入之前的状态;**本地就有目标,不需要上 GitLab 取旧程序**。
180
+
181
+ | | 值 | 出处 |
182
+ |---|---|---|
183
+ | 桥接(**生产位,已换回**) | 234840 B `a76a602c…` | `….pre_rebuild_20260923_113609`(09-16 15:19)= SDK 前最后一版 |
184
+ | 桥接源码 | blob `3524fa97` | `d3f7306b`(= `30018f84` 的父提交)那一份 |
185
+ | 核心库 | 5442072 B `f3446320…` | **未动**(见下一节;本次回退不需要它) |
186
+
187
+ 回退三步与判据:
188
+
189
+ ```sh
190
+ D=core/gripper/native
191
+ # ① 先确认旧桥接不依赖 SDK:NEEDED 无 libslam_sdk.so.0、slam_sdk:: 未定义符号 0 条
192
+ readelf -d $D/dist/fays_opencv48/bin/fayssense_orb_slam_sn219_opencv48_mark_only | grep -c libslam_sdk # → 0
193
+ nm -DC --undefined-only $D/dist/fays_opencv48/bin/fayssense_orb_slam_sn219_opencv48_mark_only \
194
+ | grep -c 'slam_sdk::' # → 0
195
+ # ② 换生产位二进制(**顺序关键**:换完再删库;反了会让在役的 SDK 桥接装载失败)
196
+ cp -a $D/dist/fays_opencv48/bin/fayssense_orb_slam_sn219_opencv48_mark_only.pre_rebuild_20260923_113609 \
197
+ $D/dist/fays_opencv48/bin/fayssense_orb_slam_sn219_opencv48_mark_only
198
+ # ③ 删 SDK 运行库
199
+ rm -f $D/dist/orb_mark_only/lib/libslam_sdk.so{,.0,.0.2.0}
200
+ ```
201
+
202
+ **这次只换桥接、不动核心库**(与 2.1 那节「两个文件同进同退」相反):回退后的桥接调的是
203
+ `System::MapChanged()`,现役核心库同时导出它和 `GetRuntimeMapChangeIndex()` ⇒ 该桥接的全部
204
+ 未定义符号都有定义。**回退源码也不丢任何 legacy 功能**:`Host:(<ns>)`、`[TIME_DROP]`、
205
+ `[TIME_REBASE]`、`[POSE_REBASE]`、`[POSE_HOLD]`、`TimeRegressionGuard`、CPU 亲和与
206
+ `[FAYS-AFFINITY]` 在父提交里**全都已存在**(逐项与 `a76a602c` 对过),唯一被撤掉的是只在
207
+ SDK 路径生效的 `g_sdk_imu_carry`。
208
+
209
+ **已删除**(本次):`orb_slam_src/slam_sdk/`(厂商源码树 67 文件)、`build.sh` 的 SDK 构建段
210
+ (段序回到 `1/3 DBoW2 → 2/3 核心库 → 3/3 桥接`)、`dist/fays_opencv48/CMakeLists.txt` 的
211
+ `KSQ_SLAM_SDK_*` 挂载点、契约测试 `test_slam_engine_switch_contract.py`(及
212
+ `run_contract_tests.py` 里的条目)、`process_controller.py` 的 `DEFAULT_SLAM_ENGINE` 注入点、
213
+ `tools/tests/test_slam_ready_gate.py` 的 [9] 节、部署位 `libslam_sdk.so{,.0,.0.2.0}`、
214
+ 带 SDK 路径的构建缓存(`build/slam_sdk*` 与 `build/bridge`)。
215
+ 厂商交付目录 `tools/SLAM_SDK_upload/`(159MB)一并删除,留档
216
+ `~/SLAM_SDK_upload_20260923.tgz`(5.7MB;**已排除**那份与 `native/ORBvoc.txt`
217
+ 逐字节相同(`5420bad0…`)的 139MB 词典,需要时从 `native/` 取)。
218
+
219
+ **保留**:`System.h` / `System.cc` 的只读适配接口与 `GetRuntimeMapChangeIndex()`(它们在
220
+ 现役核心库 `f3446320` 里,删掉要重编核心库,而回退只需换桥接);`pre_sdk_swap_lines.json`、
221
+ `bridge.readelf-d.txt`、`bridge.symbols.txt.gz`、`libORB_SLAM3.*` 与
222
+ `tools/audit_slam_line_classes.py` 属 P0 记录与通用工具,不是桥接程序。
223
+
224
+ **L1 实测(回退后)**:契约测试 **12 模块 / 6 OK / 4 SKIP / 2 RED**(RED 的两个是本就陈旧的
225
+ 契约,与 SDK 无关),`test_orb_preintegration_guard_contract` 6/6 OK;
226
+ `tools/tests/test_slam_ready_gate.py` **ALL PASS**。
227
+ **L2 实测(回退后)**:真实 `LD_LIBRARY_PATH`(`build_fays_runtime_env()`)下桥接 `ldd`
228
+ not found = 0、`ldd -r` undefined symbol = 0、`libORB_SLAM3.so` 只解析到一处、
229
+ `libslam_sdk` 一行都没有。
230
+ **未做**:L3 真机复验——起主程序录一段,看日志里没有 `[SLAM_ENGINE]`/`[SDK_IMU]`、
231
+ 没有 `Insufficient IMU measurements samples=1`、位姿列非零、`[FPS_DATA] image≈50 imu≈1000`。
232
+
233
+ ### 空预积分守卫修复(2026-09-23 13:43:51 装入,**桥接未动**)
234
+
235
+ 换 SDK 引擎后「主程序一解算就崩」的根因:`Optimizer::InertialOptimization`
236
+ (11 参数重载)的加边循环里,判空是**只打印不跳过**的形态 ——
237
+
238
+ ```cpp
239
+ if(!pKFi->mpImuPreintegrated)
240
+ std::cout << "Not preintegrated measurement" << std::endl;
241
+ pKFi->mpImuPreintegrated->SetNewBias(...); // ← 下一行照样解引用
242
+ ```
243
+
244
+ 原生日志在 `[FATAL_SIGNAL]` 前一行正是那句打印。空预积分是**设计内的合法态**
245
+ (`Tracking.cc` 里 IMU 空档期建的关键帧就写 `NULL`),所以这不是竞态,是
246
+ 「没处理的分支」。同族共 5 处,形态各不相同(只打印不跳过 / 连打印都没有 /
247
+ 只看 `bImu` / 赋值派生 / 清理路径),全部补上判空 + 跳过。
248
+
249
+ | | 大小 | md5 | 说明 |
250
+ |---|---|---|---|
251
+ | `libORB_SLAM3.so`(**新**) | 5442072 | `f3446320…` | 5 处判空 |
252
+ | 同上(回退点) | 5442072 | `583a3533…` | 存为 `….pre_rebuild_20260923_134351` |
253
+ | 桥接 | 240688 | `92855fd2…` | **未重编**(这次只动核心库) |
254
+
255
+ **回退只需换一个文件**(与 2.1 那节不同,那次桥接也换了):
256
+
257
+ ```sh
258
+ cp -a core/gripper/native/dist/orb_mark_only/lib/libORB_SLAM3.so.pre_rebuild_20260923_134351 \
259
+ core/gripper/native/dist/orb_mark_only/lib/libORB_SLAM3.so
260
+ ```
261
+
262
+ L1 实测:导出符号集 6946 → 6946 **零增零减**;`readelf -d` 的
263
+ NEEDED/RPATH/RUNPATH/FLAGS 与回退点**逐字符相同**;同一环境下新旧库
264
+ `ldd -r` 输出**逐字节相同**(含同样的 10 项 not-found —— 那是我少给
265
+ `LD_LIBRARY_PATH` 造成的,不是回归);原生 ctest **7/7**;
266
+ `test_orb_preintegration_guard_contract` **6/6 OK**(全套 12 模块,
267
+ RED 的仍是那 2 个陈旧契约)。
268
+
269
+ `Not preintegrated measurement` **不命中** `_ERROR_RE`(`protocol.py:96`),
270
+ 不会把 UI 锁进 Error。
271
+
272
+ **未做**:L4 真机验收。当初让触发变密的上游条件(SDK 引擎路径按 `imu_ts <= ts` 过滤 IMU
273
+ ⇒ IMU 饥饿更频繁 ⇒ NULL 预积分的关键帧更多)已随 SDK 接入整体回退而消失,但这 5 处判空
274
+ **是在役修复,不要回退**——空预积分本身是设计内的合法态,legacy 路径同样会产生(只是撞得少)。
275
+ 守卫让那些帧**被静默跳过**(少一条惯性边)而不是崩,所以「不崩了」不等于「解算变好了」,
276
+ 量级看那句 `Not preintegrated measurement` 的行数。
277
+
278
+ ## 注意
279
+
280
+ - `readelf -d` 里 **RPATH/NEEDED/FLAGS 必须逐字符相同**,这是主 README 记的成败判据。
281
+ (换 SDK 核那次唯一的故意改动是「新增对 `libslam_sdk.so` 的 NEEDED」,已随回退撤销。)
282
+ - 源码树**路径**会经 `__FILE__` 进 `.rodata`,所以 md5 不同**不代表**代码不同。
283
+ 判「是不是同一份代码」要看主 README 记的四层比对,不要只看 md5。
284
+ - 与其手工跑上面三行,不如直接用 `orb_slam_src/README.md` 里的重编脚本流程;
285
+ 本目录只是把「改动前长什么样」钉死。
collector/core/gripper/orb_slam_src/tests/baselines/bridge.readelf-d.txt ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Dynamic section at offset 0x2e5f8 contains 40 entries:
3
+ 标记 类型 名称/值
4
+ 0x0000000000000001 (NEEDED) 共享库:[libfays_vikit.so]
5
+ 0x0000000000000001 (NEEDED) 共享库:[libopencv_calib3d.so.408]
6
+ 0x0000000000000001 (NEEDED) 共享库:[libORB_SLAM3.so]
7
+ 0x0000000000000001 (NEEDED) 共享库:[libopencv_imgcodecs.so.408]
8
+ 0x0000000000000001 (NEEDED) 共享库:[libopencv_imgproc.so.408]
9
+ 0x0000000000000001 (NEEDED) 共享库:[libopencv_core.so.408]
10
+ 0x0000000000000001 (NEEDED) 共享库:[libpango_display.so.0]
11
+ 0x0000000000000001 (NEEDED) 共享库:[libpango_opengl.so.0]
12
+ 0x0000000000000001 (NEEDED) 共享库:[libepoxy.so.0]
13
+ 0x0000000000000001 (NEEDED) 共享库:[libstdc++.so.6]
14
+ 0x0000000000000001 (NEEDED) 共享库:[libm.so.6]
15
+ 0x0000000000000001 (NEEDED) 共享库:[libgcc_s.so.1]
16
+ 0x0000000000000001 (NEEDED) 共享库:[libc.so.6]
17
+ 0x000000000000000f (RPATH) Library rpath: [/usr/local/lib:$ORIGIN/../../../FaysSense_VI_Kit_Release/lib/fays_atrak/x86_64/Release:$ORIGIN/../../../FaysSense_VI_Kit_Release/thirdparty/ft602-linux-x86_64:/home/stouch/collector/core/gripper/native/dist/orb_mark_only/lib:$ORIGIN/../../../ORB-SLAM/Thirdparty/DBoW2/lib:$ORIGIN/../../../ORB-SLAM/Thirdparty/g2o/lib]
18
+ 0x000000000000000c (INIT) 0x8000
19
+ 0x000000000000000d (FINI) 0x27d74
20
+ 0x0000000000000019 (INIT_ARRAY) 0x2efc8
21
+ 0x000000000000001b (INIT_ARRAYSZ) 16 (bytes)
22
+ 0x000000000000001a (FINI_ARRAY) 0x2efd8
23
+ 0x000000000000001c (FINI_ARRAYSZ) 8 (bytes)
24
+ 0x000000006ffffef5 (GNU_HASH) 0x3e8
25
+ 0x0000000000000005 (STRTAB) 0x2390
26
+ 0x0000000000000006 (SYMTAB) 0x668
27
+ 0x000000000000000a (STRSZ) 11308 (bytes)
28
+ 0x000000000000000b (SYMENT) 24 (bytes)
29
+ 0x0000000000000015 (DEBUG) 0x0
30
+ 0x0000000000000003 (PLTGOT) 0x2f8b8
31
+ 0x0000000000000002 (PLTRELSZ) 5256 (bytes)
32
+ 0x0000000000000014 (PLTREL) RELA
33
+ 0x0000000000000017 (JMPREL) 0x5cf0
34
+ 0x0000000000000007 (RELA) 0x5420
35
+ 0x0000000000000008 (RELASZ) 2256 (bytes)
36
+ 0x0000000000000009 (RELAENT) 24 (bytes)
37
+ 0x0000000000000018 (BIND_NOW)
38
+ 0x000000006ffffffb (FLAGS_1) 标志: NOW PIE
39
+ 0x000000006ffffffe (VERNEED) 0x5230
40
+ 0x000000006fffffff (VERNEEDNUM) 4
41
+ 0x000000006ffffff0 (VERSYM) 0x4fbc
42
+ 0x000000006ffffff9 (RELACOUNT) 36
43
+ 0x0000000000000000 (NULL) 0x0
collector/core/gripper/orb_slam_src/tests/baselines/bridge.symbols.txt.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a00ab1302392a5cbb66baccc3c85b16cc2350b800a5ebd2ff6eff4b57e24cbb
3
+ size 863
collector/core/gripper/orb_slam_src/tests/baselines/libORB_SLAM3.readelf-d.txt ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Dynamic section at offset 0x4282a0 contains 43 entries:
3
+ 标记 类型 名称/值
4
+ 0x0000000000000001 (NEEDED) 共享库:[libDBoW2.so]
5
+ 0x0000000000000001 (NEEDED) 共享库:[libg2o.so]
6
+ 0x0000000000000001 (NEEDED) 共享库:[libboost_serialization.so.1.83.0]
7
+ 0x0000000000000001 (NEEDED) 共享库:[libcrypto.so.3]
8
+ 0x0000000000000001 (NEEDED) 共享库:[libopencv_highgui.so.408]
9
+ 0x0000000000000001 (NEEDED) 共享库:[libopencv_calib3d.so.408]
10
+ 0x0000000000000001 (NEEDED) 共享库:[libopencv_features2d.so.408]
11
+ 0x0000000000000001 (NEEDED) 共享库:[libopencv_imgproc.so.408]
12
+ 0x0000000000000001 (NEEDED) 共享库:[libopencv_core.so.408]
13
+ 0x0000000000000001 (NEEDED) 共享库:[libpango_display.so.0]
14
+ 0x0000000000000001 (NEEDED) 共享库:[libpango_vars.so.0]
15
+ 0x0000000000000001 (NEEDED) 共享库:[libpango_opengl.so.0]
16
+ 0x0000000000000001 (NEEDED) 共享库:[libepoxy.so.0]
17
+ 0x0000000000000001 (NEEDED) 共享库:[libpango_core.so.0]
18
+ 0x0000000000000001 (NEEDED) 共享库:[libstdc++.so.6]
19
+ 0x0000000000000001 (NEEDED) 共享库:[libm.so.6]
20
+ 0x0000000000000001 (NEEDED) 共享库:[libgcc_s.so.1]
21
+ 0x0000000000000001 (NEEDED) 共享库:[libc.so.6]
22
+ 0x000000000000000e (SONAME) Library soname: [libORB_SLAM3.so]
23
+ 0x000000000000001d (RUNPATH) Library runpath: [/usr/local/lib:$ORIGIN/../../../ORB-SLAM/Thirdparty/DBoW2/lib:$ORIGIN/../../../ORB-SLAM/Thirdparty/g2o/lib:$ORIGIN]
24
+ 0x000000000000000c (INIT) 0x12b000
25
+ 0x000000000000000d (FINI) 0x3bcc34
26
+ 0x0000000000000019 (INIT_ARRAY) 0x41abd0
27
+ 0x000000000000001b (INIT_ARRAYSZ) 168 (bytes)
28
+ 0x000000000000001a (FINI_ARRAY) 0x41ac78
29
+ 0x000000000000001c (FINI_ARRAYSZ) 8 (bytes)
30
+ 0x000000006ffffef5 (GNU_HASH) 0x2f0
31
+ 0x0000000000000005 (STRTAB) 0x389c8
32
+ 0x0000000000000006 (SYMTAB) 0xcf70
33
+ 0x000000000000000a (STRSZ) 727576 (bytes)
34
+ 0x000000000000000b (SYMENT) 24 (bytes)
35
+ 0x0000000000000003 (PLTGOT) 0x42cfe8
36
+ 0x0000000000000002 (PLTRELSZ) 39672 (bytes)
37
+ 0x0000000000000014 (PLTREL) RELA
38
+ 0x0000000000000017 (JMPREL) 0x120870
39
+ 0x0000000000000007 (RELA) 0xee068
40
+ 0x0000000000000008 (RELASZ) 206856 (bytes)
41
+ 0x0000000000000009 (RELAENT) 24 (bytes)
42
+ 0x000000006ffffffe (VERNEED) 0xede18
43
+ 0x000000006fffffff (VERNEEDNUM) 5
44
+ 0x000000006ffffff0 (VERSYM) 0xea3e0
45
+ 0x000000006ffffff9 (RELACOUNT) 43
46
+ 0x0000000000000000 (NULL) 0x0
collector/core/gripper/orb_slam_src/tests/baselines/libORB_SLAM3.symbols.txt.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f621bdbaf2370733a5892bd55a06c4bad724a0b1e04451bc94f2a483d78302d
3
+ size 45612
collector/core/gripper/orb_slam_src/tests/baselines/pre_sdk_swap_lines.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "error_classified": {
3
+ "2026-09-20 11:40:42.617 [ ERROR] StereoOnlineCapture(): get img failed": 1,
4
+ "2026-09-20 11:40:42.649 [ ERROR] ImuOnlineCapture(): DQBUF error: Invalid argumentIMU FPS: 997.640204": 1,
5
+ "ERROR building inertial edge": 1106,
6
+ "Failed to dequeue buffer": 1,
7
+ "Δq(ERROR building inertial edge10f):": 1
8
+ },
9
+ "error_re_raw": {
10
+ "2026-09-20 11:40:42.617 [ ERROR] StereoOnlineCapture(): get img failed": 1,
11
+ "2026-09-20 11:40:42.649 [ ERROR] ImuOnlineCapture(): DQBUF error: Invalid argumentIMU FPS: 997.640204": 1,
12
+ "ERROR building inertial edge": 1106,
13
+ "Failed to dequeue buffer": 1,
14
+ "[FAYS-CALIB] WARN SetStereoFPS(50) failed": 19,
15
+ "Δq(ERROR building inertial edge10f):": 1
16
+ },
17
+ "file_count": 20,
18
+ "kinds": {
19
+ "affinity": 5379,
20
+ "error": 1110,
21
+ "fays_rates": 5326,
22
+ "log": 44161,
23
+ "mp_cleanup": 5255,
24
+ "orb_diagnostic": 5361,
25
+ "orb_stage": 5401,
26
+ "origin": 17,
27
+ "pose": 154828,
28
+ "ready": 17,
29
+ "status": 716,
30
+ "time_drop": 75
31
+ },
32
+ "log_dir": "/home/stouch/collector/logs/slam_native",
33
+ "parsed_lines_total": 227646,
34
+ "per_file_parsed": {
35
+ "20260918_170654_3500000262300098_slam_stdout.log": 577,
36
+ "20260918_171611_3500000262300098_slam_stdout.log": 21894,
37
+ "20260918_172033_3500000262300098_slam_stdout.log": 4062,
38
+ "20260918_172832_3500000262300098_slam_stdout.log": 18572,
39
+ "20260918_174843_3500000262300098_slam_stdout.log": 49206,
40
+ "20260920_102832_3500000262300098_slam_stdout.log": 17496,
41
+ "20260920_104215_3500000262300098_slam_stdout.log": 28522,
42
+ "20260920_104605_3500000262300098_slam_stdout.log": 4638,
43
+ "20260920_104815_3500000262300098_slam_stdout.log": 3371,
44
+ "20260920_111212_3500000262300098_slam_stdout.log": 15994,
45
+ "20260920_113632_3500000262300098_slam_stdout.log": 3311,
46
+ "20260920_113830_3500000262300098_slam_stdout.log": 3869,
47
+ "20260920_114045_3500000262300098_slam_stdout.log": 281,
48
+ "20260920_140606_3500000262300098_slam_stdout.log": 5202,
49
+ "20260921_111153_3500000262300098_slam_stdout.log": 4111,
50
+ "20260921_112000_3500000262300098_slam_stdout.log": 19645,
51
+ "20260921_112804_3500000262300098_slam_stdout.log": 18018,
52
+ "20260921_115938_3500000262300098_slam_stdout.log": 85,
53
+ "20260921_162111_3500000262300098_slam_stdout.log": 4,
54
+ "20260921_162558_3500000262300098_slam_stdout.log": 8788
55
+ }
56
+ }
collector/core/gripper/orb_slam_src/tests/run_contract_tests.py CHANGED
@@ -1,7 +1,7 @@
1
  #!/usr/bin/env python3
2
- """跑本目录的 11 个 Python 契约测试(只读 ORB/桥接源码,不需要硬件)。
3
 
4
- 为什么需要这个加载器,而不是 `python test_x.py`:这 11 份里有 4 份
5
  (test_connect_debug、test_fays_sdk_shutdown、test_orb_stereo_baseline、
6
  test_slam_offline_evaluation)**没有 `unittest.main()` 入口** —— 直接执行等于
7
  只 import 一遍就退出,**rc=0、零输出**,看起来全绿。本加载器按模块加载,
@@ -12,7 +12,7 @@ test_slam_offline_evaluation)**没有 `unittest.main()` 入口** —— 直接
12
  python tests/run_contract_tests.py # 从本树任意位置
13
  python core/gripper/orb_slam_src/tests/run_contract_tests.py
14
 
15
- 退出码:0 = 全部加载成功(含已知的 4 个 RED —— 陈旧契约,见 README);
16
  1 = 有模块 import 失败(那才是环境问题)。
17
  """
18
  import importlib.util
@@ -31,6 +31,7 @@ TESTS = [
31
  "test_fays_sdk_shutdown",
32
  "test_orb_frame_lastkf_contract",
33
  "test_orb_mp_cleanup_contract",
 
34
  "test_orb_stereo_baseline",
35
  "test_slam_offline_evaluation",
36
  ]
@@ -61,11 +62,14 @@ def verdict(path: Path) -> tuple[str, bool]:
61
  def main() -> int:
62
  here = Path(__file__).resolve().parent
63
  broken = False
 
64
  for stem in TESTS:
65
  text, failed = verdict(here / f"{stem}.py")
66
  broken = broken or failed
 
67
  print(f" {stem:44s} {text}")
68
- print(f"\n 共 {len(TESTS)} 个模块;RED 的 4 个是**本来就红**的陈旧契约"
 
69
  f"(见 README「Python 契约测试」)。")
70
  return 1 if broken else 0
71
 
 
1
  #!/usr/bin/env python3
2
+ """跑本目录的 12 个 Python 契约测试(只读 ORB/桥接源码,不需要硬件)。
3
 
4
+ 为什么需要这个加载器,而不是 `python test_x.py`:这 12 份里有 4 份
5
  (test_connect_debug、test_fays_sdk_shutdown、test_orb_stereo_baseline、
6
  test_slam_offline_evaluation)**没有 `unittest.main()` 入口** —— 直接执行等于
7
  只 import 一遍就退出,**rc=0、零输出**,看起来全绿。本加载器按模块加载,
 
12
  python tests/run_contract_tests.py # 从本树任意位置
13
  python core/gripper/orb_slam_src/tests/run_contract_tests.py
14
 
15
+ 退出码:0 = 全部加载成功(含已知的 2 个 RED —— 陈旧契约,见 README);
16
  1 = 有模块 import 失败(那才是环境问题)。
17
  """
18
  import importlib.util
 
31
  "test_fays_sdk_shutdown",
32
  "test_orb_frame_lastkf_contract",
33
  "test_orb_mp_cleanup_contract",
34
+ "test_orb_preintegration_guard_contract",
35
  "test_orb_stereo_baseline",
36
  "test_slam_offline_evaluation",
37
  ]
 
62
  def main() -> int:
63
  here = Path(__file__).resolve().parent
64
  broken = False
65
+ red = 0
66
  for stem in TESTS:
67
  text, failed = verdict(here / f"{stem}.py")
68
  broken = broken or failed
69
+ red += text.startswith("RED")
70
  print(f" {stem:44s} {text}")
71
+ # 红模块数**数出来**,不写字面量:加一个模块就手改一次数字,早晚改成假的
72
+ print(f"\n 共 {len(TESTS)} 个模块;RED 的 {red} 个是**本来就红**的陈旧契约"
73
  f"(见 README「Python 契约测试」)。")
74
  return 1 if broken else 0
75
 
collector/core/gripper/orb_slam_src/tests/test_orb_preintegration_guard_contract.py ADDED
@@ -0,0 +1,490 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """静态安全契约:`mpImuPreintegrated` 的每一处解引用都必须判空。
3
+
4
+ 2026-09-23 的 SIGSEGV(`fault_addr=0x8b8`)回溯为
5
+ `IMU::Preintegrated::SetNewBias` ← `Optimizer::InertialOptimization`
6
+ ← `LocalMapping::InitializeIMU+0x87b` ← `LocalMapping::Run+0x66e`,
7
+ 原生日志在 `[FATAL_SIGNAL]` 前一行正是 `Not preintegrated measurement`。
8
+
9
+ 根因不是「多线程竞态」,而是一句**只打印不跳过**的判空:
10
+
11
+ if(!pKFi->mpImuPreintegrated)
12
+ std::cout << "Not preintegrated measurement" << std::endl;
13
+
14
+ pKFi->mpImuPreintegrated->SetNewBias(...); // ← 下一行照样解引用
15
+
16
+ 打印出来说明**这个状态真会发生**,而代码什么都没做。空预积分是设计内的合法态
17
+ (`Tracking.cc` 里 IMU 空档期建的关键帧就写 `mpImuPreintegrated=NULL`),
18
+ 所以这不是「异常输入」,是「没处理的分支」。
19
+
20
+ 同一族本轮共查出 5 处,形态各不相同(只打印不跳过 / 连打印都没有 / 只看
21
+ `bImu` / 赋值派生 / 清理路径),所以本测试**不逐条点名**,而是验证那条通用
22
+ 不变量——「任何解引用都必须被某处判空支配」。四种判定规则对应树里真实存在的
23
+ 四种写法:
24
+
25
+ R0 同行短路:`!pFrame->mpImuPreintegrated || !(pFrame->mpImuPreintegrated->dT > 0.f)`
26
+ R1 外层条件:解引用所在的 `if/for/while` 条件里提到了同一对象
27
+ R2 跳过式守卫:前面有 `if(!<对象>)`,其语句体(块**或单条语句**,
28
+ 花括号可以写在下一行)以 continue/return 结束,中间没有再赋值,
29
+ 且**与解引用同层支配**(光判「守卫体结束在解引用之前」不够,
30
+ 见 `_dominates`)
31
+ R3 正向守卫:前面有 `if(<对象>)` 且紧接的就是本条语句(无花括号写法)
32
+
33
+ 扫描器本身也要反向验证(`test_scanner_keeps_its_teeth`):把本轮的 5 处
34
+ 修复逐一改回原样,扫描器必须变红。理由是最下面那条 R2 曾被证伪过一次 ——
35
+ 第一版扫描器在这 5 处里对 `LocalMapping` 那处**毫无反应**,因为更早的计数
36
+ 循环里有个同名的守卫替它「顶」了,只是那个块早就闭合了。全绿的扫描器
37
+ 不等于有牙的扫描器。
38
+
39
+ 为什么不用「往回数 N 行」:第一版审计脚本那样做,在 `FullInertialBA` 上把
40
+ **已被外层判空支配**的 `C.block(9,9)` 误报成危险(判空在 60 行外),又在
41
+ `LocalMapping` 上漏掉了正向写法 `if(keyFrame->mpImuPreintegrated)`。两种误判
42
+ 都会让人去改本来正确的代码。
43
+
44
+ 扫描前先剥掉注释与字符串字面量:本次修复自己写的注释里就含
45
+ `mpImuPreintegrated` 字样,不剥注释的扫描器会被自己骗过。
46
+
47
+ 原生侧的行为验证在 tests/native/(ctest 名见 CMakeLists)。
48
+ """
49
+
50
+ from pathlib import Path
51
+ import re
52
+ import unittest
53
+
54
+
55
+ ROOT = Path(__file__).resolve().parents[1]
56
+ SRC = ROOT / "ORB-SLAM/src"
57
+ INCLUDE = ROOT / "ORB-SLAM/include"
58
+
59
+ MEMBER = r"mpImuPreintegrated(?:Frame)?"
60
+
61
+ # 解引用点:<链>->mpImuPreintegrated-> 或 <链>.mpImuPreintegrated->
62
+ # 链**按结构**拼(基址 + 若干个成员步),不能用扁平字符类:把 `(` 和 `\w`
63
+ # 放进同一个类里,`(pFrame->mpImuPreintegrated` 会被当成「类匹配到 (pFrame」
64
+ # 而整串吞掉,身份随之变成 `(pFrame->mpImuPreintegrated`,与守卫对不上;
65
+ # 反过来若不含 `(`,`(*itKF)->mpImuPreintegrated` 从 `)` 起抓又变成
66
+ # `itKF)`(`\w` 吃掉了 itKF)。两种错法都真发生过。
67
+ _BASE = r"(?:\(\s*\*\s*\w+\s*\)|\w+)"
68
+ _STEP = r"(?:->|\.)\s*\w+"
69
+ DEREF = re.compile(rf"({_BASE}(?:\s*{_STEP})*)\s*(->|\.)\s*({MEMBER})\s*->")
70
+
71
+
72
+ def _identity(chain, sep, member):
73
+ """只取链的最后一段做身份:守卫也写作同样的末段(见模块 docstring)。"""
74
+ last = re.split(r"(?:->|\.)", chain)[-1].strip()
75
+ return f"{last}{sep}{member}"
76
+
77
+
78
+ def _mentions(text, ident):
79
+ """text 里是否提到该对象。
80
+
81
+ 用 `(?<!\\w)`/`(?!\\w)` 而不是 `\\b`:身份可能以 `(` 开头
82
+ (`(*itKF)->mpImuPreintegrated`),而 `(` 与它前面的 `!` 之间没有词边界,
83
+ `\\b(` 永远匹配不上。同时这个写法仍能挡住 `xmpImuPreintegrated` 这种后缀误配。
84
+ """
85
+ return re.search(rf"(?<!\w){re.escape(ident)}(?!\w)", text) is not None
86
+
87
+
88
+ def _strip_comments_and_strings(lines):
89
+ """剥掉 // 注释、/* */ 注释与字符串字面量,其余原样(够用的精度即可)。"""
90
+ out, in_block = [], False
91
+ for line in lines:
92
+ buf, i, quote = [], 0, None
93
+ while i < len(line):
94
+ two = line[i:i + 2]
95
+ if in_block:
96
+ if two == "*/":
97
+ in_block = False
98
+ i += 2
99
+ else:
100
+ i += 1
101
+ continue
102
+ ch = line[i]
103
+ if quote:
104
+ if ch == "\\":
105
+ i += 2
106
+ continue
107
+ if ch == quote:
108
+ quote = None
109
+ i += 1
110
+ continue
111
+ if two == "//":
112
+ break
113
+ if two == "/*":
114
+ in_block = True
115
+ i += 2
116
+ continue
117
+ if ch in "\"'":
118
+ quote = ch
119
+ i += 1
120
+ continue
121
+ buf.append(ch)
122
+ i += 1
123
+ out.append("".join(buf))
124
+ return out
125
+
126
+
127
+ def _block_end(lines, brace_line, brace_col):
128
+ """从 lines[brace_line][brace_col] 的 '{' 起配平,返回 (结束行, 结束列)。"""
129
+ depth = 0
130
+ for r in range(brace_line, len(lines)):
131
+ start = brace_col if r == brace_line else 0
132
+ for c in range(start, len(lines[r])):
133
+ if lines[r][c] == "{":
134
+ depth += 1
135
+ elif lines[r][c] == "}":
136
+ depth -= 1
137
+ if depth == 0:
138
+ return r, c
139
+ return None, None
140
+
141
+
142
+ def _condition_above(lines, brace_line, brace_col):
143
+ """返回开启该 '{' 的控制语句条件文本(找不到返回 None)。
144
+
145
+ 条件可能跨行,必须**整段拼起来**再返回:`if(a && b &&` 换行 `c)` 这种写法
146
+ 下,只返回第一行会得到不含 `c` 的残句,把已被支配的解引用误判成没守卫
147
+ (LocalMapping::KeyFrameCulling 的预积分判空正是这种写法)。
148
+ """
149
+ same = lines[brace_line][:brace_col]
150
+ r = brace_line
151
+ while r >= 0 and brace_line - r <= 6:
152
+ candidate = same if r == brace_line else lines[r]
153
+ if re.search(r"\b(if|for|while|else)\b", candidate):
154
+ joined = "\n".join(lines[r:brace_line] + [same])
155
+ return " ".join(joined.split())
156
+ r -= 1
157
+ return None
158
+
159
+
160
+ def _enclosing_conditions(lines, index):
161
+ """包住 lines[index] 的所有控制语句条件(由内到外)。"""
162
+ conds, depth = [], 0
163
+ r = index
164
+ while r >= 0:
165
+ line = lines[r]
166
+ for c in range(len(line) - 1, -1, -1):
167
+ ch = line[c]
168
+ if ch == "}":
169
+ depth += 1
170
+ elif ch == "{":
171
+ if depth == 0:
172
+ cond = _condition_above(lines, r, c)
173
+ if cond:
174
+ conds.append(cond)
175
+ else:
176
+ depth -= 1
177
+ r -= 1
178
+ return conds
179
+
180
+
181
+ def _condition_end(lines, cond_line, limit=6):
182
+ """条件文本的结束行:从 cond_line 起数圆括号,配平的那一行。
183
+
184
+ 没有它就会把条件的续行当成语句:`if (!a || !b ||` 换行 `!c)` 换行 `{`
185
+ 这种写法下,`_statement_body` 会认第 2 行为「单条语句」,于是那个真正
186
+ 的 `{` 块永远找不到,守卫体里也就找不到 return。
187
+ """
188
+ bal = 0
189
+ for r in range(cond_line, min(len(lines), cond_line + limit)):
190
+ bal += lines[r].count("(") - lines[r].count(")")
191
+ if bal <= 0:
192
+ return r
193
+ return cond_line
194
+
195
+
196
+ def _brace_depths(lines):
197
+ """每行**行首**的花括号嵌套深度(剥注释后按行数,够用的精度即可)。"""
198
+ depths, d = [], 0
199
+ for line in lines:
200
+ depths.append(d)
201
+ d += line.count("{") - line.count("}")
202
+ return depths
203
+
204
+
205
+ def _dominates(depths, guard_line, body_end, index):
206
+ """跳过式守卫是否**支配** index:同层,且中途没有退出那一层。
207
+
208
+ 只用「守卫体结束在解引用之前」判是不够的 —— 那等于说「文件里前面某处
209
+ 有个 continue」,跟这个解引用在不在它辖内毫无关系。清理路径里那个
210
+ `if(!keyFrame->mpImuPreintegrated || ...) { ...; break; }` 属于更早的
211
+ 计数循环、块早就闭合了,却会「保护」到 80 行以外、跨了两个 for 的解引用:
212
+ 反向验证(真的把守卫摘掉)时正是它把红挡住了。
213
+ """
214
+ d = depths[guard_line]
215
+ if depths[index] != d:
216
+ return False
217
+ return min(depths[body_end:index + 1]) >= d
218
+
219
+
220
+ def _scope_start(lines, index):
221
+ """最近的上一个顶格行 —— 本树函数定义都顶格,用它给回看划界。
222
+
223
+ 不划界就得靠「往回数 N 行」:N 小了会漏掉函数开头就设好的早退守卫
224
+ (PoseInertialOptimizationLastKeyFrame 的守卫在解引用前 200 行开外),
225
+ N 大了又会把上一个函数里的同名守卫算进来。
226
+ """
227
+ for r in range(index - 1, -1, -1):
228
+ if lines[r] and not lines[r][0].isspace():
229
+ return r
230
+ return 0
231
+
232
+
233
+ def _statement_body(lines, cond_line, limit=6):
234
+ """条件行所辖的语句体 → (文本, 结束行号),认不出返回 (None, None)。
235
+
236
+ 本树三种写法都要认:`if(...) {` 同行开块、`if(...)` 换行 `{`、
237
+ `if(!x)` 换行 `continue;`(单条语句、没有花括号),且条件本身可跨行。
238
+ """
239
+ cond_line = _condition_end(lines, cond_line, limit)
240
+ brace = lines[cond_line].find("{")
241
+ if brace != -1:
242
+ end_r, _ = _block_end(lines, cond_line, brace)
243
+ if end_r is None:
244
+ return None, None
245
+ return "\n".join(lines[cond_line:end_r + 1]), end_r
246
+ r = cond_line + 1
247
+ while r < len(lines) and r - cond_line <= limit:
248
+ if not lines[r].strip():
249
+ r += 1
250
+ continue
251
+ b = lines[r].find("{")
252
+ if b != -1:
253
+ end_r, _ = _block_end(lines, r, b)
254
+ if end_r is None:
255
+ return None, None
256
+ return "\n".join(lines[cond_line:end_r + 1]), end_r
257
+ # 单条语句,且它自己也可能跨行(`if(x)` 换行 `sum +=` 换行 `f();`),
258
+ # 所以要续到出现 `;` 为止,否则语句体截断、end_row 落在解引用之前。
259
+ rr = r
260
+ while rr < len(lines) and rr - cond_line <= limit + 4:
261
+ if ";" in lines[rr]:
262
+ break
263
+ rr += 1
264
+ return "\n".join(lines[cond_line:rr + 1]), rr
265
+ return None, None
266
+
267
+
268
+ def _condition_start(lines, j, limit=5):
269
+ """提到本对象的第 j 行往上找辖它的 `if` 行。
270
+
271
+ 条件是允许跨行的(`if (!a || !b ||` 换行 `!c)`),所以不能要求 `if` 与
272
+ 对象名同行 —— 只要求往上几行内出现 `if`,且中途没有语句结束符。
273
+ """
274
+ k = j
275
+ while k >= 0 and j - k <= limit:
276
+ if re.search(r"\bif\b", lines[k]):
277
+ return k
278
+ if k != j and re.search(r"[;{}]", lines[k]):
279
+ return None
280
+ k -= 1
281
+ return None
282
+
283
+
284
+ def _guard_before(lines, index, col, ident, depths=None):
285
+ """支配 lines[index][col] 处解引用的守卫;返回命中的规则名或 None。"""
286
+ if depths is None:
287
+ depths = _brace_depths(lines)
288
+ # R0 同行短路:解引用**位置之前**的本行文本已经测过这个对象。
289
+ # 必须用 col(匹配起点)而不是 find():`!x || !(x->dT>0)` 里 find 取的是
290
+ # 第一个 x,那段前缀当然不含 x,会把短路保护误判成没守卫。
291
+ if _mentions(lines[index][:col], ident):
292
+ return "R0"
293
+
294
+ # R1 外层条件
295
+ if any(_mentions(c, ident) for c in _enclosing_conditions(lines, index)):
296
+ return "R1"
297
+
298
+ for j in range(index - 1, _scope_start(lines, index), -1):
299
+ if not _mentions(lines[j], ident):
300
+ continue
301
+ k = _condition_start(lines, j)
302
+ if k is None or k >= index or k <= _scope_start(lines, index):
303
+ continue
304
+ cond = "\n".join(lines[k:j + 1])
305
+ body, body_end = _statement_body(lines, k)
306
+ if body is None:
307
+ continue
308
+ negated = re.search(rf"!\s*{re.escape(ident)}", cond)
309
+ if negated:
310
+ # R2 跳过式:否定条件 + 语句体真的退出,且守卫整体在解引用之前
311
+ if body_end is not None and body_end < index and \
312
+ _dominates(depths, k, body_end, index) and \
313
+ re.search(r"\b(continue|return)\b", body):
314
+ between = "\n".join(lines[k:index])
315
+ if not re.search(rf"{re.escape(ident)}\s*=", between):
316
+ return "R2"
317
+ else:
318
+ # R3 正向:`if(<对象>)` 且解引用就落在它的语句体里
319
+ if body_end is not None and k <= index <= body_end:
320
+ return "R3"
321
+ return None
322
+
323
+
324
+ class PreintegrationGuardContractTest(unittest.TestCase):
325
+ @classmethod
326
+ def setUpClass(cls):
327
+ cls.files = {}
328
+ for path in sorted(SRC.glob("*.cc")) + sorted(INCLUDE.glob("*.h")):
329
+ cls.files[path] = _strip_comments_and_strings(
330
+ path.read_text(errors="replace").splitlines())
331
+
332
+ def test_every_dereference_is_dominated_by_a_null_check(self):
333
+ offenders, checked = [], 0
334
+ for path, lines in self.files.items():
335
+ for i, line in enumerate(lines):
336
+ for m in DEREF.finditer(line):
337
+ checked += 1
338
+ ident = _identity(m.group(1), m.group(2), m.group(3))
339
+ if _guard_before(lines, i, m.start(), ident) is None:
340
+ offenders.append(f"{path.name}:{i + 1} {line.strip()[:70]}")
341
+
342
+ self.assertGreater(checked, 15,
343
+ f"只扫到 {checked} 处解引用,扫描器多半坏了"
344
+ f"(本树应有 20+ 处)")
345
+ self.assertEqual(
346
+ offenders, [],
347
+ "有 mpImuPreintegrated 解引用没有被判空支配 —— 空预积分是设计内的"
348
+ "合法态(IMU 空档期建的关键帧就是 NULL),会直接 SIGSEGV:\n "
349
+ + "\n ".join(offenders))
350
+
351
+ def test_no_print_without_skip_pattern(self):
352
+ """盯 2026-09-23 的原始形态:判空了却继续往下解引用。"""
353
+ offenders = []
354
+ for path, lines in self.files.items():
355
+ for i, line in enumerate(lines):
356
+ if not re.search(rf"\bif\b.*!\s*[\w\)\]]*{MEMBER}", line):
357
+ continue
358
+ body, _ = _statement_body(lines, i)
359
+ if body is not None and not re.search(r"\b(continue|return)\b", body):
360
+ offenders.append(f"{path.name}:{i + 1} {line.strip()[:70]}")
361
+ self.assertEqual(
362
+ offenders, [],
363
+ "发现「判空但不跳过」——这正是 2026-09-23 崩溃的形态"
364
+ "(打印 Not preintegrated measurement 后照样 SetNewBias):\n "
365
+ + "\n ".join(offenders))
366
+
367
+ def test_inertial_optimization_edge_loops_guard_both_overloads(self):
368
+ """两个 InertialOptimization 重载的加边循环都必须判空。
369
+
370
+ 2026-09-23 崩的是 11 参数重载(LocalMapping::InitializeIMU 调它),
371
+ 而 5 参数重载连打印都没有、同样没判空——只修前者会剩一颗地雷。
372
+ """
373
+ source = "\n".join(self.files[SRC / "Optimizer.cc"])
374
+ self.assertEqual(
375
+ len(re.findall(r"\nvoid Optimizer::InertialOptimization\s*\(", source)), 3,
376
+ "InertialOptimization 重载数变了;新增重载必须同样判空")
377
+
378
+ # 按签名切出两个「加边循环」重载的函数体(第三个只有 Map*,Rwg,scale)
379
+ bodies = {}
380
+ for label, sig in (
381
+ ("11 参数", r"void Optimizer::InertialOptimization\(Map \*pMap, "
382
+ r"Eigen::Matrix3d &Rwg, double &scale,"),
383
+ ("5 参数", r"void Optimizer::InertialOptimization\(Map \*pMap, "
384
+ r"Eigen::Vector3d &bg,"),
385
+ ):
386
+ start = re.search(sig, source)
387
+ self.assertIsNotNone(start, f"找不到 {label} 重载的签名")
388
+ bodies[label] = source[start.start():source.find("\nvoid Optimizer::",
389
+ start.end())]
390
+
391
+ for label, body in bodies.items():
392
+ self.assertRegex(
393
+ body, r"!\s*pKFi->mpImuPreintegrated\s*\)\s*\{[^}]*continue;",
394
+ f"{label}重载的加边循环里,判空后没有 continue —— "
395
+ f"只打印不跳过等于没判(2026-09-23 崩溃的原始形态)")
396
+ # 判空必须**支配**SetNewBias:守卫块的花括号要闭合在它之前
397
+ guard = re.search(r"!\s*pKFi->mpImuPreintegrated", body)
398
+ bias = body.find("pKFi->mpImuPreintegrated->SetNewBias")
399
+ self.assertNotEqual(bias, -1, f"{label}重载里找不到 SetNewBias")
400
+ self.assertLess(guard.start(), bias,
401
+ f"{label}重载的判空排在 SetNewBias 之后,等于没判")
402
+
403
+ def test_full_inertial_ba_gates_on_preintegration_too(self):
404
+ """FullInertialBA 的条件必须同时判 bImu 与预积分。
405
+
406
+ `bImu` 记的是「这个关键帧有 IMU 采样」,不是「建出了预积分」——
407
+ 两者可以同时成立与不成立,只看 bImu 会漏。
408
+ """
409
+ source = "\n".join(self.files[SRC / "Optimizer.cc"])
410
+ start = source.find("void Optimizer::FullInertialBA")
411
+ self.assertNotEqual(start, -1, "找不到 FullInertialBA 定义")
412
+ body = source[start:source.find("\nvoid Optimizer::", start + 1)]
413
+
414
+ self.assertRegex(
415
+ body, r"pKFi->bImu\s*&&\s*pKFi->mPrevKF->bImu\s*&&\s*"
416
+ r"pKFi->mpImuPreintegrated",
417
+ "FullInertialBA 只看 bImu 没看 mpImuPreintegrated —— "
418
+ "有 IMU 采样但没建出预积分的关键帧会在这里 SIGSEGV")
419
+
420
+ # 本轮 5 处修复的「修复前 / 修复后」对照。反着用:把已修好的文本换回
421
+ # 修复前的样子,扫描器必须报出至少一处 —— 报了才证明它有牙。
422
+ UNDONE = [
423
+ ("Optimizer.cc 11 参数重载:判空退回「只打印不跳过」",
424
+ "Optimizer.cc",
425
+ ' std::cout << "Not preintegrated measurement" << std::endl;\n'
426
+ " continue;\n }",
427
+ ' std::cout << "Not preintegrated measurement" << std::endl;\n'
428
+ " }"),
429
+ ("Optimizer.cc 5 参数重载:摘掉整个判空",
430
+ "Optimizer.cc",
431
+ " if(!pKFi->mpImuPreintegrated)\n {\n"
432
+ ' std::cout << "Not preintegrated measurement" << std::endl;\n'
433
+ " continue;\n }\n\n"
434
+ " pKFi->mpImuPreintegrated->SetNewBias(pKFi->mPrevKF->GetImuBias());",
435
+ " pKFi->mpImuPreintegrated->SetNewBias(pKFi->mPrevKF->GetImuBias());"),
436
+ ("Optimizer.cc FullInertialBA:退回只看 bImu",
437
+ "Optimizer.cc",
438
+ "if(pKFi->bImu && pKFi->mPrevKF->bImu && pKFi->mpImuPreintegrated)",
439
+ "if(pKFi->bImu && pKFi->mPrevKF->bImu)"),
440
+ ("LocalMapping.cc 清理路径:摘掉 DiscardMeasurements 的判空",
441
+ "LocalMapping.cc",
442
+ " if(keyFrame->mpImuPreintegrated)\n"
443
+ " runDiscardedMeasurements +=\n"
444
+ " keyFrame->mpImuPreintegrated->DiscardMeasurements();",
445
+ " runDiscardedMeasurements +=\n"
446
+ " keyFrame->mpImuPreintegrated->DiscardMeasurements();"),
447
+ ("Tracking.cc 单目分支:摘掉重新播种的判空",
448
+ "Tracking.cc",
449
+ " if(pKFcur->mpImuPreintegrated)\n"
450
+ " mpImuPreintegratedFromLastKF = new IMU::Preintegrated("
451
+ "pKFcur->mpImuPreintegrated->GetUpdatedBias(),pKFcur->mImuCalib);",
452
+ " mpImuPreintegratedFromLastKF = new IMU::Preintegrated("
453
+ "pKFcur->mpImuPreintegrated->GetUpdatedBias(),pKFcur->mImuCalib);"),
454
+ ]
455
+
456
+ def test_scanner_keeps_its_teeth(self):
457
+ """把 5 处修复逐一改回原样,扫描器必须变红。"""
458
+ for label, fname, fixed, broken in self.UNDONE:
459
+ text = (SRC / fname).read_text(errors="replace")
460
+ self.assertIn(fixed, text,
461
+ f"{label}:锚点没找到,本条已失效,必须按新代码重写锚点")
462
+ lines = _strip_comments_and_strings(
463
+ text.replace(fixed, broken, 1).splitlines())
464
+ depths = _brace_depths(lines)
465
+ offenders = []
466
+ for i, line in enumerate(lines):
467
+ for m in DEREF.finditer(line):
468
+ ident = _identity(m.group(1), m.group(2), m.group(3))
469
+ if _guard_before(lines, i, m.start(), ident, depths) is None:
470
+ offenders.append(f"{fname}:{i + 1}")
471
+ self.assertNotEqual(
472
+ offenders, [],
473
+ f"{label}:摘掉守卫后扫描器一声不吭 —— 这条规则没牙,"
474
+ f"等于给后面的人一张假绿灯")
475
+
476
+ def test_map_cleanup_discard_measurements_guards_null(self):
477
+ """地图清理路径的 DiscardMeasurements 调用必须判空(同一族)。"""
478
+ source = "\n".join(self.files[SRC / "LocalMapping.cc"])
479
+ hits = [m.start() for m in re.finditer(r"DiscardMeasurements\(\)", source)]
480
+ self.assertEqual(len(hits), 1,
481
+ f"DiscardMeasurements 调用点数量变了({len(hits)} 个)")
482
+ window = source[max(0, hits[0] - 400):hits[0]]
483
+ self.assertRegex(
484
+ window, r"if\s*\(\s*keyFrame->mpImuPreintegrated\s*\)",
485
+ "地图清理里 DiscardMeasurements 没有判空 —— 清理到 IMU 空档期建的"
486
+ "关键帧(预积分为 NULL)就会 SIGSEGV")
487
+
488
+
489
+ if __name__ == "__main__":
490
+ unittest.main()
collector/core/gripper/runtime/device_access.py CHANGED
@@ -3,60 +3,131 @@ from contextlib import contextmanager
3
  import fcntl
4
  import os
5
  import stat
 
6
  import time
7
 
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  @contextmanager
10
  def device_access_guard(path, *, timeout=30.0, cancelled=None):
11
  # Read-only flock also works for a lock created by a sudo-launched process.
12
  # Do not truncate, unlink or follow symlinks: every caller must lock the
13
  # same inode for the whole operation/lease lifetime.
14
  flags = os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW
15
- try:
16
- fd = os.open(path, flags)
17
- except FileNotFoundError:
18
- try:
19
- fd = os.open(path, flags | os.O_CREAT | os.O_EXCL, 0o644)
20
- except FileExistsError:
21
- fd = os.open(path, flags)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  acquired = False
23
  owner_pid = os.getpid()
24
  try:
25
- if not stat.S_ISREG(os.fstat(fd).st_mode):
26
- raise RuntimeError(f"设备锁不是普通文件: {path}")
27
- deadline = time.monotonic() + timeout
28
- while True:
29
- if cancelled is not None and cancelled():
30
- raise RuntimeError("设备操作已取消")
31
- try:
32
- fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
33
- acquired = True
34
- break
35
- except BlockingIOError:
36
- if time.monotonic() >= deadline:
37
- raise RuntimeError(f"设备正在使用或初始化,请稍后重试: {path}")
38
- time.sleep(0.05)
 
 
 
39
  yield
40
  finally:
41
- try:
42
- # O_CLOEXEC does not prevent inheritance by fork-only workers.
43
- # close(fd) alone leaves flock held by their duplicate descriptors.
44
- # Only the acquiring process may release the shared lock explicitly.
45
- if acquired and os.getpid() == owner_pid:
46
- fcntl.flock(fd, fcntl.LOCK_UN)
47
- finally:
48
- os.close(fd)
 
 
 
 
 
 
 
 
 
 
49
 
50
 
51
  FAYS_SDK_INITIALIZATION_LOCK = "/tmp/ksq-fays-sdk-serial-probe.lock"
52
 
53
 
54
- def fays_device_guard(stereo_port, *, timeout=0.0):
 
55
  import re
56
  if not re.fullmatch(r"/dev/video[0-9]+", str(stereo_port)):
57
  raise RuntimeError("Fays stereo 节点无效,拒绝访问 SDK")
 
 
 
 
58
  return device_access_guard(
59
- f"/tmp/ksq-fays-sdk-device-{os.path.basename(stereo_port)}.lock",
60
  timeout=timeout,
61
  )
62
 
 
3
  import fcntl
4
  import os
5
  import stat
6
+ import threading
7
  import time
8
 
9
 
10
+ _HELD_LOCK = threading.RLock()
11
+ _HELD_BY_PROCESS = {} # 锁文件路径 -> (持有者线程 ident, 深度)
12
+ _PATH_LOCKS = {} # 锁文件路径 -> 进程内互斥(同进程不同线程排队)
13
+
14
+
15
+ def _path_lock(path):
16
+ with _HELD_LOCK:
17
+ lock = _PATH_LOCKS.get(path)
18
+ if lock is None:
19
+ lock = threading.Lock()
20
+ _PATH_LOCKS[path] = lock
21
+ return lock
22
+
23
+
24
+ def device_guard_held_by_process(path):
25
+ """本进程是否正持有 ``path`` 上的 guard。
26
+
27
+ flock 绑在 **open file description** 上,不是进程上:同一进程再 open
28
+ 一次同一文件,非阻塞加锁照样 EWOULDBLOCK。所以「加锁失败」推不出
29
+ 「被别的会话占用」——也可能是自己。要区分归属只能看这份进程内登记
30
+ 表,否则自我探测会把本机唯一那台设备判成「别人正在用」而跳过。
31
+ """
32
+ with _HELD_LOCK:
33
+ entry = _HELD_BY_PROCESS.get(str(path))
34
+ return entry is not None and entry[1] > 0
35
+
36
+
37
+ def _open_lock_file(path, flags):
38
+ try:
39
+ return os.open(path, flags)
40
+ except FileNotFoundError:
41
+ try:
42
+ return os.open(path, flags | os.O_CREAT | os.O_EXCL, 0o644)
43
+ except FileExistsError:
44
+ return os.open(path, flags)
45
+
46
+
47
  @contextmanager
48
  def device_access_guard(path, *, timeout=30.0, cancelled=None):
49
  # Read-only flock also works for a lock created by a sudo-launched process.
50
  # Do not truncate, unlink or follow symlinks: every caller must lock the
51
  # same inode for the whole operation/lease lifetime.
52
  flags = os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW
53
+ hold_key = str(path)
54
+ ident = threading.get_ident()
55
+ deadline = time.monotonic() + timeout
56
+
57
+ # 同线程重入:本线程已经持有这把锁 → 只加深度,绝不再开 fd 加第二次。
58
+ # flock 认的是 open file description,认不出「这是我自己」,再开一个 fd
59
+ # 必然 EWOULDBLOCK —— 同一个操作在内部再套一层就会把自己挡死。
60
+ with _HELD_LOCK:
61
+ entry = _HELD_BY_PROCESS.get(hold_key)
62
+ nested = entry is not None and entry[0] == ident
63
+ if nested:
64
+ _HELD_BY_PROCESS[hold_key] = (ident, entry[1] + 1)
65
+
66
+ if not nested:
67
+ # 同进程不同线程:排队等,而不是互撞。flock 只挡得住别的进程,挡不住
68
+ # 自己人;进程内串行化由这把互斥负责。等待上限与 flock 共用同一个
69
+ # deadline,所以 timeout=0 的调用点语义不变(立刻失败,用来探测)。
70
+ path_lock = _path_lock(hold_key)
71
+ if not path_lock.acquire(timeout=max(0.0, deadline - time.monotonic())):
72
+ raise RuntimeError(f"设备正在使用或初始化,请稍后重试: {path}")
73
+
74
+ fd = None
75
  acquired = False
76
  owner_pid = os.getpid()
77
  try:
78
+ if not nested:
79
+ fd = _open_lock_file(path, flags)
80
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
81
+ raise RuntimeError(f"设备锁不是普通文件: {path}")
82
+ while True:
83
+ if cancelled is not None and cancelled():
84
+ raise RuntimeError("设备操作已取消")
85
+ try:
86
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
87
+ acquired = True
88
+ break
89
+ except BlockingIOError:
90
+ if time.monotonic() >= deadline:
91
+ raise RuntimeError(f"设备正在使用或初始化,请稍后重试: {path}")
92
+ time.sleep(0.05)
93
+ with _HELD_LOCK:
94
+ _HELD_BY_PROCESS[hold_key] = (ident, 1)
95
  yield
96
  finally:
97
+ with _HELD_LOCK:
98
+ current = _HELD_BY_PROCESS.get(hold_key)
99
+ if current is not None:
100
+ if current[1] > 1:
101
+ _HELD_BY_PROCESS[hold_key] = (current[0], current[1] - 1)
102
+ else:
103
+ _HELD_BY_PROCESS.pop(hold_key, None)
104
+ if not nested:
105
+ try:
106
+ # O_CLOEXEC does not prevent inheritance by fork-only workers.
107
+ # close(fd) alone leaves flock held by their duplicate descriptors.
108
+ # Only the acquiring process may release the shared lock explicitly.
109
+ if acquired and os.getpid() == owner_pid:
110
+ fcntl.flock(fd, fcntl.LOCK_UN)
111
+ finally:
112
+ if fd is not None:
113
+ os.close(fd)
114
+ path_lock.release()
115
 
116
 
117
  FAYS_SDK_INITIALIZATION_LOCK = "/tmp/ksq-fays-sdk-serial-probe.lock"
118
 
119
 
120
+ def fays_device_guard_path(stereo_port):
121
+ """Fays 设备 guard 的锁文件路径(调用方用它查本进程是否已持有)。"""
122
  import re
123
  if not re.fullmatch(r"/dev/video[0-9]+", str(stereo_port)):
124
  raise RuntimeError("Fays stereo 节点无效,拒绝访问 SDK")
125
+ return f"/tmp/ksq-fays-sdk-device-{os.path.basename(stereo_port)}.lock"
126
+
127
+
128
+ def fays_device_guard(stereo_port, *, timeout=0.0):
129
  return device_access_guard(
130
+ fays_device_guard_path(stereo_port),
131
  timeout=timeout,
132
  )
133
 
collector/core/gripper/sightac_sdk/api_new/__init__.py CHANGED
@@ -1,3 +1,3 @@
1
- # Pyarmor 8.5.12 (trial), 000000, non-profits, 2026-09-09T18:33:47.704240
2
  from pyarmor_runtime_000000 import __pyarmor__
3
- __pyarmor__(__name__, __file__, b'PY000000\x00\x03\x0c\x00\xcb\r\r\n\x80\x00\x01\x00\x08\x00\x00\x00\x04\x00\x00\x00@\x00\x00\x00\xb0\x02\x00\x00\x12\t\x04\x00\x06\xf9!\x9cF\xf9{jW\x03\x87\x8f7\x81\xa0s\x00\x00\x00\x00\x00\x00\x00\x00\x86Y\xa2\xf1\x1f$\xca)\xa0f/\xd0\xcf\xb3\xc9\xe7@4\xec\x89\xc139\xf6cK9\xd3BG\xe3\x80\x8f\x15\x15\xd8\xb2\x9d\xf0?!8T\xc8\xaf\xa8\x91,dV<\xd1\xda\xb3\xbf5\xb8\xd2\x84\xf5\xe5i\xba\n\xbf\x1d\xaf?.Y\xe9\xff\xbcy\xd5\x04)!\xff\x14,\x02\xa8\xe9\x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D\xf5\x05\'\xbe\xc8\xb2%e\xd2!X\x87\xe7\t\x0e\xd6x\xc4\xcdH\xac\xec\xdd1\xab\xda`}S\x90\xa64\xb1\x8fN3\xf2\xb8\x8a\xd7\x92\x15^%!Z\xc54\xac\xf8\x1b\x9d-\xec\xda\xd7<\xfd\xa2\xe8\x17?9\xe5\x1e\xdb\x1a;\xa7U#\'\xe6\x0f-\xc8\x95\x96\x00\x92\xaaIR\x1b\x80\xd8t"c\x99\xb7?\xe4\t\x17*\xe1\xf1m;z6rA\x00~r\x9d\x9d\xa7H\x06u"e\xbf(9@\x86C\xf0\xdc\xc0\x9c\xaczD,P\x8e\xe6\xf9p\x00\xd6IgOW\xde\x82\x9d\xb6R8\xfe\x7f4\xd0\xc6\xb5\xe5\xce\x97\xaa!*r\x8c\xaf>^\xeceW\xd5\xef\x07\xe0\xcd\xbe\xbe\xe1\xa2\x99De\xb6Lhj\x86\x8fW\x8d\xff&\xf0\x10\xa5,\xac\xccQ\xdc\x99\x12\xc3\xa8\x8f\x1c\x80}\xd0\x99\xbb\xdf\xb8SREL')
 
1
+ # Pyarmor 8.5.12 (trial), 000000, non-profits, 2026-09-16T04:10:32.010162
2
  from pyarmor_runtime_000000 import __pyarmor__
3
+ __pyarmor__(__name__, __file__, b'PY000000\x00\x03\n\x00o\r\r\n\x80\x00\x01\x00\x08\x00\x00\x00\x04\x00\x00\x00@\x00\x00\x00R\x02\x00\x00\x12\t\x04\x00\x83\xce\x0b\x80J,\\J:R\x9d^\xa9\xa3\x8f8\x00\x00\x00\x00\x00\x00\x00\x00v\xda\xd04\xbf\x02U\x89\xd0|:\x05\xb3(q8@\x8d\xcbmT\xdax9\x07\xd6L\x1a\xfe\x0em\x1d\x1c\x8a\x15\xac)\xc0\x96\xe5S\x18\x81a\x17\x93P\xec\xee\xf34"N\xa2I\x86\x97\xdevS\x9bB\'\x96\xa0[\x10\x87j\xc8\xba\x17\xa7A1t>O\xd4\x9c\x93\x03\x99%uVAz\x8b\x81\x88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0f\x81\x9bE\x02#k\xb24\x08V\xd8,k\xbc\x9d\xccs\x10\xd5\xc5%\xdbp^\xf2E\xfa\x15`\xa6\x05/\x94\xbc\xcaE\xe7\xd5i\xfc\xa1\xc8b\x81T\xe0\'\x8b^\xfa\xaf\xb23YI\xb0\x8a\x81H\xfbC\x8e{\xdb\xea\x8a\x81\xa8\xeb\xe1\x0c\x08<]\x15q3\xad\xcf\xf9H\'<\'pU\xb54NX\x97\x01\x81\x8c\x17\xd5\xcf<\x96\xb5\x87\xf3\xb0/I\x91\x06\xba\xd8\xef')
collector/core/gripper/sightac_sdk/api_new/platform_utils.py CHANGED
@@ -1,3 +1,3 @@
1
- # Pyarmor 8.5.12 (trial), 000000, non-profits, 2026-09-09T18:33:47.771312
2
  from pyarmor_runtime_000000 import __pyarmor__
3
- __pyarmor__(__name__, __file__, b'PY000000\x00\x03\x0c\x00\xcb\r\r\n\x80\x00\x01\x00\x08\x00\x00\x00\x04\x00\x00\x00@\x00\x00\x00\x1a\r\x00\x00\x12\t\x04\x00\xe7\xcf\xa2\x98Nr\x8f\x86H\x03IC\x8c\xdc\x0b\xd2\x00\x00\x00\x00\x00\x00\x00\x00h\xc9\x9af\x88\xa8\x12*S\xcf7O\xc6\x14\xaf\xf238D44K\x93s=T\xbdp\xdb\xeb)K\xa6^\x02\xc4\xe5\xeb\xbc\xe9?u.\x1d\xe5\xdf\xa5\xe2\xbc@\xa5\x8c\xf9j1u0K\x9a\xdd\x9c0\xe7\xf7l&\xbe\xd0+6\x1a\xe1\x05\x99\x98\x8aT:\xdd\xae>R\xcf3D\xdf\x8d\xc0\xcc\x95\x8at\xce\xea\xf5\xc0\xfa\xdbh\xc82\x9d\x0f\x95\xdbh\x02@c\xbc\x07\xb3\xf3\xf6\xf9q\x97K\x1f\xfb\x10\x9d\x92\xef%|Y\xaa;3\xba:\x94\x90}>M\xaaeH\xc0OG\x8c}\xd8\xc1\xac\x17\x8eA\x08\t\xf8\xf5\\: R>G\xc4\xb9\xd4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4|\xac\xc3\xcbJ\x8d\x90\x12\x8bt\xb0\x904\xfd\xc8Q%Yv\xa1\xb6<\x0cf\xb2\xca\xa0\xa1&\xa1AvEZ\xf4U\x96~\xe6\xbd\xde\xbe\xd6\x97~%m\xa4\xed\xda\x15FW\x0b^\x9a\xa99\xf6IH\xc7\xcc\xd0! w\xd3U\x84i\xf2\x0f\xd84!\xb4C\xceuP\xee\xc7cr0\xf3\xec\xd9\x008\xaf\xde\xf8\xb7\xabp\xc2\xef')
 
1
+ # Pyarmor 8.5.12 (trial), 000000, non-profits, 2026-09-16T04:10:31.973472
2
  from pyarmor_runtime_000000 import __pyarmor__
3
+ __pyarmor__(__name__, __file__, b'PY000000\x00\x03\n\x00o\r\r\n\x80\x00\x01\x00\x08\x00\x00\x00\x04\x00\x00\x00@\x00\x00\x00\x0f\n\x00\x00\x12\t\x04\x00\x15\xcf\xb0Nd\x1f*\xee\xaap;2\xda\xdf\xef\xd6\x00\x00\x00\x00\x00\x00\x00\x00\xf9\x13{\xbf\x9cP\xa8\\n\xf4<cE\x08\x9e\x9d\x84\xecD\x1d\x06w\x14\x9a\xafTS\x004\xd4$D\xb4\x8ba\xa9\x88\x07\x87\xa6Kq&fw\xfa\xd0\x81B\xb8K\xc3Sj3A\x0c\xe5\r\xf8w\x81\xd4\xd4\xad\xc4a\xe18|M\xb5?\xeeD\xfc\xea |G<\xe2po\xcb\x1a\xcb\x1aTc\xb1%8a\x05Z\xd7\xedR\x99\x95\x00XB\xbc%\xb9\xfa\xdf,\xfe\xfbS\xdc?\x139\xf3{\xec^\xcaG#/a\xf1Zl\t\xe5-Q\t\xa7$9\xf0\xc9\xc2)\'\xe2\x0ez\xb6]\xc8\x15\xea\xefs\xfa\xfd\x85\xb0\xb9\xbf\xf3\xa6\xad\x18\xd3N\xcc{\xfe\x0cJ\xf0\xe4 \xcc$\x06`\x88\xa4\x0e\xcd\x1ai\x93\rw\x9d\xbc\xd6b\xfcOoq9\xa7\xbf\xb0\x0fc\x12\x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\x7fj\xa0\xad?L\x95\xb1\xed\xc7\r\x00\xb5\xc1\xfc\x15\xd4l\x99\x08\xca\xbel}\x1fV\xacw\x04.n\xbaq\xbb\x94\x9ee\x80\xfc\x04\x05\x86\x86\xfa\xc6\x94\xd3\xf9\xa9%}\xd9\xe1em\xa4\xec\x86\xca\xc3]\x13\xa27j{L\x13\xca\x03\xcd\xd2\xfc0\xac\x9b\xe6|\xd9\xeeP321\xad\x056\xd3\t+\xfe\xba\x85\x0f\xce\x06\xda\x0e \xe5\xad(\x93,\xc5\xfcd\xa6c\xc7\x9d\xbb8}\xfd39\x9ci2\x8b-\xc6\x8ey\xab\xeb\x96\xe3QD\x1e\x1f7t\x17\xcb\x0f\x11\xfb\r\x04\xc9{\xef\xb0\x16\x01-m\xea\xa1\x94\xe6\r\xb2j\xff\x1e\xc7\x86F\xa7\xe7\xcb\x83\xbeE\x93\xcdj\x90\x07\xadp\xec\x02\xa4\xd5\xad\x06\xc5\xa9c\xea\x87\x81M\x96T\xceC\xff`\xcf_\x93\x935\xb9\x00y\xfc!k\x9e \xec\xa37S)\x03SU\xc4\xbd[\xee\x1ca\xf5\x12\xf0\x1ff6\xb5\xdb*\xe91\xa3\xebG\xef_\xb1\xe9\x87*\xf8l\xa1\xb2\xdc\xf6\x00tF\xd2\xd8\xf2\xf8(\x8d\xf7d\x1a\x10\xe4\x01\x01\xdc\xfa_F\xda\xe1uM\xd9\\H|\xcd\xd5\x11tiA&\x11\\Ms:\x1b._q\t\x17)\x9c^\xcd\x18\x0c\xefi#\x86b\xed\xd2\xee\x98\x92H\x9f\xe1k\xb9O\xda\xa5lu\x18-\x1a\x1e\xf5w\xc5\xda\x0f\x8a\n\xef|\xc9J\x0c\xa2\xc5\xedzPbtA\xbeS\xc1S\x84\xc9u\x9d\xe7\x97\x91\x1a%\xd2$\xfd\xcc/P\x13\xf6;\xa7\xdaa\n4\x036\xea\xfa\xb2<\xa3\x91vz\xb6;\xff/.c"h\x12\x80\xe4\x9a\xfbJ\x11\xff\x8c.Q:\x05\x8b\x86\xd4\xfe\xc4+\t<\x8e\xc2i\t"\xf8\xa3\xad\x1d\x0f\x12\xc9=\x83\xac\x03\xe3\xecv\x10@\xc8\xda\xaco8k\xc7\xbe\xfb/\xed\xe9\x0b=|qo\x94m|\xe6\x850\xed\x04c_\xb5\x89\x83y\xdb')
collector/core/gripper/sightac_sdk/api_new/sensor_function.py CHANGED
The diff for this file is too large to render. See raw diff
 
collector/core/gripper/sightac_sdk/api_new/sensor_gripper.py CHANGED
The diff for this file is too large to render. See raw diff
 
collector/core/gripper/sightac_sdk/api_new/touch_sensor.py CHANGED
The diff for this file is too large to render. See raw diff
 
collector/core/gripper/sightac_sdk/api_new/touch_sensor_base.py DELETED
The diff for this file is too large to render. See raw diff
 
collector/core/gripper/sightac_sdk/api_new/xu_camera.py CHANGED
The diff for this file is too large to render. See raw diff
 
collector/core/gripper/sightac_sdk/pyarmor_runtime_000000/__init__.py CHANGED
@@ -1,2 +1,2 @@
1
- # Pyarmor 8.5.12 (trial), 000000, 2026-09-09T18:33:48.325537
2
  from .pyarmor_runtime import __pyarmor__
 
1
+ # Pyarmor 8.5.12 (trial), 000000, 2026-09-16T04:10:31.969969
2
  from .pyarmor_runtime import __pyarmor__
collector/core/gripper/sightac_sdk/pyarmor_runtime_000000/pyarmor_runtime.so CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:6f8655b0125d80acc0d8bf62bc2bf97beae5f88d23f0b0b8f60c8a5473cd68ca
3
- size 796488
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:23d9e96a6c135737943ed8797e54e18cdbf6253c5013675ec5bc042ce17b5ce4
3
+ size 788264
collector/docs/core.md CHANGED
@@ -1030,6 +1030,64 @@ import;回归 `tools/tests/test_frame_gap.py`。背景见
1030
  | `core/gripper/devices/` | ESP32 串口/控制板、Sightac 与 DECXIN 相机服务、USB 拓扑关联 |
1031
  | `core/gripper/control/` | 夹爪板状态、百分比与双路 Fz 锁存 |
1032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1033
  ### core/gripper/calibration.py
1034
 
1035
  **作用**:**新夹爪接入即自动就位**(v1.3.4)。Fays 的运行标定是**逐设备出厂
 
1030
  | `core/gripper/devices/` | ESP32 串口/控制板、Sightac 与 DECXIN 相机服务、USB 拓扑关联 |
1031
  | `core/gripper/control/` | 夹爪板状态、百分比与双路 Fz 锁存 |
1032
 
1033
+ ### core/gripper/fays_single.py(配对链与离线入口)
1034
+
1035
+ **作用**:单夹爪场景的 Fays 租约。配对链是「UVC 组 → 唯一 ESP32(bus +
1036
+ outer_path)→ 读板子 NVS 里记的 Fays 序列号(串口 `QF`)→ 按官方 SDK 读到的
1037
+ 产品序列号唯一匹配在线 Fays」,每一步都**失败关闭**(不按端口号或枚举顺序
1038
+ 猜);绑定序列号写错的症状就是「连不上」,所以宁可当场报错。
1039
+
1040
+ **关键接口(离线入口,v1.3.12)**:都不取租约、不建 IPC 目录,供 GUI 直接调。
1041
+
1042
+ | 方法 | 签名 | 作用 |
1043
+ |---|---|---|
1044
+ | `esp_binding_status` | `(esp_serial)` | 连接与绑定现状:`{"esp_serial","device","bound","response","reason"}`。`reason==""` 且 `bound==""` =**读通了但没绑定**(新板子的正常状态,界面可直接进写入步骤);`reason` 非空则带上串口层原文(如 `串口连接失败: serial open/handshake failed: Write timeout`),由界面如实显示、不猜 |
1045
+ | `online_fays_serials` | `()` | 枚举在线 Fays 产品序列号 → `(by_serial, skipped)`;探测口径与 `acquire()` 完全一致(超速预检 + `--serial-only-fast`),所以列出来的就是配对会认的;`skipped` 是被别的会话独占的那些。无完整设备组抛 `GripperFaysError` |
1046
+ | `write_bound_serial` | `(esp_serial, fays_serial)` | `WF:<serial>` 写 NVS → 立刻 `QF` **回读**并返回值。回读为空串就是空串,**不谎报成功**;缺节点/连不上/板上 `ERR` 都带原因抛出 |
1047
+ | `esp_console_report` | `(esp_serial, seconds=3.0)` | 只读诊断:`{"esp_serial","device","physical_usb_path","connected","last_error","state","bound","lines","read_only_lines","read_only_error","seconds"}`。除握手 `?` 外不发命令、不改板子状态;`lines` 是随后板上主动吐出的整行。**握手失败不是「没有证据」**:此时会再 `open_readonly()` 一次(一个字节都不写)收 `seconds` 秒进 `read_only_lines` —— 写阻塞时读这条路仍然通,于是能分清「板子哑了」(0 行)与「板子在说话、只是不收主机写入」(有行),两者归因与处置都不同 |
1048
+
1049
+ **公开行为(v1.3.12)**:三件事都在主程序夹爪右键菜单里(见 `docs/ui.md`)——
1050
+ 串口诊断打印板上原样输出,配对序列号走「探板 → 在**在线** Fays 里挑一台 →
1051
+ 确认 → 写入 → 回读」。只给选**不给手输**:写错序列号会让这只夹爪静默指向
1052
+ 别的 Fays,比现状更难排查。三条链路共用主窗口的 `_gripper_offline_guard`
1053
+ (序列号 + 录制检查)、`_gripper_offline_take_over`(先关掉已开的夹爪让出
1054
+ 串口)、`_reopen_after_offline`(善后):**只读诊断一律开回**,探板/写入失败
1055
+ 不开回(板子状态未知,交回用户决定),用户取消/没找到在线 Fays 则开回。
1056
+
1057
+ **ESP32 串口(`core/gripper/devices/gripper_serial.py`)**:`GripperSerial` 是
1058
+ 唯一资源所有者。`connect()` 以 `exclusive=True` 独占打开,并在
1059
+ `CONNECT_BOOT_TIMEOUT` 内反复发 `?` 要一行以 `STATE` 开头的响应;`send()` 只
1060
+ 接受**该命令自己的响应前缀**,免得固件周期性的 `STATE` 顶替真响应(`QF` 是
1061
+ 两字符命令,前缀表按完整命令查,只查首字符会让它永远命中不到);`WF:` 的三
1062
+ 种终态都算本条命令的响应。`read_lines(duration, *, limit=200)`(v1.3.12)是
1063
+ 只读诊断用的收集器:不发任何命令,超时那次 `readline` 返回空串就继续等到时
1064
+ 间上限。v1.3.12 起 `connect()` = `open_readonly()` + `handshake()` 两半,两半
1065
+ 可以单独调:**只读打开再收一段**这条路在「写不进去」的板子上依然走得通,是
1066
+ 诊断拿得到 TX 侧证据的唯一途径。
1067
+
1068
+ **关键数据**:`connect()` 报的 `serial open/handshake failed: Write timeout` 与
1069
+ `serial handshake timeout after N attempts` 是两件事 —— 前者是写阻塞(3 字节
1070
+ 的 `?` 都送不进设备),后者是**写得进去、板子不回话**。两种都表明**板子没在
1071
+ 服务自己的 USB 串口**,但归因不能说死成「固件没烧」:ESP32-S3 的
1072
+ USB-Serial-JTAG(`303a:1001`)节点由芯片自带的 USB 外设枚举,与固件是否在跑
1073
+ 无关,所以「节点在」不能当「板子在服务串口」;而官方 issue(espressif/esp-idf
1074
+ #18996)记录了另一种情形——固件完好,USB 外设被 DTR/RTS 触发的复位打死,
1075
+ 设备仍留在总线上、两个方向皆死寂,只有**物理断电/EN 复位**能恢复。写超时的
1076
+ 宿主侧机制也不是「FIFO 被灌满」:设备端只是不再「受理」新的 OUT 包
1077
+ (TRM 33.3.3:缓冲要有空位才收,空位只在固件读走数据后恢复),一个挂起的写
1078
+ URB 就让 cdc-acm 的 `chars_in_buffer`(1 个 wb 即 `writesize = maxp*20 ≥ 256`)
1079
+ 压过 `WAKEUP_CHARS`,`n_tty_poll` 于是不再报 POLLOUT —— pyserial 的写后
1080
+ `select` 超时,抛 `SerialTimeoutException('Write timeout')`。权限/占用不在这条
1081
+ 路上:被占是 `[Errno 16] Device or resource busy`(或 `Errno 13`),不是写超时。
1082
+ 写阻塞时第一笔 `?` 就可能卡住,日志里一条 `[Serial] connect attempt n/8` 都不会
1083
+ 出现,事后看会误判成没试过握手 —— 所以 v1.3.12 起异常路径额外打一行
1084
+ `[Serial] 握手中断于第 N 次写(最后一次读回 ...): <异常>`,把「卡在第几笔」
1085
+ 和「卡之前读到过什么」一起留痕。
1086
+
1087
+ **调用关系**:`acquire()` 走完整配对(主程序连接夹爪时);GUI 三入口走上面四
1088
+ 个离线方法;离线回归见 `tools/tests/test_gripper_fays_pairing.py`(配对链
1089
+ 失败关闭)与 `tools/tests/test_gripper_esp_binding.py`(离线入口 + 界面流程)。
1090
+
1091
  ### core/gripper/calibration.py
1092
 
1093
  **作用**:**新夹爪接入即自动就位**(v1.3.4)。Fays 的运行标定是**逐设备出厂
collector/docs/tools.md CHANGED
@@ -422,7 +422,7 @@ venv/bin/python tools/audit_frame_gaps.py [任务目录] [选项] # 默认 dat
422
 
423
  ## tests/ 测试
424
 
425
- 测试脚本见 `tools/tests/`(当前 56 份;离线测试加 `QT_QPA_PLATFORM=offscreen` 无需任何硬件,真机测试需对应设备在线)。完整运行命令见 `README.md` 测试节;下表是早期 16 份,末尾补上帧空洞相关的 5 份。
426
 
427
  | 文件 | 类型 | 一句话 |
428
  | --- | --- | --- |
@@ -447,3 +447,5 @@ venv/bin/python tools/audit_frame_gaps.py [任务目录] [选项] # 默认 dat
447
  | `test_ext_frame_gap.py` | 离线 | 落盘侧空洞端到端(含 parquet `*_gap_*` 注入) |
448
  | `test_camera_log_archive.py` | 离线 | camera-service 日志留档 + 告警摘录(健康会话零命中) |
449
  | `test_audit_frame_gaps.py` | 离线 | 审计脚本三层判据/四桶/退出码(全合成 fixture) |
 
 
 
422
 
423
  ## tests/ 测试
424
 
425
+ 测试脚本见 `tools/tests/`(当前 71 份;离线测试加 `QT_QPA_PLATFORM=offscreen` 无需任何硬件,真机测试需对应设备在线)。完整运行命令见 `README.md` 测试节。**下表只列了一部分**(早期 16 份 + 帧空洞相关的 5 份 + 夹爪配对/离线入口),其余按需现查文件名。
426
 
427
  | 文件 | 类型 | 一句话 |
428
  | --- | --- | --- |
 
447
  | `test_ext_frame_gap.py` | 离线 | 落盘侧空洞端到端(含 parquet `*_gap_*` 注入) |
448
  | `test_camera_log_archive.py` | 离线 | camera-service 日志留档 + 告警摘录(健康会话零命中) |
449
  | `test_audit_frame_gaps.py` | 离线 | 审计脚本三层判据/四桶/退出码(全合成 fixture) |
450
+ | `test_gripper_fays_pairing.py` | 离线 | 夹爪配对链失败关闭(QF/WF、按 USB serial 唯一匹配、不猜端口) |
451
+ | `test_gripper_esp_binding.py` | 离线 | 夹爪离线入口:串口诊断只读收集(含写阻塞时仍走通的只读复检、以及卡在第几笔写的留痕日志)、绑定读写与回读、界面三条链路的善后口径、「板子没在服务串口」提示的挂载范围 |
collector/docs/ui.md CHANGED
@@ -260,16 +260,18 @@
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
 
 
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
+ | `gripper_binding_requested`(信号) | `pyqtSignal(object)` | 夹爪条目右键选「读取/写入 Fays 绑定序列号」 | 由 `MainWindow` 连接 |
264
+ | `gripper_diagnostics_requested`(信号) | `pyqtSignal(object)` | 夹爪条目右键选「ESP32 串口诊断」 | 由 `MainWindow` 连接 |
265
+ | `_on_context_menu` | `(pos)` | `Qt.CustomContextMenu` 回调:仅 `dev.group == "gripper"` 且非组标题/占位项才弹菜单(表驱动三项,顺序=重读标定 / 配对序列号 / 串口诊断,顺序是契约的一部分,见 `test_gripper_calibration_autogen.py` §14);`_locked`(录制中)时菜单项 `setEnabled(False)` 且选中后直接返回;按 `chosen is action` 判等,只弹不选不发信号 | — |
266
+ | `_refresh_hint_text` | `()` | 底部提示:有夹爪时追加「;右键夹爪可重读标定 / 配对序列号 / 串口诊断」 | 由 `refresh_texts` 调用 |
267
 
268
  **关键数据**:
269
 
270
+ - `_ICON = {"uvc": "📹", "d435": "🔭", "s80m": "👁", "data_ble": "🧤", "usb_glove": "🧤", "ble": "🎧", "gripper": "🤖"}`;`_GROUP_ORDER = ["camera", "glove", "gripper", "other_ble"]`;`_GROUP_TITLE` 对应中文组标题。
271
  - `_items`:device key → `QTreeWidgetItem`;`_last_check`:key → 上次勾选状态(防 `itemChanged` 误触发);`_group_expanded`:组展开状态(初始 camera/glove 展开、other_ble 折叠);`_has_gripper`:列表里是否有夹爪(决定底部提示是否提右键入口,两个分支都要更新,空设备分支需重置)。
272
  - 命名持久化:`config.settings.save_device_name`(device_names.json)。
273
 
274
+ **调用关系**:由 `ui/main_window.py` 构造并连接 `device_toggled`/`device_renamed`/`gripper_recalibration_requested`/`gripper_binding_requested`/`gripper_diagnostics_requested`(信号名按字符串 connect,写错不会报错、只是永远不触发 —— `tools/tests/test_gripper_esp_binding.py` §9 静态比对两处名字);`tools/tests/device_panel_gui_smoke_test.py` 直接构造。依赖 `config.settings.save_device_name`、`config.i18n.tr`。夹爪右键三条链路的完整链路(关夹爪 → 后台线程 → 完成后按原样开回)见 `docs/core.md`「夹爪」节与 `ui/main_window.py` 的 `_on_gripper_recalibration` / `_on_gripper_binding` / `_on_gripper_diagnostics`;三条共用 `_gripper_offline_guard`(序列号+录制检查)、`_gripper_offline_take_over`(让出串口)、`_reopen_after_offline`(善后)三件骨架。
275
 
276
  ### ui/exposure_dialog.py
277
 
collector/tools/audit_slam_line_classes.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """SLAM 桥接 stdout 的「行分类基线」——换核心前后做 A/B。
3
+
4
+ 为什么需要它:桥接与主程序之间靠 stdout 逐行文本协议说话,而
5
+ `core/gripper/slam/protocol.py` 里有一条**粘滞**的判据 `_ERROR_RE`
6
+ (命中即 ProtocolEvent("error") → state.error → 锁死 wait_sdk_ready 就绪门,
7
+ 2026-09-10 18:32 有过一次假超时的先例)。换 SLAM 核心之后,日志文本会变,
8
+ 必须能一眼看出「哪些行改了类」而不是靠肉眼看几十兆日志。
9
+
10
+ 用法:
11
+
12
+ # 冻结基线(换核心之前跑)
13
+ python3 tools/audit_slam_line_classes.py --capture baseline.json
14
+
15
+ # 换核心之后比对
16
+ python3 tools/audit_slam_line_classes.py --compare baseline.json
17
+
18
+ 比对是**确定性**的:同一批日志跑两次结果逐字节相同。
19
+
20
+ 注意区分两个概念(本工具都记):
21
+ * `error_classified`:真正走完 parse_slam_line 落到 "error" 分支的行
22
+ —— **这才是锁死就绪门的那个集合**;
23
+ * `error_re_raw`:`_ERROR_RE` 的裸命中集合(超集)。它更大,因为
24
+ parse_slam_line 对 `[FPS_DATA]` 等前缀会**提前返回**,那些行即便含
25
+ "cannot" 也不会变成 error。只看裸命中会高估风险。
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import argparse
31
+ import json
32
+ import sys
33
+ from collections import Counter
34
+ from pathlib import Path
35
+
36
+ REPO_ROOT = Path(__file__).resolve().parent.parent
37
+ sys.path.insert(0, str(REPO_ROOT))
38
+
39
+ from core.gripper.slam.protocol import ( # noqa: E402
40
+ _ERROR_RE,
41
+ parse_slam_line,
42
+ )
43
+
44
+ DEFAULT_LOG_DIR = REPO_ROOT / "logs" / "slam_native"
45
+
46
+
47
+ def _iter_bridge_lines(path: Path):
48
+ """Yield the raw bridge stdout lines out of an archived JSONL log.
49
+
50
+ 留档不是纯文本:每行是 `{"time":…, "arrival_monotonic":…, "line": "<原始行>"}`
51
+ (少数归档事件记录没有 `line` 字段)。**必须取内层 `line`**——实时链路
52
+ `parse_slam_line()` 看到的就是它;直接拿整个 JSON 信封去分类,会把
53
+ `"time": …` 这类信封字段也算进去,得到一份假的基线。
54
+ """
55
+ with path.open("r", encoding="utf-8", errors="replace") as fh:
56
+ for raw_line in fh:
57
+ raw_line = raw_line.strip()
58
+ if not raw_line:
59
+ continue
60
+ if raw_line.startswith("{"):
61
+ try:
62
+ record = json.loads(raw_line)
63
+ except json.JSONDecodeError:
64
+ yield raw_line # 坏 JSON:当纯文本处理,不静默丢
65
+ continue
66
+ if isinstance(record, dict) and "line" in record:
67
+ yield str(record["line"])
68
+ # 没有 line 的是归档事件(native_process_started 等),跳过
69
+ continue
70
+ yield raw_line
71
+
72
+
73
+ def classify_file(path: Path):
74
+ """Return (kind_counter, error_lines, raw_regex_lines) for one log."""
75
+ kinds: Counter[str] = Counter()
76
+ errors: Counter[str] = Counter()
77
+ raw_hits: Counter[str] = Counter()
78
+ for raw in _iter_bridge_lines(path):
79
+ raw = raw.strip()
80
+ if not raw:
81
+ continue
82
+ if _ERROR_RE.search(raw):
83
+ raw_hits[raw] += 1
84
+ event = parse_slam_line(raw)
85
+ if event is None:
86
+ continue
87
+ kinds[event.kind] += 1
88
+ if event.kind == "error":
89
+ errors[raw] += 1
90
+ return kinds, errors, raw_hits
91
+
92
+
93
+ def scan(log_dir: Path):
94
+ files = sorted(log_dir.glob("*_slam_stdout.log"))
95
+ if not files:
96
+ raise SystemExit(f"没有找到日志:{log_dir}/*_slam_stdout.log")
97
+
98
+ kinds_total: Counter[str] = Counter()
99
+ errors_total: Counter[str] = Counter()
100
+ raw_total: Counter[str] = Counter()
101
+ per_file = {}
102
+ for path in files:
103
+ kinds, errors, raw_hits = classify_file(path)
104
+ kinds_total.update(kinds)
105
+ errors_total.update(errors)
106
+ raw_total.update(raw_hits)
107
+ per_file[path.name] = sum(kinds.values())
108
+
109
+ return {
110
+ "log_dir": str(log_dir),
111
+ "file_count": len(files),
112
+ "parsed_lines_total": sum(kinds_total.values()),
113
+ "kinds": dict(sorted(kinds_total.items())),
114
+ "error_classified": dict(sorted(errors_total.items())),
115
+ "error_re_raw": dict(sorted(raw_total.items())),
116
+ "per_file_parsed": per_file,
117
+ }
118
+
119
+
120
+ def main() -> int:
121
+ ap = argparse.ArgumentParser(description=__doc__,
122
+ formatter_class=argparse.RawDescriptionHelpFormatter)
123
+ ap.add_argument("--log-dir", type=Path, default=DEFAULT_LOG_DIR)
124
+ g = ap.add_mutually_exclusive_group(required=True)
125
+ g.add_argument("--capture", type=Path, metavar="OUT.json",
126
+ help="把当前分类结果写成基线")
127
+ g.add_argument("--compare", type=Path, metavar="BASE.json",
128
+ help="与基线比对")
129
+ args = ap.parse_args()
130
+
131
+ current = scan(args.log_dir)
132
+
133
+ if args.capture:
134
+ args.capture.write_text(
135
+ json.dumps(current, ensure_ascii=False, indent=2, sort_keys=True),
136
+ encoding="utf-8",
137
+ )
138
+ print(f"[基线已冻结] {args.capture}")
139
+ print(f" 日志 {current['file_count']} 份,"
140
+ f"解析 {current['parsed_lines_total']} 行")
141
+ print(f" kind 分布:{current['kinds']}")
142
+ print(f" error 分类行:{len(current['error_classified'])} 种")
143
+ print(f" _ERROR_RE 裸命中:{len(current['error_re_raw'])} 种")
144
+ return 0
145
+
146
+ base = json.loads(args.compare.read_text(encoding="utf-8"))
147
+ problems = []
148
+
149
+ print(f"=== 与基线比对({args.compare})===")
150
+ if base["log_dir"] != current["log_dir"]:
151
+ print(f" [注] 日志目录不同:基线 {base['log_dir']} -> 现在 {current['log_dir']}")
152
+
153
+ base_kinds = Counter(base["kinds"])
154
+ cur_kinds = Counter(current["kinds"])
155
+ for kind in sorted(set(base_kinds) | set(cur_kinds)):
156
+ b, c = base_kinds.get(kind, 0), cur_kinds.get(kind, 0)
157
+ if b != c:
158
+ print(f" kind {kind!r}: {b} -> {c}")
159
+ if base_kinds == cur_kinds:
160
+ print(" kind 分布:一致")
161
+
162
+ print("\n--- 新增的 error 分类行(最要紧)---")
163
+ base_err = Counter(base["error_classified"])
164
+ cur_err = Counter(current["error_classified"])
165
+ new_err = cur_err - base_err
166
+ if new_err:
167
+ for line, n in sorted(new_err.items()):
168
+ print(f" [新增] x{n} {line}")
169
+ problems.append(f"{len(new_err)} 种新的 error 分类行")
170
+ else:
171
+ print(" 无(好)")
172
+
173
+ gone_err = base_err - cur_err
174
+ if gone_err:
175
+ print("\n--- 基线里有、现在没有的 error 行 ---")
176
+ for line, n in sorted(gone_err.items()):
177
+ print(f" [消失] x{n} {line}")
178
+
179
+ print("\n--- 新增的 _ERROR_RE 裸命中(提示性,未必真的锁门)---")
180
+ new_raw = Counter(current["error_re_raw"]) - Counter(base["error_re_raw"])
181
+ if new_raw:
182
+ for line, n in sorted(new_raw.items()):
183
+ print(f" [新增] x{n} {line}")
184
+ else:
185
+ print(" 无")
186
+
187
+ if problems:
188
+ print(f"\n[需人工判定] {'; '.join(problems)}")
189
+ print(" 逐条判:是「新文本恰好含 error/cannot 等词」,还是真出错。")
190
+ print(" 前者按 protocol.py 的 _IGNORED_NON_FATAL_RE 补白名单(留证据)。")
191
+ return 1
192
+ print("\n[通过] 没有新增的 error 分类行")
193
+ return 0
194
+
195
+
196
+ if __name__ == "__main__":
197
+ raise SystemExit(main())
collector/tools/tests/test_device_access_selflock.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """设备 guard 的「自己挡自己」误判 —— 离线自检(不碰真设备/真 SDK/真串口)。
4
+
5
+ QT_QPA_PLATFORM=offscreen venv/bin/python \
6
+ tools/tests/test_device_access_selflock.py
7
+
8
+ 背景:2026-09-24 现场日志里反复出现
9
+
10
+ ESP32 … 绑定的 Fays 序列号 3500000262300100 不在当前在线的 Fays 中,
11
+ 拒绝按端口或枚举顺序猜测配对:在线 serial=[<无>];
12
+ 另有正在被占用的 Fays 未能探测: [4-1.1(/dev/video0)]
13
+
14
+ 而同一份日志在 20 秒前刚打印过「租约已锁定: stereo=/dev/video0」——占用它的
15
+ 就是本进程自己。`fays_single._device_in_use` 原先只看 flock「加锁失败」就判定
16
+ 「别的会话在用」,但 **flock 绑在 open file description 上,不是进程上**:同一
17
+ 进程再 open 一次同一文件,非阻塞加锁照样 EWOULDBLOCK。于是本机唯一那台 Fays
18
+ 被自己跳过,「在线 serial」为空,配对失败关闭。
19
+
20
+ 覆盖:
21
+ 1. 前提本身:裸 fcntl 下同一进程两个 fd 也互斥(这条 OS 语义是修法的基础)
22
+ 2. device_guard_held_by_process 随持有/释放正确翻转
23
+ 3. 本进程持有时 _device_in_use **不**判为占用(本次修的 bug)
24
+ 4. 同线程嵌套持有:只加深度,不再开 fd(否则同一操作自己挡死自己)
25
+ 5. 同进程另一线程持有时:带 timeout 的调用**排队等到**,timeout=0 立刻失败
26
+ (现场形态:读出厂标定与启动身份探测在同一进程里抢同一把设备锁)
27
+ 6. 别的进程持有时 _device_in_use 仍判为占用(跨进程独占语义没被削弱)
28
+ 7. 节点无效时 _device_in_use 返回 False(留给 SDK 预检报错,行为不变)
29
+ 8. fays_device_guard_path 拒绝非 /dev/videoN
30
+ 9. UVC 配对失败文案带上逐组拒绝原因(原先只报 matches/groups 计数)
31
+
32
+ 退出码 0 = 全部通过。
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import fcntl
38
+ import os
39
+ import subprocess
40
+ import sys
41
+ import threading
42
+ import time
43
+
44
+ REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
45
+ os.path.abspath(__file__))))
46
+ sys.path.insert(0, REPO_ROOT)
47
+
48
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
49
+
50
+ from unittest import mock # noqa: E402
51
+
52
+ from core.gripper.fays_single import SingleFaysLease # noqa: E402
53
+ from core.gripper.runtime.device_access import ( # noqa: E402
54
+ device_guard_held_by_process,
55
+ device_access_guard,
56
+ fays_device_guard,
57
+ fays_device_guard_path,
58
+ )
59
+
60
+ FAILS = []
61
+
62
+ # 用 video997 这种不可能存在的节点名:走的是同一条按节点名取锁文件的代码路径,
63
+ # 但绝不会和真机上的会话抢同一把锁(测试跑的时候用户可能正在启动夹爪)。
64
+ FAKE_PORT = "/dev/video997"
65
+ LOCK_PATH = fays_device_guard_path(FAKE_PORT)
66
+
67
+ HOLDER_SRC = """
68
+ import fcntl, os, sys, time
69
+ fd = os.open(sys.argv[1], os.O_RDONLY | os.O_CREAT, 0o644)
70
+ fcntl.flock(fd, fcntl.LOCK_EX)
71
+ sys.stdout.write("HELD\\n")
72
+ sys.stdout.flush()
73
+ time.sleep(float(sys.argv[2]))
74
+ """
75
+
76
+
77
+ def check(cond, msg):
78
+ if cond:
79
+ print(f" PASS: {msg}")
80
+ else:
81
+ print(f" FAIL: {msg}")
82
+ FAILS.append(msg)
83
+
84
+
85
+ def test_flock_premise():
86
+ """前提:flock 绑在 open file description 上 —— 同一进程两个 fd 也互斥。"""
87
+ path = f"{LOCK_PATH}.premise"
88
+ fd1 = os.open(path, os.O_RDONLY | os.O_CREAT, 0o644)
89
+ fd2 = os.open(path, os.O_RDONLY | os.O_CREAT, 0o644)
90
+ try:
91
+ fcntl.flock(fd1, fcntl.LOCK_EX | fcntl.LOCK_NB)
92
+ second_blocked = False
93
+ try:
94
+ fcntl.flock(fd2, fcntl.LOCK_EX | fcntl.LOCK_NB)
95
+ except BlockingIOError:
96
+ second_blocked = True
97
+ check(second_blocked,
98
+ "flock 前提:同一进程第二个 fd 非阻塞加锁被拒(这就是误判的来源)")
99
+ check(not device_guard_held_by_process(path),
100
+ "裸 fcntl 加锁不进登记表(登记表只由 device_access_guard 维护)")
101
+ finally:
102
+ os.close(fd2)
103
+ os.close(fd1)
104
+
105
+
106
+ def test_registry_tracks_hold():
107
+ check(not device_guard_held_by_process(LOCK_PATH),
108
+ "未持有时登记表为 False")
109
+ with fays_device_guard(FAKE_PORT, timeout=0.0):
110
+ check(device_guard_held_by_process(LOCK_PATH),
111
+ "持有时登记表为 True")
112
+ check(SingleFaysLease._device_in_use(
113
+ {"ports": {"stereo_dev_port": FAKE_PORT}}) is False,
114
+ "本进程自己持有 → 不判为「别的会话占用」(修的就是这条)")
115
+ check(not device_guard_held_by_process(LOCK_PATH),
116
+ "释放后登记表回到 False")
117
+
118
+
119
+ def test_nested_hold_depth():
120
+ with fays_device_guard(FAKE_PORT, timeout=0.0):
121
+ with fays_device_guard(FAKE_PORT, timeout=0.0):
122
+ check(device_guard_held_by_process(LOCK_PATH),
123
+ "嵌套持有期间仍登记为 True")
124
+ check(device_guard_held_by_process(LOCK_PATH),
125
+ "内层退出没解掉外层的持有(深度计数正确)")
126
+ check(not device_guard_held_by_process(LOCK_PATH),
127
+ "全部退出后登记表清空")
128
+
129
+
130
+ def test_cross_thread_waits():
131
+ """同进程另一线程正在用:带 timeout 的调用排队等到,timeout=0 立刻失败。
132
+
133
+ 现场形态就是这个:读出厂标定(calibration.py,持锁十几秒)与启动时的身份
134
+ 探测(fays_serial_probe.py)在同一个进程里跑,后者必须等,不能失败。
135
+ """
136
+ holding = threading.Event()
137
+ released = threading.Event()
138
+
139
+ def holder():
140
+ with fays_device_guard(FAKE_PORT, timeout=0.0):
141
+ holding.set()
142
+ released.wait(timeout=10)
143
+
144
+ thread = threading.Thread(target=holder, daemon=True)
145
+ thread.start()
146
+ check(holding.wait(timeout=5), "持锁线程已进入 guard")
147
+ check(device_guard_held_by_process(LOCK_PATH),
148
+ "另一线程持有 → 登记表仍为 True(guard 是全进程的)")
149
+
150
+ busy_failed = False
151
+ try:
152
+ with fays_device_guard(FAKE_PORT, timeout=0.0):
153
+ pass
154
+ except RuntimeError:
155
+ busy_failed = True
156
+ check(busy_failed, "同进程另一线程持有时 timeout=0 立刻失败(探测语义不变)")
157
+
158
+ waited = {"ok": False}
159
+
160
+ def waiter():
161
+ with fays_device_guard(FAKE_PORT, timeout=10.0):
162
+ waited["ok"] = True
163
+
164
+ thread2 = threading.Thread(target=waiter, daemon=True)
165
+ thread2.start()
166
+ time.sleep(0.3)
167
+ released.set()
168
+ thread.join(timeout=10)
169
+ thread2.join(timeout=10)
170
+ check(waited["ok"], "带 timeout 的调用排到队(等待而不是失败)")
171
+ check(not device_guard_held_by_process(LOCK_PATH), "全部退出后登记表清空")
172
+
173
+
174
+ def test_other_process_still_blocks():
175
+ """别的进程持有时必须仍然判为占用 —— 否则修法等于把独占语义关掉。"""
176
+ proc = subprocess.Popen(
177
+ [sys.executable, "-c", HOLDER_SRC, LOCK_PATH, "10"],
178
+ stdout=subprocess.PIPE, text=True)
179
+ try:
180
+ line = proc.stdout.readline().strip()
181
+ check(line == "HELD", "子进程成功持有 guard")
182
+ check(SingleFaysLease._device_in_use(
183
+ {"ports": {"stereo_dev_port": FAKE_PORT}}) is True,
184
+ "别的进程持有 → 仍判为占用(跨进程独占没被削弱)")
185
+ check(not device_guard_held_by_process(LOCK_PATH),
186
+ "别的进程的持有不进本进程登记表")
187
+ finally:
188
+ proc.terminate()
189
+ proc.wait(timeout=5)
190
+
191
+
192
+ def test_invalid_node():
193
+ check(SingleFaysLease._device_in_use(
194
+ {"ports": {"stereo_dev_port": "/dev/ttyACM0"}}) is False,
195
+ "节点不是 /dev/videoN → 不判占用(留给 SDK 预检报错,行为不变)")
196
+ check(SingleFaysLease._device_in_use({"ports": {}}) is False,
197
+ "缺 stereo 端口 → 不判占用")
198
+ raised = False
199
+ try:
200
+ fays_device_guard_path("/dev/ttyACM0")
201
+ except RuntimeError:
202
+ raised = True
203
+ check(raised, "fays_device_guard_path 拒绝非 /dev/videoN")
204
+
205
+
206
+ def test_pairing_message_carries_reason():
207
+ """配对失败必须把逐组拒绝原因带出来,不能只剩 matches/groups 计数。"""
208
+ from core.gripper.devices.uvc_camera_service import (
209
+ UvcCameraServiceError, UvcCameraServiceManager,
210
+ )
211
+
212
+ service = object.__new__(UvcCameraServiceManager)
213
+ reason = "sightac mode=failed error='MJPEG 640x480@30: Invalid mode'"
214
+ group = {"physical_usb_path": "3-1", "valid": False}
215
+ with mock.patch.object(service, "_discovery_scope", return_value=(3, "1")), \
216
+ mock.patch.object(service, "_run_discovery", return_value=[group]), \
217
+ mock.patch.object(service, "_associate_group",
218
+ side_effect=UvcCameraServiceError(reason)), \
219
+ mock.patch.object(service, "_assignment_identity",
220
+ return_value=("68:EE:8F:C6:0D:20", "3500000262300100")):
221
+ try:
222
+ service._resolve_current_group({"id": "umi"})
223
+ check(False, "配对不唯一时必须抛错")
224
+ except UvcCameraServiceError as exc:
225
+ text = str(exc)
226
+ check("matches=0" in text and "groups=1" in text,
227
+ "文案仍保留 matches/groups 计数")
228
+ check(reason in text, "文案带上了逐组拒绝原因(真因不再被吞)")
229
+
230
+
231
+ def main():
232
+ print("[1. flock 前提]")
233
+ test_flock_premise()
234
+ print("\n[2. 登记表随持有/释放翻转]")
235
+ test_registry_tracks_hold()
236
+ print("\n[3. 嵌套持有深度]")
237
+ test_nested_hold_depth()
238
+ print("\n[4. 同进程跨线程排队]")
239
+ test_cross_thread_waits()
240
+ print("\n[5. 跨进程独占仍然生效]")
241
+ test_other_process_still_blocks()
242
+ print("\n[6. 无效节点行为不变]")
243
+ test_invalid_node()
244
+ print("\n[7. 配对失败文案带原因]")
245
+ test_pairing_message_carries_reason()
246
+
247
+ print()
248
+ if FAILS:
249
+ print(f"❌ {len(FAILS)} 项失败:")
250
+ for item in FAILS:
251
+ print(f" - {item}")
252
+ return 1
253
+ print("✅ 全部通过")
254
+ return 0
255
+
256
+
257
+ if __name__ == "__main__":
258
+ sys.exit(main())
collector/tools/tests/test_gripper_calibration_autogen.py CHANGED
@@ -776,10 +776,13 @@ def test_device_panel_menu():
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}")
@@ -788,7 +791,12 @@ def test_device_panel_menu():
788
  "没有夹爪时不提右键入口")
789
 
790
  emitted = []
791
- panel.gripper_recalibration_requested.connect(emitted.append)
 
 
 
 
 
792
 
793
  class _FakeAction:
794
  def __init__(self, text):
@@ -801,6 +809,7 @@ def test_device_panel_menu():
801
  class _FakeMenu:
802
  last = None
803
  accept = False # True → exec_ 返回本次刚建的那一项(模拟用户点选)
 
804
 
805
  def __init__(self, _parent):
806
  _FakeMenu.last = self
@@ -813,7 +822,14 @@ def test_device_panel_menu():
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()
@@ -824,26 +840,33 @@ def test_device_panel_menu():
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()
 
776
  "先决条件:DeviceInfo.group 按 kind 派生正确")
777
  panel.set_devices([gripper, camera])
778
 
779
+ for name in ("gripper_recalibration_requested",
780
+ "gripper_binding_requested",
781
+ "gripper_diagnostics_requested"):
782
+ check(hasattr(panel, name), f"面板暴露 {name} 信号")
783
  # 与实现同一口径取自翻译表,语言切换下都成立(英文界面断言中文会误判)
784
+ hint_with = tr("双击设备可重命名") + tr(
785
+ ";右键夹爪可重读标定 / 配对序列号 / 串口诊断")
786
  hint_without = tr("双击设备可重命名")
787
  check(panel._refresh_hint.text() == hint_with,
788
  f"有夹爪时底部提示右键入口:{panel._refresh_hint.text()!r}")
 
791
  "没有夹爪时不提右键入口")
792
 
793
  emitted = []
794
+ panel.gripper_recalibration_requested.connect(
795
+ lambda dev: emitted.append(("recalib", dev)))
796
+ panel.gripper_binding_requested.connect(
797
+ lambda dev: emitted.append(("binding", dev)))
798
+ panel.gripper_diagnostics_requested.connect(
799
+ lambda dev: emitted.append(("diagnostics", dev)))
800
 
801
  class _FakeAction:
802
  def __init__(self, text):
 
809
  class _FakeMenu:
810
  last = None
811
  accept = False # True → exec_ 返回本次刚建的那一项(模拟用户点选)
812
+ pick = 0 # 点第几项
813
 
814
  def __init__(self, _parent):
815
  _FakeMenu.last = self
 
822
 
823
  def exec_(self, _pos):
824
  # 必须回传自己 addAction 造的那个对象(实现按 `chosen is action` 判等)
825
+ if not _FakeMenu.accept or not self.actions:
826
+ return None
827
+ return self.actions[min(_FakeMenu.pick, len(self.actions) - 1)]
828
+
829
+ # 菜单项顺序是契约的一部分:重读标定必须留在第一项
830
+ menu_texts = [tr("重新读取出厂标定"), tr("读取/写入 Fays 绑定序列号"),
831
+ tr("ESP32 串口诊断")]
832
+ menu_actions = ["recalib", "binding", "diagnostics"]
833
 
834
  panel.set_devices([gripper, camera])
835
  gpos = panel._tree.visualItemRect(panel._items[gripper.key]).center()
 
840
  _FakeMenu.last = None
841
  panel._on_context_menu(cpos)
842
  check(_FakeMenu.last is None, "相机行右键不弹夹爪菜单(无菜单对象)")
843
+ check(emitted == [], "相机行不发夹爪信号")
844
 
845
  _FakeMenu.last = None
846
  panel._on_context_menu(gpos)
847
  menu = _FakeMenu.last
848
+ check(menu is not None and len(menu.actions) == len(menu_texts),
849
+ f"夹爪行右键弹出菜单,共 {len(menu_texts)} 项")
850
+ check([a.text for a in menu.actions] == menu_texts,
851
+ f"菜单文案与顺序:{[a.text for a in menu.actions]!r}")
852
  check(emitted == [], "只弹菜单不选 → 不发信号")
853
 
854
+ # 每一项都要能选中,且发的是它自己那条信号
855
+ for index, (want, text) in enumerate(zip(menu_actions, menu_texts)):
856
+ emitted.clear()
857
+ _FakeMenu.accept = True
858
+ _FakeMenu.pick = index
859
+ panel._on_context_menu(gpos)
860
+ check(emitted and emitted[-1][0] == want
861
+ and emitted[-1][1].key == gripper.key,
862
+ f"选中「{text}」→ 发 {want} 信号带该夹爪:{emitted}")
863
 
864
  panel.set_locked(True)
865
  before = len(emitted)
866
+ for index in range(len(menu_texts)):
867
+ _FakeMenu.pick = index
868
+ panel._on_context_menu(gpos)
869
+ check(len(emitted) == before, "录制中三项都不触发(设备要独占)")
870
  panel.set_locked(False)
871
 
872
  panel.deleteLater()
collector/tools/tests/test_gripper_esp_binding.py ADDED
@@ -0,0 +1,1147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """夹爪配对与串口诊断 —— 离线自检(不碰真设备/真 SDK/真串口)。
4
+
5
+ QT_QPA_PLATFORM=offscreen venv/bin/python \
6
+ tools/tests/test_gripper_esp_binding.py
7
+
8
+ 背景:接新的夹爪时主程序报
9
+ ``ESP32 AC:27:6E:C7:BA:68 串口连接失败,无法查询绑定的 Fays 序列号:
10
+ serial open/handshake failed: Write timeout``,用户无法判断板子到底是坏了、
11
+ 没烧固件还是串口被别的进程占着。为此主程序夹爪右键菜单加了两个入口:
12
+
13
+ * ESP32 串口诊断 —— 只读地把板上原样输出打出来,回答「板子在不在说话」
14
+ * 读取/写入 Fays 绑定序列号 —— 读 ``QF`` / 写 ``WF:``,新板子不必再开
15
+ 厂商工具包 GUI
16
+
17
+ 本测试用假串口/假设备枚举/假单板租约,逐条钉住「失败关闭 + 如实汇报」:
18
+
19
+ 覆盖:
20
+ 1. GripperSerial.read_lines:只读收集、跳过空行、上限、串口没开的空返回
21
+ 1b. open_readonly / handshake:只读打开一个字节都不写、能收 TX 侧输出、
22
+ 随后可补握手;没打开就握手如实报错
23
+ 2. esp_binding_status:已绑定 / 未绑定(不算失败)/ 读不通带底层原文 /
24
+ 缺串口节点;任何路径都不抛异常,且总是归还串口
25
+ 3. online_fays_serials:枚举口径与 acquire 一致;无完整设备组时明确报错
26
+ 4. write_bound_serial:缺节点/连不上/写失败都带原因抛出;回读空值不谎报成功
27
+ 5. esp_console_report:连上才发 ? 与 QF(不多发命令);连不上如实带串口层原文,
28
+ 并且**仍然只读复检一次**(写阻塞时也只有这条路能拿到 TX 侧证据)
29
+ 6. 主窗口离线骨架:前置检查、暂时关闭与开回、录制中不给入口
30
+ 7. 主窗口绑定流程:探板失败不开回;没找到在线 Fays 就停手;挑目标 → 写入 →
31
+ 回读一致才说成功
32
+ 8. 主窗口串口诊断:原文进日志、摘要进弹窗;只读操作一律开回
33
+ 9. 面板信号名与主窗口 connect 的名字一致(信号名打错就永远不触发)
34
+ 10. 「板子没在服务串口」的处置提示:写超时/无应答族才追加,口被占/没权限/
35
+ 缺节点不加(主机侧原因不该被引到重烧固件上去)
36
+
37
+ 退出码 0 = 全部通过。
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import os
43
+ import sys
44
+ from functools import partial
45
+
46
+ REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
47
+ os.path.abspath(__file__))))
48
+ sys.path.insert(0, REPO_ROOT)
49
+
50
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
51
+
52
+ from unittest import mock # noqa: E402
53
+
54
+ import serial # noqa: E402
55
+
56
+ from core.gripper import fays_single # noqa: E402
57
+ from core.gripper.devices.gripper_serial import GripperSerial # noqa: E402
58
+ from core.gripper.fays_single import ( # noqa: E402
59
+ GripperFaysError, SingleFaysLease,
60
+ )
61
+
62
+ FAILS = []
63
+ ESP_SERIAL = "AC:27:6E:C7:BA:68"
64
+ FAYS_SERIAL = "3500000262300089"
65
+ OTHER_FAYS_SERIAL = "3500000262300097"
66
+ WRITE_TIMEOUT = "serial open/handshake failed: Write timeout"
67
+
68
+
69
+ def check(cond, msg):
70
+ if cond:
71
+ print(f" PASS: {msg}")
72
+ else:
73
+ print(f" FAIL: {msg}")
74
+ FAILS.append(msg)
75
+
76
+
77
+ def section(title):
78
+ print(f"\n[{title}]")
79
+
80
+
81
+ def _esp(serial=ESP_SERIAL, device="/dev/ttyACM0", physical="1-2.2.1"):
82
+ return {
83
+ "serial": serial,
84
+ "device": device,
85
+ "physical_usb_path": physical,
86
+ "vendor_id": "303a",
87
+ "product_id": "1001",
88
+ }
89
+
90
+
91
+ def _fays_group(physical="1-2.3", stereo="/dev/video4", imu="/dev/video5"):
92
+ """一台完整 S80M(stereo 接口 00 + IMU 接口 02)。"""
93
+ return {
94
+ "physical_usb_path": physical,
95
+ "ports": {"stereo_dev_port": stereo, "imu_dev_port": imu},
96
+ "stereo": {"device": stereo, "physical_usb_path": physical,
97
+ "usb_device_sysfs_path": f"/sys/bus/usb/devices/{physical}",
98
+ "interface_number": "00"},
99
+ "imu": {"device": imu, "physical_usb_path": physical,
100
+ "usb_device_sysfs_path": f"/sys/bus/usb/devices/{physical}",
101
+ "interface_number": "02"},
102
+ "config_updated": False,
103
+ }
104
+
105
+
106
+ class _Clock:
107
+ """可推进的假时钟:read_lines 的截止时间是按秒算的,真等会拖慢测试。"""
108
+
109
+ def __init__(self, now=1000.0):
110
+ self.now = now
111
+
112
+ def __call__(self):
113
+ return self.now
114
+
115
+ def advance(self, dt):
116
+ self.now += dt
117
+
118
+
119
+ class _ScriptedSerial:
120
+ """假串口:握手固定回 STATE,其余行按脚本逐条喂。
121
+
122
+ None 表示「这一行读到空」(CDC 超时/空行);``boom_at`` 之后 readline
123
+ 抛 IOError,用来复现「板子中途掉线」。每次读都推进假时钟,所以脚本耗尽
124
+ 后 read_lines 会在假时间里走到截止,而不是死循环。
125
+ """
126
+
127
+ def __init__(self, lines, clock, *, step=0.1, boom_at=None):
128
+ self._lines = list(lines)
129
+ self._clock = clock
130
+ self._step = step
131
+ self._boom_at = boom_at
132
+ self._reads = 0
133
+ self.is_open = True
134
+ self.writes = []
135
+ self._handshake = False
136
+
137
+ def reset_input_buffer(self):
138
+ pass
139
+
140
+ def write(self, data):
141
+ self.writes.append(data)
142
+ self._handshake = (data == b"?\r\n")
143
+
144
+ def readline(self):
145
+ self._clock.advance(self._step)
146
+ self._reads += 1
147
+ if self._boom_at is not None and self._reads > self._boom_at:
148
+ raise IOError("device disconnected")
149
+ if self._handshake:
150
+ self._handshake = False
151
+ return b"STATE ST=0 RAW=0 PCT=0 Z=0 L=0\r\n"
152
+ if not self._lines:
153
+ return b""
154
+ line = self._lines.pop(0)
155
+ return b"" if line is None else (line + "\r\n").encode()
156
+
157
+ def cancel_write(self):
158
+ pass
159
+
160
+ def reset_output_buffer(self):
161
+ pass
162
+
163
+ def close(self):
164
+ self.is_open = False
165
+
166
+
167
+ def _read_bridge(lines, *, step=0.1, boom_at=None):
168
+ """返回 (已握手的 GripperSerial, 假串口, 假时钟)。"""
169
+ clock = _Clock()
170
+ holder = {}
171
+ fake = _ScriptedSerial(lines, clock, step=step, boom_at=boom_at)
172
+
173
+ def factory(port, baud, **kwargs):
174
+ holder["port"] = port
175
+ return fake
176
+
177
+ bridge = GripperSerial(serial_factory=factory, clock=clock,
178
+ sleep=lambda _s: None,
179
+ logger=lambda *_a, **_k: None)
180
+ check(bridge.connect("/dev/ttyACM0"), "先决条件:假串口握手成功")
181
+ return bridge, fake, clock
182
+
183
+
184
+ # ═══════════════════════════════════════════════════════════════════
185
+ # 1. GripperSerial.read_lines
186
+ # ═══════════════════════════════════════════════════════════════════
187
+
188
+ def test_read_lines():
189
+ section("1. GripperSerial.read_lines(只读诊断)")
190
+ bridge, fake, _clock = _read_bridge(
191
+ ["STATE ST=0 RAW=1", None, "DATA 1 2 3", ""])
192
+ before = list(fake.writes)
193
+ lines = bridge.read_lines(3.0)
194
+ check(lines == ["STATE ST=0 RAW=1", "DATA 1 2 3"],
195
+ f"收集到板上主动输出的整行、跳过空行:{lines}")
196
+ check(fake.writes == before,
197
+ "只读:除握手那条 ? 外不再往板子写任何命令")
198
+
199
+ bridge, _fake, _c = _read_bridge([None, None])
200
+ check(bridge.read_lines(1.0) == [],
201
+ "板子一行都不吐 → 空列表(=没有程序在写这个口)")
202
+
203
+ bridge, _fake, _c = _read_bridge([f"L{i}" for i in range(50)])
204
+ check(len(bridge.read_lines(10.0, limit=5)) == 5,
205
+ "limit 封顶:行数上限生效,不会把内存读爆")
206
+
207
+ bridge, _fake, _c = _read_bridge(["A", "B", "C"], boom_at=3)
208
+ check(bridge.read_lines(3.0) == ["A", "B"],
209
+ "中途掉线:已收到的行仍然如实返回(不吞掉证据)")
210
+
211
+ bridge, _fake, _c = _read_bridge([])
212
+ bridge.disconnect()
213
+ check(bridge.read_lines(1.0) == [],
214
+ "串口没打开时返回空列表(不抛异常、不偷偷开端口)")
215
+
216
+
217
+ def test_open_readonly():
218
+ section("1b. open_readonly / handshake(写阻塞时仍能拿到 TX 侧证据)")
219
+ clock = _Clock()
220
+ fake = _ScriptedSerial(["OTA AP: ESP32_OTA IP: 192.168.4.1", "READY"],
221
+ clock)
222
+
223
+ def factory(port, baud, **kwargs):
224
+ return fake
225
+
226
+ bridge = GripperSerial(serial_factory=factory, clock=clock,
227
+ sleep=lambda _s: None, logger=lambda *_a, **_k: None)
228
+ check(bridge.open_readonly("/dev/ttyACM0"), "只读打开成功")
229
+ check(fake.writes == [],
230
+ f"一个字节都没往板子写(写阻塞的板子也因此读得到):{fake.writes}")
231
+ lines = bridge.read_lines(3.0)
232
+ check(lines == ["OTA AP: ESP32_OTA IP: 192.168.4.1", "READY"],
233
+ f"只读打开后能收板上原生输出:{lines}")
234
+ check(fake.writes == [], "收完还是没写过任何命令")
235
+ check(bridge.handshake(), "随后可以在这条已打开的口上补握手")
236
+ check(fake.writes == [b"?\r\n"], f"握手才写出那一条 ?:{fake.writes}")
237
+
238
+ # 没打开就握手:如实报错,不去偷偷开端口
239
+ bridge = GripperSerial(serial_factory=factory, clock=clock,
240
+ sleep=lambda _s: None, logger=lambda *_a, **_k: None)
241
+ check(bridge.handshake() is False
242
+ and "not open" in str(bridge.last_error),
243
+ f"没打开就握手:报错而不是假装成功:{bridge.last_error}")
244
+
245
+ # 打开失败:与 connect 同一口径(口被占/权限/节点不在都走这里)
246
+ def busy_factory(port, baud, **kwargs):
247
+ raise IOError(16, "Device or resource busy")
248
+
249
+ bridge = GripperSerial(serial_factory=busy_factory, clock=clock,
250
+ sleep=lambda _s: None, logger=lambda *_a, **_k: None)
251
+ check(bridge.open_readonly("/dev/ttyACM0") is False
252
+ and "Device or resource busy" in str(bridge.last_error),
253
+ f"口被占时只读打开也如实失败:{bridge.last_error}")
254
+
255
+
256
+ # ═══════════════════════════════════════════════════════════════════
257
+ # 2-5. SingleFaysLease 的四个对外方法
258
+ # ═══════════════════════════════════════════════════════════════════
259
+
260
+ def _lease_with(responses, *, connect_ok=True, last_error=None, lines=(),
261
+ esp=None, raise_on=None):
262
+ """(假单板租约, 假 GripperSerial 实例)。
263
+
264
+ ``raise_on`` 是 ``{方法名: 异常}``:让某一步抛错,验证异常原样上传。
265
+ """
266
+ instance = mock.MagicMock()
267
+ instance.connect.return_value = connect_ok
268
+ instance.last_error = last_error
269
+ instance.send.side_effect = list(responses)
270
+ instance.read_lines.return_value = list(lines)
271
+ for name, exc in (raise_on or {}).items():
272
+ getattr(instance, name).side_effect = exc
273
+ lease = SingleFaysLease(logger=lambda _t: None)
274
+ return lease, instance
275
+
276
+
277
+ def _patch_lease(instance, esp=None):
278
+ """把 fays_single 的板子枚举与 GripperSerial 一起换掉。"""
279
+ return (
280
+ mock.patch.object(fays_single, "discover_esp32_devices",
281
+ return_value=list(esp if esp is not None
282
+ else [_esp()])),
283
+ mock.patch.object(fays_single, "GripperSerial",
284
+ return_value=instance),
285
+ )
286
+
287
+
288
+ def test_esp_binding_status():
289
+ section("2. esp_binding_status(读现状,未绑定不算失败)")
290
+ lease, instance = _lease_with([f"FAYS_SERIAL:{FAYS_SERIAL}"])
291
+ esp_p, serial_p = _patch_lease(instance)
292
+ with esp_p, serial_p:
293
+ status = lease.esp_binding_status(ESP_SERIAL)
294
+ check(status["bound"] == FAYS_SERIAL and status["reason"] == "",
295
+ f"已绑定:{status}")
296
+ check(status["device"] == "/dev/ttyACM0",
297
+ "回报的是实际打开的那个串口节点")
298
+ check(instance.disconnect.called, "读完就把串口还回去")
299
+
300
+ lease, instance = _lease_with(["ERR FAYS_SERIAL_NOT_SET"])
301
+ esp_p, serial_p = _patch_lease(instance)
302
+ with esp_p, serial_p:
303
+ status = lease.esp_binding_status(ESP_SERIAL)
304
+ check(status["bound"] == "" and status["reason"] == "",
305
+ f"未绑定是正常状态(新板子):{status}")
306
+ check(status["response"] == "ERR FAYS_SERIAL_NOT_SET",
307
+ "板上原话照样带回,界面可显示")
308
+
309
+ lease, instance = _lease_with(["STATE ST=0", "FAYS_SERIAL:" + FAYS_SERIAL])
310
+ esp_p, serial_p = _patch_lease(instance)
311
+ with esp_p, serial_p, mock.patch.object(fays_single.time, "sleep"):
312
+ status = lease.esp_binding_status(ESP_SERIAL)
313
+ check(status["bound"] == FAYS_SERIAL,
314
+ "固件插进来的 STATE 行不误判成「未绑定」(重试取真响应)")
315
+
316
+ lease, instance = _lease_with(["ERR"])
317
+ esp_p, serial_p = _patch_lease(instance)
318
+ with esp_p, serial_p:
319
+ status = lease.esp_binding_status(ESP_SERIAL)
320
+ check(status["bound"] == "" and "查询绑定序列号失败" in status["reason"],
321
+ f"老固件不认 QF → 当读不通(不猜):{status['reason']}")
322
+
323
+ lease, instance = _lease_with([], connect_ok=False,
324
+ last_error=WRITE_TIMEOUT)
325
+ esp_p, serial_p = _patch_lease(instance)
326
+ with esp_p, serial_p:
327
+ status = lease.esp_binding_status(ESP_SERIAL)
328
+ check(status["reason"] == f"串口连接失败: {WRITE_TIMEOUT}",
329
+ f"连不上时带上串口层原文:{status['reason']}")
330
+ check(not instance.send.called,
331
+ "没连上就不发命令(板子没在服务串口,多写只会更堵)")
332
+ check(status["esp_serial"] == ESP_SERIAL,
333
+ "连不上也回报是哪个板子,用户才知道该拔哪根线")
334
+
335
+ lease, instance = _lease_with([])
336
+ esp_p, serial_p = _patch_lease(instance, esp=[_esp(device="")])
337
+ with esp_p, serial_p:
338
+ status = lease.esp_binding_status(ESP_SERIAL)
339
+ check("缺少串口节点" in status["reason"],
340
+ f"节点缺失如实报:{status['reason']}")
341
+
342
+ lease, instance = _lease_with([])
343
+ esp_p, serial_p = _patch_lease(instance, esp=[])
344
+ with esp_p, serial_p:
345
+ try:
346
+ lease.esp_binding_status(ESP_SERIAL)
347
+ check(False, "板子不在列表里应拒绝")
348
+ except GripperFaysError as exc:
349
+ check("未唯一匹配" in str(exc),
350
+ f"板子按 USB serial 唯一匹配,找不到就拒绝:{exc}")
351
+
352
+
353
+ def test_online_fays_serials():
354
+ section("3. online_fays_serials(在线 Fays 枚举口径)")
355
+ lease, _instance = _lease_with([])
356
+ group = _fays_group()
357
+ with mock.patch.object(fays_single, "discover_fays_device_groups",
358
+ return_value=[group]), \
359
+ mock.patch.object(fays_single, "validate_fays_superspeed"), \
360
+ mock.patch.object(SingleFaysLease, "_device_in_use",
361
+ return_value=False), \
362
+ mock.patch.object(fays_single, "probe_product_serial",
363
+ return_value=FAYS_SERIAL), \
364
+ mock.patch.object(fays_single, "build_fays_probe_env",
365
+ return_value={}), \
366
+ mock.patch.object(fays_single, "validate_fays_sdk_access"):
367
+ by_serial, skipped = lease.online_fays_serials()
368
+ check(list(by_serial) == [FAYS_SERIAL] and skipped == [],
369
+ f"列出在线序列号 → 给界面挑:{list(by_serial)}")
370
+ check(by_serial[FAYS_SERIAL] is group, "序列号映射回设备组(写入后要靠它)")
371
+
372
+ lease, _instance = _lease_with([])
373
+ with mock.patch.object(fays_single, "discover_fays_device_groups",
374
+ return_value=[]):
375
+ try:
376
+ lease.online_fays_serials()
377
+ check(False, "没有完整 Fays 设备组时应明确报错")
378
+ except GripperFaysError as exc:
379
+ check("未发现完整的 Fays S80M" in str(exc),
380
+ f"无设备组时明说缺什么(stereo + IMU 都要在):{exc}")
381
+
382
+
383
+ def test_write_bound_serial():
384
+ section("4. write_bound_serial(写 NVS + 回读)")
385
+ lease, instance = _lease_with([])
386
+ instance.query_fays_serial.return_value = FAYS_SERIAL
387
+ esp_p, serial_p = _patch_lease(instance)
388
+ with esp_p, serial_p:
389
+ readback = lease.write_bound_serial(ESP_SERIAL, FAYS_SERIAL)
390
+ check(readback == FAYS_SERIAL, f"写完立刻回读:{readback}")
391
+ check(instance.set_fays_serial.call_args == mock.call(FAYS_SERIAL),
392
+ "写的是用户挑的那一台(WF:<serial>)")
393
+ check(instance.disconnect.called, "写完就把串口还回去")
394
+
395
+ lease, instance = _lease_with([])
396
+ instance.query_fays_serial.return_value = ""
397
+ esp_p, serial_p = _patch_lease(instance)
398
+ with esp_p, serial_p:
399
+ readback = lease.write_bound_serial(ESP_SERIAL, FAYS_SERIAL)
400
+ check(readback == "", "回读为空就是空(不谎报写入成功)")
401
+
402
+ lease, instance = _lease_with([], connect_ok=False,
403
+ last_error=WRITE_TIMEOUT)
404
+ esp_p, serial_p = _patch_lease(instance)
405
+ with esp_p, serial_p:
406
+ try:
407
+ lease.write_bound_serial(ESP_SERIAL, FAYS_SERIAL)
408
+ check(False, "连不上时应抛出")
409
+ except GripperFaysError as exc:
410
+ check(WRITE_TIMEOUT in str(exc) and ESP_SERIAL in str(exc),
411
+ f"连不上带板子与串口层原文:{exc}")
412
+ check(not instance.set_fays_serial.called,
413
+ "没连上就不发 WF(避免半条命令留在 FIFO 里)")
414
+
415
+ lease, instance = _lease_with([])
416
+ esp_p, serial_p = _patch_lease(instance, esp=[_esp(device="")])
417
+ with esp_p, serial_p:
418
+ try:
419
+ lease.write_bound_serial(ESP_SERIAL, FAYS_SERIAL)
420
+ check(False, "缺串口节点时应抛出")
421
+ except GripperFaysError as exc:
422
+ check("缺少串口节点" in str(exc), f"缺节点如实报:{exc}")
423
+
424
+ lease, instance = _lease_with(
425
+ [], raise_on={"set_fays_serial": RuntimeError(
426
+ "ESP32 写入 Fays 序列号失败: ERR FAYS_SERIAL_INVALID")})
427
+ esp_p, serial_p = _patch_lease(instance)
428
+ with esp_p, serial_p:
429
+ try:
430
+ lease.write_bound_serial(ESP_SERIAL, "bad serial")
431
+ check(False, "板上拒绝写入时应抛出")
432
+ except RuntimeError as exc:
433
+ check("FAYS_SERIAL_INVALID" in str(exc),
434
+ f"板上回执原文上传给界面:{exc}")
435
+ check(instance.disconnect.called, "写失败也要归还串口(finally 路径)")
436
+
437
+
438
+ def test_esp_console_report():
439
+ section("5. esp_console_report(只读诊断)")
440
+ lease, instance = _lease_with(
441
+ ["STATE ST=0 RAW=0", f"FAYS_SERIAL:{FAYS_SERIAL}"],
442
+ lines=["STATE ST=0 RAW=0", "DATA 1 2 3"])
443
+ esp_p, serial_p = _patch_lease(instance)
444
+ with esp_p, serial_p:
445
+ report = lease.esp_console_report(ESP_SERIAL)
446
+ check(report["connected"] is True, "连上标记为真")
447
+ check(report["state"] == "STATE ST=0 RAW=0", "带回 ? 的原样响应")
448
+ check(report["bound"] == f"FAYS_SERIAL:{FAYS_SERIAL}",
449
+ "带回 QF 的原样响应(界面原样显示,不再解析一遍)")
450
+ check(report["lines"] == ["STATE ST=0 RAW=0", "DATA 1 2 3"],
451
+ "带回随后板上主动输出的整行")
452
+ check(report["esp_serial"] == ESP_SERIAL
453
+ and report["device"] == "/dev/ttyACM0"
454
+ and report["physical_usb_path"] == "1-2.2.1",
455
+ "身份三件套齐全(序列号/节点/物理口)")
456
+ check(report["seconds"] == 3.0, "默认收 3 秒")
457
+ check(instance.send.call_args_list == [mock.call("?"), mock.call("QF")],
458
+ f"诊断只发 ? 与 QF 两条(不额外发命令):"
459
+ f"{instance.send.call_args_list}")
460
+ check(instance.disconnect.called, "诊断完归还串口")
461
+
462
+ lease, instance = _lease_with([], connect_ok=False,
463
+ last_error=WRITE_TIMEOUT,
464
+ lines=["OTA AP: ESP32_OTA IP: 192.168.4.1"])
465
+ esp_p, serial_p = _patch_lease(instance)
466
+ with esp_p, serial_p:
467
+ report = lease.esp_console_report(ESP_SERIAL)
468
+ check(report["connected"] is False, "连不上标记为假")
469
+ check(report["last_error"] == WRITE_TIMEOUT,
470
+ f"串口层原文原样带出(这就是用户报的那句):{report['last_error']}")
471
+ check(report["lines"] == [], "没连上就没有输出行")
472
+ check(report["state"] == "" and report["bound"] == "",
473
+ "没连上不填假的握手/绑定值")
474
+ check(instance.open_readonly.called,
475
+ "握手失败后仍然只读复检一次:写阻塞的板子只有这条路能拿到证据")
476
+ check(report["read_only_lines"] == ["OTA AP: ESP32_OTA IP: 192.168.4.1"],
477
+ f"只读复检收到的行带回给界面(板子在说话):{report['read_only_lines']}")
478
+ check(report["read_only_error"] == "",
479
+ "只读复检成功就没有额外错误")
480
+ check(not instance.send.called,
481
+ "没连上不发任何命令(只读复检也不写字节)")
482
+ check(instance.disconnect.called, "失败路径也要归还串口")
483
+
484
+ lease, instance = _lease_with([])
485
+ esp_p, serial_p = _patch_lease(instance, esp=[_esp(device="")])
486
+ with esp_p, serial_p:
487
+ report = lease.esp_console_report(ESP_SERIAL)
488
+ check(report["last_error"] == "缺少串口节点,无法打开"
489
+ and report["connected"] is False,
490
+ f"节点缺失如实报:{report['last_error']}")
491
+ check(not instance.open_readonly.called,
492
+ "连节点都没有就不去试着打开(省一次无意义的失败)")
493
+
494
+
495
+ class _WriteBlocksSerial:
496
+ """写就抛 SerialTimeoutException 的假串口 —— 复现现场那块板子。
497
+
498
+ USB-Serial-JTAG 的收端没人排空时,主机这侧的 write 就是这样失败的;
499
+ 此时 read 这条路仍然通(板子说了话就收得到)。
500
+ """
501
+
502
+ def __init__(self, lines=()):
503
+ self.is_open = True
504
+ self.writes = []
505
+ self._lines = list(lines)
506
+
507
+ def reset_input_buffer(self):
508
+ pass
509
+
510
+ def write(self, data):
511
+ self.writes.append(data)
512
+ raise serial.SerialTimeoutException("Write timeout")
513
+
514
+ def readline(self):
515
+ if not self._lines:
516
+ return b""
517
+ return (self._lines.pop(0) + "\r\n").encode()
518
+
519
+ def cancel_write(self):
520
+ pass
521
+
522
+ def reset_output_buffer(self):
523
+ pass
524
+
525
+ def close(self):
526
+ self.is_open = False
527
+
528
+
529
+ def test_esp_console_report_write_blocked():
530
+ section("5b. 写阻塞的板子:真 GripperSerial 走通只读复检(拿得到 TX 证据)")
531
+ clock = _Clock()
532
+ blocked = _WriteBlocksSerial()
533
+ # 第一次打开(握手那次)写就超时;只读复检那次换成一块在说话的板子
534
+ replier = _ScriptedSerial(["OTA AP: ESP32_OTA IP: 192.168.4.1", "READY"],
535
+ clock)
536
+ opened = []
537
+
538
+ def factory(port, baud, **kwargs):
539
+ opened.append(port)
540
+ return blocked if len(opened) == 1 else replier
541
+
542
+ logs = []
543
+ # lease 把 driver 的 logger 原样交给 GripperSerial,所以在这一层接日志
544
+ lease = SingleFaysLease(
545
+ logger=lambda *a: logs.append(" ".join(str(x) for x in a)))
546
+ with mock.patch.object(fays_single, "discover_esp32_devices",
547
+ return_value=[_esp()]), \
548
+ mock.patch.object(fays_single, "GripperSerial",
549
+ partial(GripperSerial, serial_factory=factory,
550
+ clock=clock, sleep=lambda _s: None)):
551
+ report = lease.esp_console_report(ESP_SERIAL)
552
+ check(report["connected"] is False, "写阻塞 → 连不上")
553
+ # 日志必须能自己说清「卡在哪一写」:只写进去一笔就阻塞时,上面一行
554
+ # attempt 都不会出现,事后看日志会误判成「根本没试过握手」。
555
+ stuck = [line for line in logs if "握手中断于第 1 次写" in line]
556
+ check(len(stuck) == 1 and "Write timeout" in stuck[0],
557
+ f"日志记下中断在第几次写、原因是什么:{logs}")
558
+ check(not any("connect attempt" in line for line in logs),
559
+ f"第一笔写就阻塞 ⇒ 一条 attempt 行都不该有:{logs}")
560
+ check(report["last_error"] == WRITE_TIMEOUT,
561
+ f"串口层原文就是用户报的那句:{report['last_error']}")
562
+ check(blocked.writes == [b"?\r\n"],
563
+ f"握手只写到一半(第一次写就超时):{blocked.writes}")
564
+ check(opened == ["/dev/ttyACM0", "/dev/ttyACM0"],
565
+ f"失败后重新只读打开了同一个节点:{opened}")
566
+ check(report["read_only_lines"] == ["OTA AP: ESP32_OTA IP: 192.168.4.1",
567
+ "READY"],
568
+ f"只读复检拿到板子 TX 侧的原样输出:{report['read_only_lines']}")
569
+ check(report["read_only_error"] == "",
570
+ f"只读复检成功:{report['read_only_error']}")
571
+ check(replier.writes == [],
572
+ f"只读复检一个字节都没写(板子收不了,写了只会更堵):{replier.writes}")
573
+
574
+ # 只读复检自己都打不开(被抢口/没权限):如实报,不冒充「板子哑了」
575
+ clock = _Clock()
576
+ blocked = _WriteBlocksSerial()
577
+ opened = []
578
+
579
+ def busy_factory(port, baud, **kwargs):
580
+ opened.append(port)
581
+ if len(opened) == 1:
582
+ return blocked
583
+ raise IOError(16, "Device or resource busy")
584
+
585
+ lease = SingleFaysLease(logger=lambda _t: None)
586
+ with mock.patch.object(fays_single, "discover_esp32_devices",
587
+ return_value=[_esp()]), \
588
+ mock.patch.object(fays_single, "GripperSerial",
589
+ partial(GripperSerial, serial_factory=busy_factory,
590
+ clock=clock, sleep=lambda _s: None)):
591
+ report = lease.esp_console_report(ESP_SERIAL)
592
+ check(report["last_error"] == WRITE_TIMEOUT,
593
+ f"板子那条原文不被复检的失败顶掉:{report['last_error']}")
594
+ check("Device or resource busy" in report["read_only_error"]
595
+ and report["read_only_lines"] == [],
596
+ f"只读复检打不开时单独带自己的原因:{report['read_only_error']}")
597
+
598
+
599
+ # ═══════════════════════════════════════════════════════════════════
600
+ # 6-8. 主窗口离线操作
601
+ # ═══════════════════════════════════════════════════════════════════
602
+
603
+ class _Recorder:
604
+ """替身信号:直接记录 emit 参数,不经 Qt 队列(本用例只查流程与文案)。"""
605
+
606
+ def __init__(self):
607
+ self.calls = []
608
+
609
+ def emit(self, *args):
610
+ self.calls.append(args)
611
+
612
+
613
+ class _Boxes:
614
+ """替身弹窗:记录标题/正文,返回值由用例预设。"""
615
+
616
+ def __init__(self):
617
+ self.calls = []
618
+ # 与真 Qt 一样是可按位或的整数(实现里写 Yes|No 当按钮组合)
619
+ self.Yes, self.No = 1, 0
620
+ self.question_answer = self.Yes
621
+
622
+ def _record(self, level, title, text):
623
+ self.calls.append((level, title, text))
624
+
625
+ def question(self, _parent, title, text, *_a, **_k):
626
+ self._record("question", title, text)
627
+ return self.question_answer
628
+
629
+ def warning(self, _parent, title, text):
630
+ self._record("warning", title, text)
631
+
632
+ def critical(self, _parent, title, text):
633
+ self._record("critical", title, text)
634
+
635
+ def information(self, _parent, title, text):
636
+ self._record("information", title, text)
637
+
638
+ def texts(self):
639
+ return " | ".join(text for _lvl, _t, text in self.calls)
640
+
641
+ def titles(self):
642
+ return " | ".join(title for _lvl, title, _t2 in self.calls)
643
+
644
+ def levels(self):
645
+ return [level for level, _t, _t2 in self.calls]
646
+
647
+
648
+ def _fake_window(*, recording=False, workers=None):
649
+ """只带离线操作所需状态的主窗口(绕过 Qt 初始化)。
650
+
651
+ 三个跨线程信号换成 :class:`_Recorder`:实例属性遮蔽类上的 pyqtSignal,
652
+ 省掉线程与事件循环,用例可直接读 emit 参数。
653
+ """
654
+ import ui.main_window as main_window
655
+
656
+ window = main_window.MainWindow.__new__(main_window.MainWindow)
657
+ logs = []
658
+ window._log = logs.append
659
+ window._logs = logs
660
+ window._workers = dict(workers or {})
661
+ window._active_device_keys = set()
662
+ window._gripper_recalib_reopen = set()
663
+ window._pipeline = mock.MagicMock(is_recording=recording)
664
+ window._device_panel = mock.MagicMock()
665
+ window._device_panel.device_for_key.return_value = None
666
+ window._gripper_recalibration_done = _Recorder()
667
+ window._gripper_binding_probe_done = _Recorder()
668
+ window._gripper_binding_write_done = _Recorder()
669
+ window._gripper_diagnostics_done = _Recorder()
670
+ window._closed = []
671
+ window._close_gripper = window._closed.append
672
+ # 状态栏刷新要 grid 等控件(本用例只查「有没有刷新」)
673
+ window._status_updates = []
674
+ window._update_status = lambda: window._status_updates.append(True)
675
+ window._toggled = []
676
+ window._on_device_toggled = lambda dev, on: window._toggled.append(
677
+ (dev.key, on))
678
+ return window
679
+
680
+
681
+ def _gripper_dev(serial=ESP_SERIAL, key="gripper:AC276EC7BA68"):
682
+ from core.device_detector import DeviceInfo
683
+ return DeviceInfo(key=key, kind="gripper", display_name="UMI",
684
+ serial=serial)
685
+
686
+
687
+ def _install_lease(window, lease):
688
+ """把主窗口后台线程里的 SingleFaysLease 换成假租约,并同步执行线程体。"""
689
+ starts = []
690
+
691
+ def starter(worker, dev, label, name, extra=()):
692
+ starts.append((name, label) + tuple(extra)) # (线程名, 标签[, 目标])
693
+ worker(dev, label, *extra) # 同步跑,省掉线程与 Qt 队列
694
+
695
+ window._start_gripper_worker = starter
696
+ window._starts = starts
697
+ return mock.patch.object(fays_single, "SingleFaysLease",
698
+ return_value=lease)
699
+
700
+
701
+ def test_window_offline_bookkeeping():
702
+ section("6. 主窗口离线骨架(前置检查 / 让出设备 / 开回)")
703
+ window = _fake_window()
704
+ boxes = _Boxes()
705
+ import ui.main_window as main_window
706
+
707
+ dev = _gripper_dev(serial="")
708
+ with mock.patch.object(main_window, "QMessageBox", boxes):
709
+ check(window._gripper_offline_guard(dev, "重读标定") is False,
710
+ "没读到 ESP32 序列号 → 不给进(定位不到控制板)")
711
+ check(boxes.levels() == ["warning"] and "夹爪无序列号" in boxes.calls[0][1],
712
+ f"并弹窗说明原因:{boxes.calls}")
713
+
714
+ window = _fake_window(recording=True)
715
+ boxes = _Boxes()
716
+ with mock.patch.object(main_window, "QMessageBox", boxes):
717
+ check(window._gripper_offline_guard(_gripper_dev(), "改写绑定序列号")
718
+ is False, "录制中 → 不给进(设备要独占)")
719
+ check("录制中不可改写绑定序列号,请先停止录制。" in boxes.texts(),
720
+ f"录制中的文案按动作区分:{boxes.texts()}")
721
+
722
+ window = _fake_window()
723
+ with mock.patch.object(main_window, "QMessageBox", _Boxes()):
724
+ check(window._gripper_offline_guard(_gripper_dev(), "做串口诊断")
725
+ is True, "都满足时放行")
726
+
727
+ # 本来就没开:什么都不记,也不该替用户打开
728
+ window = _fake_window()
729
+ window._gripper_offline_take_over(_gripper_dev(), "UMI — x", "重读标定")
730
+ check(window._closed == [] and not window._gripper_recalib_reopen,
731
+ "设备本来没开 → 不关也不记待开回")
732
+ check(window._reopen_after_offline("gripper:AC276EC7BA68", False) is False,
733
+ "没记待开回 → 善后不动设备")
734
+
735
+ # 开着:关掉并记下待开回(与用户点开关同一口径)
736
+ dev = _gripper_dev()
737
+ window = _fake_window(workers={dev.key: {"kind": "gripper"}})
738
+ window._device_panel.device_for_key.return_value = dev
739
+ window._gripper_offline_take_over(dev, "UMI — x", "重读标定")
740
+ check(window._closed == [dev.key], "开着 → 先关掉让出串口")
741
+ check(window._gripper_recalib_reopen == {dev.key}, "记下完成要开回")
742
+ check(dev.key not in window._active_device_keys, "不再算当前显示设备")
743
+ check(window._status_updates, "状态栏同步刷新(不让用户看着还是「运行中」)")
744
+ check(window._device_panel.set_checked.call_args == mock.call(dev.key, False),
745
+ "面板勾选状态同步取消")
746
+ check(any("已暂时关闭以重读标定" in line for line in window._logs),
747
+ f"日志说明为什么关:{window._logs}")
748
+ check(window._gripper_reopen_forget(dev.key) is True,
749
+ "取出待开回标记")
750
+ check(window._gripper_reopen_forget(dev.key) is False,
751
+ "取出即消费(回调重入不会开两次)")
752
+
753
+ window = _fake_window(workers={dev.key: {"kind": "gripper"}})
754
+ window._device_panel.device_for_key.return_value = dev
755
+ window._gripper_recalib_reopen = {dev.key}
756
+ check(window._reopen_after_offline(dev.key, True) is True
757
+ and window._toggled == [(dev.key, True)],
758
+ "善后按用户点开关那条路开回来")
759
+
760
+ window = _fake_window()
761
+ window._device_panel.device_for_key.return_value = None
762
+ check(window._reopen_after_offline(dev.key, True) is False,
763
+ "期间设备拔了/列表重建过 → 不擅自开")
764
+
765
+ # 探板失败:不开回(板子状态未知,交回用户决定)
766
+ dev = _gripper_dev()
767
+ window = _fake_window(workers={dev.key: {"kind": "gripper"}})
768
+ window._device_panel.device_for_key.return_value = dev
769
+ window._gripper_recalib_reopen = {dev.key}
770
+ boxes = _Boxes()
771
+ with mock.patch.object(main_window, "QMessageBox", boxes):
772
+ window._on_gripper_binding_probe_done(
773
+ dev.key, "UMI — x", f"串口连接失败: {WRITE_TIMEOUT}", {})
774
+ check(window._toggled == [], "探板失败不自动开回(避免二次弹错)")
775
+ check(not window._gripper_recalib_reopen, "失败也清掉待开回记录")
776
+ check("串口连接失败" in boxes.texts() and "夹爪仍在设备列表中" in boxes.texts(),
777
+ f"失败弹窗带底层原因与去向:{boxes.texts()}")
778
+ check("ESP32 串口诊断" in boxes.texts(),
779
+ "失败弹窗指向诊断入口(用户下一步该干什么)")
780
+
781
+
782
+ def test_window_binding_flow():
783
+ section("7. 主窗口绑定流程(探板 → 挑目标 → 写入 → 回读)")
784
+ dev = _gripper_dev()
785
+ boxes = _Boxes()
786
+ import ui.main_window as main_window
787
+
788
+ lease, instance = _lease_with([f"FAYS_SERIAL:{FAYS_SERIAL}"])
789
+ instance.query_fays_serial.return_value = FAYS_SERIAL
790
+ instance.set_fays_serial.return_value = True
791
+ window = _fake_window()
792
+ window._device_panel.device_for_key.return_value = dev
793
+ with mock.patch.object(main_window, "QMessageBox", boxes), \
794
+ mock.patch.object(main_window, "QInputDialog") as dialog, \
795
+ _install_lease(window, lease), \
796
+ mock.patch.object(fays_single, "discover_esp32_devices",
797
+ return_value=[_esp()]), \
798
+ mock.patch.object(fays_single, "GripperSerial",
799
+ return_value=instance), \
800
+ mock.patch.object(lease, "online_fays_serials",
801
+ return_value=({FAYS_SERIAL: _fays_group()}, [])):
802
+ dialog.getItem.return_value = (FAYS_SERIAL, True)
803
+ window._on_gripper_binding(dev)
804
+ check(window._starts and window._starts[0][0] == "gripper-binding-probe",
805
+ f"先起探板线程:{window._starts}")
806
+ probe = window._gripper_binding_probe_done.calls
807
+ check(len(probe) == 1 and probe[0][2] == "",
808
+ f"探板成功不报错:{probe}")
809
+ info = probe[0][3]
810
+ check(info["bound"] == FAYS_SERIAL and info["online"] == [FAYS_SERIAL],
811
+ f"探板带回现状 + 在线清单:{info['bound']} / {info['online']}")
812
+ window._on_gripper_binding_probe_done(*probe[0])
813
+ check(dialog.getItem.called, "弹选择框让用户挑(不给手输)")
814
+ check(dialog.getItem.call_args[0][3] == [FAYS_SERIAL],
815
+ f"候选项就是当前在线的 Fays:{dialog.getItem.call_args[0][3]}")
816
+ check(window._starts[-1][0] == "gripper-binding-write",
817
+ f"确认后起写入线程:{window._starts}")
818
+ check(window._starts[-1][2] == FAYS_SERIAL,
819
+ f"写入线程带的是用户挑的那一台:{window._starts[-1]}")
820
+ write = window._gripper_binding_write_done.calls
821
+ check(len(write) == 1 and write[0][2] == "",
822
+ f"写入成功不报错:{write}")
823
+ check(write[0][3]["readback"] == FAYS_SERIAL,
824
+ f"回读值带回主线程:{write[0][3]}")
825
+ window._on_gripper_binding_write_done(*write[0])
826
+ check(instance.set_fays_serial.called, "真的发了 WF:")
827
+ check(boxes.calls[-1][0] == "information"
828
+ and "绑定完成" in boxes.calls[-1][1],
829
+ f"回读一致才说成功(不是警告):{boxes.calls[-1]}")
830
+ check(any("已写入" in line and FAYS_SERIAL in line
831
+ for line in window._logs), f"日志留痕:{window._logs}")
832
+
833
+ # 回读对不上:明说不算成功(不猜)
834
+ dev = _gripper_dev()
835
+ window = _fake_window()
836
+ window._device_panel.device_for_key.return_value = dev
837
+ boxes = _Boxes()
838
+ with mock.patch.object(main_window, "QMessageBox", boxes):
839
+ window._on_gripper_binding_write_done(
840
+ dev.key, "UMI — x", "",
841
+ {"written": FAYS_SERIAL, "readback": ""})
842
+ check(boxes.levels() == ["warning"] and "回读不一致" in boxes.calls[0][1],
843
+ f"回读为空 → 警告而不是成功:{boxes.calls}")
844
+ check(window._toggled == [], "写入异常也不自动开回")
845
+
846
+ # 没有在线 Fays:停手,并把夹爪开回来(板子没被改动)
847
+ dev = _gripper_dev()
848
+ window = _fake_window(workers={dev.key: {"kind": "gripper"}})
849
+ window._device_panel.device_for_key.return_value = dev
850
+ window._gripper_recalib_reopen = {dev.key}
851
+ boxes = _Boxes()
852
+ with mock.patch.object(main_window, "QMessageBox", boxes), \
853
+ mock.patch.object(main_window, "QInputDialog") as dialog:
854
+ window._on_gripper_binding_probe_done(
855
+ dev.key, "UMI — x", "",
856
+ {"esp_serial": ESP_SERIAL, "bound": "", "online": [],
857
+ "online_error": "未发现完整的 Fays S80M"})
858
+ check(not dialog.getItem.called, "没有候选就不弹选择框")
859
+ check("未找到在线 Fays" in boxes.titles() and "stereo 与 IMU" in boxes.texts(),
860
+ f"明说缺什么、怎么补救:{boxes.calls}")
861
+ check(window._toggled == [(dev.key, True)],
862
+ "板子没被改动 → 把原先开着的夹爪开回来")
863
+
864
+ # 用户放弃写入:同样开回
865
+ dev = _gripper_dev()
866
+ window = _fake_window(workers={dev.key: {"kind": "gripper"}})
867
+ window._device_panel.device_for_key.return_value = dev
868
+ window._gripper_recalib_reopen = {dev.key}
869
+ boxes = _Boxes()
870
+ with mock.patch.object(main_window, "QMessageBox", boxes), \
871
+ mock.patch.object(main_window, "QInputDialog") as dialog:
872
+ dialog.getItem.return_value = (FAYS_SERIAL, False)
873
+ window._on_gripper_binding_probe_done(
874
+ dev.key, "UMI — x", "",
875
+ {"esp_serial": ESP_SERIAL, "bound": "", "online": [FAYS_SERIAL]})
876
+ check(window._toggled == [(dev.key, True)], "用户取消 → 开回来")
877
+ check(any("已取消" in line for line in window._logs),
878
+ f"日志记下用户取消:{window._logs}")
879
+
880
+ # 确认框里选「否」:也不写
881
+ window = _fake_window()
882
+ window._device_panel.device_for_key.return_value = dev
883
+ boxes = _Boxes()
884
+ boxes.question_answer = boxes.No
885
+ with mock.patch.object(main_window, "QMessageBox", boxes), \
886
+ mock.patch.object(main_window, "QInputDialog") as dialog, \
887
+ _install_lease(window, _lease_with([])[0]):
888
+ dialog.getItem.return_value = (FAYS_SERIAL, True)
889
+ chosen = window._ask_target_fays_serial(
890
+ {"esp_serial": ESP_SERIAL, "bound": "", "online": [FAYS_SERIAL]},
891
+ "UMI — x")
892
+ check(chosen is None, "确认框选否 → 不给写入目标")
893
+ check("覆盖原值" in boxes.texts(), f"确认框写清后果:{boxes.texts()}")
894
+
895
+ # 已绑定另一台:默认选中当前那台(最不容易误改)
896
+ window = _fake_window()
897
+ boxes = _Boxes()
898
+ with mock.patch.object(main_window, "QMessageBox", boxes), \
899
+ mock.patch.object(main_window, "QInputDialog") as dialog:
900
+ dialog.getItem.return_value = (OTHER_FAYS_SERIAL, True)
901
+ window._ask_target_fays_serial(
902
+ {"esp_serial": ESP_SERIAL, "bound": FAYS_SERIAL,
903
+ "online": [FAYS_SERIAL, OTHER_FAYS_SERIAL]}, "UMI — x")
904
+ args = dialog.getItem.call_args[0]
905
+ check(list(args[3]) == [FAYS_SERIAL, OTHER_FAYS_SERIAL]
906
+ and args[4] == 0,
907
+ f"候选项按序列号排序、默认落在当前绑定那台:{args[3:5]}")
908
+ check(FAYS_SERIAL in args[2], f"提示里说明当前绑定:{args[2]}")
909
+
910
+
911
+ def test_window_diagnostics():
912
+ section("8. 主窗口串口诊断(只读,一律开回)")
913
+ import ui.main_window as main_window
914
+
915
+ dev = _gripper_dev()
916
+ lease, instance = _lease_with(
917
+ ["STATE ST=0 RAW=0", f"FAYS_SERIAL:{FAYS_SERIAL}"],
918
+ lines=["STATE ST=0 RAW=0", "DATA 1 2 3"])
919
+ window = _fake_window()
920
+ window._device_panel.device_for_key.return_value = dev
921
+ boxes = _Boxes()
922
+ with mock.patch.object(main_window, "QMessageBox", boxes), \
923
+ _install_lease(window, lease), \
924
+ mock.patch.object(fays_single, "discover_esp32_devices",
925
+ return_value=[_esp()]), \
926
+ mock.patch.object(fays_single, "GripperSerial",
927
+ return_value=instance):
928
+ window._on_gripper_diagnostics(dev)
929
+ check(window._starts and window._starts[0][0] == "gripper-diagnostics",
930
+ f"起诊断线程:{window._starts}")
931
+ report = window._gripper_diagnostics_done.calls
932
+ check(len(report) == 1 and report[0][2] == "",
933
+ f"诊断成功不报错:{report}")
934
+ window._on_gripper_diagnostics_done(*report[0])
935
+ raw = [line for line in window._logs if line.startswith("[夹爪串口]")]
936
+ check(raw == ["[夹爪串口] STATE ST=0 RAW=0", "[夹爪串口] DATA 1 2 3"],
937
+ f"板上原样输出逐行进日志:{raw}")
938
+ check(boxes.levels() == ["information"] and "DATA 1 2 3" in boxes.texts(),
939
+ f"摘要弹窗带上输出行:{boxes.texts()}")
940
+ check(any("握手响应" in line for line in window._logs),
941
+ f"日志摘要含握手响应:{window._logs}")
942
+
943
+ # 连不上(用户报的那种):原文 + 只读复检的证据 + 处置梯子
944
+ dev = _gripper_dev()
945
+ lease, instance = _lease_with([], connect_ok=False,
946
+ last_error=WRITE_TIMEOUT)
947
+ window = _fake_window()
948
+ window._device_panel.device_for_key.return_value = dev
949
+ boxes = _Boxes()
950
+ with mock.patch.object(main_window, "QMessageBox", boxes), \
951
+ _install_lease(window, lease), \
952
+ mock.patch.object(fays_single, "discover_esp32_devices",
953
+ return_value=[_esp()]), \
954
+ mock.patch.object(fays_single, "GripperSerial",
955
+ return_value=instance):
956
+ window._on_gripper_diagnostics(dev)
957
+ window._on_gripper_diagnostics_done(
958
+ *window._gripper_diagnostics_done.calls[0])
959
+ check(boxes.levels() == ["critical"], "连不上是 critical,不是 information")
960
+ check(WRITE_TIMEOUT in boxes.texts(),
961
+ f"串口层原文原样显示(不翻译、不美化):{boxes.texts()}")
962
+ check("/dev/ttyACM0" in boxes.texts(),
963
+ f"带上串口节点,用户能确认说的是哪块板:{boxes.texts()}")
964
+ check("只读" in boxes.texts() and "收到 0 行" in boxes.texts(),
965
+ f"报出只读复检收到几行(这才是能分辨病因的证据):{boxes.texts()}")
966
+ check("一行都没有" in boxes.texts(),
967
+ f"0 行时把「板上没有程序在写这个口」说明白:{boxes.texts()}")
968
+ check("断电" in boxes.texts() and "flash_esp32.sh" in boxes.texts(),
969
+ f"给出从低到高的处置梯子:{boxes.texts()}")
970
+ check(any(WRITE_TIMEOUT in line for line in window._logs),
971
+ f"原文也进日志(可回查):{window._logs}")
972
+ check(any("只读复检" in line for line in window._logs),
973
+ f"只读复检的结论也进日志:{window._logs}")
974
+
975
+ # 板子在说话、只是不收写入:首句的归因要跟着变(不能还说板子哑了)
976
+ dev = _gripper_dev()
977
+ lease, instance = _lease_with([], connect_ok=False,
978
+ last_error=WRITE_TIMEOUT,
979
+ lines=["STATE ST=0 RAW=7"])
980
+ window = _fake_window()
981
+ window._device_panel.device_for_key.return_value = dev
982
+ boxes = _Boxes()
983
+ with mock.patch.object(main_window, "QMessageBox", boxes), \
984
+ _install_lease(window, lease), \
985
+ mock.patch.object(fays_single, "discover_esp32_devices",
986
+ return_value=[_esp()]), \
987
+ mock.patch.object(fays_single, "GripperSerial",
988
+ return_value=instance):
989
+ window._on_gripper_diagnostics(dev)
990
+ window._on_gripper_diagnostics_done(
991
+ *window._gripper_diagnostics_done.calls[0])
992
+ raw = [line for line in window._logs if line.startswith("[夹爪串口]")]
993
+ check(raw == ["[夹爪串口] STATE ST=0 RAW=7"],
994
+ f"只读复检收到的行逐行进日志:{raw}")
995
+ check("收到 1 行" in boxes.texts() and "STATE ST=0 RAW=7" in boxes.texts(),
996
+ f"摘要里带上只读复检收到的行:{boxes.texts()}")
997
+ check("不接收主机写入" in boxes.texts(),
998
+ f"有输出时归因改成「不收写入」,不说板子哑了:{boxes.texts()}")
999
+ check("一行都没有" not in boxes.texts(),
1000
+ "有输出就不说「一行都没有」")
1001
+
1002
+ # 只读操作的失败路径也要开回(板子没被改动)
1003
+ dev = _gripper_dev()
1004
+ window = _fake_window(workers={dev.key: {"kind": "gripper"}})
1005
+ window._device_panel.device_for_key.return_value = dev
1006
+ window._gripper_recalib_reopen = {dev.key}
1007
+ boxes = _Boxes()
1008
+ with mock.patch.object(main_window, "QMessageBox", boxes):
1009
+ window._on_gripper_diagnostics_done(
1010
+ dev.key, "UMI — x", "定位 ESP32 失败", {})
1011
+ check(window._toggled == [(dev.key, True)],
1012
+ "诊断只读 → 无论成败都按原样开回")
1013
+ check("定位 ESP32 失败" in boxes.texts(), f"失败原因照报:{boxes.texts()}")
1014
+
1015
+
1016
+ def test_serial_stuck_hint():
1017
+ section("10. 「板子没在服务串口」的处置提示(该给的给、不该给的不给)")
1018
+ import ui.main_window as main_window
1019
+
1020
+ window = _fake_window()
1021
+
1022
+ # 该给:写阻塞(用户在 2026-09-23 报的那条)
1023
+ hint = window._gripper_serial_stuck_hint(
1024
+ "ESP32 AC:27:6E:C7:BA:68 串口连接失败,无法查询绑定的 Fays 序列号: "
1025
+ + WRITE_TIMEOUT)
1026
+ check("断电" in hint and "flash_esp32.sh" in hint,
1027
+ f"写超时 → 给断电梯子(最便宜的一步排最前):{hint}")
1028
+ check("测试连接" in hint,
1029
+ "先让人证明主机能不能连上板子(下载通路),再决定要不要重烧")
1030
+ check("--erase" in hint and "NVS" in hint,
1031
+ f"提醒 --erase 会擦掉 NVS 里的绑定、烧完要补写:{hint}")
1032
+ check("权限问题" in hint,
1033
+ "明确排除权限/占用,省掉一轮查 udev 的白工")
1034
+
1035
+ # 该给:写得进去、板子完全不回话(另一种「没在服务串口」的报法)
1036
+ hint = window._gripper_serial_stuck_hint(
1037
+ "ESP32 X 串口连接失败,无法查询绑定的 Fays 序列号: "
1038
+ "serial handshake timeout after 8 attempts")
1039
+ check("断电" in hint,
1040
+ f"无应答也指向板子(不是主机侧)→ 给同一套梯子:{hint}")
1041
+
1042
+ # 不该给:口被别的进程占 —— 主机侧原因,引到重烧固件是误导
1043
+ busy = window._gripper_serial_stuck_hint(
1044
+ "串口连接失败: serial open/handshake failed: [Errno 16] "
1045
+ "Device or resource busy")
1046
+ check(busy == "", f"口被占 → 不加板子侧提示:{busy!r}")
1047
+ denied = window._gripper_serial_stuck_hint(
1048
+ "串口连接失败: serial open/handshake failed: [Errno 13] "
1049
+ "Permission denied: '/dev/ttyACM0'")
1050
+ check(denied == "", f"没权限 → 不加板子侧提示:{denied!r}")
1051
+ check(window._gripper_serial_stuck_hint("缺少串口节点,无法打开") == "",
1052
+ "节点不在 → 不加板子侧提示(那是没插好/插错口)")
1053
+ check(window._gripper_serial_stuck_hint("") == "",
1054
+ "空原因不加提示(骨架路径出错时不硬塞一段无关的话)")
1055
+
1056
+ # 五个串口失败入口都挂上:写在弹窗正文里,跟着原文一起给
1057
+ dev = _gripper_dev()
1058
+ window = _fake_window()
1059
+ boxes = _Boxes()
1060
+ wrapped = ("ESP32 AC:27:6E:C7:BA:68 串口连接失败,无法查询绑定的 Fays "
1061
+ "序列号: " + WRITE_TIMEOUT)
1062
+ with mock.patch.object(main_window, "QMessageBox", boxes):
1063
+ window._on_gripper_error(dev.key, wrapped)
1064
+ window._on_gripper_recalibration_done(dev.key, "UMI — x", wrapped)
1065
+ window._on_gripper_binding_probe_done(
1066
+ dev.key, "UMI — x", "串口连接失败: " + WRITE_TIMEOUT, {})
1067
+ window._on_gripper_binding_write_done(
1068
+ dev.key, "UMI — x",
1069
+ "ESP32 X 串口连接失败,无法写入 Fays 序列号: " + WRITE_TIMEOUT, {})
1070
+ check(len(boxes.calls) == 4
1071
+ and all("断电" in text for _l, _t, text in boxes.calls),
1072
+ f"四条串口失败入口都给下一步(不再只有诊断那条给):"
1073
+ f"{[t for _l, t, _x in boxes.calls]}")
1074
+ check(all("flash_esp32.sh" in text for _l, _t, text in boxes.calls),
1075
+ "四条给的是同一套梯子(口径一致,不各说各的)")
1076
+ check(all(WRITE_TIMEOUT in text for _l, _t, text in boxes.calls),
1077
+ "原文仍然原样保留在提示前面")
1078
+
1079
+
1080
+ # ═══════════════════════════════════════════════════════════════════
1081
+ # 9. 信号名跨文件一致
1082
+ # ═══════════════════════════════════════════════════════════════════
1083
+
1084
+ def test_signal_names_are_wired():
1085
+ section("9. 面板信号与主窗口的连接名一致")
1086
+
1087
+ # 面板发出信号、主窗口按名 connect:名字打错不会报错,只是永远不触发
1088
+ panel_src = open(os.path.join(REPO_ROOT, "ui", "device_panel.py"),
1089
+ encoding="utf-8").read()
1090
+ window_src = open(os.path.join(REPO_ROOT, "ui", "main_window.py"),
1091
+ encoding="utf-8").read()
1092
+ for name in ("gripper_recalibration_requested",
1093
+ "gripper_binding_requested",
1094
+ "gripper_diagnostics_requested"):
1095
+ check(f"{name} = pyqtSignal(" in panel_src,
1096
+ f"面板声明了 {name}")
1097
+ check(f"self._device_panel.{name}.connect(" in window_src,
1098
+ f"主窗口 connect 了 {name}")
1099
+
1100
+ # 线程体签名与 _start_gripper_worker 的调用口径一致(错一个参数=开了线程就崩)
1101
+ import ast
1102
+ tree = ast.parse(window_src)
1103
+ found = {}
1104
+ for node in ast.walk(tree):
1105
+ if isinstance(node, ast.FunctionDef) and node.name in (
1106
+ "_gripper_recalibration_worker", "_gripper_binding_probe_worker",
1107
+ "_gripper_binding_write_worker", "_gripper_diagnostics_worker"):
1108
+ found[node.name] = len([a for a in node.args.args
1109
+ if a.arg != "self"])
1110
+ check(found == {"_gripper_recalibration_worker": 2,
1111
+ "_gripper_binding_probe_worker": 2,
1112
+ "_gripper_binding_write_worker": 3,
1113
+ "_gripper_diagnostics_worker": 2},
1114
+ f"四个线程体都是 (dev, label[, 目标序列号]):{found}")
1115
+
1116
+ # 三个 done 信号都用 object 载荷:PyQt5 的 str 信号不认 dict
1117
+ for sig in ("_gripper_binding_probe_done", "_gripper_binding_write_done",
1118
+ "_gripper_diagnostics_done"):
1119
+ check(f"{sig} = pyqtSignal(str, str, str, object)" in window_src,
1120
+ f"{sig} 用 object 声明 dict 载荷(否则跨线程静默丢参)")
1121
+
1122
+
1123
+ def main():
1124
+ test_read_lines()
1125
+ test_open_readonly()
1126
+ test_esp_binding_status()
1127
+ test_online_fays_serials()
1128
+ test_write_bound_serial()
1129
+ test_esp_console_report()
1130
+ test_esp_console_report_write_blocked()
1131
+ test_window_offline_bookkeeping()
1132
+ test_window_binding_flow()
1133
+ test_window_diagnostics()
1134
+ test_signal_names_are_wired()
1135
+ test_serial_stuck_hint()
1136
+ print()
1137
+ if FAILS:
1138
+ print(f"❌ {len(FAILS)} 项失败:")
1139
+ for item in FAILS:
1140
+ print(f" - {item}")
1141
+ return 1
1142
+ print("✅ 全部通过")
1143
+ return 0
1144
+
1145
+
1146
+ if __name__ == "__main__":
1147
+ sys.exit(main())
collector/tools/tests/test_tactile_ready_gate.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """触觉就绪门的契约测试 —— 「事件置位」不等于「触觉可用」。
2
+
3
+ 用法:
4
+ venv/bin/python tools/tests/test_tactile_ready_gate.py
5
+
6
+ 为什么要有它:`TactileProcessManager._initialize_all_input()` 的**失败路径
7
+ 上也调 `ready_event.set()`**(为了让 `wait_ready()` 不必干等满超时),于是
8
+ `wait_ready()` 原先只看事件置位就返回 True —— 两路全灭也报「就绪」。主程序
9
+ 据此打「相机 + 触觉 + SLAM 链路就绪」,触觉面板空白,而日志里那两条
10
+ `[Tactile:left|right] ERROR:` 没人会去看。
11
+
12
+ 2026-09-23 实锤:sightac 的 PyArmor runtime 按 3.12 编、venv 却是 3.10,
13
+ 输入子进程一 spawn 就 `undefined symbol: _PyCode_Validate`,两路全灭;从
14
+ 09-21 16:22(最后一次正常)到 09-23 修好,整整两天每次连接都报「已就绪」。
15
+
16
+ 这里钉两条:
17
+ 1. 两路都失败 → `wait_ready()` 必须返回 False(桥接那句
18
+ `RuntimeError("触觉双进程未就绪: …")` 才有机会被执行到);
19
+ 2. 只灭一路 → 仍返回 True(半边触觉也比没有强),但调用方要能从
20
+ `snapshot()` 里读到是哪一路,好把话说准。
21
+
22
+ 纯 Python,不碰硬件:状态直接按失败路径的形状摆好。
23
+ """
24
+ import os
25
+ import sys
26
+
27
+ ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
28
+ sys.path.insert(0, ROOT)
29
+
30
+ from unittest.mock import MagicMock # noqa: E402
31
+
32
+ from core.gripper.devices.tactile_process_manager import ( # noqa: E402
33
+ TactileProcessManager,
34
+ TactileState,
35
+ )
36
+
37
+ _FAILS = []
38
+
39
+
40
+ def check(name, cond, detail=""):
41
+ print(f" [{'PASS' if cond else 'FAIL'}] {name}"
42
+ + (f" — {detail}" if detail else ""))
43
+ if not cond:
44
+ _FAILS.append(name)
45
+
46
+
47
+ def manager_with(errors):
48
+ """按 `_initialize_all_input` 失败路径的形状摆状态并返回 manager。
49
+
50
+ 关键就在这:失败路径**同时**做两件事 —— 写 `sides[side].error`、
51
+ `ready_event.set()`。只照抄其中一件就复现不出这个坑。
52
+ """
53
+ state = TactileState()
54
+ manager = TactileProcessManager(state, discovery=MagicMock())
55
+ with state.lock:
56
+ for side, error in zip(("left", "right"), errors):
57
+ if error is not None:
58
+ state.sides[side].error = error
59
+ state.sides[side].ready_event.set()
60
+ return manager, state
61
+
62
+
63
+ def main():
64
+ print("[1] 失败路径的事件置位骗不过 wait_ready")
65
+ manager, _ = manager_with(["左路炸了", "右路也炸了"])
66
+ check("两路都失败 → False", manager.wait_ready(timeout=0.05) is False)
67
+
68
+ print("[2] 只灭一路仍然放行(半边触觉也比没有强)")
69
+ manager, state = manager_with([None, "右路炸了"])
70
+ check("只灭一路 → True", manager.wait_ready(timeout=0.05) is True)
71
+ snapshot = manager.snapshot()
72
+ check("但那一路的 error 读得出来(调用方据此改口径)",
73
+ getattr(snapshot, "right").error == "右路炸了"
74
+ and getattr(snapshot, "left").error is None,
75
+ f"left={getattr(snapshot, 'left').error!r} "
76
+ f"right={getattr(snapshot, 'right').error!r}")
77
+
78
+ print("[3] 两路都好照旧放行(没被上一条误伤)")
79
+ manager, _ = manager_with([None, None])
80
+ check("两路都好 → True", manager.wait_ready(timeout=0.05) is True)
81
+
82
+ print("[4] 超时仍然是 False(原有语义不许被改掉)")
83
+ state = TactileState()
84
+ manager = TactileProcessManager(state, discovery=MagicMock())
85
+ with state.lock:
86
+ state.sides["left"].ready_event.set() # 只置位一路,另一路永不置位
87
+ check("等不到第二路 → False", manager.wait_ready(timeout=0.05) is False)
88
+
89
+ print()
90
+ if _FAILS:
91
+ print(f"FAILED: {len(_FAILS)} 项 — {_FAILS}")
92
+ return 1
93
+ print("ALL PASS")
94
+ return 0
95
+
96
+
97
+ if __name__ == "__main__":
98
+ sys.exit(main())
collector/ui/device_panel.py CHANGED
@@ -36,8 +36,11 @@ class DevicePanel(QWidget):
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)
@@ -219,11 +222,11 @@ class DevicePanel(QWidget):
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
@@ -232,13 +235,25 @@ class DevicePanel(QWidget):
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, "📹")
 
36
 
37
  device_toggled = pyqtSignal(object, bool) # (DeviceInfo, checked)
38
  device_renamed = pyqtSignal(object, str) # (DeviceInfo, new_name)
39
+ # 夹爪右键菜单(都只带被点的那台 DeviceInfo;三件都要独占设备):
40
+ # 重新读取厂商出厂标定 / 读写 ESP32 NVS 里绑定的 Fays 序列号 / 串口诊断
41
  gripper_recalibration_requested = pyqtSignal(object)
42
+ gripper_binding_requested = pyqtSignal(object)
43
+ gripper_diagnostics_requested = pyqtSignal(object)
44
 
45
  def __init__(self, parent=None):
46
  super().__init__(parent)
 
222
  """底部提示:夹爪在场时才提右键菜单(别的设备没有这个菜单)。"""
223
  text = tr("双击设备可重命名")
224
  if self._has_gripper:
225
+ text += tr(";右键夹爪可重读标定 / 配对序列号 / 串口诊断")
226
  self._refresh_hint.setText(text)
227
 
228
  def _on_context_menu(self, pos):
229
+ """夹爪条目右键 → 重读标定 / 读写绑定序列号 / ESP32 串口诊断。"""
230
  item = self._tree.itemAt(pos)
231
  if item is None:
232
  return
 
235
  return # 组标题 / 占位项
236
  if dev.group != "gripper":
237
  return
238
+ # 三件都要独占设备,录制中不给入口(与 set_locked 的灰显口径一致)
239
  menu = QMenu(self)
240
+ entries = (
241
+ (tr("重新读取出厂标定"), self.gripper_recalibration_requested),
242
+ (tr("读取/写入 Fays 绑定序列号"), self.gripper_binding_requested),
243
+ (tr("ESP32 串口诊断"), self.gripper_diagnostics_requested),
244
+ )
245
+ actions = []
246
+ for text, signal in entries:
247
+ action = menu.addAction(text)
248
+ action.setEnabled(not self._locked)
249
+ actions.append((action, signal))
250
  chosen = menu.exec_(self._tree.viewport().mapToGlobal(pos))
251
+ if self._locked:
252
+ return
253
+ for action, signal in actions:
254
+ if chosen is action:
255
+ signal.emit(dev)
256
+ return
257
 
258
  def _row_text(self, dev) -> str:
259
  icon = _ICON.get(dev.kind, "📹")
collector/ui/main_window.py CHANGED
@@ -22,7 +22,7 @@ from PyQt5.QtWidgets import (
22
  QMainWindow, QWidget, QVBoxLayout, QDockWidget, QTextEdit,
23
  QTableWidget, QTableWidgetItem, QMessageBox, QLabel,
24
  QAbstractItemView, QToolBar, QAction, QStackedWidget, QComboBox,
25
- QApplication, QDesktopWidget,
26
  )
27
 
28
  from config import settings
@@ -143,6 +143,13 @@ class MainWindow(QMainWindow):
143
  # 重读夹爪出厂标定完成(标定线程 → 主线程):(dev_key, label, 错误文案)
144
  # 错误文案空串 = 成功。用 str 而非 Exception:跨线程只传可显示文本。
145
  _gripper_recalibration_done = pyqtSignal(str, str, str)
 
 
 
 
 
 
 
146
 
147
  def __init__(self):
148
  super().__init__()
@@ -166,7 +173,9 @@ class MainWindow(QMainWindow):
166
  # 引用同一 dict,离线测试注入假条目沿用同一形状)
167
  self._device_manager = DeviceManager()
168
  self._workers = self._device_manager.entries
169
- # 重读标定前这台夹爪是否开着(标定独占设备,完了要开回原来的状态)
 
 
170
  self._gripper_recalib_reopen = set()
171
  # ── 面板开关分派表(kind → 具体开启/关闭动作;路由口径在
172
  # core.device_manager.dispatch_toggle)──
@@ -358,6 +367,16 @@ class MainWindow(QMainWindow):
358
  self._on_gripper_recalibration)
359
  self._gripper_recalibration_done.connect(
360
  self._on_gripper_recalibration_done)
 
 
 
 
 
 
 
 
 
 
361
  self._device_dock = QDockWidget(tr("📷 设备检测"), self)
362
  self._device_dock.setWidget(self._device_panel)
363
  self._device_dock.setFeatures(
@@ -1945,30 +1964,127 @@ class MainWindow(QMainWindow):
1945
  def _on_gripper_error(self, dev_key: str, msg: str):
1946
  """桥接启动失败:弹窗 + 回收槽位 + 面板回退勾选。"""
1947
  self._log(tr("[夹爪] 启动失败: {}", msg))
1948
- QMessageBox.critical(self, tr("夹爪启动失败"), msg)
 
1949
  self._close_gripper(dev_key)
1950
  self._active_device_keys.discard(dev_key)
1951
  self._device_panel.set_checked(dev_key, False)
1952
  self._device_panel.set_active_keys(self._active_device_keys)
1953
  self._update_status()
1954
 
1955
- def _on_gripper_recalibration(self, dev):
1956
- """右键夹爪 → 重新读取这只夹爪的厂商出厂标定。
1957
-
1958
- 出厂标定是**逐设备**的(内参/基线/IMU 外参逐台不同),所以只能从这
1959
- 只夹爪自身读,不能抄别的;读错设备会让 SLAM 位姿系统性跑偏。标定要
1960
- 独占设备,因此先关掉这台夹爪(若已开),完成后再自动开回来。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1961
  """
1962
- label = self._device_label(dev)
1963
  if not dev.serial:
1964
  QMessageBox.warning(
1965
  self, tr("夹爪无序列号"),
1966
  tr("未读取到夹爪 ESP32 序列号,无法定位控制板。"))
1967
- return
1968
  if self._pipeline.is_recording:
1969
  QMessageBox.warning(
1970
  self, tr("录制中"),
1971
- tr("录制中不可重读标定,请先停止录制。"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1972
  return
1973
  answer = QMessageBox.question(
1974
  self, tr("重新读取出厂标定"),
@@ -1979,23 +2095,11 @@ class MainWindow(QMainWindow):
1979
  if answer != QMessageBox.Yes:
1980
  return
1981
 
1982
- was_open = dev.key in self._workers
1983
- if was_open:
1984
- self._gripper_recalib_reopen.add(dev.key)
1985
- self._close_gripper(dev.key)
1986
- self._active_device_keys.discard(dev.key)
1987
- self._device_panel.set_checked(dev.key, False)
1988
- self._device_panel.set_active_keys(self._active_device_keys)
1989
- self._update_status()
1990
  self._log(tr("[夹爪] {} 正在重新读取厂商出厂标定…", label))
1991
-
1992
- thread = threading.Thread(
1993
- target=self._gripper_recalibration_worker,
1994
- args=(dev, label),
1995
- name="gripper-recalibration",
1996
- daemon=True,
1997
- )
1998
- thread.start()
1999
 
2000
  def _gripper_recalibration_worker(self, dev, label: str):
2001
  """标定线程:读设备 → 写 YAML。结果经信号回主线程弹窗。"""
@@ -2011,24 +2115,312 @@ class MainWindow(QMainWindow):
2011
  def _on_gripper_recalibration_done(self, dev_key: str, label: str,
2012
  reason: str):
2013
  """标定结果回主线程:失败弹窗,成功把原先开着的夹爪开回来。"""
2014
- reopen = dev_key in self._gripper_recalib_reopen
2015
- self._gripper_recalib_reopen.discard(dev_key)
2016
  if reason:
2017
  self._log(tr("[夹爪] {} 重读标定失败: {}", label, reason))
2018
  QMessageBox.critical(
2019
  self, tr("重读标定失败"),
2020
  tr("「{}」的出厂标定未能重新读取。\n\n{}\n\n"
2021
- "夹爪仍在设备列表中,可重新勾选开启。", label, reason))
 
2022
  return
2023
  self._log(tr("[夹爪] {} 出厂标定已更新", label))
2024
- if not reopen:
2025
- return # 本来就没开,不擅自打开
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2026
  dev = self._device_panel.device_for_key(dev_key)
2027
  if dev is None:
2028
- return # 标定期间设备拔了/列表重建过,不自动开
2029
- # 自动开回来 = 用户点开关那条路,勾选状态与 _active_device_keys 一致
2030
- self._device_panel.set_checked(dev_key, True)
2031
- self._on_device_toggled(dev, True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2032
 
2033
  def _on_device_toggled(self, dev, on: bool):
2034
  """面板开关 → 打开/关闭设备(多路并发:只动自己,不互拆)。
 
22
  QMainWindow, QWidget, QVBoxLayout, QDockWidget, QTextEdit,
23
  QTableWidget, QTableWidgetItem, QMessageBox, QLabel,
24
  QAbstractItemView, QToolBar, QAction, QStackedWidget, QComboBox,
25
+ QApplication, QDesktopWidget, QInputDialog,
26
  )
27
 
28
  from config import settings
 
143
  # 重读夹爪出厂标定完成(标定线程 → 主线程):(dev_key, label, 错误文案)
144
  # 错误文案空串 = 成功。用 str 而非 Exception:跨线程只传可显示文本。
145
  _gripper_recalibration_done = pyqtSignal(str, str, str)
146
+ # 配对绑定:探板结果 (dev_key, label, 错误文案, 探板结果 dict)
147
+ _gripper_binding_probe_done = pyqtSignal(str, str, str, object)
148
+ # 配对绑定:写入结果 (dev_key, label, 错误文案, 写入结果 dict)
149
+ # dict 必须声明 object:PyQt5 的 str 信号不认 dict 载荷
150
+ _gripper_binding_write_done = pyqtSignal(str, str, str, object)
151
+ # 串口诊断结果 (dev_key, label, 错误文案, 诊断报告 dict)
152
+ _gripper_diagnostics_done = pyqtSignal(str, str, str, object)
153
 
154
  def __init__(self):
155
  super().__init__()
 
173
  # 引用同一 dict,离线测试注入假条目沿用同一形状)
174
  self._device_manager = DeviceManager()
175
  self._workers = self._device_manager.entries
176
+ # 离线操作(重读标定 / 改写绑定序列号 / 串口诊断)前这台夹爪是否
177
+ # 开着:三件事都要独占设备,先把主程序手里的串口让出来,完了按原样
178
+ # 开回去。集合里是 device key。
179
  self._gripper_recalib_reopen = set()
180
  # ── 面板开关分派表(kind → 具体开启/关闭动作;路由口径在
181
  # core.device_manager.dispatch_toggle)──
 
367
  self._on_gripper_recalibration)
368
  self._gripper_recalibration_done.connect(
369
  self._on_gripper_recalibration_done)
370
+ self._device_panel.gripper_binding_requested.connect(
371
+ self._on_gripper_binding)
372
+ self._gripper_binding_probe_done.connect(
373
+ self._on_gripper_binding_probe_done)
374
+ self._gripper_binding_write_done.connect(
375
+ self._on_gripper_binding_write_done)
376
+ self._device_panel.gripper_diagnostics_requested.connect(
377
+ self._on_gripper_diagnostics)
378
+ self._gripper_diagnostics_done.connect(
379
+ self._on_gripper_diagnostics_done)
380
  self._device_dock = QDockWidget(tr("📷 设备检测"), self)
381
  self._device_dock.setWidget(self._device_panel)
382
  self._device_dock.setFeatures(
 
1964
  def _on_gripper_error(self, dev_key: str, msg: str):
1965
  """桥接启动失败:弹窗 + 回收槽位 + 面板回退勾选。"""
1966
  self._log(tr("[夹爪] 启动失败: {}", msg))
1967
+ QMessageBox.critical(self, tr("夹爪启动失败"),
1968
+ msg + self._gripper_serial_stuck_hint(msg))
1969
  self._close_gripper(dev_key)
1970
  self._active_device_keys.discard(dev_key)
1971
  self._device_panel.set_checked(dev_key, False)
1972
  self._device_panel.set_active_keys(self._active_device_keys)
1973
  self._update_status()
1974
 
1975
+ # ── 夹爪离线操作共用骨架 ────────────────────────────
1976
+ # 重读标定 / 改写绑定序列号 / 串口诊断三件事都要**独占这只夹爪的串口**,
1977
+ # 门槛与善后完全一样:设备必须已登记 ESP32 序列号(没有序列号就定位不到
1978
+ # 控制板),录制中一律不给入口,执行前先把已经开着的夹爪关掉、完了按原
1979
+ # 样开回来。差异只在弹窗文案与后台线程体,所以共用下面这套骨架。
1980
+
1981
+ # 板子「节点在、但握手不上」时追加的现场处置梯子。串口层对这件事有两
1982
+ # 种报法,都表明**板子没在服务自己的 USB 串口**:
1983
+ # `Write timeout` —— 主机写不进去(pyserial 的 SerialTimeoutException)
1984
+ # `serial handshake timeout after N attempts` —— 写得进去、板子不回话
1985
+ # 打开失败的种类不在此列:被别的进程占(Errno 16)、没权限(Errno 13)、
1986
+ # 节点不在,���是主机侧/部署侧原因,各有各的处置,混进同一段提示反倒
1987
+ # 误导(它们也都被包在 `serial open/handshake failed: ...` 这句里,
1988
+ # 所以判据只能取原因、不能取前缀)。
1989
+ _SERIAL_STUCK_MARKS = ("Write timeout",
1990
+ "serial handshake timeout after")
1991
+
1992
+ def _gripper_serial_stuck_hint(self, reason: str,
1993
+ board_silent=None) -> str:
1994
+ """``reason`` 属于「板子没在服务 USB 串口」时给出的下一步,否则空串。
1995
+
1996
+ ``board_silent`` 只在做过只读诊断的路径上传:True=只读期间一行都
1997
+ 没收到,False=收到了行(板子在说话、只是不收主机写入)。两种归因
1998
+ 不同,梯子相同,所以只换首句。``None``=没测过,按写不进去表述。
1999
+
2000
+ 梯子按代价从低到高:先断板子自身的电(这一条对「固件没跑」与
2001
+ 「USB 外设被复位打死」两种解释都成立,也最便宜),再证明主机能不能
2002
+ 连上板子(工具包「测试连接」= esptool read_mac,走的是和刷写同一条
2003
+ 下载通路),最后才重烧。最后一句是 `--erase` 的后果:整片擦除会连
2004
+ NVS 里的 Fays 绑定一起清掉。
2005
+ """
2006
+ text = str(reason or "")
2007
+ if not any(mark in text for mark in self._SERIAL_STUCK_MARKS):
2008
+ return ""
2009
+ if board_silent is False:
2010
+ lead = tr("节点在、但握手不上:板子在输出、却不接收主机写入,"
2011
+ "通常是板上程序的状态出了问题。")
2012
+ else:
2013
+ lead = tr("节点在、但握手不上:板子没在服务自己的 USB 串口,"
2014
+ "不是权限问题,也不是被别的程序占着。")
2015
+ return "\n\n" + lead + "\n" + tr(
2016
+ "先把控制板断电 5 秒再上电(有独立供电的连同电源一起断)后重试;"
2017
+ "仍不行就关掉主程序,用 STOUCH_Gripper_Tools 的「测试连接」读一次 "
2018
+ "MAC —— 读得到说明板子通信正常、问题在板上固件,用 flash_esp32.sh "
2019
+ "重烧;读不到先换线换口,别反复重烧。\n"
2020
+ "重烧若用过 --erase,NVS 里的 Fays 绑定会被一并擦掉,"
2021
+ "烧完必须重新写入序列号。")
2022
+
2023
+ def _gripper_offline_guard(self, dev, action_text: str) -> bool:
2024
+ """离线操作前置检查:通过返回 True,否则已弹窗说明原因。
2025
+
2026
+ ``action_text`` 是接在「录制中不可…」里的动作短语(如「重读标定」)。
2027
  """
 
2028
  if not dev.serial:
2029
  QMessageBox.warning(
2030
  self, tr("夹爪无序列号"),
2031
  tr("未读取到夹爪 ESP32 序列号,无法定位控制板。"))
2032
+ return False
2033
  if self._pipeline.is_recording:
2034
  QMessageBox.warning(
2035
  self, tr("录制中"),
2036
+ tr("录制中不可{},请先停止录制。", action_text))
2037
+ return False
2038
+ return True
2039
+
2040
+ def _gripper_offline_take_over(self, dev, label: str, action_text: str):
2041
+ """把夹爪从主程序手里让出来:关掉已开的链路,记下待开回。
2042
+
2043
+ 本来就没开则什么都不记 —— 善后时不会擅自替用户打开设备。
2044
+ """
2045
+ if dev.key not in self._workers:
2046
+ return
2047
+ self._gripper_recalib_reopen.add(dev.key)
2048
+ self._close_gripper(dev.key)
2049
+ self._active_device_keys.discard(dev.key)
2050
+ self._device_panel.set_checked(dev.key, False)
2051
+ self._device_panel.set_active_keys(self._active_device_keys)
2052
+ self._update_status()
2053
+ self._log(tr("[夹爪] {} 已暂时关闭以{}", label, action_text))
2054
+
2055
+ def _gripper_reopen_forget(self, dev_key: str) -> bool:
2056
+ """取出「完了要开回」的标记(取出即消费,回调重入不会开两次)。"""
2057
+ if dev_key not in self._gripper_recalib_reopen:
2058
+ return False
2059
+ self._gripper_recalib_reopen.discard(dev_key)
2060
+ return True
2061
+
2062
+ def _reopen_after_offline(self, dev_key: str, reopen: bool) -> bool:
2063
+ """离线操作善后:原先开着的才开回来,返回是否真的开了。
2064
+
2065
+ 只在**没有改动板子就收场**的路径上调用(只读诊断、用户取消、没找到
2066
+ 可写入的目标);探板/写入失败不开回 —— 板子状态未知,交回用户决定,
2067
+ 与重读标定的口径一致(弹窗里都会说明夹爪仍在设备列表中)。
2068
+ """
2069
+ if not reopen:
2070
+ return False
2071
+ dev = self._device_panel.device_for_key(dev_key)
2072
+ if dev is None:
2073
+ return False # 期间设备拔了/列表重建过,不自动开
2074
+ # 自动开回来 = ���户点开关那条路,勾选状态与 _active_device_keys 一致
2075
+ self._device_panel.set_checked(dev_key, True)
2076
+ self._on_device_toggled(dev, True)
2077
+ return True
2078
+
2079
+ def _on_gripper_recalibration(self, dev):
2080
+ """右键夹爪 → 重新读取这只夹爪的厂商出厂标定。
2081
+
2082
+ 出厂标定是**逐设备**的(内参/基线/IMU 外参逐台不同),所以只能从这
2083
+ 只夹爪自身读,不能抄别的;读错设备会让 SLAM 位姿系统性跑偏。标定要
2084
+ 独占设备,因此先关掉这台夹爪(若已开),完成后再自动开回来。
2085
+ """
2086
+ label = self._device_label(dev)
2087
+ if not self._gripper_offline_guard(dev, tr("重读标定")):
2088
  return
2089
  answer = QMessageBox.question(
2090
  self, tr("重新读取出厂标定"),
 
2095
  if answer != QMessageBox.Yes:
2096
  return
2097
 
2098
+ self._gripper_offline_take_over(dev, label, tr("重读标定"))
 
 
 
 
 
 
 
2099
  self._log(tr("[夹爪] {} 正在重新读取厂商出厂标定…", label))
2100
+ self._start_gripper_worker(
2101
+ self._gripper_recalibration_worker, dev, label,
2102
+ "gripper-recalibration")
 
 
 
 
 
2103
 
2104
  def _gripper_recalibration_worker(self, dev, label: str):
2105
  """标定线程:读设备 → 写 YAML。结果经信号回主线程弹窗。"""
 
2115
  def _on_gripper_recalibration_done(self, dev_key: str, label: str,
2116
  reason: str):
2117
  """标定结果回主线程:失败弹窗,成功把原先开着的夹爪开回来。"""
2118
+ reopen = self._gripper_reopen_forget(dev_key)
 
2119
  if reason:
2120
  self._log(tr("[夹爪] {} 重读标定失败: {}", label, reason))
2121
  QMessageBox.critical(
2122
  self, tr("重读标定失败"),
2123
  tr("「{}」的出厂标定未能重新读取。\n\n{}\n\n"
2124
+ "夹爪仍在设备列表中,可重新勾选开启。", label, reason)
2125
+ + self._gripper_serial_stuck_hint(reason))
2126
  return
2127
  self._log(tr("[夹爪] {} 出厂标定已更新", label))
2128
+ self._reopen_after_offline(dev_key, reopen)
2129
+
2130
+ # ── 夹爪配对:读写 ESP32 NVS 里绑定的 Fays 序列号 ─────────
2131
+ # 配对链是「按 USB 序列号唯一确定控制板 → 读板子 NVS 里记的 Fays 产品
2132
+ # 序列号 → 和 SDK 枚举到的 Fays 设备对上」。换新夹爪时新板子的 NVS 还是
2133
+ # 空的(固件回 ERR FAYS_SERIAL_NOT_SET),主程序因此认不出来 —— 这一步
2134
+ # 就是让用户在主程序里把新板子指到眼前这台 Fays 上,不必去开厂商工具包。
2135
+ # 分两段:先探板(读现状 + 列出在线 Fays),再由用户挑目标写入。
2136
+
2137
+ def _on_gripper_binding(self, dev):
2138
+ """右键夹爪 → 读取/改写 ESP32 绑定的 Fays 序列号(第一步:探板)。"""
2139
+ label = self._device_label(dev)
2140
+ if not self._gripper_offline_guard(dev, tr("改写绑定序列号")):
2141
+ return
2142
+ self._gripper_offline_take_over(dev, label, tr("改写绑定序列号"))
2143
+ self._log(tr("[夹爪] {} 正在读取 ESP32 绑定信息…", label))
2144
+ self._start_gripper_worker(
2145
+ self._gripper_binding_probe_worker, dev, label,
2146
+ "gripper-binding-probe")
2147
+
2148
+ def _gripper_binding_probe_worker(self, dev, label: str):
2149
+ """探板线程:读绑定现状 + 列出在线 Fays 序列号 → 回主线程挑目标。"""
2150
+ reason = ""
2151
+ info = {}
2152
+ try:
2153
+ from core.gripper.fays_single import SingleFaysLease
2154
+ lease = SingleFaysLease(logger=self._log)
2155
+ info = dict(lease.esp_binding_status(dev.serial) or {})
2156
+ if info.get("reason"):
2157
+ # 板子没读通就别再枚举 Fays 了:先解决连不上的问题
2158
+ reason = str(info["reason"])
2159
+ else:
2160
+ try:
2161
+ by_serial, skipped = lease.online_fays_serials()
2162
+ info["online"] = sorted(str(s) for s in by_serial)
2163
+ info["skipped"] = [str(s) for s in skipped]
2164
+ except Exception as exc:
2165
+ # 枚举失败不算探板失败:板子现状已经读到了,照样报给用户
2166
+ info["online"] = []
2167
+ info["online_error"] = str(exc)
2168
+ except Exception as exc: # 定位不到 ESP32 等前置失败
2169
+ reason = str(exc)
2170
+ self._gripper_binding_probe_done.emit(dev.key, label, reason, info)
2171
+
2172
+ def _on_gripper_binding_probe_done(self, dev_key: str, label: str,
2173
+ reason: str, info):
2174
+ """探板结果回主线程:如实汇报现状 → 挑目标 → 起写入线程。"""
2175
+ reopen = self._gripper_reopen_forget(dev_key)
2176
+ if reason:
2177
+ self._log(tr("[夹爪] {} 读取绑定信息失败: {}", label, reason))
2178
+ QMessageBox.critical(
2179
+ self, tr("读取绑定信息失败"),
2180
+ tr("「{}」的 ESP32 绑定信息未能读出。\n\n{}\n\n"
2181
+ "夹爪仍在设备列表中,可重新勾选开启。\n"
2182
+ "想先看板上到底在输出什么,用右键菜单的「ESP32 串口诊断」。",
2183
+ label, reason)
2184
+ + self._gripper_serial_stuck_hint(reason))
2185
+ return # 板子状态未知,不开回(与重读标定同口径)
2186
  dev = self._device_panel.device_for_key(dev_key)
2187
  if dev is None:
2188
+ self._log(tr("[夹爪] {} 已从设备列表消失,中止绑定", label))
2189
+ return
2190
+ bound = str(info.get("bound") or "")
2191
+ board = str(info.get("esp_serial") or "")
2192
+ online = [str(s) for s in (info.get("online") or [])]
2193
+ online_error = str(info.get("online_error") or "")
2194
+ self._log(tr("[夹爪] {} ESP32 {} 当前绑定: {};在线 Fays: {}",
2195
+ label, board, bound or tr("<未绑定>"),
2196
+ ", ".join(online) if online else tr("无")))
2197
+ for skipped in (info.get("skipped") or []):
2198
+ self._log(tr("[夹爪] {} 跳过被占用的 Fays: {}", label, skipped))
2199
+ if online_error or not online:
2200
+ QMessageBox.warning(
2201
+ self, tr("未找到在线 Fays"),
2202
+ tr("ESP32 {} 读通了(当前绑定:{}),但本机没有可用于配对的"
2203
+ "在线 Fays S80M。\n\n{}\n\n"
2204
+ "请把 Fays 的 stereo 与 IMU 两根线都插好再重试;被其他程序"
2205
+ "占用的那一台也不能当目标。",
2206
+ board, bound or tr("<未绑定>"),
2207
+ online_error or tr("未枚举到任何 Fays 产品序列号。")))
2208
+ self._reopen_after_offline(dev_key, reopen)
2209
+ return
2210
+ chosen = self._ask_target_fays_serial(info, label)
2211
+ if not chosen:
2212
+ self._log(tr("[夹爪] {} 已取消绑定序列号改写", label))
2213
+ self._reopen_after_offline(dev_key, reopen)
2214
+ return
2215
+ self._log(tr("[夹爪] {} 正在把 {} 写入 ESP32 {}…",
2216
+ label, chosen, board))
2217
+ self._start_gripper_worker(
2218
+ self._gripper_binding_write_worker, dev, label,
2219
+ "gripper-binding-write", extra=(chosen,))
2220
+
2221
+ def _ask_target_fays_serial(self, info, label: str):
2222
+ """让用户在**当前在线的** Fays 序列号里挑一个写进板子。放弃返回 None。
2223
+
2224
+ 只给选不给手输:写错序列号会让这只夹爪静默指向别的 Fays —— 配对是
2225
+ 唯一匹配,写错了症状就是「连不上」,比现在更难排查。
2226
+ """
2227
+ online = sorted(str(s) for s in (info.get("online") or []))
2228
+ if not online:
2229
+ return None
2230
+ current = str(info.get("bound") or "")
2231
+ index = online.index(current) if current in online else 0
2232
+ chosen, ok = QInputDialog.getItem(
2233
+ self, tr("绑定 Fays 序列号"),
2234
+ tr("把哪一台 Fays 的序列号写进「{}」的 ESP32 {}?\n\n"
2235
+ "当前绑定:{}", label, info.get("esp_serial") or "",
2236
+ current or tr("<未绑定>")),
2237
+ online, index, False)
2238
+ if not ok or not chosen:
2239
+ return None
2240
+ answer = QMessageBox.question(
2241
+ self, tr("绑定 Fays 序列号"),
2242
+ tr("将把序列号「{}」写入 ESP32 {} 的 NVS 并持久化(覆盖原值 "
2243
+ "{})。\n\n写完这只夹爪就固定配对这一台 Fays。\n\n继续?",
2244
+ chosen, info.get("esp_serial") or "",
2245
+ current or tr("<未��定>")),
2246
+ QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
2247
+ if answer != QMessageBox.Yes:
2248
+ return None
2249
+ return chosen
2250
+
2251
+ def _gripper_binding_write_worker(self, dev, label: str,
2252
+ fays_serial: str):
2253
+ """写入线程:``WF:`` 写 NVS → 立刻 ``QF`` 回读 → 回主线程报结果。"""
2254
+ reason = ""
2255
+ result = {}
2256
+ try:
2257
+ from core.gripper.fays_single import SingleFaysLease
2258
+ lease = SingleFaysLease(logger=self._log)
2259
+ readback = lease.write_bound_serial(dev.serial, fays_serial)
2260
+ result = {"written": fays_serial, "readback": readback or ""}
2261
+ except Exception as exc: # 校验失败/写失败/读不回都走这里
2262
+ reason = str(exc)
2263
+ self._gripper_binding_write_done.emit(dev.key, label, reason, result)
2264
+
2265
+ def _on_gripper_binding_write_done(self, dev_key: str, label: str,
2266
+ reason: str, result):
2267
+ """写入结果回主线程:回读值对不上就明说不算成功(不猜)。"""
2268
+ reopen = self._gripper_reopen_forget(dev_key)
2269
+ if reason:
2270
+ self._log(tr("[夹爪] {} 写入绑定序列号失败: {}", label, reason))
2271
+ QMessageBox.critical(
2272
+ self, tr("写入绑定序列号失败"),
2273
+ tr("「{}」的 ESP32 未能写入绑定序列号。\n\n{}\n\n"
2274
+ "夹爪仍在设备列表中,可重新勾选开启;"
2275
+ "想确认板上读到了什么,用右键菜单的「ESP32 串口诊断」。",
2276
+ label, reason)
2277
+ + self._gripper_serial_stuck_hint(reason))
2278
+ return
2279
+ written = str((result or {}).get("written") or "")
2280
+ readback = str((result or {}).get("readback") or "")
2281
+ self._log(tr("[夹爪] {} 绑定序列号已写入 {},回读 {}",
2282
+ label, written, readback or tr("<空>")))
2283
+ if readback != written:
2284
+ QMessageBox.warning(
2285
+ self, tr("回读不一致"),
2286
+ tr("已向「{}」的 ESP32 写入 {},但立刻回读得到的是 {}。\n\n"
2287
+ "板上可能没保存成功,请重试;"
2288
+ "想确认板上到底记了什么,用右键菜单的「ESP32 串口诊断」。",
2289
+ label, written, readback or tr("<空>")))
2290
+ else:
2291
+ QMessageBox.information(
2292
+ self, tr("绑定完成"),
2293
+ tr("「{}」已绑定 Fays 序列号 {}。\n\n"
2294
+ "现在可关掉再勾选开启这只夹爪,主程序会按新绑定配对。",
2295
+ label, readback))
2296
+ self._reopen_after_offline(dev_key, reopen)
2297
+
2298
+ # ── 夹爪 ESP32 串口诊断(只读)─────────────────────────
2299
+ # 夹爪连不上时最需要回答的问题是「板子到底在不在说话」。串口节点是 USB
2300
+ # 外设枚举出来的(303a:1001 是芯片自带的 USB-Serial-JTAG,与固件是否在跑
2301
+ # 无关),所以「节点在」不能当「板子在服务串口」。诊断因此先握手,握不上
2302
+ # 再**只读**开着口收一段:写阻塞时读这条路仍然通,收到行=板子在说话只是
2303
+ # 不收主机写入,一行都没有=板上没有程序在写这个口。
2304
+
2305
+ def _on_gripper_diagnostics(self, dev):
2306
+ """右键夹爪 → 只读串口诊断:把这台 ESP32 的原样输出打出来。"""
2307
+ label = self._device_label(dev)
2308
+ if not self._gripper_offline_guard(dev, tr("做串口诊断")):
2309
+ return
2310
+ self._gripper_offline_take_over(dev, label, tr("做串口诊断"))
2311
+ self._log(tr("[夹爪] {} 正在做 ESP32 串口诊断"
2312
+ "(只读,握手失败会再只读复检,最长约 6 秒)…",
2313
+ label))
2314
+ self._start_gripper_worker(
2315
+ self._gripper_diagnostics_worker, dev, label, "gripper-diagnostics")
2316
+
2317
+ def _gripper_diagnostics_worker(self, dev, label: str):
2318
+ """诊断线程:开串口收板上原样输出 → 回主线程打日志 + 弹摘要。"""
2319
+ reason = ""
2320
+ report = {}
2321
+ try:
2322
+ from core.gripper.fays_single import SingleFaysLease
2323
+ lease = SingleFaysLease(logger=self._log)
2324
+ report = dict(lease.esp_console_report(dev.serial) or {})
2325
+ except Exception as exc:
2326
+ reason = str(exc)
2327
+ self._gripper_diagnostics_done.emit(dev.key, label, reason, report)
2328
+
2329
+ def _on_gripper_diagnostics_done(self, dev_key: str, label: str,
2330
+ reason: str, report):
2331
+ """诊断结果回主线程:原文进日志,摘要弹窗。诊断只读,一律开回。"""
2332
+ reopen = self._gripper_reopen_forget(dev_key)
2333
+ if reason:
2334
+ self._log(tr("[夹爪] {} 串口诊断未能进行: {}", label, reason))
2335
+ QMessageBox.critical(
2336
+ self, tr("ESP32 串口诊断"),
2337
+ tr("「{}」的串口诊断没能进行。\n\n{}\n\n"
2338
+ "夹爪仍在设备列表中,可重新勾选开启。", label, reason))
2339
+ self._reopen_after_offline(dev_key, reopen)
2340
+ return
2341
+ report = report or {}
2342
+ board = str(report.get("esp_serial") or dev_key)
2343
+ device = str(report.get("device") or "")
2344
+ path = str(report.get("physical_usb_path") or "")
2345
+ lines = [str(line) for line in (report.get("lines") or [])]
2346
+ self._log(tr("[夹爪] {} 诊断: ESP32 {} 串口节点 {} 物理口 {}",
2347
+ label, board, device or tr("<无>"),
2348
+ path or tr("<未知>")))
2349
+ if not report.get("connected"):
2350
+ err = str(report.get("last_error") or "")
2351
+ read_lines = [str(line)
2352
+ for line in (report.get("read_only_lines") or [])]
2353
+ read_error = str(report.get("read_only_error") or "")
2354
+ self._log(tr("[夹爪] {} 未握手: {}", label, err or tr("<无错误文本>")))
2355
+ # 只读复检的结果单独记一行:这是「板子哑了」与「板子会说话但
2356
+ # 不收写入」的分界,也是下次回查时最先要看的东西。
2357
+ if read_error:
2358
+ self._log(tr("[夹爪] {} 只读复检也打不开: {}",
2359
+ label, read_error))
2360
+ else:
2361
+ self._log(tr("[夹爪] {} 只读复检 {} 秒收到 {} 行",
2362
+ label, report.get("seconds"), len(read_lines)))
2363
+ for line in read_lines:
2364
+ self._log(f"[夹爪串口] {line}")
2365
+ shown = read_lines[:20]
2366
+ body = "\n".join(f" {line}" for line in shown)
2367
+ if not shown:
2368
+ body = tr(" (一行都没有:板上没有程序在写这个口)")
2369
+ elif len(read_lines) > len(shown):
2370
+ body += "\n" + tr(" …(共 {} 行,完整输出见日志)",
2371
+ len(read_lines))
2372
+ QMessageBox.critical(
2373
+ self, tr("ESP32 串口诊断"),
2374
+ tr("「{}」的 ESP32 没能在串口上握手。\n\n"
2375
+ "串口层原文:\n{}\n\n"
2376
+ "串口节点:{}\n\n"
2377
+ "不写任何字节、只读 {} 秒,收到 {} 行:\n{}",
2378
+ label, err or tr("<无>"), device or tr("<无>"),
2379
+ report.get("seconds"), len(read_lines), body)
2380
+ + self._gripper_serial_stuck_hint(
2381
+ err,
2382
+ # 只读复检自己都没打开(被抢口/权限)=没测到静默,
2383
+ # 不按「板子哑了」表述
2384
+ board_silent=(None if read_error else not read_lines)))
2385
+ self._reopen_after_offline(dev_key, reopen)
2386
+ return
2387
+ state = str(report.get("state") or "")
2388
+ bound = str(report.get("bound") or "")
2389
+ self._log(tr("[夹爪] {} 握手响应: {};绑定: {}",
2390
+ label, state or tr("<无>"), bound or tr("<未绑定>")))
2391
+ for line in lines:
2392
+ self._log(f"[夹爪串口] {line}")
2393
+ shown = lines[:20]
2394
+ body = [
2395
+ tr("ESP32 序列号: {}", board),
2396
+ tr("串口节点: {}", device or tr("<无>")),
2397
+ tr("物理口: {}", path or tr("<未知>")),
2398
+ tr("握手响应: {}", state or tr("<无>")),
2399
+ tr("绑定序列号: {}", bound or tr("<未绑定>")),
2400
+ "",
2401
+ tr("{} 秒内板上主动输出 {} 行:",
2402
+ report.get("seconds"), len(lines)),
2403
+ ]
2404
+ body += [f" {line}" for line in shown] or [tr(" (一行都没有)")]
2405
+ if len(lines) > len(shown):
2406
+ body.append(tr(" …(共 {} 行,完整输出见日志)", len(lines)))
2407
+ QMessageBox.information(
2408
+ self, tr("ESP32 串口诊断"), "\n".join(body))
2409
+ self._reopen_after_offline(dev_key, reopen)
2410
+
2411
+ def _start_gripper_worker(self, worker, dev, label: str, name: str,
2412
+ extra: tuple = ()):
2413
+ """起一个夹爪后台线程(``dev``/``label`` 固定为前两个参数)。
2414
+
2415
+ 四件离线操作的线程体签名一致(dev, label[, 额外参数]),线程名写进
2416
+ ps/top 便于现场排查哪只夹爪在占用串口。
2417
+ """
2418
+ threading.Thread(
2419
+ target=worker,
2420
+ args=(dev, label) + tuple(extra),
2421
+ name=name,
2422
+ daemon=True,
2423
+ ).start()
2424
 
2425
  def _on_device_toggled(self, dev, on: bool):
2426
  """面板开关 → 打开/关闭设备(多路并发:只动自己,不互拆)。