14 KiB
单相机自动切换 Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. This task uses native execution in the existing session; no subagent dispatch.
Goal: 在同一服务端入口下替换 RealSense 与 MV-CS050-10UM,Qt 自动识别当前相机并切换 RGBD 或二维平面操作。
Architecture: 服务端增加一个自动相机适配器,保持逻辑设备 ID 稳定,实际型号、序列号和会话代次动态变化。适配器一次只拥有一个采集实例;Qt 通过 CameraService 查询真实能力,现有页面消费同一身份与图像。二维操作复用 TouchPlanner 的射线平面求交,配置仍使用 QSettings。
Tech Stack: Qt 5.12.4、现有 qmake/CMake、protobuf/gRPC、现有 OpenCV/FFmpeg/RealSense SDK;海康 MVS SDK 为服务端可选依赖。
Spec: docs/superpowers/specs/2026-10-12-camera-capability-modes-design.md
Global Constraints
- 同一时间只使用一台相机,不实施双相机协同或并行采集。
- 不硬编码 IP、名称或序列号。
- 保留现有页面导航、视频获取通道、TCP 和手眼保存机制。
- Qt 5.12.4 和现有 C++ 标准保持不变。
- SDK 未安装时明确提示驱动不可用,不影响原有相机驱动构建。
- 自动化测试不发送机械臂运动指令。
- 力传感器尚无型号和协议,本次仅预留接入契约和状态;不提供真实力控。
Review Focus
- 同一逻辑设备 ID 换了硬件:必须检测序列号和会话变化,旧图像、标定与路径不得继续使用。
- 采集帧跨越机器人读取窗口,或两台机器时钟不同:保留时间不确定区间并拒绝不能确定同步的数据。
- 单台设备拔出或发现两台设备:清除活动相机,禁止静默选取设备或回退定位方式。
- 内参被 ROI、分辨率或镜头变化影响:阻止定位,不能缩放旧内参冒充新标定。
- MVS 缺失或传感器未接入:不伪造图像、深度、时间戳或零力反馈。
Task 1: 服务端身份与能力协议
Files:
- Modify (both repositories):
protos/cmvr/api/camera_command.proto - Modify (server):
cmvr-es/devices/camera/abstract_camera.h - Modify (server):
cmvr-es/service/grpc/src/grpc_camera_service.cpp - Modify (server): RealSense header/source for actual device identity
- Test (server, new):
cmvr-es/service/grpc/tests/camera_capabilities_test.cpp
Interfaces (new definitions, not existing interfaces):
-
CameraCapabilitiesmessage: version, driver, model, serial, transport, raw_image, valid_intrinsics, capture_timestamp, metric_aligned_depth, distortion_model, session_generation, unavailable_reason. -
Append
CameraState.capabilities; appendFrameData.camera_serialandFrameData.camera_session_generationusing unused field numbers. Preserve existing fields. -
AbstractCamera::getCapabilities()returns a value snapshot; default reports unsupported/unknown, never inferred capabilities. -
Write tests: empty capability fields remain unknown; non-depth driver cannot advertise metric depth; serialized legacy fields retain their values; raw and video frames carry the same hardware identity.
-
Run those tests to establish failure before adding capability fields and producers.
-
Extend both proto copies and regenerate using project build tooling. Use SDK-reported model/serial; RealSense metric capability additionally requires the supported depth output mode and geometry path.
-
Include identity, distortion model and real capture timestamp in raw GetRGBImage response, not response receipt time. Return no usable image when capture identity is missing or stale in automatic mode.
-
Run protocol/producer tests and existing camera stream policy tests; check that old clients ignore new fields.
Task 2: MVS 灰度采集与单实例生命周期
Files:
- Create (server):
cmvr-es/devices/camera/mvs_camera/include/mvs_camera.h - Create (server):
cmvr-es/devices/camera/mvs_camera/src/mvs_camera.cpp - Create (server):
cmvr-es/devices/camera/mvs_camera/CMakeLists.txt - Create (server):
cmvr-es/devices/camera/mvs_camera/tests/mvs_camera_test.cpp - Modify (both repositories):
protos/cmvr/config/camera_config/camera_config.proto - Modify (server):
cmvr-es/devices/camera/CMakeLists.txt
Interfaces (new):
-
MvsCamera final : AbstractCameraimplements existing init/start/stop, state, raw image and encoded frame interfaces. -
MvsCameraConfig: id, serial, capture, encoder, fx/fy/cx/cy, exactly five Brown distortion coefficients, calibration_width/height. Unspecified intrinsics do not prevent preview but disable calibration and positioning. -
An SDK discovery helper returns attached model/serial/transport descriptors without starting acquisition.
-
Obtain and inspect official MVS headers/sample definitions on the server before implementing calls. If SDK is unavailable, build the explicit unsupported adapter branch and document the hardware-validation limitation; do not fabricate SDK declarations.
-
Write fake-SDK tests: Mono8 ownership after buffer release, actual frame width/height, start/stop/restart, no duplicate producer, shutdown while awaiting frame, timeout, SDK missing.
-
Run tests to establish failure, then implement optional SDK compilation using its actual headers/libraries.
-
Acquire images on one worker, copy SDK-owned buffers before releasing them, and publish through the existing CameraStreamEncoder/stream interface. Preserve sensor frame number and distinguish SDK sensor timing from host receive timing; advertise timestamp capability only when bounded capture timing is actually established.
-
Keep raw acquisition dimensions separate from preview encoding dimensions. A mismatched intrinsics configuration blocks raw calibration capture, not video preview.
-
Run fake-SDK tests. With hardware/SDK present, verify real Mono8 snapshots and steady video without any robot moves.
Task 3: 服务端自动相机适配器
Files:
- Create (server):
cmvr-es/devices/camera/auto_camera/include/auto_camera.h - Create (server):
cmvr-es/devices/camera/auto_camera/src/auto_camera.cpp - Create (server):
cmvr-es/devices/camera/auto_camera/CMakeLists.txt - Create (server):
cmvr-es/devices/camera/auto_camera/tests/auto_camera_test.cpp - Modify (server):
cmvr-es/devices/camera/camera_factory.h, camera CMakeLists - Modify (both repositories): camera_config.proto
- Create (Qt documentation):
docs/CAMERA_AUTO_MODE.mdwith a standalone configuration example; do not overwrite live configuration.
Interfaces (new):
-
AutoCameraConfig: id, RealSense capture/encoder profile, MVS profile, per-serial calibration entries. -
AutoCamera final : AbstractCamera, stable logical id; internal device and capabilities refer to the current real hardware. -
discoverAttachedCamera()uses RealSense SDK enumeration and Task 2 discovery; result is none, unique, ambiguous, or unavailable. -
session_generationincreases before clearing/replacing the delegate; all frames carry that generation. -
Write fake-device tests: unique RealSense, unique MVS, none, ambiguous, unplug during raw capture, replaced serial under the same logical ID, and outstanding stream lease during replacement.
-
Run tests to establish failure; implement delegation using existing camera methods, without changing DeviceManager global registration behavior.
-
On refresh/start, retire the old delegate and its producer before creating a new one. On disappearance, fail current reads and terminate the old stream epoch. Never encode or read through a freed delegate; never combine producer indexes from different sessions.
-
One logical auto-camera entry must replace the separate enabled camera entries in the deployment example. Preserve separate legacy configurations for users who do not enable auto mode.
-
Run lifecycle tests and verify at most one acquisition instance starts at any point. Refresh/reconnect supports replacement; automatic hotplug monitoring is added only if its lifecycle can use existing events without a second capture instance.
Task 4: Qt 自动能力同步与标定归属
Files:
- Modify:
src/robotclient.h,src/robotclient.cpp - Modify:
src/mainwindow.h,src/mainwindow.cpp - Modify:
ui/handeyecalibrationwidget.h/.cpp/.ui - Modify:
src/touchoperationwidget.h/.cpp - Modify:
src/handeyestore.h/.cpp,src/calibrationfile.h - Test:
tests/touchintegration_test.cpp,tests/touchoperation_test.cpp,tests/handeyeui_test.cpp,tests/handeyestore_test.cpp
Interfaces (new):
-
RobotClient::requestCameraCapabilities(const QString &cameraId, quint64 token)and matchingcameraCapabilitiesReceived(token, cameraId, capabilities, success, detail). -
Each calibration page accepts an active-camera snapshot through
setCameraCapabilities(const QString &cameraId, const QVariantMap &capabilities). -
Add optional cameraSerial and cameraModel fields to HandEyeStore::Record. Preserve legacy files but require explicit identity confirmation; known mismatched identity must be rejected.
-
Add tests for unknown capabilities, server reconnect, delayed stale response, same ID/new serial, same serial/new acquisition generation, and legacy result identity confirmation. Run them red.
-
Query asynchronously after connection and device discovery; match callbacks to session/token. MainWindow supplies the same unique active camera to the camera, handeye and touch pages. No new two-camera selector or navigation.
-
Clear frame/target/path on identity, generation, calibration or intrinsics changes. Hide incompatible saved results; reject imports belonging to another known camera.
-
Display current model and automatic mode compactly. Preview may start with unknown/missing intrinsics; sampling and coordinate conversion remain blocked with a precise reason.
-
Run widget/store/loopback tests. Assert read/identity refresh requests issue zero robot motion RPCs.
Task 5: 二维平面参数与定位流程
Files:
- Create:
src/touchplanestore.h/.cpp - Modify:
src/touchoperationwidget.h/.cpp,src/touchplanner.h/.cpp - Modify:
src/robotclient.h/.cpp,src/mainwindow.cpp - Modify:
CmvrControlStation.pro,CMakeLists.txtand affected test .pro files - Test:
tests/touchplanner_test.cpp,tests/touchoperation_test.cpp,tests/touchintegration_test.cpp - Document:
docs/CAMERA_AUTO_MODE.mdwith a plane JSON example
Interfaces (new):
-
TouchPlaneStore::Record: name, endpoint/device scope, cameraSerial, handEyeName, handEyeFingerprint, intrinsicsFingerprint, Plane, operatingRadiusM. -
TouchPlaneStore::parse(const QVariantMap &, Record &, QString &error),load(QSettings &, endpoint, device, serial, Record &, error),save(...). Parsing failure leaves the previous value unchanged. -
Plane JSON contract: schema_version=1, units="m", frame="robot_base", name, robot_id, camera_serial, handeye_name/fingerprint, intrinsics_fingerprint, origin[3], normal[3], operating_radius_m. Normal must be finite and unit length within 1e-6; radius finite, >0 and <= configured maxTravelM.
-
A separate
requestTouchImage(cameraId, token)returns raw image, matched intrinsics and bounded local capture interval without pretending it is RGBD. Existing requestTouchRgbdImage retains its strict checks. -
Add parser/load tests for serial mismatch, missing plane, invalid units/frame/normal, NaN, handeye replacement, intrinsics replacement and QSettings failure. Add UI tests for switching RGBD → plane → RGBD and failure remaining in the selected mode. Run red.
-
Add an import-plane button and short current-plane state to the existing task panel. Do not recreate the deleted mandatory three-contact teach controls.
-
Reuse observation pose bracketing. In plane mode lock the raw grayscale frame only when its capture interval is wholly inside the robot-reading interval. Reuse the existing RGBD clock conversion logic as a shared helper, preserving uncertainty and validation.
-
Call resolvePixels for plane mode, then invert Base_T_Camera for camera XYZ display. Use the imported plane normal for approach/retract and the current selected TCP orientation; call buildPlan with depthTargets=false. Keep depth mode's depth validation and depthTargets=true.
-
Keep explicit path preview/confirmation and existing motion interfaces. Missing depth is an error in depth mode, never an automatic fallback to plane mode.
-
Run geometry and widget tests, including parallel rays, behind-camera intersections, invalid plane bounds, old frames, and 1–2 arbitrary non-board target pixels. Verify existing RGBD tests still pass.
Task 6: 力传感器预留与整体验证
Files:
- Modify:
src/touchoperationwidget.h/.cpp - Document:
docs/CAMERA_AUTO_MODE.md - Test:
tests/touchoperation_test.cpp
Interfaces:
-
This phase exposes no live sensor API. UI state is “力传感器:未接入”; no fabricated zero force, no enabled force-control buttons.
-
Document future sensor contract: identity, robot binding, Fx/Fy/Fz in N, timestamp/validity, force coordinate frame, sensor-to-tool transform, range and fault. Torque is explicitly absent for a three-axis sensor.
-
Add a UI assertion that unconnected force is represented as unavailable and cannot be selected as contact feedback.
-
Implement the compact state row in the current action panel; document recalibration after mechanical installation changes and future server/controller-side contact control.
-
Run affected QtTest suites and Python handeye tests only where affected; regenerate protobufs and build the Qt executable with existing Qt/MinGW versions.
-
Build the server with MVS disabled to prove optional dependency compatibility; with SDK available, build the enabled adapter and verify a real camera stream and image/capability response.
-
Review diff for stale callbacks, frame/SDK buffer lifetime, single producer ownership, unit/transform direction, and changes outside this feature.
-
Report exact files and checks, and separately state any SDK/hardware limitation. Do not claim hardware switching or force control is validated without corresponding evidence. Do not send physical movement commands as an automatic check.
Execution and deployment
Implement in the current session after plan review. Preserve existing local changes and do not commit or push unrelated files. Server changes are first built and packaged with the configuration example; a running service is not replaced as part of automated tests. The unresolved actual-motion issue remains a separate prerequisite for a physical touch trial.