feat: integrate hand-eye calibration, TCP and touch operation
This commit is contained in:
parent
1473cee798
commit
87fb869403
4
.gitignore
vendored
4
.gitignore
vendored
@ -19,3 +19,7 @@
|
||||
*.pfx
|
||||
*.p12
|
||||
*.key
|
||||
/build-*/
|
||||
/.qtcreator/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
|
||||
@ -152,10 +152,14 @@ if(CMVR_WITH_MSQUIC)
|
||||
endif()
|
||||
|
||||
set(CMVR_SOURCES
|
||||
src/agvmapviewwidget.cpp
|
||||
src/agvmapviewwidget.h
|
||||
src/audiostreammanager.cpp
|
||||
src/audiostreammanager.h
|
||||
src/configeditorwidget.cpp
|
||||
src/configeditorwidget.h
|
||||
src/jointfloweditor.cpp
|
||||
src/jointfloweditor.h
|
||||
src/main.cpp
|
||||
src/mainwindow.cpp
|
||||
src/mainwindow_ui.cpp
|
||||
@ -166,6 +170,8 @@ set(CMVR_SOURCES
|
||||
src/rpcservicewidget.h
|
||||
src/robotclient.cpp
|
||||
src/robotclient.h
|
||||
src/tactileheatmapwidget.cpp
|
||||
src/tactileheatmapwidget.h
|
||||
src/trendwidget.cpp
|
||||
src/trendwidget.h
|
||||
src/uiicons.h
|
||||
@ -191,6 +197,20 @@ set(CMVR_SOURCES
|
||||
ui/rpcservicewidget.ui
|
||||
resources.qrc)
|
||||
|
||||
list(APPEND CMVR_SOURCES
|
||||
src/handeyebridge.cpp src/handeyebridge.h
|
||||
src/handeyestore.cpp src/handeyestore.h
|
||||
src/handeyeurdf.cpp src/handeyeurdf.h
|
||||
src/touchplanner.cpp src/touchplanner.h
|
||||
src/touchsequencecontroller.cpp src/touchsequencecontroller.h
|
||||
src/touchvideowidget.cpp src/touchvideowidget.h
|
||||
src/touchplanestore.cpp src/touchplanestore.h src/cameracapabilities.h
|
||||
src/touchoperationwidget.cpp src/touchoperationwidget.h
|
||||
src/handeyemotionwidget.cpp src/handeyemotionwidget.h
|
||||
src/tcpcalibration.cpp src/tcpcalibration.h
|
||||
src/tcpjogcontroller.cpp src/tcpjogcontroller.h
|
||||
src/tcptoolstore.cpp src/tcptoolstore.h
|
||||
src/tcpcalibrationwidget.cpp src/tcpcalibrationwidget.h)
|
||||
add_executable(CmvrControlStation ${CMVR_SOURCES})
|
||||
if(WIN32)
|
||||
set_target_properties(CmvrControlStation PROPERTIES WIN32_EXECUTABLE TRUE)
|
||||
@ -354,6 +374,31 @@ add_custom_command(TARGET CmvrControlStation POST_BUILD
|
||||
"$<TARGET_FILE_DIR:CmvrControlStation>/models")
|
||||
|
||||
install(TARGETS CmvrControlStation RUNTIME DESTINATION bin)
|
||||
add_custom_command(TARGET CmvrControlStation POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "$<TARGET_FILE_DIR:CmvrControlStation>/scripts"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/handeye_worker.py"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/handeye_math.py"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/handeye_refinement.py"
|
||||
"$<TARGET_FILE_DIR:CmvrControlStation>/scripts")
|
||||
install(FILES scripts/handeye_worker.py scripts/handeye_math.py scripts/handeye_refinement.py DESTINATION bin/scripts)
|
||||
if(WIN32)
|
||||
set(CMVR_HAND_EYE_JPEG_PLUGIN "${CMVR_QT_PLUGIN_ROOT}/imageformats/qjpeg$<$<CONFIG:Debug>:d>.dll")
|
||||
add_custom_command(TARGET CmvrControlStation POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "$<TARGET_FILE_DIR:CmvrControlStation>/imageformats"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMVR_HAND_EYE_JPEG_PLUGIN}"
|
||||
"$<TARGET_FILE_DIR:CmvrControlStation>/imageformats/")
|
||||
install(FILES "${CMVR_HAND_EYE_JPEG_PLUGIN}" DESTINATION bin/imageformats)
|
||||
set(CMVR_HAND_EYE_RUNTIME_DIR "${CMAKE_CURRENT_SOURCE_DIR}/third_party/handeye-runtime" CACHE PATH "Bundled Windows x64 hand-eye runtime")
|
||||
if(NOT EXISTS "${CMVR_HAND_EYE_RUNTIME_DIR}/manifest.json")
|
||||
message(FATAL_ERROR "Build the bundled runtime with scripts/package_handeye_runtime.py first")
|
||||
endif()
|
||||
add_custom_command(TARGET CmvrControlStation POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "$<TARGET_FILE_DIR:CmvrControlStation>/runtime/handeye"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMVR_HAND_EYE_RUNTIME_DIR}"
|
||||
"$<TARGET_FILE_DIR:CmvrControlStation>/runtime/handeye")
|
||||
install(DIRECTORY "${CMVR_HAND_EYE_RUNTIME_DIR}/" DESTINATION bin/runtime/handeye)
|
||||
endif()
|
||||
install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/models/"
|
||||
DESTINATION bin/models)
|
||||
install(PROGRAMS "${CMVR_ASSIMP_SCENE_PARSER}"
|
||||
|
||||
@ -136,7 +136,7 @@ msg_protobuf_compiler.CONFIG += target_predeps
|
||||
config_protobuf_compiler.name = Protobuf ${QMAKE_FILE_IN}
|
||||
config_protobuf_compiler.input = CONFIG_PROTO_FILES
|
||||
config_protobuf_compiler.output = $$PROTO_GEN_DIR/cmvr/config/${QMAKE_FILE_BASE}/${QMAKE_FILE_BASE}.pb.cc
|
||||
config_protobuf_compiler.commands = $$quote($$PROTOC) --proto_path=$$quote($$PROTO_ROOT) --cpp_out=$$quote($$PROTO_GEN_DIR) $$quote($$PWD/${QMAKE_FILE_IN})
|
||||
config_protobuf_compiler.commands = $$quote($$PROTOC) --proto_path=$$quote($$PROTO_ROOT) --cpp_out=$$quote($$PROTO_GEN_DIR) $$quote($$PROTO_ROOT/cmvr/config/${QMAKE_FILE_BASE}/${QMAKE_FILE_BASE}.proto)
|
||||
config_protobuf_compiler.depends = $$CONFIG_PROTO_FILES
|
||||
config_protobuf_compiler.variable_out = SOURCES
|
||||
config_protobuf_compiler.CONFIG += target_predeps
|
||||
@ -144,7 +144,7 @@ config_protobuf_compiler.CONFIG += target_predeps
|
||||
config_root_protobuf_compiler.name = Protobuf ${QMAKE_FILE_IN}
|
||||
config_root_protobuf_compiler.input = CONFIG_ROOT_PROTO_FILES
|
||||
config_root_protobuf_compiler.output = $$PROTO_GEN_DIR/cmvr/config/${QMAKE_FILE_BASE}.pb.cc
|
||||
config_root_protobuf_compiler.commands = $$quote($$PROTOC) --proto_path=$$quote($$PROTO_ROOT) --cpp_out=$$quote($$PROTO_GEN_DIR) $$quote($$PWD/${QMAKE_FILE_IN})
|
||||
config_root_protobuf_compiler.commands = $$quote($$PROTOC) --proto_path=$$quote($$PROTO_ROOT) --cpp_out=$$quote($$PROTO_GEN_DIR) $$quote($$PROTO_ROOT/cmvr/config/${QMAKE_FILE_BASE}.proto)
|
||||
config_root_protobuf_compiler.depends = $$CONFIG_ROOT_PROTO_FILES $$COMMON_PROTO_FILES
|
||||
config_root_protobuf_compiler.variable_out = SOURCES
|
||||
config_root_protobuf_compiler.CONFIG += target_predeps
|
||||
@ -152,7 +152,7 @@ config_root_protobuf_compiler.CONFIG += target_predeps
|
||||
common_protobuf_compiler.name = Protobuf ${QMAKE_FILE_IN}
|
||||
common_protobuf_compiler.input = COMMON_PROTO_FILES
|
||||
common_protobuf_compiler.output = $$PROTO_GEN_DIR/cmvr/common/${QMAKE_FILE_BASE}.pb.cc
|
||||
common_protobuf_compiler.commands = $$quote($$PROTOC) --proto_path=$$quote($$PROTO_ROOT) --cpp_out=$$quote($$PROTO_GEN_DIR) $$quote($$PWD/${QMAKE_FILE_IN})
|
||||
common_protobuf_compiler.commands = $$quote($$PROTOC) --proto_path=$$quote($$PROTO_ROOT) --cpp_out=$$quote($$PROTO_GEN_DIR) $$quote($$PROTO_ROOT/cmvr/common/${QMAKE_FILE_BASE}.proto)
|
||||
common_protobuf_compiler.depends = $$COMMON_PROTO_FILES
|
||||
common_protobuf_compiler.variable_out = SOURCES
|
||||
common_protobuf_compiler.CONFIG += target_predeps
|
||||
@ -160,7 +160,7 @@ common_protobuf_compiler.CONFIG += target_predeps
|
||||
mujoco_protobuf_compiler.name = Protobuf ${QMAKE_FILE_IN}
|
||||
mujoco_protobuf_compiler.input = MUJOCO_PROTO_FILES
|
||||
mujoco_protobuf_compiler.output = $$PROTO_GEN_DIR/cmvr/config/mujoco_config/${QMAKE_FILE_BASE}.pb.cc
|
||||
mujoco_protobuf_compiler.commands = $$quote($$PROTOC) --proto_path=$$quote($$PROTO_ROOT) --cpp_out=$$quote($$PROTO_GEN_DIR) $$quote($$PWD/${QMAKE_FILE_IN})
|
||||
mujoco_protobuf_compiler.commands = $$quote($$PROTOC) --proto_path=$$quote($$PROTO_ROOT) --cpp_out=$$quote($$PROTO_GEN_DIR) $$quote($$PROTO_ROOT/cmvr/config/mujoco_config/${QMAKE_FILE_BASE}.proto)
|
||||
mujoco_protobuf_compiler.depends = $$MUJOCO_PROTO_FILES
|
||||
mujoco_protobuf_compiler.variable_out = SOURCES
|
||||
mujoco_protobuf_compiler.CONFIG += target_predeps
|
||||
@ -237,6 +237,19 @@ CONFIG(debug, debug|release) {
|
||||
!exists($$ASSIMP_SCENE_PARSER): error("Qt3D Assimp scene parser not found in the selected Qt Kit.")
|
||||
|
||||
SOURCES += \
|
||||
src/handeyebridge.cpp \
|
||||
src/handeyestore.cpp \
|
||||
src/handeyeurdf.cpp \
|
||||
src/touchplanner.cpp \
|
||||
src/touchsequencecontroller.cpp \
|
||||
src/touchvideowidget.cpp \
|
||||
src/touchoperationwidget.cpp \
|
||||
src/handeyemotionwidget.cpp \
|
||||
src/tcpcalibration.cpp \
|
||||
src/tcpjogcontroller.cpp \
|
||||
src/tcptoolstore.cpp \
|
||||
src/tcpcalibrationwidget.cpp \
|
||||
src/agvmapviewwidget.cpp \
|
||||
src/audiostreammanager.cpp \
|
||||
src/configeditorwidget.cpp \
|
||||
src/main.cpp \
|
||||
@ -245,6 +258,8 @@ SOURCES += \
|
||||
src/quictestserver.cpp \
|
||||
src/rpcservicewidget.cpp \
|
||||
src/robotclient.cpp \
|
||||
src/tactileheatmapwidget.cpp \
|
||||
src/jointfloweditor.cpp \
|
||||
src/trendwidget.cpp \
|
||||
src/urdfviewerwidget.cpp \
|
||||
src/videodecoder.cpp \
|
||||
@ -252,12 +267,27 @@ SOURCES += \
|
||||
ui/handeyecalibrationwidget.cpp
|
||||
|
||||
HEADERS += \
|
||||
src/handeyebridge.h \
|
||||
src/handeyestore.h \
|
||||
src/handeyeurdf.h \
|
||||
src/touchplanner.h \
|
||||
src/touchsequencecontroller.h \
|
||||
src/touchvideowidget.h \
|
||||
src/touchoperationwidget.h \
|
||||
src/handeyemotionwidget.h \
|
||||
src/tcpcalibration.h \
|
||||
src/tcpjogcontroller.h \
|
||||
src/tcptoolstore.h \
|
||||
src/tcpcalibrationwidget.h \
|
||||
src/agvmapviewwidget.h \
|
||||
src/audiostreammanager.h \
|
||||
src/configeditorwidget.h \
|
||||
src/mainwindow.h \
|
||||
src/quictestserver.h \
|
||||
src/rpcservicewidget.h \
|
||||
src/robotclient.h \
|
||||
src/tactileheatmapwidget.h \
|
||||
src/jointfloweditor.h \
|
||||
src/trendwidget.h \
|
||||
src/uiicons.h \
|
||||
src/urdfviewerwidget.h \
|
||||
@ -290,12 +320,33 @@ quic_ca_deployment.path = $$DESTDIR
|
||||
assimp_scene_parser_deployment.files = $$ASSIMP_SCENE_PARSER
|
||||
assimp_scene_parser_deployment.path = $$DESTDIR/sceneparsers
|
||||
COPIES += runtime_library_deployment quic_certificate_deployment quic_ca_deployment assimp_scene_parser_deployment
|
||||
handeye_algorithm_deployment.files = $$PWD/scripts/handeye_worker.py $$PWD/scripts/handeye_math.py $$PWD/scripts/handeye_refinement.py
|
||||
handeye_algorithm_deployment.path = $$DESTDIR/scripts
|
||||
COPIES += handeye_algorithm_deployment
|
||||
win32 {
|
||||
CONFIG(debug, debug|release): HAND_EYE_JPEG_PLUGIN = $$[QT_INSTALL_PLUGINS]/imageformats/qjpegd.dll
|
||||
else: HAND_EYE_JPEG_PLUGIN = $$[QT_INSTALL_PLUGINS]/imageformats/qjpeg.dll
|
||||
handeye_image_plugin.files = $$HAND_EYE_JPEG_PLUGIN
|
||||
handeye_image_plugin.path = $$DESTDIR/imageformats
|
||||
COPIES += handeye_image_plugin
|
||||
}
|
||||
DISTFILES += scripts/handeye_worker.py scripts/handeye_math.py scripts/handeye_refinement.py
|
||||
DISTFILES += scripts/package_handeye_runtime.py
|
||||
|
||||
QMAKE_POST_LINK += $$QMAKE_COPY_DIR $$shell_quote($$shell_path($$MODEL_DIR)) $$shell_quote($$shell_path($$DESTDIR/models))
|
||||
|
||||
win32 {
|
||||
isEmpty(HAND_EYE_RUNTIME_DIR): HAND_EYE_RUNTIME_DIR = $$PWD/third_party/handeye-runtime
|
||||
!exists($$HAND_EYE_RUNTIME_DIR/manifest.json): error(Build the bundled runtime with scripts/package_handeye_runtime.py first)
|
||||
QMAKE_POST_LINK += $$escape_expand(\n\t) if not exist $$shell_quote($$shell_path($$DESTDIR/runtime)) $$QMAKE_MKDIR $$shell_quote($$shell_path($$DESTDIR/runtime))
|
||||
QMAKE_POST_LINK += $$escape_expand(\n\t) $$QMAKE_COPY_DIR $$shell_quote($$shell_path($$HAND_EYE_RUNTIME_DIR)) $$shell_quote($$shell_path($$DESTDIR/runtime/handeye))
|
||||
QMAKE_POST_LINK += $$escape_expand(\n\t) $$QMAKE_COPY_FILE $$shell_quote($$shell_path($$MSQUIC_TEST_CERT)) $$shell_quote($$shell_path($$DESTDIR/quic-test-server.pfx))
|
||||
QMAKE_POST_LINK += $$escape_expand(\n\t) $$QMAKE_COPY_FILE $$shell_quote($$shell_path($$MSQUIC_TEST_CA)) $$shell_quote($$shell_path($$DESTDIR/quic-test-ca.crt))
|
||||
}
|
||||
|
||||
win32:RC_ICONS =
|
||||
|
||||
HEADERS += src/calibrationfile.h
|
||||
|
||||
SOURCES += src/touchplanestore.cpp
|
||||
HEADERS += src/touchplanestore.h src/cameracapabilities.h
|
||||
|
||||
80
docs/CAMERA_AUTO_MODE.md
Normal file
80
docs/CAMERA_AUTO_MODE.md
Normal file
@ -0,0 +1,80 @@
|
||||
# 单相机自动识别与定位模式
|
||||
|
||||
实现日期:2026-10-12;2026-10-13 合并新版相机页与协议。
|
||||
|
||||
连接服务后,上位机通过 `CameraService.GetStatus` 获取当前物理相机型号、序列号、采集代次和能力。服务端 `AutoCamera` 只启动唯一已连接的相机:RealSense 或 MVS 工业相机。没有相机、发现多台或驱动不可用时不会任意选择设备。
|
||||
|
||||
| 实际数据 | 页面模式 |
|
||||
| --- | --- |
|
||||
| 有效原始图像、内参、采集时间、公制配准深度 | RGBD 深度定位 |
|
||||
| 有效原始图像、内参、采集时间,无深度 | 二维平面定位 |
|
||||
| 其余情况或旧服务没有能力字段 | 视频预览;标定/取点受缺失条件限制 |
|
||||
|
||||
相机选择、标定和末端操作复用现有 gRPC、解码和显示通道。深度预览不能借给标定页:进入标定或末端页时,同相机的深度会话会结束并重新订阅 RGB。修改相机身份、采集代次、分辨率或内参会清除锁定画面、目标点和待执行路径。不会自动恢复旧运动。
|
||||
|
||||
## 服务端配置
|
||||
|
||||
源码在 `F:/cmvr-es/cmvr-es`;新驱动位于 `cmvr-es/devices/camera/auto_camera` 和 `mvs_camera`。把现有相机配置中的独立后端替换成一个 `auto_camera` 条目,保留其逻辑 ID 和 DeviceManager 相机引用;不要同时启用同一硬件的旧 RealSense/MVS 条目。
|
||||
|
||||
以下是 CameraRootConfig 的 protobuf 文本示例。`camera_active` 是示例 ID,实际使用原配置的 ID;MVS 的序列号及内参必须填写真实标定值。
|
||||
|
||||
```text
|
||||
camera {
|
||||
cameras {
|
||||
id: "camera_active"
|
||||
auto_camera {
|
||||
id: "camera_active"
|
||||
realsense {
|
||||
camera_mode: CAMERA_MODE_VIDEO
|
||||
capture { width: 640 height: 480 fps: 30 stream_mode: STREAM_MODE_RGBD }
|
||||
encoder { width: 640 height: 480 fps: 30 codec: "H264" buffer_size: 4 }
|
||||
align_mode: ALIGN_MODE_COLOR
|
||||
sync: true
|
||||
}
|
||||
mvs {
|
||||
capture { width: 2448 height: 2048 fps: 15 stream_mode: STREAM_MODE_RGB }
|
||||
encoder { width: 1224 height: 1024 fps: 15 codec: "H264" buffer_size: 4 }
|
||||
// 在实机确认原始尺寸;本示例未提供内参,因此只允许预览。
|
||||
// 填入 serial、fx/fy/cx/cy、5 个 coeffs 和 calibration_width/height。
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
MVS 驱动使用官方 `MvCameraControl`,与项目的 HCNetSDK 网络监控相机驱动不同。服务端需安装对应系统/架构的 MVS SDK,CMake 通过 `MVS_ROOT`、`MVS_INCLUDE_DIR` 和 `MVS_LIBRARY` 查找 SDK。例如已有正常构建目录中:
|
||||
|
||||
```bash
|
||||
MVS_ROOT=/opt/MVS cmake -S . -B build
|
||||
cmake --build build --target cmvr_es
|
||||
```
|
||||
|
||||
没有 SDK 时会编译明确报告不可用的适配器,不影响原有驱动。SDK 可用后使用 Mono8、软件触发、独立采集线程;SDK 缓冲区复制后释放。触发前与读到图像后的服务器 UTC 构成真实采集区间,再按请求/响应时刻转换到客户端时间区间。曝光超时结束本次采集,关闭旧会话后才允许重新触发。
|
||||
|
||||
二维内参必须绑定当前物理序列号、原始分辨率。ROI 偏移、binning 和 decimation 需读取验证为完整标定几何;无法验证时只预览。RealSense 纯 COLOR 配置缺少本实现需要的可靠采集时间,亦只预览。不要使用截图时间冒充曝光时间。
|
||||
|
||||
`CameraState.codec` 保留已分发协议的编号 10,`capabilities` 使用 11。上位机和新服务端协议已同步。此前尚未部署的相机能力实验版本使用过编号 10,不能与本版本混用。
|
||||
|
||||
AbstractCamera 和媒体帧结构发生兼容扩展,因此部署时需重编全部相关驱动和服务;不要只替换一个驱动库。此次只在隔离目录构建与测试,没有替换运行中的服务或配置。
|
||||
|
||||
## 二维相机的末端操作
|
||||
|
||||
MV-CS050-10UM 没有深度。选择对应手眼和 TCP 后,在任务配置导出平面模板,填入真实基座坐标系下的平面原点、朝向离开表面的单位法向和操作半径,再导入。模板默认数值只是占位,不能直接作为测量结果。
|
||||
|
||||
文件字段为 `schema_version=1`、`units="m"`、`frame="robot_base"`、`name`、`robot_id`、`camera_serial`、`handeye_name`、`handeye_fingerprint`、`intrinsics_fingerprint`、`origin[3]`、`normal[3]`、`operating_radius_m`。指纹由模板自动生成;改换标定或内参后重新导出匹配模板。平面保存沿用 QSettings,并按服务器、机械臂和相机序列号隔离。
|
||||
|
||||
像素经去畸变生成相机射线,再使用手眼关系和锁定时的机器人位姿变换到基座,与已知平面求交。界面显示相机与基座 XYZ;滑动沿用该平面法向与 TCP。目标像素不需要棋盘格,但必须位于已配置的真实平面和有效操作范围内。只靠二维像素和手眼矩阵不能确定任意空间深度。
|
||||
|
||||
RGBD 继续使用真实公制深度、同帧配准和原有时序校验;深度失败不会静默改用平面。旧手眼文件缺少物理序列号时需要显式确认归属,已知序列号不匹配的记录不显示、不使用。
|
||||
|
||||
## 三轴力传感器
|
||||
|
||||
界面只显示“未接入”,尚无真实力控。后续接口需要:传感器身份、绑定机器人、有效标记、采集时间、Fx/Fy/Fz(N)、测量坐标系、传感器到工具安装变换、量程及故障。三轴力不包含力矩。接触停止与闭环应在有明确时效保证的服务端/控制器实现;加装改变工具尺寸后需重新 TCP 标定。
|
||||
|
||||
## 已完成验证与边界
|
||||
|
||||
- Qt 5.12.4 / MinGW 7.3 / C++14 构建;手眼与末端 UI 回归、协议兼容、原始灰度取点与平面换算。
|
||||
- 服务端隔离构建,单采集实例、替换相机、旧租约释放、故障退出、媒体 Hub、真实回环 gRPC 双向订阅结束测试通过。
|
||||
- 上述服务端验证完成于 2026-10-12。2026-10-13 合并时调整了 codec/capabilities 字段编号;本地协议与 Qt 构建通过,但服务器连接超时,最后的编号调整尚未远端复编。
|
||||
- 当前机器及服务器未安装 MVS SDK。启用 SDK 的分支、MV-CS050-10UM 实机采集和真实相机替换尚未验证。
|
||||
- 未发送真实机械臂运动指令;之前“读数变化而机器人未实际运动”的问题仍需独立实机确认。
|
||||
31
docs/CONTROLLER_TCP_OFFSET.md
Normal file
31
docs/CONTROLLER_TCP_OFFSET.md
Normal file
@ -0,0 +1,31 @@
|
||||
# 控制器活动 TCP 偏移读取
|
||||
|
||||
TCP 标定页面的“从控制器读取”使用当前连接和机械臂 ID,通过已有
|
||||
`cmvr.api.ArmService/ExecuteJsonCommand` 发送:
|
||||
|
||||
```json
|
||||
{"command":"get_active_tcp_offset"}
|
||||
```
|
||||
|
||||
服务端目前由 AuboArm 驱动调用 `getRobotConfig()->getTcpOffset()`。
|
||||
其他未适配驱动返回不支持,不把失败转换成零偏移。
|
||||
响应同时包含 `success`、`device_id`、`offset`(六个数)、
|
||||
`transform: T_flange_tcp`、`units: m_rad` 和
|
||||
`rotation_convention: RzRyRx`。这是相对法兰的活动工具偏移,不是机器人基座下的实时 TCP 位姿。
|
||||
|
||||
Qt 校验设备、单位、姿态约定和有限数值后,将平移转换为 mm,角度转换为度。
|
||||
读取会清空本轮采样,成功后确认偏移;失败保持未确认。
|
||||
切换连接或机械臂后,过期响应不会被应用。
|
||||
这是按按钮实时读取,不是后台持续轮询;在示教器更换活动工具后需重新读取。
|
||||
|
||||
## 2026-10-10 验证
|
||||
|
||||
- TCP 页面测试 17 项通过。
|
||||
- loopback 集成测试通过,覆盖错误单位、设备不匹配、无效值、合法零偏移及 UI 回填。
|
||||
- Qt 调试程序编译通过,输出 `bin/debug/CmvrControlStation_touch_preview.exe`。
|
||||
- 服务器驱动编译、链接通过,已按用户授权重启服务。
|
||||
- `192.168.0.28:50052` 的 `aubo_arm` 实际读取成功,返回六项零偏移。
|
||||
- 部署时原驱动备份:服务器
|
||||
`/home/cmvr/Projects/cmvr-es/output/lib/libaubo_arm.so.before-tcp-20261010-162143`。
|
||||
- 服务以原参数和环境后台启动,日志为服务器 `/tmp/cmvr-tcp-service.log`。
|
||||
此次未更改设备配置或开机启动设置。
|
||||
154
docs/HANDEYE_MIGRATION.md
Normal file
154
docs/HANDEYE_MIGRATION.md
Normal file
@ -0,0 +1,154 @@
|
||||
# Qt 手眼标定迁移说明
|
||||
|
||||
## 页面与使用流程
|
||||
|
||||
沿用侧栏「复杂控制 → 手眼标定」的第 14 号页面。原先该入口显示占位内容,`ui/handeyecalibrationwidget.ui/.h/.cpp` 是空 QWidget;现在入口实例化这个已有页面类。没有新增一级导航。
|
||||
|
||||
布局沿用机械臂页、相机页和 TCP 标定页的 `panel`、`sectionTitle`、`mutedLabel`、按钮和表格样式。`.ui` 管理滚动页面:左上为相机视频与检测,右上为相机选择及标定配置,下方并排放置采样数据与标定结果 / 保存。配置项按每行两组紧凑排列;板型参数和动态列表使用当前工程已有的 C++ 控件方式。
|
||||
|
||||
1. 在机械臂页面选择实际设备并连接服务。在工具坐标标定页确认控制器当前活动工具偏移,用于将反馈 TCP 位姿还原为法兰位姿。
|
||||
2. 手眼页的相机来自现有相机配置列表。选择相机并开始视频,复用当前 RobotClient 相机流。已有相机流可以共享;页面只停止自己启动的流。
|
||||
3. 选择安装方式、棋盘格 / ChArUco、实际板尺寸。棋盘格行列表示内角点数;ChArUco 表示方格数。尺寸界面使用 mm,算法使用 m。
|
||||
4. 核对真实相机畸变模型、彩色对齐方式和服务器时钟后勾选确认。实时检测预览按算法完成速度刷新,角点、轴线始终绘制在它们所属的图像上。
|
||||
5. 每次停稳后采集。联合标定至少 6 组(位姿法至少 5 组),建议 12–15 组,并覆盖至少两个独立旋转轴。表格显示两组位姿、重投影误差及帧时间。
|
||||
6. 计算后查看 4×4 矩阵、方向、重投影 / AX=XB / 固定目标误差。异常点会标记为已剔除。质量不合格的结果可以查看但不能保存。
|
||||
7. 输入名称保存。机械臂页速度控制区域「视觉坐标 → 手眼标定 · 仅坐标转换」的列表立即刷新。同名更新和删除都使用现有 QMessageBox 交互。
|
||||
8. 在机械臂页选择记录,输入相机坐标点,点击转换。显示实际计算出的基座坐标。此操作不会发送运动。
|
||||
|
||||
## 真实调用链与线程
|
||||
|
||||
- 视频:已有 `CameraService.GetRGBImageStream` → RobotClient 流读取线程 → 已有 FFmpeg VideoDecoder → `videoFrameReceived(cameraId, VideoFrame, detail)` → 原有 VideoRenderWidget。
|
||||
- 为 `VideoFrame` 增加原始解码 PTS、对应相机内参和帧时间。通过解码 PTS 与输入包匹配元数据,避免 B 帧 / 延迟解码时把最新包时间错误赋给旧图像。未知、重复或无法匹配的 PTS 不用于采点。
|
||||
- 原始彩色尺寸与内参:新增的 RobotClient 请求包装复用同一 CameraService 通道上的真实 `GetRGBImage` RPC。校验 BGR / 灰度数据长度、维度、有限正焦距及畸变系数;QImage 持有独立数据。
|
||||
- 算法:HandEyeBridge 的 QThread 内运行持久 QProcess,执行随应用部署的 Python worker。图像平面编码、检测和求解不阻塞 GUI。一次只允许一个算法请求,限制积压;页面退出停止算法,线程析构时释放资源。
|
||||
- 机器人:复用 `requestTcpCalibrationPose` → 工作线程 `GetArmInfo` 与 `getRobotState` → `actual_tcp_pose`、关节速度和安全 / 运行状态校验。没有增加机器人通信实例。该接口仅接受现有代码已核对姿态约定的驱动;未知驱动返回明确错误,不猜测单位。
|
||||
- 位姿回调、视频回调和算法结果最终都在 UI 线程更新控件。请求 token 和算法代次隔离过期响应;连接、机械臂、相机、参考工具及参数变化会失效当前采样过程。
|
||||
|
||||
## phone 算法来源与数学定义
|
||||
|
||||
源文件:`F:/phone/scripts/handeye_calibration_gui.py`。
|
||||
|
||||
迁移至 `scripts/handeye_math.py` / `scripts/handeye_worker.py`,保留主要函数和源代码行区间注释:
|
||||
|
||||
- `estimate_planar_pose`(174–247):平面 IPPE 候选与 PnP 精化。
|
||||
- `estimate_charuco_pose`(250–266)及页面检测逻辑(1905–1952)。
|
||||
- `solve_handeye_matrix`(289–311)。
|
||||
- `fixed_target_consistency`(322–361)。
|
||||
- `ax_xb_all_pair_metrics`(364–389)。
|
||||
- `leave_one_out_handeye_metrics`(427–478)。
|
||||
- `robust_handeye_calibration`(481–592):五种 OpenCV 求解器、自动比较、MAD 异常值剔除与交叉验证。
|
||||
|
||||
支持 Eye-in-Hand 和 Eye-to-Hand。沿用 phone 重投影筛选和质量阈值,并补充输入边界、SE(3)、正深度、独立旋转轴检查。至少保留 5 个有效样本;不会为了凑够样本数保留不合格的重投影点。
|
||||
|
||||
所有矩阵采用行优先存储、列向量左乘、平移单位 m。`T_parent_child` 表示将 child 坐标表达成 parent 坐标:
|
||||
|
||||
- 机器人输入:`T_base_flange`。反馈实际为活动 TCP;先按 `T_base_tcp × inverse(T_flange_tcp)` 还原。
|
||||
- 相机输入:`T_camera_target`,由当前图像中的真实标定板检测取得。
|
||||
- Eye-in-Hand 输出:`T_flange_camera`;使用时 `p_base = T_base_flange × T_flange_camera × p_camera`。
|
||||
- Eye-to-Hand 输出:`T_base_camera`;使用时 `p_base = T_base_camera × p_camera`。
|
||||
- 机器人姿态沿现有已验证接口使用 m、rad,旋转为 `Rz(rz) × Ry(ry) × Rx(rx)`。界面显示 mm / degree,未更改底层姿态定义。
|
||||
|
||||
## 联合标定与重投影非线性精修(2026-09-30)
|
||||
|
||||
页面默认选择“联合标定 + 重投影精修”,保留“原有手眼标定(对比)”。切换计算方式或初值算法只失效计算结果,保留原始采样;更改相机、安装方式、标定板参数仍重置采样。布局保持左上视频、右上配置、下方采样与结果。
|
||||
|
||||
新增 `scripts/handeye_refinement.py::refine_joint`。先沿用 phone 的求解器选择和异常样本剔除产生初值,再通过 Huber 损失、SE(3) 指数更新和解析雅可比的阻尼 LM,同时优化两个刚体变换(12 个自由度)。这是在迁移算法之上的新增实现,不声称 phone 原代码已经包含联合精修。没有新增 scipy 或 C++ OpenCV 依赖。
|
||||
|
||||
定义 `G = T_base_flange`、`C = T_camera_target`:
|
||||
|
||||
| 安装方式 | 优化 X | 优化 Y | 约束 | 用于投影的预测 C |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Eye-in-Hand | T_flange_camera | T_base_target | G X C = Y | inverse(X) inverse(G) Y |
|
||||
| Eye-to-Hand | T_base_camera | T_flange_target | X C = G Y | inverse(X) G Y |
|
||||
|
||||
两种模式均对所有保留帧的真实角点进行联合优化。每帧保存 `image_points`、单位为 m 的 `object_points`、对应 `corner_ids`、该帧缩放后的 `K`、Brown 畸变 `D`、图像尺寸和两组测量位姿。支持 ChArUco 每帧可见角点不同;不能将局部列表下标代替板上 ID。内参、畸变、板尺寸及机器人位姿作为固定测量值,不在本阶段估计机器人运动学或相机内参。
|
||||
|
||||
质量检查及验证:
|
||||
|
||||
- 联合标定至少 6 个有效样本,原有算法仍至少 5 个;界面建议采集 12–15 个并覆盖多个旋转轴。
|
||||
- Huber 点残差阈值 1.5 px,最多 80 次迭代。使用平移 0.2 m / 旋转 1 rad 的参数尺度检查雅可比秩及条件数(上限 1e6)。检查矩阵、坐标对应、正深度和有限值;不收敛不允许保存。
|
||||
- RMS 定义为所有角点二维残差范数的均方根,不是单坐标 RMS,也不是原有 PnP 均值。精修后全点 RMS 上限 1.5 px;鲁棒目标不得增加;全点 RMS 上升不得超过 max(0.01 px, 初值 RMS 的 1%)。
|
||||
- 6–8 组使用留一验证,9 组及以上使用确定性的三折验证。每折只用训练帧重新求手眼初值与两个变换,不复用全量拟合结果;在未参与该折拟合的帧上计算像素残差。所有保留帧必须完成验证,汇总 RMS 上限 3 px。此前 phone 的异常样本筛选是全量初始化步骤,因此此验证针对保留样本的拟合稳定性,不替代独立实机验收数据。
|
||||
- 保留原有 AX=XB 与固定目标一致性 5 mm / 2° 检查。像素误差低不能覆盖物理位姿不一致。所有诊断及验证折索引映射回原始采样列表。
|
||||
|
||||
QSettings 仍使用原来的 v1 主键和机械臂隔离方式;新增可选字段 `refinement`、`observations`,兼容旧记录。保存初始及最终 X/Y、矩阵含义、两类像素误差、迭代及条件数、验证折、完整原始观测。旧记录没有角点,仍可选择使用,但不能直接进行像素精修。读取联合结果时校验质量标记、方向和主矩阵一致性。
|
||||
|
||||
Record.transform 保存最终 X,既有 `calibrationsChanged` 刷新与 `cameraPointToBase` 流程因此实际使用精修后的矩阵。Y 同时保存并展示,用于标定板固定关系;不将它误用为机械臂视觉运动的手眼矩阵。当前没有完整视觉运动接口的 TODO 保持不变。
|
||||
|
||||
本次增量文件:新增 `scripts/handeye_refinement.py`、`tests/test_handeye_refinement.py`、`tests/test_handeye_joint_worker.py`;修改 worker、原手眼页面 `.h/.cpp/.ui`、HandEyeStore `.h/.cpp`、存储与页面测试、qmake/CMake 脚本部署和本说明。其余先前迁移文件不因联合优化而重构。
|
||||
|
||||
相关数学资料:[Tabb / Ahmad Yousef 的联合标定迭代方法论文(含修订说明)](https://arxiv.org/abs/1907.12425);针孔/Brown 投影使用 [OpenCV projectPoints 文档](https://docs.opencv.org/4.x/d9/d0c/group__calib3d.html)。这里固定内参的独立实现不等同于复现论文全部实验配置,真实定位精度仍需实机独立点位验证。
|
||||
|
||||
## 采样同步与已确认的相机限制
|
||||
|
||||
采样执行「静止位姿读前 → 新视频帧检测 → 静止位姿读后」。帧的服务器 UTC 时间必须位于读取时间窗内、PTS 匹配且未过期;前后法兰偏差不得超过 0.5 mm / 0.2°。整组保存两类变换、帧序号和读前读后时间。重复采样、运动、超时、检测失败都不追加记录。
|
||||
|
||||
这是静止条件下的软件配对,**不是传感器硬件曝光同步**。当前服务的部分时间戳是编码 / 处理时间,因此仍需保持机械臂及对应固定物静止,并确保两端时钟同步。上线前需要在实机上验证该时间模型。
|
||||
|
||||
从当前后端源码已确认以下限制,并在 Qt 侧拒绝不确定数据:
|
||||
|
||||
- unary `GetRGBImage` 不填拍摄时间戳,RealSense 还可能返回缓存图。因此单帧 RPC 只提供原生尺寸与内参,不直接用于成对采样。
|
||||
- RealSense 编码流缩放后未缩放内参。Qt 根据原生图像尺寸换算焦距和主点,校验宽高比与流内参一致性;不支持任意裁剪。
|
||||
- RealSense 深度对齐 RGB 的现有内参存在语义问题。使用者必须确认原生彩色或对齐到彩色,不能把深度对齐画面用于本实现。
|
||||
- 当前 UVC 后端没有有效标定内参;Hikvision 原生单帧接口未实现。它们会收到明确提示,不能绕过有效内参检查采点。
|
||||
- 协议没有畸变模型字段。当前检测适用普通针孔 / Brown 模型;鱼眼或未知模型不能直接套用。
|
||||
|
||||
## 持久化与机械臂页面使用
|
||||
|
||||
沿用应用默认 QSettings(正常运行组织 CMVR、应用 CMVR Control Station;Windows 通常位于 HKCU/Software/CMVR/CMVR Control Station)。主键 `handEyeCalibration/v1/<SHA256(endpoint + NUL + device)>`,记录当前连接和机械臂,其他机械臂不会混入列表。
|
||||
|
||||
每条记录包含名称、相机 ID、安装模式、求解器、创建时间、完整矩阵、方向、单位、有效样本数、误差、板参数和内参。允许同一机械臂的多个相机、多次标定;不静默覆盖同名结果。
|
||||
|
||||
保存 / 修改 / 删除成功后发出 `calibrationsChanged`,MainWindow 根据当前上下文转发给 HandEyeMotionWidget 重新加载。启动及切换机械臂也从同一个存储加载,并恢复当前选择。配置损坏、非有限数、非刚体矩阵、写入失败均返回错误。
|
||||
|
||||
HandEyeMotionWidget 读取选中记录的完整矩阵,实际调用 `HandEyeStore::cameraPointToBase`。Eye-in-Hand 在转换时重新读取当前真实位姿,并去掉控制器活动 TCP 偏移。转换结果通过 `basePointPrepared(cameraId, profileName, baseXYZmetres)` 提供;输入、选择、连接、参考偏移变化会清空旧结果。
|
||||
|
||||
保留一处业务 TODO:当前工程没有视觉目标运动流程及目标姿态语义,不能凭一个相机点推造完整 MoveL 目标。将来应由真实视觉运动流程消费已准备的基座点并定义方向、工具关系和运动约束,本次不虚构该接口。
|
||||
|
||||
## 文件与运行环境
|
||||
|
||||
本次修改:
|
||||
|
||||
- `ui/handeyecalibrationwidget.ui/.h/.cpp`:原页面完整实现。
|
||||
- `src/mainwindow.cpp/.h`、`src/mainwindow_ui.cpp`:原入口实例化、信号槽、相机流共享和机械臂页嵌入。
|
||||
- `src/robotclient.cpp/.h`:现有相机 RPC 包装和流元数据传递。
|
||||
- `src/videoframe.h`、`src/videodecoder.cpp`:精确解码时间与帧元数据。
|
||||
- `CmvrControlStation.pro`、`CMakeLists.txt`:新源码和 Python 算法脚本部署。
|
||||
- `styles.qss`:速度控制三个页签的宽度及视觉坐标输入框留白,沿用已有配色和字体。
|
||||
|
||||
本次新增:
|
||||
|
||||
- `src/handeyebridge.h/.cpp`:异步算法桥接。
|
||||
- `src/handeyestore.h/.cpp`:既有 QSettings 下的记录和坐标转换。
|
||||
- `src/handeyemotionwidget.h/.cpp`:机械臂页内部的记录选择和转换区域。
|
||||
- `scripts/handeye_math.py`、`scripts/handeye_worker.py`。
|
||||
- `tests/test_handeye_worker.py`、`tests/handeyestore_test.cpp/.pro`、`tests/handeyemotion_test.cpp/.pro`、`tests/handeyeui_test.cpp/.pro`、`tests/handeyeintegration_test.cpp`、`tests/run_handeye_integration.py`。
|
||||
- 本说明。
|
||||
|
||||
未升级 Qt 或 C++,未改造其他导航。算法现在使用随上位机部署的独立 Python 运行时、OpenCV(含 aruco)和 NumPy;进入页面自动检查,无需操作人员安装或选择环境。旧环境设置和 `CMVR_HANDEYE_PYTHON` 不再用于程序启动。三个脚本和运行时均随 qmake / CMake 部署,详见 [内置运行时说明](HANDEYE_RUNTIME.md)。
|
||||
|
||||
## 验证记录
|
||||
|
||||
### 2026-10-08:采样照片与 URDF 更新
|
||||
|
||||
- 采样表新增“采样照片 / 查看”。算法进程仅对成对采集请求,将用于检测的原始帧编码成 JPEG;通过时间与静止校验后,图像和该行观测一起入缓存。查看窗口可切换角点/坐标轴叠加;不会使用后续视频帧替换照片。
|
||||
- 照片仅在本次采样会话缓存,每张最多 2 MiB、最多 100 组。删除行、重置和切换采样上下文同步释放;不写入 QSettings,重启后不能恢复照片。原始角点、内参及标定记录仍按原机制持久化。Windows 构建随程序部署 Qt JPEG 插件。
|
||||
- 机械臂页“视觉坐标”中,“标定结果”下拉框仍按服务器和机械臂隔离,选中矩阵进入原有相机点到基座点转换;新增“URDF 标定更新”。可读取当前模型或选择 URDF,明确选择参考 Link、相机光学 Link,确认坐标关系后导出新文件并加载到现有模型查看器。
|
||||
- Eye-in-Hand 使用 `Flange_T_Camera`,参考 Link 必须对应标定法兰;Eye-to-Hand 使用 `Base_T_Camera`,参考 Link 必须对应标定基座。相机 Link 必须是该标定的光学坐标系,不能直接将标定矩阵写到有额外旋转的相机外壳坐标系。
|
||||
- `src/handeyeurdf.h/.cpp` 解析并验证模型;现有相机入口关节必须固定,参考到该关节父 Link 的链必须固定。写入 `T_parent_camera = inverse(T_reference_parent) * T_reference_camera`。不存在的相机 Link 创建为参考 Link 的固定子节点;m/rad 与 URDF XYZ/RPY 一致。
|
||||
- 原 URDF 保留,禁止覆盖源文件或其他已有目标文件。输出经 QSaveFile 原子保存;相对 mesh/texture 路径转为绝对路径,`package://` 保留原语义,建议输出到原模型目录。模型加载失败时提示并尝试恢复旧模型;导出的文件仍保留。重启可通过已有 URDF 选择入口加载导出文件。
|
||||
- 不修改运动关节,不发送机器人运动指令。无法表达为上述固定链时明确报错。模块测试 17 项、机械臂页面测试 23 项通过,覆盖两种模式、现有/新增光学 Link、完整矩阵重建、切换上下文失效、源文件保留和窄面板布局;区域高度不足时纵向滚动,不挤压输入框。
|
||||
- 照片相关页面测试 18 项、Python 检测和数学测试 41 项通过。MainWindow 本机回环联调确认导出的模型通过既有 URDF 查看器加载;未连接真实设备。
|
||||
|
||||
- Qt 5.12.4 / MinGW 7.3 / C++14:完整 Debug 工程编译、链接通过。验证产物 `bin/debug/CmvrControlStation_handeye_preview.exe`,三个算法脚本已部署到同目录的 scripts 中。
|
||||
- Python 检测 / 数学 / 联合精修测试:37 项通过,覆盖五种初值求解器、两种模式的两组变换、合成真值、噪声、异常点、退化姿态、雅可比数值核对、独立验证、棋盘格 / 部分 ChArUco、像素格式及错误输入。
|
||||
- QSettings 与矩阵转换测试:90 项通过,包含旧记录兼容、完整原始观测与联合矩阵持久化、拒绝损坏数据。
|
||||
- 机械臂页记录选择与坐标转换测试:12 项通过。
|
||||
- Qt 页面与真实 Python 进程测试:14 项通过,覆盖启动失败重启、实际检测、原始角点配对、重复点、缺失时间戳、过期响应、相机替换及内参缩放;两种模式均实际经过计算、保存、重新加载和相机点转换,核对独立合成真值。
|
||||
- MainWindow + RobotClient 本机回环 gRPC 联调通过:原始 BGR、内参、无效数据、断线 / 演示拒绝、保存 / 删除即时同步、机器人隔离、两种实际坐标转换、编码格式和相机流所有权。未产生机器人运动指令。
|
||||
- 现有 TCP 全链路回归通过,包括真实回环 MoveL 目标计算、停止及参考偏移失效处理。
|
||||
- 已渲染手眼页与机械臂页检查布局。离屏 OpenGL 环境不能作为实机视频画面验收。
|
||||
|
||||
编码视频的 PTS 匹配路径已完成编译和代码检查,但没有完成压缩流端到端自动测试:本机 FFmpeg 不含 H.264 编码器,phone OpenCV 的 H.264 写出也缺少 OpenH264;未为测试安装或下载额外依赖。需要在真实服务器视频流上补做解码时间戳对应检查。
|
||||
|
||||
以上自动测试使用合成板图、合成坐标真值及本机回环假服务,不等同于相机和机械臂实机精度验收。实机仍需独立点位验证及上述帧时间检查。
|
||||
63
docs/HANDEYE_RUNTIME.md
Normal file
63
docs/HANDEYE_RUNTIME.md
Normal file
@ -0,0 +1,63 @@
|
||||
# 内置手眼标定运行时
|
||||
|
||||
上位机仅从自身目录加载 `runtime/handeye/python.exe` 和 `scripts/handeye_worker.py`,不再读取旧的 `handEyeCalibration/python` 设置、`CMVR_HANDEYE_PYTHON` 或系统 Python。进入手眼页面自动检查;关闭页面释放进程。算法仍在工作线程管理的独立进程中运行,保持界面响应。
|
||||
|
||||
页面已移除算法环境、路径、浏览与检查控件。组件缺失时提示重新部署完整程序,不要求操作人员安装依赖。
|
||||
|
||||
## 发布目录
|
||||
|
||||
```text
|
||||
上位机目录/
|
||||
CmvrControlStation_handeye_preview.exe # 当前 Debug 验证程序
|
||||
...原有 Qt、通信 DLL、模型、证书等资源...
|
||||
scripts/
|
||||
handeye_worker.py
|
||||
handeye_math.py
|
||||
handeye_refinement.py
|
||||
runtime/handeye/
|
||||
python.exe
|
||||
python312.dll
|
||||
python312.zip
|
||||
python312._pth
|
||||
LICENSE.txt
|
||||
manifest.json
|
||||
...Python 扩展和运行库...
|
||||
Lib/site-packages/
|
||||
numpy/
|
||||
numpy.libs/
|
||||
cv2/
|
||||
...对应 dist-info 元数据与许可证...
|
||||
```
|
||||
|
||||
发布时复制完整程序目录,不能只复制 EXE。运行时约 178 MiB(未压缩),无需目标电脑安装 Python、Anaconda 或 pip;启动、检测和求解均无需联网。Windows x64 运行时使用官方 CPython 3.12.4 嵌入式包,配合本项目已验证的 NumPy 2.5.2 和 OpenCV-contrib 4.11.0.86。
|
||||
|
||||
采用 [Python 官方嵌入式分发方式](https://docs.python.org/3.12/using/windows.html#the-embeddable-package)。`python312._pth` 只包含包内标准库和依赖路径,不启用用户 site-packages;Qt 使用 `-I -B -u` 启动并清除继承的 `PYTHON*` 环境变量。worker 只显式加入自身脚本目录,用于加载同包的数学模块。
|
||||
|
||||
## 开发构建
|
||||
|
||||
生成器为 `scripts/package_handeye_runtime.py`。首次构建运行时需使用具备上述已验证依赖的 Windows x64 Python 3.12 环境:
|
||||
|
||||
```powershell
|
||||
& 'F:\phone\.handeye_venv\Scripts\python.exe' -B scripts/package_handeye_runtime.py
|
||||
```
|
||||
|
||||
源虚拟环境只在**打包阶段**使用。生成器下载并校验固定 SHA256 的官方 Python ZIP,复制 NumPy、其依赖 DLL、OpenCV 和许可证,不复制虚拟环境、Anaconda、Jupyter 或其他设备 SDK。也可用 `--archive` 指定已下载的同一 ZIP 离线打包。成功后产生文件哈希清单及版本记录。
|
||||
|
||||
默认输出 `third_party/handeye-runtime`(二进制产物被 Git 忽略)。生成器拒绝覆盖已有目录;重新生成时指定新的 `--output`,审核后通过构建参数选择。现有运行时已生成,无需重复打包。
|
||||
|
||||
- qmake:默认读取上述目录,链接后复制至 `bin/debug/runtime/handeye` 或 Release 输出目录;可设置 `HAND_EYE_RUNTIME_DIR`。
|
||||
- CMake:通过 `CMVR_HAND_EYE_RUNTIME_DIR` 指定运行时;构建后复制,`cmake --install` 也包含运行时及算法脚本。
|
||||
- 缺少 `manifest.json` 时构建配置明确失败,避免产出缺失算法环境的安装目录。
|
||||
- 运行时原件或版本有变化后需重新执行链接 / 部署,不能只拷贝新 EXE。
|
||||
|
||||
本机实际验证使用 qmake / Qt 5.12.4 / MinGW 7.3;CMake 部署规则已补齐但未另行完整构建。
|
||||
|
||||
## 验证
|
||||
|
||||
```powershell
|
||||
& '.\third_party\handeye-runtime\python.exe' -I -B -m unittest discover -s tests -p 'test_handeye*.py' -v
|
||||
```
|
||||
|
||||
40 项通过,包含将完整运行时与脚本迁移至中文 / 空格临时目录、PATH 仅保留 Windows System32、设置无效 PYTHONHOME / PYTHONPATH,再执行真实棋盘检测和 Eye-in-Hand / Eye-to-Hand 联合精修;核对模块和搜索路径均位于迁移后的目录,验证文件哈希与许可证。
|
||||
|
||||
Qt 页面测试使用测试 EXE 同目录的 `runtime/handeye` 和 `scripts`,15 项通过,涵盖自动启动、隐藏后重启、忽略无效旧路径、真实成对采点、计算、保存、重新加载与实际坐标转换。没有在另外一台全新 Windows 电脑上验收;实机发布仍需验证原有 Qt、相机及通信依赖和机器人精度。
|
||||
108
docs/INCOMING_MAIN_MERGE.md
Normal file
108
docs/INCOMING_MAIN_MERGE.md
Normal file
@ -0,0 +1,108 @@
|
||||
# 新下载工程与原本地工程的差异及合并结果
|
||||
|
||||
日期:2026-10-13。
|
||||
|
||||
目标工程:`F:/QT/CmvrControlStation`。
|
||||
新版本来源:`F:/QT/CmvrControlStation-main/cmvrcontrolstation`。来源为解压快照,没有 `.git`,因此不能确认对应的远端提交。三方比较使用原本地 `HEAD 1473cee` 作为共同参考,并逐项处理实际内容差异。
|
||||
|
||||
## 主要区别
|
||||
|
||||
| 内容 | 新下载目录 | 原本地目录 / 合并处理 |
|
||||
| --- | --- | --- |
|
||||
| AGV | 地图控件、地图流、导航与手动速度控制更新 | 纳入更新 |
|
||||
| 关节动作 | 点位记录、分组、单步与循环流程编辑器 | 纳入更新,并补停止及等待回调联锁 |
|
||||
| 灵巧手 | 状态、指尖触觉数据及热图 | 纳入更新 |
|
||||
| 相机 | 设备下拉、状态、深度截图及预览控制 | 与本地自动识别、标定页视频复用合并 |
|
||||
| TCP | 两个标定/末端 `.cpp` 较旧,配套功能文件不完整 | 保留完整本地四点/六点法、控制器偏移读取、按机器人保存和实际点动 |
|
||||
| 手眼 | 缺少完整算法桥、存储及使用模块 | 保留本地联合标定、重投影精修、内置算法环境、照片缓存、URDF及坐标换算 |
|
||||
| 末端操作 | 缺少完整采点、路径和执行模块 | 保留任意像素、RGBD及二维平面定位、观察位和动作流程 |
|
||||
| 相机自适应 | 没有能力/物理身份/采集代次链路 | 保留单相机自动识别及切换,详见 CAMERA_AUTO_MODE.md |
|
||||
|
||||
忽略换行方式后,共有 13 个双方修改文件、10 个仅新版本修改文件、7 个新版本新增文件、6 个仅本地修改文件,以及 72 个仅本地新增文件。`include`、`lib`、`tools`、`models`、`icons` 内容没有实质变化:头文件、部分文本模型和图标只有 LF/CRLF 差异;89 个库文件逐字节一致。这些依赖目录没有覆盖。
|
||||
|
||||
## 合并策略与冲突修复
|
||||
|
||||
- 三方合并 28 个来源文件;保留本地功能文件、脚本、内置算法运行时和测试。源目录保持未修改。
|
||||
- CMake/qmake 纳入 AGV、JointFlowEditor、TactileHeatmapWidget,同时保留本地标定/末端模块和算法部署。保持 Qt 5.12.4、MinGW 7.3、C++14。
|
||||
- 合并 MainWindow/RobotClient 的入口、信号、异步回调与资源生命周期,保留现有 16 个页面。标定页继续获得真实机械臂关节遥测。
|
||||
- 新相机下拉代替旧输入框后继续同步当前标定上下文。标定与末端页只复用 RGB 会话;已有深度会话时结束旧模式并重建 RGB。
|
||||
- 被替换视频会话的终止通知不再关闭新预览。视频控件保留本地动态比例;复查后恢复静态照片与取点标记共用画布的实现,避免照片子控件遮盖标记。
|
||||
- 全局停止、机械臂停止、断开及同设备其他动作会取消关节流程;自身流程 MoveJ 不触发自我取消。等待回调校验执行代次,旧回调不能推进新的流程。
|
||||
- 解决 protobuf 字段碰撞:保留 `CameraState.codec=10`,使用 `capabilities=11`;同步本地服务端协议。不能把字段号冲突当作普通文本拼接。
|
||||
|
||||
新增源文件:`src/agvmapviewwidget.*`、`src/jointfloweditor.*`、`src/tactileheatmapwidget.*`、`resources/joint_programs.json`。该 JSON 保留为来源资源,没有覆盖运行目录的现有用户点位文件。
|
||||
|
||||
## 验证
|
||||
|
||||
- 合并预览程序完整编译和链接成功:`bin/debug/CmvrControlStation_merged_preview.exe`。
|
||||
- 末端操作:25 项通过;手眼 UI:22 项通过;手眼选择/变换/URDF:23 项通过;TCP 算法:16 项通过。
|
||||
- 协议兼容:3 项通过,包括已分发的第 10 号 codec 字段。
|
||||
- 关节流程:4 类停止/手动动作联锁及旧等待回调,共 5 个回归场景通过。修复前这些场景均失败。
|
||||
- 真实 RobotClient 的本地回环测试通过:按机器人 TCP 列表、保存传播、实际 MoveL 目标换算、TCP 枢轴、取消及切换设备;原始灰度/RGBD数据校验、时钟换算、深度→RGB模式切换和终止通知。
|
||||
- 单相机 Demo 视频启动、接收画面和停止自检通过;源码无残留合并标记,`git diff --check` 通过。
|
||||
|
||||
以上回环运动请求仅连接测试自己的 `127.0.0.1` 临时服务,GUI流程测试不连接服务端。没有发送真实机械臂运动指令。
|
||||
|
||||
## 备份与使用
|
||||
|
||||
比较清单:`build/incoming-main-merge/comparison.json`;依赖比较:`native-comparison.json`。
|
||||
合并前备份:`local-sources-before.tar.gz` 和 `incoming-sources-before.tar.gz`,均在 `build/incoming-main-merge/`。它们保留双方存在差异的源文件,不包含构建目录和 SDK 库。
|
||||
|
||||
继续在原工程打开 `CmvrControlStation.pro`,执行 qmake 后编译即可。预览版使用单独名称,未覆盖之前的可执行文件。可使用 `bin/debug/run_merged_preview.cmd` 启动预览版;该入口补充本机 Qt DLL 搜索路径。
|
||||
|
||||
此次没有提交、推送或替换服务器服务。新增 AGV/灵巧手功能仍需匹配版本的服务端及实机验证。相机服务在 2026-10-12 完成隔离构建和生命周期测试;2026-10-13 最后同步的协议编号调整因服务器 `192.168.0.28` 连接超时,未在服务器重新编译。MVS SDK 及实机验证边界见 CAMERA_AUTO_MODE.md。
|
||||
|
||||
## 合并后本地功能保留复查(2026-10-13)
|
||||
|
||||
按用户要求再次对照 `local-sources-before.tar.gz`,检查了备份中的全部 101 个本地差异文件,而不是只检查 Git HEAD。没有文件丢失;修复后 78 个文件忽略换行方式后与备份一致,23 个有合并或本轮修复。原有 72 个本地独有文件全部存在,其中只有 1 个状态文档及 3 个补充回归测试发生变化,功能实现文件未被替换。原有 6 个仅本地修改文件全部保持一致。qmake/CMake 未删除本地源文件或内置算法部署项。
|
||||
|
||||
发现并修复了首次合并验证漏检的三类行为退化:
|
||||
|
||||
| 问题 | 原因和修复 | 验证 |
|
||||
| --- | --- | --- |
|
||||
| 末端锁定照片遮住 A/B 目标标记 | 新版 `VideoRenderWidget::setImage` 新建的 QLabel 位于 GL 取点层之上。恢复本地 RGBA/QPainter 同画布路径,同时恢复已有 Qt 5.12 RGBA 颜色兼容处理与像素映射几何。 | Windows 软件 OpenGL 下,旧版用例因覆盖层失败;修复后实际 framebuffer 能看到标记,视频几何/锁帧/选择测试通过。 |
|
||||
| 设备和相机列表不再周期刷新 | 新版删除了 `BackendWorker::pollGrpc` 中的状态查询,自动识别仅能依赖首次或手动刷新。恢复原 1 Hz 查询和 500 ms 超时。 | 真实 RobotClient 连接本地临时 SystemService,不启动机械臂遥测、不手动刷新,验证首次发现、设备替换和断开后停止轮询。修复前缺少周期发现。 |
|
||||
| URDF 三维场景、关节绑定和限位丢失 | 新版 `loadUrdf` 无条件提前返回,只保留关节名称。恢复完整场景与限位构建;完成组件树后再接入场景,保留新版异步加载指针防护。 | 修复前场景/限位为空;修复后验证限位、遥测驱动变换、示教限幅、重新加载,并使用项目 `right_arm.urdf` 验证网格和连续遥测渲染。 |
|
||||
|
||||
再次沿入口和保存链路确认保留:TCP 四点/六点法、控制器工具偏移读取、按机器人保存/加载及实际点动;手眼联合标定、非线性精修、算法运行时、采样照片、文件导入、矩阵选择及 URDF 导出;末端观察位、任意像素目标、RGBD/二维平面定位、动作流程、停止联锁;单相机能力与物理身份过滤。TCP 与末端的真实 RobotClient 回环运动测试重新通过。
|
||||
|
||||
本轮生产修改仅为 `src/videorenderwidget.cpp/.h`、`src/robotclient.cpp`、`src/urdfviewerwidget.cpp`。新增 `tests/merge_retention_test.cpp`、`tests/urdf_retention_test.cpp`,扩充 `tests/touchvideo_test.cpp`;测试链接工具增加平台参数,以便在 Windows 上验证实际绘制。主程序重新编译链接成功,预览启动入口不变。
|
||||
|
||||
最终回归结果:视频绘制/锁帧/坐标映射 9 项通过,末端 UI 25 项通过,手眼 UI 22 项通过;自动设备发现、URDF 场景/限位/示教/重新加载、TCP 和末端 RobotClient 回环均通过。手眼测试需要运行目录旁的内置 Python 环境,已将测试程序放到现有 `bin/debug` 运行环境后完成验证。UI 业务测试使用 offscreen;实际标记绘制和 URDF 用 Windows 软件 OpenGL 单独验证。
|
||||
|
||||
本轮修复前备份、逐文件清单、失败复现及通过日志在 `build/incoming-main-merge/local-retention-audit/`。这些验证使用本地临时服务和软件 OpenGL,没有连接真实机械臂;不能代替服务端部署、相机硬件及目标机器显卡驱动联调。
|
||||
|
||||
## 关节速度面板恢复
|
||||
|
||||
对照合并前源码备份、`F:/QT/CmvrControlStation-upload` 和 Git 历史(`5c207d4`、`1473cee`),确认历史面板采用“关节名 / 实时弧度 / − / 限位指示 / +”的动态行。当前 `rebuildArmJogControls` 原布局仍在,但只由 `GetArmInfo.joint_names` 初始化;同时遥测读取只遍历名称数组。服务端缺少 GetArmInfo 或只返回位置数组时,真实关节位置无法生成控制行。该条件已通过本地旧版接口模拟服务复现,不代表已检查用户正在运行的服务端。
|
||||
|
||||
恢复和合并处理:
|
||||
|
||||
- 沿用历史关节行样式、速度倍率、按住 SpeedJ 和松开停止,保留新版“点位与流程”、笛卡尔和视觉标签页。
|
||||
- 遥测按真实关节位置数组读取。缺少名称时显示 J1、J2…,数量及顺序来自当前设备反馈,不硬编码机器人或六轴。
|
||||
- 设备信息不完整时,由当前设备有效遥测初始化关节行;其他设备的消息不会修改当前面板。
|
||||
- 空信息不清除已恢复的关节行,相同信息不重复销毁按钮;确需重建时先结束当前点动。
|
||||
- 无数据时显示等待状态,断开后禁用正反向按钮,避免空白面板和固定的“控制就绪”提示。
|
||||
|
||||
本次修改 `src/mainwindow.cpp/.h`、`src/mainwindow_ui.cpp`、`src/robotclient.cpp`;新增 `tests/jointjog_restore_test.cpp`。备份为 `local-retention-audit/before-jog-restore.tar.gz`。测试使用临时 127.0.0.1 服务模拟缺少名称和 GetArmInfo 的控制器,覆盖实时角度、倍率、关节方向、松开停止、重复刷新、机器人隔离和动态轴数。主程序预览版已重新编译。
|
||||
|
||||
|
||||
## 2026-10-14 第二次增量合并
|
||||
|
||||
来源仍为 `F:/QT/CmvrControlStation-main/cmvrcontrolstation`,目标仍为原本地工程。本轮按昨天的来源备份做增量三方合并,生产代码只修改六个文件:`src/jointfloweditor.cpp/.h`、`src/mainwindow.cpp`、`src/mainwindow_ui.cpp`、`src/robotclient.cpp`、`protos/cmvr/api/arm_command.proto`。来源目录未修改;逐文件哈希检查确认其余本地生产源码没有覆盖或丢失。
|
||||
|
||||
合入更新:关节电流列(mA)及演示数据,协议 `JointState.current=6`;流程支持选中节点后插入、同级拖动排序及自动布局;流程窗口及操作提示同步更新。保留按真实 position 数组恢复关节行、按住点动/松开停止、动态轴数、机器人隔离、停止联锁、相机能力、TCP/手眼/末端功能接线。
|
||||
|
||||
修复来源版本中的问题:
|
||||
|
||||
- “切换到根流程末尾”同步清除场景和内部选择,避免继续插在旧选中节点之后。
|
||||
- 重建画布后同步插入位置提示;进入循环时清除旧卡片选择。
|
||||
- 析构前断开场景的选择回调,避免成员销毁后仍被场景析构访问;原版本已在独立测试中复现堆损坏退出。
|
||||
- 自动排列按整棵子树的占用宽度避让,避免相邻循环展开后子节点重叠;拖动只调整同级顺序。
|
||||
- 电流数组缺项显示“未提供”,NaN/Inf 显示“无效”,真实零值显示 `0`,负值保持原符号;数据随后缺失时清除旧读数。本地服务端尚未填充新字段,不能把此上位机更新视为电流实测接口已经部署。
|
||||
|
||||
新增 `tests/jointflow_update_test.cpp/.pro`,扩展 `tests/jointjog_restore_test.cpp`。流程测试覆盖根末尾、选中后插入、取消选择后追加、嵌套循环及保存加载、相邻循环不重叠、拖动事件排序和选中卡片析构。真实 RobotClient 的临时回环测试覆盖旧服务端无名称/无电流、新字段、零值、负值、NaN/Inf、短数组及撤销读数,继续验证原关节点动/停止/动态轴数。
|
||||
|
||||
验证:Qt 5.12.4 / MinGW 7.3 主程序完整编译链接成功;流程七个场景通过;电流/旧控制器关节回环通过;原流程停止/手动操作/旧定时回调联锁五个场景通过;设备自动发现、更换及断开停止轮询通过;相机协议兼容三个测试通过。测试只使用本地临时服务或 UI 事件,没有连接真实机械臂。没有改动服务端、提交或推送仓库。
|
||||
|
||||
本轮备份、精确增量、失败复现和通过日志位于 `build/incoming-main-merge/update-2026-10-14/`,修改前备份为 `before.tar.gz`。程序仍为 `bin/debug/CmvrControlStation_merged_preview.exe`,使用 `bin/debug/run_merged_preview.cmd` 启动。
|
||||
94
docs/TOUCH_OPERATION.md
Normal file
94
docs/TOUCH_OPERATION.md
Normal file
@ -0,0 +1,94 @@
|
||||
# 末端操作:视觉取点与触控笔动作
|
||||
|
||||
## 入口与适用范围
|
||||
|
||||
入口为“复杂操作 → 末端操作”,位于手眼标定下方,页面索引 15。沿用现有面板、表格、按钮、日志和 QMessageBox。实时视频在左上,标定、观察位和双列动作参数在右上,目标坐标和执行路径在下方;执行和停止按钮固定在底部,不随内容滚动。页面视频与配置约为 7:3,视频按实际帧比例填充可用空间。进入页面后在连接和相机就绪时自动预览,没有手眼结果时可先从相机列表选择设备。离开页面仅停止本页面启动的视频会话。
|
||||
|
||||
无需棋盘格、角点或目标检测。可在锁定 RGB 画面上选择任意具有可靠深度的目标像素。单击、双击支持 1–2 个目标并依次完成;滑动必须选择 A/B 两点,按 A → B 执行。目标坐标直接由配准深度计算;直线滑动会检查中间深度,不支持沿未知曲面自动贴面运动。
|
||||
|
||||
## 操作流程
|
||||
|
||||
1. 在机械臂页选择服务器和设备;在 TCP 标定页核对控制器当前活动 TCP 偏移。
|
||||
2. 进入末端操作,将机械臂放到便于观察且离开触控面的姿态,点击“录入当前观察位”。
|
||||
3. 选择该机器人已保存的手眼标定与触控笔 TCP。相机由手眼记录确定;支持 Eye-in-Hand 和 Eye-to-Hand。
|
||||
4. 三点示教已取消。触控姿态沿用观察位所选 TCP 的姿态,接近/抬笔沿相机 Z 轴反方向。观察位需保证笔姿适合目标,且有足够接近距离。
|
||||
5. 点击“回观察位”,或通过现有机械臂页面手动返回观察位。回程是直线段,操作人员必须先确认路径净空;页面没有碰撞模型或全局绕障规划。
|
||||
6. 开始视频,核对 RGB 内参、标准 Brown 畸变模型及相机/上位机时钟。点击“锁定观察画面”,系统请求同一组原始 RGBD,并使用前后静止位姿读数夹住彩色和深度的采集时间。
|
||||
7. 在画面内点选 A/B,黑边不参与选点;选满两点后再点击将开始一组新选点。“目标点坐标换算结果”即时显示像素坐标及相机系、基座系 XYZ(mm)。这里显示深度测量得到的目标点,未叠加接触偏移。设置单击、双击或滑动及动作参数。
|
||||
8. 点击“转换 / 预览”,检查控制器活动 TCP 的逐步运动路径,确认笔姿及净空后执行。换算结果与运动路径分开显示;重新锁图、切换机器人或标定后需重新取点。
|
||||
9. 任务执行接近、接触、必要的双击短抬/第二次接触或滑动、回撤、返回观察位。两点单击/双击在每个目标后分别回到观察位。
|
||||
|
||||
执行前再次读取真实位姿,必须仍在观察位(0.5 mm / 0.2°内)。锁定图像最多用于 60 秒内的执行。完成、停止、离开页面或切换机器人后清除目标和路径,需要重新取图。
|
||||
|
||||
## 数据和真实接口
|
||||
|
||||
- 视频复用 `RobotClient::videoFrameReceived`、`VideoRenderWidget` 及现有解码线程。仅停止本页面创建的相机流;借用已运行流时不重复创建相机实例。
|
||||
- 原始 RGBD 来自 `requestTouchRgbdImage` → 现有 `CameraService.GetRGBDImages`,请求启用 `require_metric_depth`。继续使用现有 RobotClient 工作线程;彩图深度、内参及时间戳作为一次结果排队送回 UI。
|
||||
- 原始 BGR 转为拥有独立存储的 QImage;保留原始 U16/F32 小端深度数据,按服务提供的 metres_per_unit 转为 m。只接受与原始 RGB 尺寸一致、配准到 RGB 且表示 RGB 光轴 Z 的深度,绝不使用可视化灰度或默认深度比例。
|
||||
- 锁图不再混用视频帧和单独深度帧。必须同时有两张图的真实采集时间戳,帧间时间差不超过 33 ms;过期快照会在原有超时内重试。两张图均须落在前后静止位姿读取之间。取消/退出后迟到结果作废。
|
||||
- 位姿复用 `requestTcpCalibrationPose` → `getRobotState.actual_tcp_pose`,检查真实连接、静止、故障/保护停止/急停、数据来源和请求时间。该值为控制器活动 TCP,先去除已核对的活动偏移得到法兰位姿。
|
||||
- 运动复用 `requestTcpJogMove` → 现有 `MoveL(base,tcp)`。路径把选定触控笔 TCP 的目标换算成控制器活动 TCP 目标;不把本机工具名称虚构成控制器坐标系。
|
||||
- 控制器逐步等待 RPC 结束,并重新读取实际位姿核对目标后才进入停留或下一步。不会将命令返回成功等同于已到位。
|
||||
- 手眼列表使用 `HandEyeStore`,TCP 列表使用 `TcpToolStore`,均按服务器和机械臂隔离。新增/修改/删除标定后即时刷新并废弃旧路径。
|
||||
|
||||
## 算法来源与坐标定义
|
||||
|
||||
phone 来源:`F:/phone/scripts/phone_workcell_motion.py` 的 `build_touch_action_plan` / `build_touch_queue_plan`,以及 `handeye_click_motion_gui.py` 的 `_localize_free_pixel`。迁移了观察位检查、单/双击和滑动顺序、法向短抬及返回观察位。Qt 版本补上接近与回撤、真实到位验证和取消状态机。
|
||||
|
||||
phone 的 `_localize_free_pixel` / `_depth_mm` 已迁移到 `TouchPlanner::resolveDepthPixels`:去畸变射线乘以光轴深度,再用手眼矩阵换算。局部取样收紧为 5×5 邻域、至少 5 个有效样本、深度极差不超过 5 mm,避免大范围填洞跨到其他表面;没有可靠深度就拒绝,不使用手动 Z 或三点平面补偿。
|
||||
|
||||
- 内部距离 m,姿态 rad,旋转约定 `Rz(rz) * Ry(ry) * Rx(rx)`,矩阵为行优先。
|
||||
- Eye-in-Hand:`Base_T_Camera = Base_T_Flange_at_capture * Flange_T_Camera`。
|
||||
- Eye-to-Hand:直接使用已保存的 `Base_T_Camera`。
|
||||
- 接近/回撤方向为 `-R_base_camera[:,2]`,沿用 phone 自由取点流程;它不是估计的表面法线。正接触偏移沿相机 +Z 推进,是几何位移,**不是力控**。触控方向由观察位笔姿决定,不因选点自动转笔。
|
||||
- `Base_T_ActiveTarget = Base_T_SelectedTarget * inverse(Flange_T_Selected) * Flange_T_Active`。
|
||||
- 拒绝无效单位/配准、NaN/Inf、深度空洞、遮挡边缘、失效标定及越界路径。滑动每隔不超过 2 像素采样,深度点偏离端点三维连线超过 3 mm 则拒绝。范围限制不替代机器人 IK、碰撞检查或关节限位。
|
||||
|
||||
## 停止、时间及保存
|
||||
|
||||
停止、页面离开、断连、控制器偏移/机器人切换、外部手动命令介入都会取消后续步骤。失败后不自动回程。位姿请求超时 6 秒,每段运动超时 30 秒,整段序列超时 180 秒。
|
||||
|
||||
双击间隔是抬笔到位后的停留时间;实际触点间隔还包含机械臂运动与通信时间,需要在目标触摸设备上验证双击识别阈值。没有硬实时或触控成功识别保证,也没有增加未经证实的压力传感器接口。
|
||||
|
||||
观察位、所用活动偏移及所选标定名称沿用 QSettings,保存于 `touchOperation/v1/SHA256(endpoint + NUL + deviceId)`。启动后按机器人恢复;活动 TCP 偏移改变时观察位失效。选定工具切换后清除图像和路径,并按新 TCP 偏移重新计算笔尖位姿。旧版三点配置不再读取。图像、目标点、已核对状态和待执行路径不会跨会话恢复。
|
||||
|
||||
## 文件与验证
|
||||
|
||||
新增 `src/touchplanner.h/.cpp`、`touchsequencecontroller.h/.cpp`、`touchvideowidget.h/.cpp`、`touchoperationwidget.h/.cpp`。
|
||||
|
||||
修改 MainWindow 的入口、上下文/列表同步、视频归属和退出取消;RobotClient 增加手动命令入队前的同步通知;qmake/CMake 登记源文件。未升级 Qt/C++,未引入额外依赖或新通信通道。
|
||||
|
||||
测试位于 `tests/touchplanner_test.*`、`touchsequence_test.*`、`touchvideo_test.*`、`touchoperation_test.*`,真实 RobotClient 与本机假服务联调为 `tests/touchintegration_test.cpp` / `run_touch_integration.py`。覆盖几何、偏移补偿、时序/取消、双点选取、图像内参缩放、配置隔离、实际回程、停止和外部命令介入。
|
||||
|
||||
测试使用合成图像/位姿和 127.0.0.1 模拟服务,不等同于实机触控精度、双击时序或碰撞验收。离屏 OpenGL 不支持真实视频显示,实机视频仍需在正常图形环境验证。
|
||||
|
||||
## 深度服务更新
|
||||
|
||||
客户端和服务端必须同时具备公制 RGBD 契约。Qt 已实现并编译;服务端源码修改在 `F:/QT/cmvr-es-depth`,补丁为 `patches/cmvr-es-metric-rgbd.patch`,基于 `cmvr-es origin/dev` 的 `9b2f5773e692706e4c618e23889befc18cbbc579`。
|
||||
|
||||
- `GetRGBDImages` 新增可选请求位和 `DepthGeometry`;旧请求行为不变。未升级服务会缺少元数据,客户端明确提示更新,不继续生成坐标。
|
||||
- RealSense 相机配置需要 `STREAM_MODE_RGBD`。服务复用现有采集线程保存原始帧组,用 SDK 的 `get_units()` 读取真实比例,用深度/彩色内外参反投影、变换、投影,按最近深度写入 RGB 尺寸的 F32 米制 Z 图。没有对应测量的像素保持 0。
|
||||
- 时间戳来自 SDK global/system time;仅有 hardware time 时拒绝公制快照,不伪造曝光时间。尝试启用 global time 失败不影响原有视频流程。
|
||||
- 当前补丁实现 RealSense 驱动,其他驱动需实现同一 metric RGBD 契约;普通彩色视频功能不受影响。没有按相机名称、IP 或机器人型号硬编码。
|
||||
- 2026-10-10 已在 `192.168.0.28` 完整编译并部署 RGBD 补丁。真实 `real_cam1` 返回 640×480 彩色图及同尺寸 F32 公制深度,三组有效深度约 10 万像素;彩色/深度采集时间差约 0.018 ms。未执行机械臂触控动作或验证触控精度。
|
||||
- Modified Brown / Inverse Brown 彩色模型通过 SDK 几何校正至针孔快照,深度同时投影到该快照;Inverse Brown 系数全零时直接使用等价的无畸变模型。无测量或无有效彩色映射的像素保留零深度。
|
||||
- Qt 使用服务端响应时间计算 RGBD 年龄,并映射到客户端请求/响应时间区间。保留原始服务器采集时间和时间区间宽度,不假设两台主机 UTC 完全一致;区间必须落在前后静止位姿之间,通信或图像年龄超过 1.5 秒拒绝。
|
||||
- 视频按钮下方显示取点前置条件;实时画面上的点击会提示先锁定同步 RGBD。“已核对相机内参与时钟”未勾选时,直接提示该项。
|
||||
- 服务器部署备份位于 `output/backup-rgbd-20261010-165239`,日志位于 `/tmp/cmvr-rgbd-service.log`。补丁文件已同步包含畸变模型兼容处理。
|
||||
|
||||
在对应服务端源代码根目录先执行 `git apply --check cmvr-es-metric-rgbd.patch`,再 `git apply cmvr-es-metric-rgbd.patch`,按照该工程原有构建流程重新生成 protobuf、编译并部署。不要只替换上位机而继续使用旧服务协议。
|
||||
|
||||
## 本地标定与观察位(2026-10-10)
|
||||
|
||||
手眼与 TCP 各自提供“已有标定 / 本地文件”模式,导入 JSON 后直接用于当前会话的坐标转换和路径计算,不写入控制器、不覆盖已有列表。切换机器人清除导入结果;重启需重新导入。文件含 endpoint/device 时必须与当前设备一致。
|
||||
|
||||
- TCP 支持 phone `save_tcp()` 格式:convention 以 T_flange_tcp 开头,aubo_pose_convention 明确米、ZYX、弧度,tool_name、translation_m[3]、orientation_rxyz[3]。
|
||||
- phone 手眼支持 primary_result、明确的 T_flange_camera 或 T_base_camera[4][4]、camera_matrix、solver、created_at、samples_used 及质量指标。不能将含义不明确的 T_eef_camera 直接作为法兰矩阵。缺少 cameraId 时绑定导入时选择的相机,需人工核对物理设备。
|
||||
- phone 导入质量门限:至少 5 组,平均重投影不超过 1.5 px,AX=XB 平移 RMS 不超过 5 mm、旋转 RMS 不超过 5°;缺失或异常指标拒绝导入。
|
||||
- Qt 单条手眼 JSON 支持 units=m_rad、name、cameraId、mode、matrixDirection、transformSI[16]、method、createdAt、sampleCount、metrics、intrinsics,以及可选 board/refinement/observations;沿用 HandEyeStore 校验。
|
||||
|
||||
观察位采用 phone TaughtPose 语义:同次真实状态的 joint_positions(rad)、所选触控笔 tcp1_pose(m、ZYX rad)、pose_frame=tcp1。内部同时保留控制器当前激活 TCP 位姿,用于现有 MoveL 接口;显示采用度与毫米。切换 TCP、机器人或控制器偏移后应重新示教;缺少关节角的旧记录不自动激活。
|
||||
|
||||
### 页面状态校验
|
||||
|
||||
实时预览采用与手眼页相同的自适应宽度和相机流;冻结画面仅用于同帧 RGBD 取点。锁定需手眼标定、当前 TCP 对应观察位及相机确认齐备。重新加载列表时,如 TCP 被删除或同名参数改变,观察位失效并要求重新录入。滑动需要 A/B 两点;底部提示按当前缺失条件显示下一步操作。
|
||||
28
docs/superpowers/plans/2026-09-30-tcp-calibration.md
Normal file
28
docs/superpowers/plans/2026-09-30-tcp-calibration.md
Normal file
@ -0,0 +1,28 @@
|
||||
# TCP calibration migration implementation plan
|
||||
|
||||
Goal: fill existing navigation slot 13 with phone-equivalent fixed-point TCP calibration, using verified robot feedback and local QSettings persistence explicitly approved by the user.
|
||||
|
||||
Initial migration scope: retain Qt 5.12.4 / MinGW 7.3 / C++14, existing .pro fixes and certificate. Reuse current checkout because the user builds this exact project in Qt Creator. No robot motion, controller writes, new navigation or dependency installation in that phase.
|
||||
|
||||
Verified design:
|
||||
- Current TCP panel is createCalibrationEntryPage in mainwindow.cpp; no TCP .ui/class/CRUD exists. Keep its stack position. Dynamic internal widget follows panel/sectionTitle/mutedLabel/primaryButton and mechanical-arm tables; no global stylesheet changes.
|
||||
- phone scripts/handeye_calibration_gui.py solve_tcp_offset: >=4 base-to-flange poses, metres and ZYX Euler radians, Rz Ry Rx; stacked [R,-I] least squares. RMS mm, save blocked above 2mm. Orientation is manual, never claimed calibrated.
|
||||
- Existing getPose ignores requested flange on vendor backends; getPoseMatrix is unimplemented. Reuse RobotClient worker/channel and getRobotState, require verified AUBO vendor, validate stopped/connected/finite feedback. Derive flange with phone robot_backend.py transform chain from explicit user-confirmed active server TCP offset. Never use telemetry display cache or simulated samples.
|
||||
- No TCP save RPC/config fields. User explicitly selected local QSettings, separate local tool names and controller frames. Persist per endpoint and device. Do not make local selection change motion/controller settings.
|
||||
|
||||
Tasks / verification:
|
||||
- [x] Numerical module + tests: known pivot solution, rank/conditioning, invalid finite inputs, duplicate poses, noisy/high-error sets, Euler and flange/tool conversions. Compare Python phone solver.
|
||||
- [x] Additive worker request/result with request token; false/demo/disconnected/vendor unsupported/state errors return explicit failure. UI ignores late results after reset/device/session changes.
|
||||
- [x] Local tool store tests: namespace isolation, restart reload, bad data, duplicate name/update, current selection, sync failure reporting.
|
||||
- [x] Populate existing TCP page: tool name/list, manual orientation, active server TCP offset confirmation, 4+ sample rows, capture/overwrite, solve/clear/save/reload, residuals and RMS, local tool preview; log via MainWindow and use QMessageBox.
|
||||
- [x] UI tests with injected result signals (no hardware) for capture flow, source/tool changes, late responses, errors, invalid RMS, round-trip save/reload. Offscreen render inspect.
|
||||
- [x] Build existing Debug target, review changes, report precise limitations (local persistence, manually confirmed active TCP, AUBO pose adapter, hardware not tested).
|
||||
|
||||
User-requested follow-up: remove vendor/connection banner; return saved TCPs to the current robot's speed-control selector and actually use offsets for movement. This supersedes the initial phase's no-motion UI scope (no hardware commands are run during development).
|
||||
|
||||
- [x] Preserve per-endpoint/per-device QSettings storage and connect save/update/delete to the same robot's tool selector.
|
||||
- [x] Generic calibration UI with clear separation of the profile being edited and the profile selected for motion.
|
||||
- [x] Bounded local-tool jogging via verified MoveL(base,tcp) with fresh feedback and rigid-transform compensation; cancellable on release/context/stop/timeout.
|
||||
- [x] Invalidate active-TCP confirmation before ordinary named MoveL and mutable ArmService RPCs.
|
||||
- [x] Numerical/state-machine tests, robot-isolated UI/store tests and real loopback gRPC integration using MainWindow/RobotClient. Document finite-step and vendor-adapter limits.
|
||||
- [x] Build the complete app to an alternate filename because the user's original executable is running; preserve the process.
|
||||
160
docs/superpowers/plans/2026-10-12-camera-capability-modes.md
Normal file
160
docs/superpowers/plans/2026-10-12-camera-capability-modes.md
Normal file
@ -0,0 +1,160 @@
|
||||
# 单相机自动切换 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
|
||||
|
||||
1. 同一逻辑设备 ID 换了硬件:必须检测序列号和会话变化,旧图像、标定与路径不得继续使用。
|
||||
2. 采集帧跨越机器人读取窗口,或两台机器时钟不同:保留时间不确定区间并拒绝不能确定同步的数据。
|
||||
3. 单台设备拔出或发现两台设备:清除活动相机,禁止静默选取设备或回退定位方式。
|
||||
4. 内参被 ROI、分辨率或镜头变化影响:阻止定位,不能缩放旧内参冒充新标定。
|
||||
5. 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):**
|
||||
- `CameraCapabilities` message: version, driver, model, serial, transport, raw_image, valid_intrinsics, capture_timestamp, metric_aligned_depth, distortion_model, session_generation, unavailable_reason.
|
||||
- Append `CameraState.capabilities`; append `FrameData.camera_serial` and `FrameData.camera_session_generation` using 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 : AbstractCamera` implements 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.md` with 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_generation` increases 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 matching `cameraCapabilitiesReceived(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.txt` and affected test .pro files
|
||||
- Test: `tests/touchplanner_test.cpp`, `tests/touchoperation_test.cpp`, `tests/touchintegration_test.cpp`
|
||||
- Document: `docs/CAMERA_AUTO_MODE.md` with 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.
|
||||
15
docs/superpowers/plans/2026-10-13-incoming-main-merge.md
Normal file
15
docs/superpowers/plans/2026-10-13-incoming-main-merge.md
Normal file
@ -0,0 +1,15 @@
|
||||
# 新下载工程与本地功能合并
|
||||
|
||||
> 按 superpowers:executing-plans 在当前会话执行;原工作区包含用户尚未提交的功能,不创建遗漏这些功能的空白分支。
|
||||
|
||||
目标:把 F:/QT/CmvrControlStation-main/cmvrcontrolstation 的更新合并到 F:/QT/CmvrControlStation,保留本地 TCP、手眼、末端操作、内置算法和相机自适应。
|
||||
|
||||
共同参考:本地 HEAD 1473cee;新目录为无 Git 元数据的源码快照,不能断言它来自哪个提交。
|
||||
|
||||
- [x] 按共同参考比较源码:13 个双方修改、10 个新版本修改、7 个新版本新增、6 个仅本地修改、72 个仅本地新增。
|
||||
- [x] 保存双方差异源码备份到 build/incoming-main-merge/*-sources-before.tar.gz,并在 staged 目录进行三方合并。
|
||||
- [x] 解决重叠改动:主窗口页面和遥测生命周期、RobotClient 信号/回调、视频比例与静态图显示、构建列表。
|
||||
- [x] 解决相机协议编号冲突:codec 保留上游编号 10,新增 capabilities 使用 11;同步本地服务端协议。服务器离线,末次远端复编未执行。
|
||||
- [x] 保持当前 Qt 5.12.4、C++14 与内置算法部署;保留本地完整标定模块,拒绝用缺少配套头文件的两个孤立 .cpp 覆盖。
|
||||
- [x] 重新生成 protobuf/UI,构建独立合并预览程序;回归 TCP/手眼/末端操作,检查新增页面。另修复并验证流程停止/旧定时器、深度→RGB切换/旧终止通知。
|
||||
- [x] 输出 docs/INCOMING_MAIN_MERGE.md;不提交、不推送、不更换真实机器人服务、不发送运动指令。
|
||||
@ -0,0 +1,89 @@
|
||||
# 相机能力自适应与末端操作模式
|
||||
|
||||
日期:2026-10-12。状态:用户已确认;已实施并完成可用环境验证,MVS SDK 与实机验证待对应环境就绪。
|
||||
|
||||
## 目标与范围
|
||||
|
||||
连接当前服务端后,按实际相机能力选择视频、手眼标定和末端定位流程。用户在 RealSense 和 MV-CS050-10UM 之间直接替换使用,同一时间只使用一台相机,不实施双相机协同或并行采集。保留现有页面导航、视频获取通道、TCP 和手眼保存机制。新增 MV-CS050-10UM 工业相机适配,以及二维平面定位模式;为后续末端三轴力传感器明确扩展边界。
|
||||
|
||||
当前使用的服务器、机械臂和相机均为动态设备,不硬编码 IP、名称或序列号。服务端识别当前实际连接的相机,向 Qt 返回唯一活动相机身份和能力。正常流程不要求用户在两台相机之间选择;发现结果不唯一或没有设备时,明确报告状态并停止自动接入,不能任意选取设备。
|
||||
|
||||
## 已核实的现有代码
|
||||
|
||||
- Qt `src/robotclient.cpp` 的 `deviceListFromStatus()` 读取系统设备列表的 `driverType`,但不足以判断具体相机型号或公制深度能力。
|
||||
- 服务端 `CameraService.GetStatus` 返回 `CameraState`;当前字段只有运行状态、帧率和分辨率。
|
||||
- 服务端 `devices/camera/hikvision_camera` 使用 HCNetSDK、`NET_DVR_Login_V40`,不能复用为 MV-CS050-10UM 的 MVS 工业相机驱动。
|
||||
- Qt `getHandEyeImage()` 已接受原始灰度图;二维相机的手眼算法无需重写。
|
||||
- Qt `getTouchRgbdImage()` 与 `TouchOperationWidget::acceptImage()` 当前强制要求同步、公制、配准 RGBD 数据。
|
||||
- `TouchPlanner::resolvePixels()` 已支持去畸变、相机射线与机器人基座平面求交,可复用。
|
||||
- `TouchPlanner::resolveDepthPixels()` 已支持深度定位,继续保留其数据有效性检查。
|
||||
- `ArmRobotState.actual_tcp_wrench` 虽有协议字段,当前机械臂驱动未找到真实三轴力传感器填充链路。灵巧手触觉模块的数据不等于末端力传感器数据。
|
||||
- 本机未找到 MVS SDK 头文件或运行库。海康适配需在服务端安装对应平台 SDK 后进行编译和实机验证。
|
||||
|
||||
## 接入方案
|
||||
|
||||
采用服务端统一适配,Qt 继续通过现有 RobotClient 和 CameraService 获取图像及状态。这能让三个现有页面共享设备身份、时间戳和资源管理。
|
||||
|
||||
备选方案是 Qt 直接接 USB 相机,但会形成两套设备与时间戳来源,也不能满足通过服务端识别相机的要求,因此不采用。
|
||||
|
||||
MVS 驱动独立于现有 HikvisionCamera。服务端使用相应 SDK 枚举真实连接设备,识别型号、序列号和连接方式,不能仅靠配置中的相机名称判断当前硬件。仅创建并启动当前活动相机的采集实例。SDK 未安装时明确提示驱动不可用,不影响原有相机驱动构建,不用 UVC 或监控 SDK 冒充接入成功。
|
||||
|
||||
切换时先停止旧相机的采集和视频生产,撤销旧设备的流租约并释放资源,再接入当前连接设备;不允许两台相机同时采集。界面在切换期间显示连接状态,旧帧、旧能力回包和旧图像请求不得进入新相机流程。设备更换可通过重新连接服务或刷新发现完成;服务端若支持热插拔通知,则复用该通知更新,不能以已配置但未连接的相机冒充活动设备。
|
||||
|
||||
## 能力信息与自动切换
|
||||
|
||||
兼容扩展 CameraState,包含版本、驱动、型号、序列号、连接类型、原始图像格式、有效内参状态、采集时间戳能力、公制配准深度能力和错误原因。新增字段必须按真实驱动结果填充,未知不能默认为支持。
|
||||
|
||||
连接成功、实际相机替换、设备发现结果更新和重新启动相机后查询能力。相机断开时清除能力缓存。回包须与服务器会话、相机身份和请求代次匹配,旧会话或旧相机回包不改变当前模式。
|
||||
|
||||
| 实际能力 | 自动模式 | 可用功能 |
|
||||
| --- | --- | --- |
|
||||
| 原始图像、有效内参、采集时间戳、公制配准深度 | RGBD 深度定位 | 视频、手眼标定、按深度定位任意有效像素 |
|
||||
| 原始图像、有效内参、采集时间戳,无深度 | 二维平面定位 | 视频、手眼标定、按已知平面定位任意有效像素 |
|
||||
| 只有视频或能力未知 | 视频预览 | 可显示视频;明确列出阻止标定或定位的缺失条件 |
|
||||
|
||||
不得仅凭 RealSense 品牌名称判定当前输出有有效深度。不得在 RGBD 深度失败时静默改用二维平面。
|
||||
|
||||
页面紧凑显示当前唯一活动相机、模式和必要条件,保持现有样式,不增加双相机选择或双画面。视频比例由帧尺寸决定,鼠标坐标始终映射到原始图像像素。
|
||||
|
||||
## 二维平面定位
|
||||
|
||||
MV-CS050-10UM 不提供深度。新增平面参数文件导入入口,不恢复用户已要求删除的强制三点接触示教 UI。
|
||||
|
||||
平面参数明确包括版本、名称、机器人身份、相机序列号、参考手眼标定、单位、坐标系、平面原点、单位法向、有效操作范围。内部使用米、机器人基座坐标系;导入时校验并保存到现有 QSettings 管理范围。页面展示当前平面和状态,缺少有效平面时允许视频,禁止生成运动路径。
|
||||
|
||||
计算链为原始像素 → 使用对应相机内参去畸变 → 相机射线 → 当前手眼变换与锁定时法兰位姿 → 基座射线与平面求交。输出相机 XYZ 和基座 XYZ,沿用现有 TCP 变换与动作序列。
|
||||
|
||||
平面定位需要一次性获得真实平面位置,但目标点不要求位于棋盘格或标定板上。仅手眼矩阵不能唯一恢复任意二维像素的三维位置。
|
||||
|
||||
拒绝无效内参、法向、相机后方交点、近平行射线、越界目标和过期图像。滑动路径须在平面有效范围内。
|
||||
|
||||
## 图像同步与标定归属
|
||||
|
||||
二维与 RGBD 都沿用现有采集前后读取真实机械臂位姿的流程。采集图像和内参必须同源、同帧,保留采集时刻及时间不确定区间;只使用处于位姿读取窗口内的帧。
|
||||
|
||||
更换相机身份、分辨率、ROI、内参、手眼结果、TCP 或平面参数后,清除当前锁定图像、目标点和待执行路径,并重新确认必要条件。标定结果按服务器、机器人和相机身份过滤;相同设备 ID 下换了硬件也不能静默沿用旧结果。
|
||||
|
||||
旧标定文件缺少相机序列号时显示为需确认匹配,不能自动绑定给新设备。改变镜头、焦距或成像模式后重新校验内参。程序重启可恢复配置选择,但不恢复旧图像和待执行动作。
|
||||
|
||||
## 三轴力传感器扩展边界
|
||||
|
||||
本阶段只预留状态区域和接口契约,默认“未接入”,不生成假力值,不启用力控运动。
|
||||
|
||||
后续设备适配必须提供传感器身份、绑定机械臂、Fx/Fy/Fz(N)、有效标志、采集时间、坐标系、传感器到工具的安装变换、量程和故障。三轴力不包含 Tx/Ty/Tz,缺失力矩不能显示成已测得的零值。
|
||||
|
||||
接入后可扩展接触确认、按压阈值与侧向力限制。传感器只能提供接触反馈,不能替代二维相机缺失的目标空间位置。加装传感器改变工具安装尺寸时需重新 TCP 标定;若同时改变相机与法兰的相对安装,则还需重新手眼标定。
|
||||
|
||||
接触停止及闭环控制应在能够保证时效的服务端或控制器实现,Qt 负责参数与状态显示。传感器型号、通讯协议、更新频率尚未给出,真实驱动与力控不纳入本次交付。
|
||||
|
||||
## 涉及文件与验证
|
||||
|
||||
协议:Qt 和服务端的 camera_command.proto、camera_config.proto 同步兼容扩展。
|
||||
|
||||
服务端:AbstractCamera、GetStatus、CameraFactory、独立 MVS 驱动及可选 SDK 构建配置。保留现有驱动和流资源管理行为。
|
||||
|
||||
Qt:RobotClient 能力查询与会话校验、MainWindow 页面同步、现有手眼和末端页面、平面配置与 TouchPlanner 调用。Qt 5.12.4 和现有 C++ 标准保持不变。
|
||||
|
||||
验证:能力缺失及旧服务兼容、单相机替换与自动模式切换、旧采集资源释放、没有相机或发现不唯一、断线和旧回包、身份与内参不匹配、二维射线求交、深度模式回归、配置重载、点击像素比例,以及 UI 与主程序编译。实机检查分别验证 MVS 采集和 RealSense 回归;自动化测试不发送机械臂运动指令。
|
||||
|
||||
尚未解决的“读数变化但机械臂未实际运动”问题不能被新模式掩盖;在真实触控验证前需独立确认运动反馈来自真实控制器。
|
||||
160
docs/tcp-calibration.md
Normal file
160
docs/tcp-calibration.md
Normal file
@ -0,0 +1,160 @@
|
||||
# 工具坐标系 TCP 标定迁移说明
|
||||
|
||||
## 页面和使用流程
|
||||
|
||||
实现位于 `F:\QT\CmvrControlStation`,仍使用 MainWindow 原来的工具坐标标定入口和堆栈索引 13。
|
||||
原页面是 `createCalibrationEntryPage` 创建的占位内容,没有专属 `.ui`、TCP 页面类或工具参数 CRUD。
|
||||
现在在原入口嵌入 `TcpCalibrationWidget`,遵循原工程动态创建控件的方式。
|
||||
|
||||
界面参考机械臂页面、配置编辑页和原标定占位页,复用 `styles.qss` 的 `panel`、`sectionTitle`、`mutedLabel`、`primaryButton`,以及既有表格、输入框和 QMessageBox。
|
||||
包含标定工具、活动 TCP 偏移核对、固定点采样表、结果与操作四个区域。日志通过信号接入 MainWindow::appendLog。
|
||||
页面不显示厂家名称或服务器/设备/演示状态摘要;上下文自动跟随机械臂页面当前选择。
|
||||
“标定工具”只负责新建或重新标定;实际点动使用哪个工具,由机械臂页面的工具坐标下拉框选择。
|
||||
|
||||
1. 连接真实机械臂,在机械臂页面选择设备,再进入原工具坐标标定入口。
|
||||
2. 从示教器核对服务端活动 TCP 的法兰到 TCP 偏移,在页面输入 XYZ(mm)和 RX/RY/RZ(度),勾选已核对。只有实际零偏移才可填全零。
|
||||
3. 输入本机工具名称,选择四点法、六点法 · XZ 或六点法 · XY。四点法在同一固定参考点改变姿态采集四次;六点法按下文的三个接近点和三个方向点采集。
|
||||
4. 点击 TCP 标定,检查 XYZ、每点残差和固定点 RMS。RMS 大于 2 mm 禁止保存,应重新采样。
|
||||
5. 四点法只计算平移,方向 RX/RY/RZ 手动输入。六点法计算完整平移和方向,方向字段只读,保存保留未舍入的结果。
|
||||
6. 点击保存工具。机械臂速度控制的工具坐标下拉框立即刷新并选择该工具,显示为“工具名(标定)”。同名记录需确认覆盖;清除或重新标定仅清空临时过程。
|
||||
7. 返回机械臂页面,选择“笛卡尔速度”页签,按住所选工具轴的方向按钮进行小步点动,松开即停止。
|
||||
|
||||
工具记录仍通过 QSettings 保存在本机,但按服务器地址和机械臂设备 ID 分别存储;不是所有机器人共用的列表。
|
||||
保存、覆盖、删除同步刷新速度控制下拉框。切换机器人或服务器后只加载该身份下的工具,可存在同名但不同偏移的工具。
|
||||
本机标定工具不会注册成控制器命名坐标系,而是由上位机将选中工具的目标位姿换算后发送给现有运动接口。
|
||||
|
||||
### 六点法 · XZ / XY
|
||||
|
||||
前三点保持工具尖端在同一固定点,改变法兰姿态,由 `solvePosition` 的最小二乘方程求 TCP 平移。后三点依次为方向原点、+X 方向点及 +Z(XZ)或 +Y(XY)方向点,保持法兰姿态一致。这与六次固定点采样不同;后三点不参与固定点残差计算。
|
||||
|
||||
`TcpCalibration::solveSixPoint` 先用已解出的偏移将后三个法兰位置换成 TCP 在基座下的位置,构造方向向量,保留 X 轴并对第二方向正交化,以右手定则补齐第三轴。最终 `R_flange_tool = transpose(R_base_flange_origin) * R_base_tool`,与原有 m/rad、ZYX 姿态格式一致。
|
||||
|
||||
拒绝秩不足、NaN/Inf、方向基线小于 10 mm、夹角不在 5°~175°、后三点相对方向原点姿态漂移超过 0.2°等情况。10 mm 是退化检查下限,不是精度推荐距离;实际距离依据工具、工作空间及示教条件确定,程序不自动移动机器人。固定点 RMS 大于 2 mm 仍禁止保存。
|
||||
|
||||
切换方法清空当前采样和结果,不删除已保存工具。记录增加方法字段,兼容没有该字段的历史固定点记录;加载和保存保留历史样本数量。四点法和两种六点法均使用原有按机器人隔离的存储与工具轴点动链路,计算与保存保持独立。
|
||||
|
||||
2026-10-08 更新验证:数值测试 16 项、页面/保存流程 16 项通过,覆盖 XZ/XY 合成真值、非零方向原点旋转、退化、重复方向原点、六点保存重载和旧记录兼容。
|
||||
|
||||
## 标定工具的实际点动链路
|
||||
|
||||
MainWindow::startCartesianJog → TcpJogController → RobotClient::requestTcpCalibrationPose → 新鲜真实反馈 → jogTarget → RobotClient::requestTcpJogMove → 原通道的 MoveL。
|
||||
|
||||
平移沿选中工具自身 XYZ 轴;旋转按所选工具自身轴生成目标,并保持所选 TCP 的目标位置不变:
|
||||
|
||||
```
|
||||
T_base_flange = T_base_activeTCP * inverse(T_flange_activeTCP)
|
||||
T_base_selectedTCP = T_base_flange * T_flange_selectedTCP
|
||||
T_target_selectedTCP = T_base_selectedTCP * delta_in_selected_axes
|
||||
T_target_activeTCP = T_target_selectedTCP * inverse(T_flange_selectedTCP) * T_flange_activeTCP
|
||||
```
|
||||
|
||||
发送的 frame 始终为 BASE,base_frame 为 `base`,tcp_frame 为 `tcp`;本机工具名称从不冒充控制器坐标名。
|
||||
已沿服务源码核实:当前适配驱动的 MoveL 对 `tcp` 读取并沿用当前 TCP 偏移,并等待到位后返回。
|
||||
界面姿态显示也使用原始活动 TCP 反馈换算为所选工具的位姿,禁止将命名 getPose 的结果重复换算。
|
||||
|
||||
SpeedL 只有 Base/Tool 枚举,不能携带任意标定偏移,且驱动禁止已有运动时叠加速度请求。因此标定工具采用有限 MoveL 小步循环,不宣称实现连续速度伺服。
|
||||
每步至多 2 mm 或 0.005 rad(约 0.29°),长工具进一步限制步长,使活动 TCP 的位移也不超过 2 mm。
|
||||
指令速度上限为平移 0.02 m/s、旋转输入 0.05 rad/s;每步重新读取反馈,连续按住最长 30 秒。实际平均速度还受 RPC 和到位等待影响。
|
||||
每段内部仍由控制器对活动 TCP 插补,旋转时所选尖端在段间有小量弦线近似误差;上述转换保证每个目标端点,而非承诺整条旋转轨迹绝对无偏差。
|
||||
|
||||
松开、切换工具/机械臂/服务器、离开机械臂页面、窗口失去激活、断连、停止按钮和超时均取消后续步进并请求 stopMotion。
|
||||
请求序号区分采点和点动,并丢弃旧反馈及重复完成消息。控制器已有坐标项保留原速度控制行为;选择“(标定)”项才进入这个新流程。
|
||||
每次重连必须核对活动 TCP 偏移;不要在点动过程中通过示教器切换它。当前协议没有自动读取该偏移的接口。
|
||||
程序内普通“末端位姿移动”会按指定控制器帧切换活动 TCP,因此在派发该 MoveL 前主动取消偏移确认、清空临时采样并停止本机 TCP 点动。
|
||||
通用 RPC 页的机械臂写命令同样使确认失效,之后需重新核对;这不会删除已保存的工具记录。
|
||||
|
||||
## phone 算法与坐标定义
|
||||
|
||||
直接参考的源码:
|
||||
|
||||
- `F:\phone\scripts\handeye_calibration_gui.py`:`aubo_pose_to_matrix`、`solve_tcp_offset`、`capture_tcp_sample`、`confirm_tcp`、`save_tcp` / `load_tcp`。
|
||||
- `F:\phone\scripts\robot_backend.py`:`flange_pose` 和 `tool_pose` 的刚体变换关系。
|
||||
|
||||
输入至少 4 个基座到法兰位姿,格式 `[x,y,z,rx,ry,rz]`,内部使用 m/rad。
|
||||
角度为 ZYX 欧拉角,旋转矩阵 `Rz(rz) * Ry(ry) * Rx(rx)`;不是旋转向量。
|
||||
齐次矩阵使用列向量约定,C++ 数组按行存储。
|
||||
|
||||
固定点方程为 `R_i * t_flange_tcp + p_i = p_fixed`。
|
||||
与 phone 一样构造 `[R_i, -I] * [t_flange_tcp; p_fixed] = -p_i`,求六个未知量的最小二乘解。
|
||||
用轻量一侧 Jacobi SVD 实现对应求解,避免引入 NumPy/Eigen 或使用正规方程放大病态误差。
|
||||
检查秩、非有限值和病态条件数;保留 phone 的毫米 RMS 和 2 mm 合格上限。
|
||||
RMS 为所有重建固定点到拟合固定点的欧氏距离的均方根,并显示每点误差。
|
||||
phone 的重复采点阈值为位移小于 1 mm 且姿态差小于 3°;Qt 对其他所有已采点进行该检查。
|
||||
|
||||
数值模块集中提供 `poseMatrix`、`matrixPose`、`flangePose`、`toolPose`;显示转换集中为 m↔mm、rad↔degree。
|
||||
对带旋转的活动偏移严格使用:
|
||||
|
||||
```
|
||||
T_base_flange = T_base_activeTCP * inverse(T_flange_activeTCP)
|
||||
T_base_localTCP = T_base_flange * T_flange_localTCP
|
||||
```
|
||||
|
||||
## 真实反馈调用链及限制
|
||||
|
||||
页面 captureRequested → RobotClient::requestTcpCalibrationPose → 既有工作线程 getTcpCalibrationPose → 既有 gRPC 通道的 GetArmInfo 和 getRobotState → state.actual_tcp_pose。
|
||||
没有创建新连接,没有使用遥测显示缓存,也不接受演示模式数据。
|
||||
|
||||
先核对返回的设备 ID 和 AUBO 驱动,再检查连接、运动、故障、停止标志、安全模式、机器人模式、反馈字段、DOF、关节位置/速度和所有数值。
|
||||
每次 RPC 有截止时间,页面另有 6 秒超时和请求序号。断连、换设备、换服务器、清除及重采均使旧响应失效。
|
||||
|
||||
已检查服务源码:命名 getPose 的驱动实现忽略帧参数,不能把它当作法兰反馈;getPoseMatrix 未实现。
|
||||
当前没有读取活动 TCP 偏移的 RPC,因此按 phone 的 gRPC 方式换算,要求用户手动确认当前偏移。采点过程中不得在示教器切换活动 TCP。
|
||||
仅对已核实的 AUBO 姿态定义开放采点,其他厂家明确报错,未猜测 Huayan 姿态约定。
|
||||
|
||||
服务端可能用全零位姿/关节数组掩盖 SDK 读取异常,客户端拒绝这些反馈;真实全零关节姿态也会被保守拒绝,可换姿态重试。
|
||||
服务端默认时间戳可能为零,因此客户端记录本次请求时间,不声称验证了硬件时间戳的新鲜度。
|
||||
没有服务端独立的 SDK 有效性标志,客户端无法完全排除服务器返回表面合法但过时的数据;实际机器人联调尚未完成。
|
||||
|
||||
## 保存和重新加载
|
||||
|
||||
工程和服务只有 TCP 名称列表,没有可调用的 TCP 偏移创建/编辑/删除/保存 RPC,也没有对应工具参数配置结构。
|
||||
按用户明确确认的方案,沿用工程默认 QSettings 增加独立的本机工具记录;没有新增文件型配置系统或控制器 Tool ID。
|
||||
名称作为当前服务器和设备下的唯一标识,记录偏移六元组(m/rad)、RMS(mm)、采样数量和当前本机工具名称。
|
||||
|
||||
Windows 默认位置:
|
||||
|
||||
```
|
||||
HKEY_CURRENT_USER\Software\CMVR\CMVR Control Station
|
||||
tcpCalibration/v1/<SHA256(endpoint + NUL + deviceId)>
|
||||
```
|
||||
|
||||
记录内同时存储服务器和设备身份,避免跨设备混用。应用启动后恢复相同连接参数和设备 ID,即加载该身份下的工具列表及当前工具;也可点击重新加载。
|
||||
保存调用 sync 并检查状态;配置损坏、同名冲突、数值异常和写入失败均报告,不静默覆盖坏配置。
|
||||
保留一个明确 TODO:待服务提供真实持久化 TCP RPC 后再接入控制器,当前不虚构接口。
|
||||
|
||||
## 文件范围
|
||||
|
||||
修改:
|
||||
|
||||
- `src/mainwindow.cpp/.h`、`src/mainwindow_ui.cpp`:原页面内容、信号槽、上下文、工具列表及点动接入。
|
||||
- `src/robotclient.h`、`src/robotclient.cpp`:通过原工作线程增加真实采点请求和校验。
|
||||
- `CmvrControlStation.pro`、`CMakeLists.txt`:登记新增模块。
|
||||
|
||||
新增:
|
||||
|
||||
- `src/tcpcalibration.h/.cpp`:数值求解和刚体转换。
|
||||
- `src/tcpcalibrationwidget.h/.cpp`:原入口内的界面与采样状态管理。
|
||||
- `src/tcptoolstore.h/.cpp`:QSettings 本机工具保存、加载、选择、删除。
|
||||
- `src/tcpjogcontroller.h/.cpp`:可取消的真实反馈读取与有限运动状态机。
|
||||
- `tests/tcpcalibration_test.cpp/.pro`、`tests/tcpworkflow_test.cpp/.pro`:算法和页面/保存流程测试。
|
||||
- `tests/tcpjog_test.cpp/.pro`:工具轴、旋转端点、停止/切换和响应隔离测试。
|
||||
- `tests/tcpintegration_test.cpp`、`tests/run_tcp_integration.py`:实际 MainWindow + RobotClient 与回环 gRPC 模拟服务联调。
|
||||
- 本说明及 `docs/superpowers/plans/2026-09-30-tcp-calibration.md`。
|
||||
|
||||
原有 protoc 路径修复、证书以及 Qt Creator 本机设置保留,属于此前环境修复,不是 TCP 算法改动。
|
||||
|
||||
## 验证
|
||||
|
||||
Qt 5.12.4、MinGW 7.3 64 位、C++14;未升级工程标准或引入数学依赖。
|
||||
算法测试 12 项通过(含初始化/清理),覆盖已知真值、phone NumPy 参考结果、退化、病态、NaN/Inf、旋转和法兰转换。
|
||||
页面/持久化测试 13 项通过(含初始化/清理),覆盖采集计算保存重开、隔离、重复/非法反馈、失败重采、旧响应、切换设备、断连、误差超限及设置写入失败。
|
||||
点动测试 7 项通过(含初始化/清理),覆盖工具轴、带旋转源偏移的 TCP 端点保持、松开后旧响应、切换及失败停止。
|
||||
回环 gRPC 联调通过:保存结果进入真实主界面下拉框;不同机器人/服务器工具隔离;真实 MoveL 请求的设备、帧和目标位姿正确;松开和切换后不继续派发运动;普通 MoveL/机械臂 RPC 派发前取消旧活动 TCP 确认。
|
||||
页面截图来自合成测试数据,不是真实机械臂测量。
|
||||
|
||||
Windows Qt 5.12.4 离屏插件不能处理 QMessageBox 的原生系统菜单;仅测试代码跳过该 Show 钩子,保留标准弹窗按钮和返回值。产品代码仍使用正常 QMessageBox。
|
||||
完整应用 qmake Debug 目标编译成功,启用 gRPC 和 MsQuic。当前旧程序正在运行,默认 exe 无法覆盖,故用同一组完整对象链接为 `bin/debug/CmvrControlStation_tcp_preview.exe`,未结束用户进程。
|
||||
构建日志为 `build/Desktop_Qt_5_12_4_MinGW_64_bit_Debug/tcp-integration-build.log`;回环联调日志为 `build/tcp-integration-test.log`。
|
||||
关闭旧程序后,Qt Creator 正常构建即可生成默认名称的新版程序。
|
||||
CMake 仅同步源文件清单,未单独执行 CMake 构建。
|
||||
真实设备采点精度、示教器偏移一致性和最终运动使用需现场验证。
|
||||
BIN
patches/cmvr-es-camera-auto-source.tar.gz
Normal file
BIN
patches/cmvr-es-camera-auto-source.tar.gz
Normal file
Binary file not shown.
278
patches/cmvr-es-metric-rgbd.patch
Normal file
278
patches/cmvr-es-metric-rgbd.patch
Normal file
@ -0,0 +1,278 @@
|
||||
diff --git a/cmvr-es/devices/camera/abstract_camera.h b/cmvr-es/devices/camera/abstract_camera.h
|
||||
index d807b658..a0e1f224 100644
|
||||
--- a/cmvr-es/devices/camera/abstract_camera.h
|
||||
+++ b/cmvr-es/devices/camera/abstract_camera.h
|
||||
@@ -26,6 +26,14 @@ namespace cmvr::device {
|
||||
float coeffs[5]{};
|
||||
|
||||
};
|
||||
+ struct RgbdGeometry {
|
||||
+ double metres_per_unit = 0;
|
||||
+ bool aligned_to_color = false;
|
||||
+ bool color_axial_z = false;
|
||||
+ std::string distortion_model;
|
||||
+ int64_t color_capture_utc_ns = 0;
|
||||
+ int64_t depth_capture_utc_ns = 0;
|
||||
+ };
|
||||
struct StreamFrameData
|
||||
{
|
||||
//原始图像数据
|
||||
@@ -102,6 +110,9 @@ namespace cmvr::device {
|
||||
virtual void getRGBImage(cv::Mat &color, Rs2Intrinsics& intrinsics) {}
|
||||
virtual void getDepthImage(cv::Mat &depth, Rs2Intrinsics& intrinsics) {}
|
||||
virtual void getRGBDImages(cv::Mat &color, cv::Mat &depth, Rs2Intrinsics& intrinsics) {}
|
||||
+ // Unsupported drivers deliberately return no metric geometry.
|
||||
+ virtual void getMetricRGBDImages(cv::Mat &color, cv::Mat &depth,
|
||||
+ Rs2Intrinsics& intrinsics, RgbdGeometry& geometry) {}
|
||||
virtual void startRecording(const std::string &video_path) {}
|
||||
virtual void stopRecording() {}
|
||||
virtual void pauseRecording() {}
|
||||
diff --git a/cmvr-es/devices/camera/realsense_camera/include/realsense_camera.h b/cmvr-es/devices/camera/realsense_camera/include/realsense_camera.h
|
||||
index ec700d96..597b9814 100644
|
||||
--- a/cmvr-es/devices/camera/realsense_camera/include/realsense_camera.h
|
||||
+++ b/cmvr-es/devices/camera/realsense_camera/include/realsense_camera.h
|
||||
@@ -28,6 +28,8 @@ namespace cmvr::device{
|
||||
void getRGBImage(cv::Mat& color, Rs2Intrinsics& intrinsics) override;
|
||||
void getDepthImage(cv::Mat& depth, Rs2Intrinsics& intrinsics) override;
|
||||
void getRGBDImages(cv::Mat &color, cv::Mat &depth, Rs2Intrinsics& intrinsics) override;
|
||||
+ void getMetricRGBDImages(cv::Mat &color, cv::Mat &depth,
|
||||
+ Rs2Intrinsics& intrinsics, RgbdGeometry& geometry) override;
|
||||
void startRecording(const std::string &video_path) override;
|
||||
void stopRecording() override;
|
||||
void pauseRecording() override;
|
||||
@@ -71,6 +73,7 @@ namespace cmvr::device{
|
||||
rs2_intrinsics intrinsics_;
|
||||
|
||||
std::mutex frame_mtx_;
|
||||
+ rs2::frameset latest_metric_frames_; // Owned SDK frames before display alignment.
|
||||
|
||||
cv::Mat dist_coeffs_;
|
||||
cv::Mat latest_rgb_;
|
||||
diff --git a/cmvr-es/devices/camera/realsense_camera/src/realsense_camera.cpp b/cmvr-es/devices/camera/realsense_camera/src/realsense_camera.cpp
|
||||
index a22918c1..4733b7f4 100644
|
||||
--- a/cmvr-es/devices/camera/realsense_camera/src/realsense_camera.cpp
|
||||
+++ b/cmvr-es/devices/camera/realsense_camera/src/realsense_camera.cpp
|
||||
@@ -6,6 +6,9 @@
|
||||
#include "../include/realsense_camera.h"
|
||||
|
||||
#include <cstring>
|
||||
+#include <cmath>
|
||||
+#include <stdexcept>
|
||||
+#include <librealsense2/rsutil.h>
|
||||
|
||||
using namespace std;
|
||||
using namespace cmvr::device;
|
||||
@@ -232,6 +235,14 @@ bool RealsenseCamera::start() {
|
||||
|
||||
// 使用相同的同步策略启动
|
||||
profile_ = pipe_.start(rs_cfg_);
|
||||
+ for (auto sensor : profile_.get_device().query_sensors()) {
|
||||
+ try {
|
||||
+ if (sensor.supports(RS2_OPTION_GLOBAL_TIME_ENABLED))
|
||||
+ sensor.set_option(RS2_OPTION_GLOBAL_TIME_ENABLED, 1.f);
|
||||
+ } catch (const rs2::error& e) {
|
||||
+ CMVR_LOG(WARNING) << "Metric RGBD global time unavailable: " << e.what();
|
||||
+ }
|
||||
+ }
|
||||
|
||||
if (stream_mode_ == RGBD_MODE){
|
||||
auto sp_depth = profile_.get_stream(RS2_STREAM_DEPTH).as<rs2::video_stream_profile>();
|
||||
@@ -350,6 +361,126 @@ bool RealsenseCamera::stop() {
|
||||
return true;
|
||||
}
|
||||
|
||||
+void RealsenseCamera::getMetricRGBDImages(cv::Mat& color, cv::Mat& depth,
|
||||
+ Rs2Intrinsics& intrinsics, RgbdGeometry& geometry) {
|
||||
+ rs2::frameset frames;
|
||||
+ {
|
||||
+ std::lock_guard lock(ctrl_mtx_);
|
||||
+ if (!state_.is_opened || stream_mode_ != RGBD_MODE)
|
||||
+ throw std::runtime_error("Metric RGBD requires an opened RGBD camera");
|
||||
+ if (state_.is_streaming) {
|
||||
+ std::lock_guard<std::mutex> frame_lock(frame_mtx_);
|
||||
+ frames = latest_metric_frames_;
|
||||
+ } else {
|
||||
+ frames = get_frameset(false);
|
||||
+ }
|
||||
+ }
|
||||
+ if (!frames) throw std::runtime_error("Waiting for a complete RGBD frameset");
|
||||
+ const auto rgb = frames.get_color_frame();
|
||||
+ const auto raw = frames.get_depth_frame();
|
||||
+ if (!rgb || !raw) throw std::runtime_error("RGBD frameset is incomplete");
|
||||
+ const auto capture = [](const rs2::frame& frame) -> int64_t {
|
||||
+ const auto domain = frame.get_frame_timestamp_domain();
|
||||
+ const double ms = frame.get_timestamp();
|
||||
+ if ((domain != RS2_TIMESTAMP_DOMAIN_GLOBAL_TIME && domain != RS2_TIMESTAMP_DOMAIN_SYSTEM_TIME)
|
||||
+ || !std::isfinite(ms) || ms <= 0 || ms > 9e12)
|
||||
+ throw std::runtime_error("RGBD requires SDK global/system capture timestamps");
|
||||
+ return static_cast<int64_t>(ms * 1000000.0);
|
||||
+ };
|
||||
+ geometry.color_capture_utc_ns = capture(rgb);
|
||||
+ geometry.depth_capture_utc_ns = capture(raw);
|
||||
+ if (std::abs(geometry.color_capture_utc_ns - geometry.depth_capture_utc_ns) > 33000000)
|
||||
+ throw std::runtime_error("RGB and depth captures differ by more than 33 ms");
|
||||
+ const auto color_profile = rgb.get_profile().as<rs2::video_stream_profile>();
|
||||
+ const auto depth_profile = raw.get_profile().as<rs2::video_stream_profile>();
|
||||
+ auto kc = color_profile.get_intrinsics();
|
||||
+ const auto kd = depth_profile.get_intrinsics();
|
||||
+ if (kc.model != RS2_DISTORTION_NONE && kc.model != RS2_DISTORTION_BROWN_CONRADY
|
||||
+ && kc.model != RS2_DISTORTION_MODIFIED_BROWN_CONRADY
|
||||
+ && kc.model != RS2_DISTORTION_INVERSE_BROWN_CONRADY)
|
||||
+ throw std::runtime_error("Unsupported RGB distortion model: " + std::to_string(kc.model));
|
||||
+ if (kd.model != RS2_DISTORTION_NONE && kd.model != RS2_DISTORTION_BROWN_CONRADY
|
||||
+ && kd.model != RS2_DISTORTION_INVERSE_BROWN_CONRADY)
|
||||
+ throw std::runtime_error("Unsupported depth deprojection model");
|
||||
+ const auto extrinsics = depth_profile.get_extrinsics_to(color_profile);
|
||||
+ const double scale = raw.get_units(); // Real sensor units, never assume millimetres.
|
||||
+ if (!std::isfinite(scale) || scale <= 0 || scale > .1)
|
||||
+ throw std::runtime_error("Invalid sensor depth units");
|
||||
+ if (rgb.get_profile().format() != RS2_FORMAT_BGR8 || raw.get_profile().format() != RS2_FORMAT_Z16)
|
||||
+ throw std::runtime_error("Metric RGBD requires BGR8 and Z16 sensor frames");
|
||||
+ color = cv::Mat(rgb.get_height(), rgb.get_width(), CV_8UC3,
|
||||
+ const_cast<void*>(rgb.get_data()), rgb.get_stride_in_bytes()).clone();
|
||||
+ cv::Mat valid_color;
|
||||
+ if (kc.model == RS2_DISTORTION_INVERSE_BROWN_CONRADY
|
||||
+ && std::all_of(std::begin(kc.coeffs),std::end(kc.coeffs),[](float v) { return v==0.f; }))
|
||||
+ kc.model = RS2_DISTORTION_NONE;
|
||||
+ if (kc.model == RS2_DISTORTION_MODIFIED_BROWN_CONRADY
|
||||
+ || kc.model == RS2_DISTORTION_INVERSE_BROWN_CONRADY) {
|
||||
+ // These models differ from OpenCV's standard Brown. Rectify with SDK
|
||||
+ // geometry, then project depth into the same pinhole image.
|
||||
+ const auto original = kc;
|
||||
+ cv::Mat map_x(color.size(), CV_32FC1), map_y(color.size(), CV_32FC1);
|
||||
+ valid_color = cv::Mat::zeros(color.size(), CV_8UC1);
|
||||
+ for (int y = 0; y < color.rows; ++y) for (int x = 0; x < color.cols; ++x) {
|
||||
+ const float ray[3] = {(x-kc.ppx)/kc.fx, (y-kc.ppy)/kc.fy, 1.f};
|
||||
+ float uv[2];
|
||||
+ bool converged = true;
|
||||
+ if (original.model == RS2_DISTORTION_INVERSE_BROWN_CONRADY) {
|
||||
+ // Inverse Brown supports SDK deprojection. Find the source
|
||||
+ // pixel whose SDK ray matches this rectified pinhole ray.
|
||||
+ uv[0]=float(x); uv[1]=float(y); converged=false;
|
||||
+ for (int iteration=0; iteration<12; ++iteration) {
|
||||
+ float actual[3]; rs2_deproject_pixel_to_point(actual,&original,uv,1.f);
|
||||
+ const float dx=(ray[0]-actual[0])*original.fx;
|
||||
+ const float dy=(ray[1]-actual[1])*original.fy;
|
||||
+ if (!std::isfinite(dx)||!std::isfinite(dy)) break;
|
||||
+ if (std::abs(dx)<.001f && std::abs(dy)<.001f) { converged=true; break; }
|
||||
+ uv[0]+=dx; uv[1]+=dy;
|
||||
+ }
|
||||
+ } else rs2_project_point_to_pixel(uv, &original, ray);
|
||||
+ if (!converged) { uv[0]=-1.f; uv[1]=-1.f; }
|
||||
+ map_x.at<float>(y,x) = uv[0]; map_y.at<float>(y,x) = uv[1];
|
||||
+ if (std::isfinite(uv[0]) && std::isfinite(uv[1]) && uv[0]>=0 && uv[1]>=0
|
||||
+ && uv[0]<color.cols-1 && uv[1]<color.rows-1)
|
||||
+ valid_color.at<uint8_t>(y,x) = 1;
|
||||
+ }
|
||||
+ cv::Mat rectified;
|
||||
+ cv::remap(color, rectified, map_x, map_y, cv::INTER_LINEAR, cv::BORDER_CONSTANT);
|
||||
+ color = rectified;
|
||||
+ kc.model = RS2_DISTORTION_NONE;
|
||||
+ std::fill(std::begin(kc.coeffs), std::end(kc.coeffs), 0.f);
|
||||
+ }
|
||||
+ depth = cv::Mat::zeros(color.rows, color.cols, CV_32FC1);
|
||||
+ // Reproject raw depth into RGB, including the baseline translation. Store
|
||||
+ // RGB-camera Z, not the original depth-camera Z. Nearest-depth z-buffer;
|
||||
+ // unobserved/occluded pixels stay zero instead of inventing a surface.
|
||||
+ const auto* bytes = static_cast<const uint8_t*>(raw.get_data());
|
||||
+ for (int y = 0; y < raw.get_height(); ++y) for (int x = 0; x < raw.get_width(); ++x) {
|
||||
+ uint16_t sample = 0;
|
||||
+ std::memcpy(&sample, bytes + y * raw.get_stride_in_bytes() + x * 2, 2);
|
||||
+ if (!sample) continue;
|
||||
+ const float z = static_cast<float>(sample * scale);
|
||||
+ if (z < .05f || z > 5.f) continue;
|
||||
+ const float pixel[2] = {static_cast<float>(x), static_cast<float>(y)};
|
||||
+ float pd[3], pc[3], uv[2];
|
||||
+ rs2_deproject_pixel_to_point(pd, &kd, pixel, z);
|
||||
+ rs2_transform_point_to_point(pc, &extrinsics, pd);
|
||||
+ if (!std::isfinite(pc[0]) || !std::isfinite(pc[1]) || !std::isfinite(pc[2]) || pc[2] <= 0) continue;
|
||||
+ rs2_project_point_to_pixel(uv, &kc, pc);
|
||||
+ if (!std::isfinite(uv[0]) || !std::isfinite(uv[1]) || uv[0] < 0 || uv[1] < 0
|
||||
+ || uv[0] > color.cols - 1 || uv[1] > color.rows - 1) continue;
|
||||
+ const int target_y=static_cast<int>(std::lround(uv[1])), target_x=static_cast<int>(std::lround(uv[0]));
|
||||
+ if (!valid_color.empty() && !valid_color.at<uint8_t>(target_y,target_x)) continue;
|
||||
+ float& stored = depth.at<float>(target_y,target_x);
|
||||
+ if (stored == 0 || pc[2] < stored) stored = pc[2];
|
||||
+ }
|
||||
+ intrinsics.fx = kc.fx; intrinsics.fy = kc.fy; intrinsics.cx = kc.ppx; intrinsics.cy = kc.ppy;
|
||||
+ for (int i = 0; i < 5; ++i) intrinsics.coeffs[i] = kc.model == RS2_DISTORTION_NONE ? 0.f : kc.coeffs[i];
|
||||
+ geometry.metres_per_unit = 1.;
|
||||
+ geometry.aligned_to_color = true; geometry.color_axial_z = true;
|
||||
+ geometry.distortion_model = kc.model == RS2_DISTORTION_NONE ? "none" : "brown_conrady";
|
||||
+}
|
||||
+
|
||||
void RealsenseCamera::getRGBImage(cv::Mat& color, Rs2Intrinsics& intrinsics) {
|
||||
intrinsics.cx = intrinsics_.ppx;
|
||||
intrinsics.cy = intrinsics_.ppy;
|
||||
@@ -727,6 +858,7 @@ rs2::frameset RealsenseCamera::get_frameset(bool align) {
|
||||
std::lock_guard<std::mutex> lock(frame_mtx_);
|
||||
constexpr unsigned int kWaitTimeoutMs = 300;
|
||||
rs2::frameset frames = pipe_.wait_for_frames(kWaitTimeoutMs);
|
||||
+ latest_metric_frames_ = frames;
|
||||
// 如果需要对齐,添加对齐逻辑
|
||||
if (align_ && align && stream_mode_ == RGBD_MODE) {
|
||||
frames = align_->process(frames);
|
||||
diff --git a/cmvr-es/service/grpc/src/grpc_camera_service.cpp b/cmvr-es/service/grpc/src/grpc_camera_service.cpp
|
||||
index d209fe13..1857fc1c 100644
|
||||
--- a/cmvr-es/service/grpc/src/grpc_camera_service.cpp
|
||||
+++ b/cmvr-es/service/grpc/src/grpc_camera_service.cpp
|
||||
@@ -320,7 +320,24 @@ grpc::Status gRPCCameraServiceImpl::GetRGBDImages(grpc::ServerContext* context,
|
||||
return failResponse(response, "Camera device not found: " + dev_id);
|
||||
}
|
||||
Rs2Intrinsics intrinsics = {0};
|
||||
- dev->getRGBDImages(color_image,depth_image, intrinsics);
|
||||
+ RgbdGeometry geometry;
|
||||
+ if (request->require_metric_depth())
|
||||
+ dev->getMetricRGBDImages(color_image, depth_image, intrinsics, geometry);
|
||||
+ else
|
||||
+ dev->getRGBDImages(color_image,depth_image, intrinsics);
|
||||
+ if (request->require_metric_depth()) {
|
||||
+ if (!geometry.aligned_to_color || !geometry.color_axial_z || geometry.metres_per_unit <= 0)
|
||||
+ return failResponse(response, "Camera driver does not provide metric RGB-aligned depth");
|
||||
+ response->mutable_depth_geometry()->set_metres_per_unit(geometry.metres_per_unit);
|
||||
+ response->mutable_depth_geometry()->set_aligned_to_color(geometry.aligned_to_color);
|
||||
+ response->mutable_depth_geometry()->set_color_axial_z(geometry.color_axial_z);
|
||||
+ const uint16_t endian_probe = 1;
|
||||
+ response->mutable_depth_geometry()->set_byte_order(
|
||||
+ *reinterpret_cast<const uint8_t*>(&endian_probe) == 1 ? "little" : "big");
|
||||
+ response->mutable_depth_geometry()->set_distortion_model(geometry.distortion_model);
|
||||
+ response->mutable_color_frame()->set_capture_utc_ns(geometry.color_capture_utc_ns);
|
||||
+ response->mutable_depth_frame()->set_capture_utc_ns(geometry.depth_capture_utc_ns);
|
||||
+ }
|
||||
if (color_image.empty()) {
|
||||
return failResponse(response, "Camera returned an empty RGB image: " + dev_id);
|
||||
}
|
||||
diff --git a/protos/cmvr/api/camera_command.proto b/protos/cmvr/api/camera_command.proto
|
||||
index 7305955a..276994ce 100644
|
||||
--- a/protos/cmvr/api/camera_command.proto
|
||||
+++ b/protos/cmvr/api/camera_command.proto
|
||||
@@ -107,6 +107,8 @@ message GetDepthImageCommand {
|
||||
message GetRGBDImagesCommand {
|
||||
message Request {
|
||||
CommandHeader.Request header = 1;
|
||||
+ // Opt-in metric snapshot; legacy requests retain their existing format.
|
||||
+ bool require_metric_depth = 2;
|
||||
}
|
||||
|
||||
message Feedback {
|
||||
@@ -114,9 +116,20 @@ message GetRGBDImagesCommand {
|
||||
FrameData color_frame = 2;
|
||||
FrameData depth_frame = 3;
|
||||
CameraIntrinsics intrinsics = 4;
|
||||
+ DepthGeometry depth_geometry = 5;
|
||||
}
|
||||
}
|
||||
|
||||
+// Raw little-endian depth samples, aligned to the accompanying native RGB.
|
||||
+// sample * metres_per_unit is RGB optical-axis Z (not range along the ray).
|
||||
+message DepthGeometry {
|
||||
+ double metres_per_unit = 1;
|
||||
+ bool aligned_to_color = 2;
|
||||
+ bool color_axial_z = 3;
|
||||
+ string byte_order = 4;
|
||||
+ string distortion_model = 5;
|
||||
+}
|
||||
+
|
||||
message StartCameraRecordingCommand {
|
||||
message Request {
|
||||
CommandHeader.Request header = 1;
|
||||
@ -37,6 +37,23 @@ message AgvNavigationStatusCommand {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 在当前活动地图中重新设置 AGV 定位位姿。
|
||||
message AgvRelocalizeCommand {
|
||||
message Request {
|
||||
// header.device_id 指定目标 AGV 设备。
|
||||
CommandHeader.Request header = 1;
|
||||
// x/y 单位:米,theta 单位:弧度,逆时针为正。
|
||||
cmvr.msgs.AgvPose2d pose = 2;
|
||||
}
|
||||
|
||||
message Feedback {
|
||||
// 成功仅表示控制器接受命令,不表示定位已经收敛。
|
||||
CommandHeader.Feedback header = 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 导航到指定地图位姿命令。
|
||||
message AgvNavigateToPoseCommand {
|
||||
// 请求体。
|
||||
@ -45,7 +62,7 @@ message AgvNavigateToPoseCommand {
|
||||
CommandHeader.Request header = 1;
|
||||
// 目标位姿。x/y 单位:米,theta 单位:弧度。
|
||||
cmvr.msgs.AgvPose2d pose = 2;
|
||||
// 通用运动约束和执行选项。
|
||||
// 通用运动约束和执行选项;默认同步阻塞至任务终态并确认停车。
|
||||
cmvr.msgs.AgvMotionOptions options = 3;
|
||||
// AGV 适配器扩展参数,用于传递厂商特有选项。
|
||||
cmvr.msgs.AgvAdapterParams adapter_params = 4;
|
||||
@ -65,7 +82,7 @@ message AgvNavigateToStationCommand {
|
||||
CommandHeader.Request header = 1;
|
||||
// 目标站点 id。
|
||||
string station_id = 2;
|
||||
// 通用运动约束和执行选项。
|
||||
// 通用运动约束和执行选项;默认同步阻塞至任务终态并确认停车。
|
||||
cmvr.msgs.AgvMotionOptions options = 3;
|
||||
// AGV 适配器扩展参数,用于传递厂商特有选项。
|
||||
cmvr.msgs.AgvAdapterParams adapter_params = 4;
|
||||
@ -85,7 +102,7 @@ message AgvFollowPathCommand {
|
||||
CommandHeader.Request header = 1;
|
||||
// 路径段列表。每段包含起点站点 id 和终点站点 id。
|
||||
repeated cmvr.msgs.AgvPathSegment path = 2;
|
||||
// 通用执行选项。上位机使用异步模式提交任务,并通过导航状态接口跟踪进度。
|
||||
// 通用执行选项;默认同步阻塞至整条路径终态并确认停车。
|
||||
cmvr.msgs.AgvMotionOptions options = 3;
|
||||
}
|
||||
// 反馈体。
|
||||
@ -95,6 +112,23 @@ message AgvFollowPathCommand {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 按指定速度执行固定距离平移命令。
|
||||
message AgvTranslateCommand {
|
||||
message Request {
|
||||
// 通用请求头。header.device_id 指定目标 AGV 设备。
|
||||
CommandHeader.Request header = 1;
|
||||
// 固定距离平移参数。
|
||||
cmvr.msgs.AgvTranslation translation = 2;
|
||||
}
|
||||
|
||||
message Feedback {
|
||||
// 仅表示控制器是否接受命令,不表示平移已经完成。
|
||||
CommandHeader.Feedback header = 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 下发底盘速度命令。
|
||||
message AgvSetVelocityCommand {
|
||||
// 请求体。
|
||||
|
||||
@ -20,6 +20,9 @@ service AgvService {
|
||||
// 清除可恢复故障或告警。
|
||||
rpc clearFault(CommandHeader.Request) returns (CommandHeader.Feedback);
|
||||
|
||||
// 在当前活动地图中重新设置定位位姿。调用前 AGV 必须已经停止。
|
||||
rpc relocalize(AgvRelocalizeCommand.Request)returns (AgvRelocalizeCommand.Feedback);
|
||||
|
||||
// 导航到指定地图位姿。目标位姿 x/y 单位为米,theta 单位为弧度。
|
||||
rpc navigateToPose(AgvNavigateToPoseCommand.Request) returns (AgvNavigateToPoseCommand.Feedback);
|
||||
|
||||
@ -69,4 +72,8 @@ service AgvService {
|
||||
|
||||
// 停止当前建图/扫图会话。
|
||||
rpc stopMapping(CommandHeader.Request) returns (CommandHeader.Feedback);
|
||||
|
||||
|
||||
// 按指定速度平移固定距离。成功返回仅表示控制器已接受命令。
|
||||
rpc translate(AgvTranslateCommand.Request) returns (AgvTranslateCommand.Feedback);
|
||||
}
|
||||
|
||||
@ -176,6 +176,7 @@ message JointState {
|
||||
repeated double velocity = 3;
|
||||
repeated double effort = 4;
|
||||
double timestamp = 5;
|
||||
repeated double current = 6; // Motor current in mA.
|
||||
}
|
||||
|
||||
message JointRequest {
|
||||
|
||||
@ -28,6 +28,10 @@ message FrameData {
|
||||
uint32 source_fps = 11;
|
||||
uint64 source_timestamp = 12;
|
||||
uint64 source_frame_number = 13;
|
||||
string camera_serial = 14;
|
||||
uint64 camera_session_generation = 15;
|
||||
string distortion_model = 16;
|
||||
int64 capture_earliest_utc_ns = 17;
|
||||
}
|
||||
|
||||
message CameraIntrinsics {
|
||||
@ -38,6 +42,22 @@ message CameraIntrinsics {
|
||||
repeated float coeffs = 5 [packed = true]; // 畸变系数(固定5个元素)
|
||||
}
|
||||
|
||||
message CameraCapabilities {
|
||||
uint32 version = 1;
|
||||
string driver = 2;
|
||||
string model = 3;
|
||||
string serial = 4;
|
||||
string transport = 5;
|
||||
bool raw_image = 6;
|
||||
bool valid_intrinsics = 7;
|
||||
bool capture_timestamp = 8;
|
||||
bool metric_aligned_depth = 9;
|
||||
string distortion_model = 10;
|
||||
uint64 session_generation = 11;
|
||||
string unavailable_reason = 12;
|
||||
string intrinsics_signature = 13;
|
||||
}
|
||||
|
||||
message CameraState {
|
||||
bool is_initialized = 1;
|
||||
bool is_opened = 2;
|
||||
@ -48,6 +68,8 @@ message CameraState {
|
||||
int32 fps = 7;
|
||||
int32 width = 8;
|
||||
int32 height = 9;
|
||||
string codec = 10;
|
||||
CameraCapabilities capabilities = 11;
|
||||
}
|
||||
|
||||
message GetCameraStateCommand {
|
||||
@ -107,6 +129,8 @@ message GetDepthImageCommand {
|
||||
message GetRGBDImagesCommand {
|
||||
message Request {
|
||||
CommandHeader.Request header = 1;
|
||||
// Opt-in metric snapshot; legacy requests retain their existing format.
|
||||
bool require_metric_depth = 2;
|
||||
}
|
||||
|
||||
message Feedback {
|
||||
@ -114,9 +138,20 @@ message GetRGBDImagesCommand {
|
||||
FrameData color_frame = 2;
|
||||
FrameData depth_frame = 3;
|
||||
CameraIntrinsics intrinsics = 4;
|
||||
DepthGeometry depth_geometry = 5;
|
||||
}
|
||||
}
|
||||
|
||||
// Raw little-endian depth samples, aligned to the accompanying native RGB.
|
||||
// sample * metres_per_unit is RGB optical-axis Z (not range along the ray).
|
||||
message DepthGeometry {
|
||||
double metres_per_unit = 1;
|
||||
bool aligned_to_color = 2;
|
||||
bool color_axial_z = 3;
|
||||
string byte_order = 4;
|
||||
string distortion_model = 5;
|
||||
}
|
||||
|
||||
message StartCameraRecordingCommand {
|
||||
message Request {
|
||||
CommandHeader.Request header = 1;
|
||||
|
||||
@ -58,6 +58,8 @@ message SensorData {
|
||||
message DexHandState {
|
||||
bool is_initialized = 1; // 是否初始化
|
||||
repeated FreedomState hands = 2; // 包含多个自由度状态
|
||||
bool has_tactile_feedback = 3; // 是否具备真实触觉传感器反馈能力
|
||||
string model = 4; // 设备型号,仅作为描述信息
|
||||
}
|
||||
|
||||
message GetDexHandStateCommand {
|
||||
|
||||
@ -116,6 +116,26 @@ message HikvisionCameraConfig {
|
||||
repeated float coeffs = 23;
|
||||
}
|
||||
|
||||
message MvsCameraConfig {
|
||||
string id = 1;
|
||||
string serial = 2;
|
||||
CameraCaptureConfig capture = 3;
|
||||
CameraEncoderConfig encoder = 4;
|
||||
float fx = 5;
|
||||
float fy = 6;
|
||||
float cx = 7;
|
||||
float cy = 8;
|
||||
repeated float coeffs = 9;
|
||||
int32 calibration_width = 10;
|
||||
int32 calibration_height = 11;
|
||||
}
|
||||
|
||||
message AutoCameraConfig {
|
||||
string id = 1;
|
||||
RealSenseCameraConfig realsense = 2;
|
||||
MvsCameraConfig mvs = 3;
|
||||
}
|
||||
|
||||
message CameraDeviceConfig {
|
||||
string id = 1;
|
||||
reserved 2;
|
||||
@ -126,6 +146,8 @@ message CameraDeviceConfig {
|
||||
MechMindCameraConfig mechmind = 12;
|
||||
MujocoCameraConfig mujoco = 13;
|
||||
HikvisionCameraConfig hikvision = 14;
|
||||
MvsCameraConfig mvs = 15;
|
||||
AutoCameraConfig auto_camera = 16;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -43,14 +43,25 @@ message ZeroSimTouchDexHand {
|
||||
string id = 1;
|
||||
}
|
||||
|
||||
message OYMotionAP001Config {
|
||||
string id = 1;
|
||||
string can_interface = 2;
|
||||
uint32 hand_id = 3;
|
||||
uint32 master_id = 4;
|
||||
uint32 command_timeout_ms = 5;
|
||||
}
|
||||
|
||||
message DexHandDeviceConfig {
|
||||
string id = 1;
|
||||
reserved 2;
|
||||
string model = 2;
|
||||
optional bool has_tactile_feedback = 3;
|
||||
|
||||
oneof backend {
|
||||
RH56DFTPDexHandConfig rh56dftp = 10;
|
||||
PX6AXGen3 px_6ax_gen3 = 11;
|
||||
ZeroSimTouchDexHand zero_sim_touch = 12;
|
||||
// Shared OYMotion backend for AP001, LiteS001 and compatible hands.
|
||||
OYMotionAP001Config oymotion_ap001 = 13;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,5 +1,7 @@
|
||||
syntax = "proto3";
|
||||
|
||||
// 文件随 AGV API 定义统一放在 cmvr/api 下,但保留 cmvr.msgs package,
|
||||
// 以兼容既有生成代码、消息完整名称和 Any type URL。
|
||||
package cmvr.msgs;
|
||||
|
||||
// AGV 在地图平面坐标系中的二维位姿。
|
||||
@ -12,6 +14,29 @@ message AgvPose2d {
|
||||
double theta = 3;
|
||||
}
|
||||
|
||||
// 固定距离平移使用的距离参考模式。
|
||||
enum AgvTranslationMode {
|
||||
// 根据底盘里程计算运动距离。
|
||||
AGV_TRANSLATION_MODE_ODOMETRY = 0;
|
||||
// 根据定位结果计算运动距离。
|
||||
AGV_TRANSLATION_MODE_LOCALIZATION = 1;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// AGV 车体坐标系下的固定距离平移参数。
|
||||
message AgvTranslation {
|
||||
// 平移距离的绝对值,单位:米,必须大于 0。
|
||||
double distance = 1;
|
||||
// 车体 X 方向速度,单位:米/秒;正为向前,负为向后。
|
||||
double vx = 2;
|
||||
// 车体 Y 方向速度,单位:米/秒;正为向左,负为向右。
|
||||
double vy = 3;
|
||||
// 距离参考模式;默认使用里程模式。
|
||||
AgvTranslationMode mode = 4;
|
||||
}
|
||||
|
||||
|
||||
// AGV 车体坐标系下的平面速度。
|
||||
message AgvVelocity {
|
||||
// 车体 X 方向线速度,单位:米/秒。
|
||||
@ -22,6 +47,9 @@ message AgvVelocity {
|
||||
double wz = 3;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
// AGV 电池状态。
|
||||
message AgvBatteryState {
|
||||
// 电量比例,范围:[0, 1],例如 0.8 表示 80%。
|
||||
@ -52,8 +80,17 @@ message AgvMotionOptions {
|
||||
double reach_angle = 6;
|
||||
// 速度比例,范围通常为 [0, 1];1 表示不降速。
|
||||
double speed_ratio = 7;
|
||||
// 是否异步执行;true 表示下发任务后立即返回。
|
||||
// 是否异步执行;false(默认)表示到达、失败、取消或遇障停止后才返回,
|
||||
// true 表示任务被控制器接受后立即返回。
|
||||
bool asynchronous = 8;
|
||||
// 同步导航的最大等待时间,单位:毫秒;0 表示使用适配器默认值。
|
||||
// gRPC deadline 应大于该值或预计行程时间,否则服务端会安全取消导航。
|
||||
int32 wait_timeout_ms = 9;
|
||||
// 同步导航的状态轮询周期,单位:毫秒;0 表示使用适配器默认值。
|
||||
int32 poll_interval_ms = 10;
|
||||
// 连续遇障且底盘停止时的最大等待时间,单位:毫秒;
|
||||
// 0 或未传表示使用适配器默认值 60000 毫秒。
|
||||
int32 blocked_timeout_ms = 11;
|
||||
}
|
||||
|
||||
// AGV 适配器扩展参数。用于传递厂商或控制器特有的参数。
|
||||
|
||||
181
resources/joint_programs.json
Normal file
181
resources/joint_programs.json
Normal file
@ -0,0 +1,181 @@
|
||||
{
|
||||
"activeGroup": "挥手",
|
||||
"groups": [
|
||||
{
|
||||
"flow": [
|
||||
],
|
||||
"moveJAcceleration": 0.1,
|
||||
"moveJVelocity": 0.1,
|
||||
"name": "默认组",
|
||||
"points": [
|
||||
]
|
||||
},
|
||||
{
|
||||
"flow": [
|
||||
{
|
||||
"collapsed": false,
|
||||
"id": "860308d9-f0fb-46f6-a0d3-30013b46827a",
|
||||
"intervalSeconds": 0.5,
|
||||
"loopCount": 1,
|
||||
"nodeName": "初始位置",
|
||||
"order": 0,
|
||||
"parentId": "",
|
||||
"pointName": "初始位置",
|
||||
"type": "single",
|
||||
"x": 40,
|
||||
"y": 40
|
||||
},
|
||||
{
|
||||
"collapsed": false,
|
||||
"id": "0ddff873-9e76-4635-917d-1d7357dddcc1",
|
||||
"intervalSeconds": 0.5,
|
||||
"loopCount": 3,
|
||||
"nodeName": "循环左右",
|
||||
"order": 1,
|
||||
"parentId": "",
|
||||
"pointName": "",
|
||||
"type": "loop",
|
||||
"x": 260,
|
||||
"y": 40
|
||||
},
|
||||
{
|
||||
"collapsed": false,
|
||||
"id": "c1a33717-b636-4eb4-80f4-91305edc64ff",
|
||||
"intervalSeconds": 0.5,
|
||||
"loopCount": 1,
|
||||
"nodeName": "挥手-右",
|
||||
"order": 0,
|
||||
"parentId": "0ddff873-9e76-4635-917d-1d7357dddcc1",
|
||||
"pointName": "挥手-右",
|
||||
"type": "single",
|
||||
"x": 40,
|
||||
"y": 140
|
||||
},
|
||||
{
|
||||
"collapsed": false,
|
||||
"id": "9851e4a8-91bd-4182-a5f5-cdd19180d0a3",
|
||||
"intervalSeconds": 0.5,
|
||||
"loopCount": 1,
|
||||
"nodeName": "挥手-左",
|
||||
"order": 1,
|
||||
"parentId": "0ddff873-9e76-4635-917d-1d7357dddcc1",
|
||||
"pointName": "挥手-左",
|
||||
"type": "single",
|
||||
"x": 260,
|
||||
"y": 140
|
||||
},
|
||||
{
|
||||
"collapsed": false,
|
||||
"id": "3b89feb6-c457-4a93-b81f-28e5b1423046",
|
||||
"intervalSeconds": 0.5,
|
||||
"loopCount": 1,
|
||||
"nodeName": "初始位置",
|
||||
"order": 2,
|
||||
"parentId": "",
|
||||
"pointName": "初始位置",
|
||||
"type": "single",
|
||||
"x": 480,
|
||||
"y": 40
|
||||
}
|
||||
],
|
||||
"moveJAcceleration": 1,
|
||||
"moveJVelocity": 1,
|
||||
"name": "挥手",
|
||||
"points": [
|
||||
{
|
||||
"deviceId": "right_ethercat_arm",
|
||||
"jointNames": [
|
||||
"right_arm_J1",
|
||||
"right_arm_J2",
|
||||
"right_arm_J3",
|
||||
"right_arm_J4",
|
||||
"right_arm_J5",
|
||||
"right_arm_J6",
|
||||
"right_arm_J7"
|
||||
],
|
||||
"name": "零位",
|
||||
"positions": [
|
||||
-9.492455370579462e-07,
|
||||
0,
|
||||
-9.492455370579462e-07,
|
||||
0,
|
||||
0,
|
||||
-9.492455370579462e-07,
|
||||
-9.492455370579462e-07
|
||||
],
|
||||
"side": "right"
|
||||
},
|
||||
{
|
||||
"deviceId": "right_ethercat_arm",
|
||||
"jointNames": [
|
||||
"right_arm_J1",
|
||||
"right_arm_J2",
|
||||
"right_arm_J3",
|
||||
"right_arm_J4",
|
||||
"right_arm_J5",
|
||||
"right_arm_J6",
|
||||
"right_arm_J7"
|
||||
],
|
||||
"name": "初始位置",
|
||||
"positions": [
|
||||
0.014501624069634246,
|
||||
-1.4912457538072925,
|
||||
-1.2003475604848106,
|
||||
-0.02585080371069905,
|
||||
-0.07927434253632026,
|
||||
-0.06444807649301221,
|
||||
-0.11000426830749717
|
||||
],
|
||||
"side": "right"
|
||||
},
|
||||
{
|
||||
"deviceId": "right_ethercat_arm",
|
||||
"jointNames": [
|
||||
"right_arm_J1",
|
||||
"right_arm_J2",
|
||||
"right_arm_J3",
|
||||
"right_arm_J4",
|
||||
"right_arm_J5",
|
||||
"right_arm_J6",
|
||||
"right_arm_J7"
|
||||
],
|
||||
"name": "挥手-右",
|
||||
"positions": [
|
||||
0.742245461282794,
|
||||
-1.490991356003361,
|
||||
-1.3799808874265822,
|
||||
1.543379267948052,
|
||||
0.14546428458983382,
|
||||
-0.06442149761797458,
|
||||
-0.4555106588858484
|
||||
],
|
||||
"side": "right"
|
||||
},
|
||||
{
|
||||
"deviceId": "right_ethercat_arm",
|
||||
"jointNames": [
|
||||
"right_arm_J1",
|
||||
"right_arm_J2",
|
||||
"right_arm_J3",
|
||||
"right_arm_J4",
|
||||
"right_arm_J5",
|
||||
"right_arm_J6",
|
||||
"right_arm_J7"
|
||||
],
|
||||
"name": "挥手-左",
|
||||
"positions": [
|
||||
0.9055916332997255,
|
||||
-1.4894905988092724,
|
||||
-1.8256241389547136,
|
||||
1.5302806287821893,
|
||||
0.019423462179279694,
|
||||
-0.06441770063582634,
|
||||
-0.4553255560061222
|
||||
],
|
||||
"side": "right"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"version": 1
|
||||
}
|
||||
458
scripts/handeye_math.py
Normal file
458
scripts/handeye_math.py
Normal file
@ -0,0 +1,458 @@
|
||||
"""Numerical hand-eye algorithms migrated from phone/scripts/handeye_calibration_gui.py.
|
||||
|
||||
Provenance: rotation angle 132-134, pose conversion 167-171, planar/IPPE
|
||||
and ChArUco 174-266, AX=XB, robust MAD, and cross validation 269-592
|
||||
(source snapshot 2026-09-30). Functions retain the upstream frame convention:
|
||||
T_parent_child maps child coordinates into parent coordinates, metres.
|
||||
No runtime dependency on the original GUI or phone project.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import math
|
||||
from typing import Any
|
||||
import cv2
|
||||
import numpy as np
|
||||
AUTO_SOLVER_LABEL = "auto"
|
||||
HAND_EYE_SOLVER_METHODS = {
|
||||
"TsaiLenz1989": cv2.CALIB_HAND_EYE_TSAI,
|
||||
"ParkBryan1994": cv2.CALIB_HAND_EYE_PARK,
|
||||
"HoraudDornaika1995": cv2.CALIB_HAND_EYE_HORAUD,
|
||||
"AndreffHoraudEspiau1999": cv2.CALIB_HAND_EYE_ANDREFF,
|
||||
"Daniilidis1999": cv2.CALIB_HAND_EYE_DANIILIDIS,
|
||||
}
|
||||
HAND_EYE_CHARACTERISTIC_LENGTH_M = .20
|
||||
HAND_EYE_OUTLIER_TRANSLATION_FLOOR_M = .002
|
||||
HAND_EYE_OUTLIER_ROTATION_FLOOR_RAD = math.radians(.35)
|
||||
|
||||
|
||||
# Upstream handeye_calibration_gui.py:132-134
|
||||
def rotation_angle_degrees(R: np.ndarray) -> float:
|
||||
trace = float(np.clip((np.trace(np.asarray(R, dtype=float)) - 1.0) / 2.0, -1.0, 1.0))
|
||||
return math.degrees(math.acos(trace))
|
||||
|
||||
# Upstream handeye_calibration_gui.py:167-171
|
||||
def rvec_tvec_to_matrix(rvec: np.ndarray, tvec: np.ndarray) -> np.ndarray:
|
||||
out = np.eye(4, dtype=np.float64)
|
||||
out[:3, :3] = cv2.Rodrigues(np.asarray(rvec, dtype=np.float64).reshape(3, 1))[0]
|
||||
out[:3, 3] = np.asarray(tvec, dtype=np.float64).reshape(3)
|
||||
return out
|
||||
|
||||
# Upstream handeye_calibration_gui.py:174-247
|
||||
def estimate_planar_pose(
|
||||
object_points: np.ndarray,
|
||||
image_points: np.ndarray,
|
||||
camera_matrix: np.ndarray,
|
||||
dist_coeffs: np.ndarray,
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Estimate a planar target pose with IPPE candidates and LM refinement.
|
||||
|
||||
IPPE explicitly handles the two-solution ambiguity of a planar target. The
|
||||
physically valid solution with the smallest reprojection error is refined
|
||||
by Levenberg-Marquardt. ITERATIVE remains as a compatibility fallback.
|
||||
"""
|
||||
obj = np.asarray(object_points, dtype=np.float64).reshape(-1, 3)
|
||||
img = np.asarray(image_points, dtype=np.float64).reshape(-1, 2)
|
||||
if len(obj) < 4 or len(obj) != len(img):
|
||||
raise ValueError("平面目标至少需要 4 个有效的二维-三维对应点")
|
||||
|
||||
candidates: list[tuple[np.ndarray, np.ndarray]] = []
|
||||
if hasattr(cv2, "solvePnPGeneric") and hasattr(cv2, "SOLVEPNP_IPPE"):
|
||||
try:
|
||||
result = cv2.solvePnPGeneric(
|
||||
obj,
|
||||
img,
|
||||
camera_matrix,
|
||||
dist_coeffs,
|
||||
flags=cv2.SOLVEPNP_IPPE,
|
||||
)
|
||||
if result and bool(result[0]):
|
||||
candidates.extend(
|
||||
(np.asarray(rvec, dtype=np.float64).reshape(3, 1),
|
||||
np.asarray(tvec, dtype=np.float64).reshape(3, 1))
|
||||
for rvec, tvec in zip(result[1], result[2])
|
||||
)
|
||||
except cv2.error:
|
||||
candidates.clear()
|
||||
|
||||
if not candidates:
|
||||
ok, rvec, tvec = cv2.solvePnP(
|
||||
obj,
|
||||
img,
|
||||
camera_matrix,
|
||||
dist_coeffs,
|
||||
flags=cv2.SOLVEPNP_ITERATIVE,
|
||||
)
|
||||
if not ok:
|
||||
raise ValueError("无法估计平面目标位姿")
|
||||
candidates.append((rvec, tvec))
|
||||
|
||||
ranked: list[tuple[float, np.ndarray, np.ndarray]] = []
|
||||
for rvec, tvec in candidates:
|
||||
try:
|
||||
if hasattr(cv2, "solvePnPRefineLM"):
|
||||
rvec, tvec = cv2.solvePnPRefineLM(
|
||||
obj,
|
||||
img,
|
||||
camera_matrix,
|
||||
dist_coeffs,
|
||||
rvec,
|
||||
tvec,
|
||||
)
|
||||
rotation = cv2.Rodrigues(np.asarray(rvec, dtype=np.float64).reshape(3, 1))[0]
|
||||
camera_points = (rotation @ obj.T).T + np.asarray(tvec, dtype=np.float64).reshape(1, 3)
|
||||
if not np.all(np.isfinite(camera_points)) or np.min(camera_points[:, 2]) <= 0:
|
||||
continue
|
||||
projected = cv2.projectPoints(obj, rvec, tvec, camera_matrix, dist_coeffs)[0].reshape(-1, 2)
|
||||
error = float(np.sqrt(np.mean(np.sum(np.square(projected - img), axis=1))))
|
||||
if math.isfinite(error):
|
||||
ranked.append((error, np.asarray(rvec, dtype=np.float64), np.asarray(tvec, dtype=np.float64)))
|
||||
except cv2.error:
|
||||
continue
|
||||
if not ranked:
|
||||
raise ValueError("平面目标 PnP 候选解均不满足正深度约束")
|
||||
_, best_rvec, best_tvec = min(ranked, key=lambda item: item[0])
|
||||
return best_rvec.reshape(3, 1), best_tvec.reshape(3, 1)
|
||||
|
||||
# Upstream handeye_calibration_gui.py:250-266
|
||||
def estimate_charuco_pose(
|
||||
board: Any,
|
||||
corners: np.ndarray,
|
||||
ids: np.ndarray,
|
||||
camera_matrix: np.ndarray,
|
||||
dist_coeffs: np.ndarray,
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Estimate ``T_camera_target`` from the detected ChArUco corners."""
|
||||
detected_corners = np.asarray(corners, dtype=np.float32).reshape(-1, 1, 2)
|
||||
detected_ids = np.asarray(ids, dtype=np.int32).reshape(-1, 1)
|
||||
object_points, image_points = board.matchImagePoints(detected_corners, detected_ids)
|
||||
if object_points is None or image_points is None or len(object_points) < 4:
|
||||
raise ValueError("有效 ChArUco 角点不足,至少需要 4 个对应点")
|
||||
rvec, tvec = estimate_planar_pose(object_points, image_points, camera_matrix, dist_coeffs)
|
||||
if not np.all(np.isfinite(rvec)) or not np.all(np.isfinite(tvec)):
|
||||
raise ValueError("无法从 ChArUco 角点估计 camera→target 位姿")
|
||||
return rvec, tvec
|
||||
|
||||
# Upstream handeye_calibration_gui.py:269-286
|
||||
def ax_xb_motion(
|
||||
robot_poses: list[np.ndarray],
|
||||
target_poses: list[np.ndarray],
|
||||
first: int,
|
||||
second: int,
|
||||
eye_in_hand: bool,
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Return the OpenCV/MoveIt motion pair satisfying ``A X = X B``."""
|
||||
base_to_eef_i, base_to_eef_j = robot_poses[first], robot_poses[second]
|
||||
if eye_in_hand:
|
||||
# (T_base_eef[j])^-1 T_base_eef[i] X = X T_cam_target[j] (T_cam_target[i])^-1
|
||||
A = np.linalg.inv(base_to_eef_j) @ base_to_eef_i
|
||||
else:
|
||||
# OpenCV's eye-to-hand form uses T_eef_base = (T_base_eef)^-1.
|
||||
# Its returned X is then T_base_camera.
|
||||
A = base_to_eef_j @ np.linalg.inv(base_to_eef_i)
|
||||
B = target_poses[second] @ np.linalg.inv(target_poses[first])
|
||||
return A, B
|
||||
|
||||
# Upstream handeye_calibration_gui.py:289-311
|
||||
def solve_handeye_matrix(
|
||||
robot_poses: list[np.ndarray],
|
||||
target_poses: list[np.ndarray],
|
||||
eye_in_hand: bool,
|
||||
method: int,
|
||||
) -> np.ndarray:
|
||||
"""Run one OpenCV hand-eye solver and validate its SE(3) result."""
|
||||
if len(robot_poses) != len(target_poses) or len(robot_poses) < 5:
|
||||
raise ValueError("手眼标定至少需要 5 组配对位姿")
|
||||
inputs = robot_poses if eye_in_hand else [np.linalg.inv(pose) for pose in robot_poses]
|
||||
rotation, translation = cv2.calibrateHandEye(
|
||||
[pose[:3, :3] for pose in inputs],
|
||||
[pose[:3, 3].reshape(3, 1) for pose in inputs],
|
||||
[pose[:3, :3] for pose in target_poses],
|
||||
[pose[:3, 3].reshape(3, 1) for pose in target_poses],
|
||||
method=method,
|
||||
)
|
||||
solution = np.eye(4, dtype=np.float64)
|
||||
solution[:3, :3] = np.asarray(rotation, dtype=np.float64).reshape(3, 3)
|
||||
solution[:3, 3] = np.asarray(translation, dtype=np.float64).reshape(3)
|
||||
if not np.all(np.isfinite(solution)) or abs(np.linalg.det(solution[:3, :3]) - 1.0) > 1e-3:
|
||||
raise ValueError("求解器返回了无效的刚体变换")
|
||||
return solution
|
||||
|
||||
# Upstream handeye_calibration_gui.py:314-319
|
||||
def _rotation_mean(rotations: list[np.ndarray]) -> np.ndarray:
|
||||
accumulator = np.sum(np.asarray(rotations, dtype=np.float64), axis=0)
|
||||
left, _, right_t = np.linalg.svd(accumulator)
|
||||
correction = np.eye(3)
|
||||
correction[2, 2] = np.linalg.det(left @ right_t)
|
||||
return left @ correction @ right_t
|
||||
|
||||
# Upstream handeye_calibration_gui.py:322-361
|
||||
def fixed_target_consistency(
|
||||
robot_poses: list[np.ndarray],
|
||||
target_poses: list[np.ndarray],
|
||||
solution: np.ndarray,
|
||||
eye_in_hand: bool,
|
||||
) -> dict[str, Any]:
|
||||
"""Measure how constant the physically fixed target/tool transform remains."""
|
||||
fixed_poses = []
|
||||
for robot_pose, target_pose in zip(robot_poses, target_poses):
|
||||
if eye_in_hand:
|
||||
fixed_poses.append(robot_pose @ solution @ target_pose)
|
||||
else:
|
||||
fixed_poses.append(np.linalg.inv(robot_pose) @ solution @ target_pose)
|
||||
center_translation = np.median(np.asarray([pose[:3, 3] for pose in fixed_poses]), axis=0)
|
||||
center_rotation = _rotation_mean([pose[:3, :3] for pose in fixed_poses])
|
||||
translation_errors = np.asarray(
|
||||
[np.linalg.norm(pose[:3, 3] - center_translation) for pose in fixed_poses],
|
||||
dtype=np.float64,
|
||||
)
|
||||
rotation_errors = np.asarray(
|
||||
[math.radians(rotation_angle_degrees(center_rotation.T @ pose[:3, :3])) for pose in fixed_poses],
|
||||
dtype=np.float64,
|
||||
)
|
||||
trans_p95 = float(np.percentile(translation_errors, 95))
|
||||
rot_p95 = float(np.percentile(rotation_errors, 95))
|
||||
# Convert angular scatter to an equivalent displacement at a 20 cm lever arm.
|
||||
score_m = trans_p95 + HAND_EYE_CHARACTERISTIC_LENGTH_M * rot_p95
|
||||
return {
|
||||
"translation_errors_m": translation_errors,
|
||||
"rotation_errors_rad": rotation_errors,
|
||||
"translation_median_m": float(np.median(translation_errors)),
|
||||
"translation_rms_m": float(np.sqrt(np.mean(np.square(translation_errors)))),
|
||||
"translation_p95_m": trans_p95,
|
||||
"translation_max_m": float(np.max(translation_errors)),
|
||||
"rotation_median_rad": float(np.median(rotation_errors)),
|
||||
"rotation_rms_rad": float(np.sqrt(np.mean(np.square(rotation_errors)))),
|
||||
"rotation_p95_rad": rot_p95,
|
||||
"rotation_max_rad": float(np.max(rotation_errors)),
|
||||
"score_m": float(score_m),
|
||||
}
|
||||
|
||||
# Upstream handeye_calibration_gui.py:364-389
|
||||
def ax_xb_all_pair_metrics(
|
||||
robot_poses: list[np.ndarray],
|
||||
target_poses: list[np.ndarray],
|
||||
solution: np.ndarray,
|
||||
eye_in_hand: bool,
|
||||
) -> dict[str, float]:
|
||||
"""Evaluate AX=XB on all pose pairs so metrics do not depend on capture order."""
|
||||
translations: list[float] = []
|
||||
rotations: list[float] = []
|
||||
for first in range(len(robot_poses) - 1):
|
||||
for second in range(first + 1, len(robot_poses)):
|
||||
A, B = ax_xb_motion(robot_poses, target_poses, first, second, eye_in_hand)
|
||||
residual = np.linalg.inv(A @ solution) @ (solution @ B)
|
||||
translations.append(float(np.linalg.norm(residual[:3, 3])))
|
||||
rotations.append(math.radians(rotation_angle_degrees(residual[:3, :3])))
|
||||
return {
|
||||
"pair_count": len(translations),
|
||||
"translation_rms_m": float(np.sqrt(np.mean(np.square(translations)))),
|
||||
"translation_median_m": float(np.median(translations)),
|
||||
"translation_p95_m": float(np.percentile(translations, 95)),
|
||||
"translation_max_m": float(np.max(translations)),
|
||||
"rotation_rms_rad": float(np.sqrt(np.mean(np.square(rotations)))),
|
||||
"rotation_median_rad": float(np.median(rotations)),
|
||||
"rotation_p95_rad": float(np.percentile(rotations, 95)),
|
||||
"rotation_max_rad": float(np.max(rotations)),
|
||||
}
|
||||
|
||||
# Upstream handeye_calibration_gui.py:392-407
|
||||
def dominant_rotation_axes(robot_poses: list[np.ndarray]) -> set[int]:
|
||||
"""Return the base-frame axes covered by meaningful relative rotations."""
|
||||
axes: set[int] = set()
|
||||
for first in range(len(robot_poses) - 1):
|
||||
for second in range(first + 1, len(robot_poses)):
|
||||
relative = np.linalg.inv(robot_poses[first]) @ robot_poses[second]
|
||||
if rotation_angle_degrees(relative[:3, :3]) < 3.0:
|
||||
continue
|
||||
rotvec = cv2.Rodrigues(relative[:3, :3])[0].reshape(3)
|
||||
norm = float(np.linalg.norm(rotvec))
|
||||
if norm <= 1e-9:
|
||||
continue
|
||||
axis = np.abs(rotvec / norm)
|
||||
if float(np.max(axis)) > 0.70:
|
||||
axes.add(int(np.argmax(axis)))
|
||||
return axes
|
||||
|
||||
# Upstream handeye_calibration_gui.py:410-418
|
||||
def _fixed_pose(
|
||||
robot_pose: np.ndarray,
|
||||
target_pose: np.ndarray,
|
||||
solution: np.ndarray,
|
||||
eye_in_hand: bool,
|
||||
) -> np.ndarray:
|
||||
if eye_in_hand:
|
||||
return robot_pose @ solution @ target_pose
|
||||
return np.linalg.inv(robot_pose) @ solution @ target_pose
|
||||
|
||||
# Upstream handeye_calibration_gui.py:421-424
|
||||
def _pose_center(poses: list[np.ndarray]) -> tuple[np.ndarray, np.ndarray]:
|
||||
translation = np.median(np.asarray([pose[:3, 3] for pose in poses]), axis=0)
|
||||
rotation = _rotation_mean([pose[:3, :3] for pose in poses])
|
||||
return rotation, translation
|
||||
|
||||
# Upstream handeye_calibration_gui.py:427-478
|
||||
def leave_one_out_handeye_metrics(
|
||||
robot_poses: list[np.ndarray],
|
||||
target_poses: list[np.ndarray],
|
||||
eye_in_hand: bool,
|
||||
method: int,
|
||||
) -> dict[str, float]:
|
||||
"""Evaluate a solver on poses excluded from each individual fit."""
|
||||
translation_errors: list[float] = []
|
||||
rotation_errors: list[float] = []
|
||||
for held_out in range(len(robot_poses)):
|
||||
train_ids = [index for index in range(len(robot_poses)) if index != held_out]
|
||||
if len(train_ids) < 5:
|
||||
continue
|
||||
train_robot = [robot_poses[index] for index in train_ids]
|
||||
train_target = [target_poses[index] for index in train_ids]
|
||||
try:
|
||||
solution = solve_handeye_matrix(train_robot, train_target, eye_in_hand, method)
|
||||
except (ValueError, cv2.error, np.linalg.LinAlgError):
|
||||
continue
|
||||
train_fixed = [
|
||||
_fixed_pose(robot_pose, target_pose, solution, eye_in_hand)
|
||||
for robot_pose, target_pose in zip(train_robot, train_target)
|
||||
]
|
||||
center_rotation, center_translation = _pose_center(train_fixed)
|
||||
test_fixed = _fixed_pose(
|
||||
robot_poses[held_out],
|
||||
target_poses[held_out],
|
||||
solution,
|
||||
eye_in_hand,
|
||||
)
|
||||
translation_errors.append(float(np.linalg.norm(test_fixed[:3, 3] - center_translation)))
|
||||
rotation_errors.append(
|
||||
math.radians(rotation_angle_degrees(center_rotation.T @ test_fixed[:3, :3]))
|
||||
)
|
||||
if not translation_errors:
|
||||
raise ValueError("留一验证没有得到有效结果")
|
||||
trans = np.asarray(translation_errors, dtype=np.float64)
|
||||
rot = np.asarray(rotation_errors, dtype=np.float64)
|
||||
trans_p95 = float(np.percentile(trans, 95))
|
||||
rot_p95 = float(np.percentile(rot, 95))
|
||||
return {
|
||||
"sample_count": len(translation_errors),
|
||||
"translation_median_m": float(np.median(trans)),
|
||||
"translation_rms_m": float(np.sqrt(np.mean(np.square(trans)))),
|
||||
"translation_p95_m": trans_p95,
|
||||
"translation_max_m": float(np.max(trans)),
|
||||
"rotation_median_rad": float(np.median(rot)),
|
||||
"rotation_rms_rad": float(np.sqrt(np.mean(np.square(rot)))),
|
||||
"rotation_p95_rad": rot_p95,
|
||||
"rotation_max_rad": float(np.max(rot)),
|
||||
"score_m": trans_p95 + HAND_EYE_CHARACTERISTIC_LENGTH_M * rot_p95,
|
||||
}
|
||||
|
||||
# Upstream handeye_calibration_gui.py:481-592
|
||||
def robust_handeye_calibration(
|
||||
robot_poses: list[np.ndarray],
|
||||
target_poses: list[np.ndarray],
|
||||
eye_in_hand: bool,
|
||||
requested_solver: str = AUTO_SOLVER_LABEL,
|
||||
) -> dict[str, Any]:
|
||||
"""Reject transform outliers, compare solvers and return the best solution."""
|
||||
if len(robot_poses) != len(target_poses) or len(robot_poses) < 5:
|
||||
raise ValueError("手眼标定至少需要 5 组配对位姿")
|
||||
active = list(range(len(robot_poses)))
|
||||
rejected: list[dict[str, Any]] = []
|
||||
maximum_rejections = min(4, max(0, len(active) // 5), max(0, len(active) - 6))
|
||||
|
||||
# Remove at most one sample per iteration and recompute the solution. This
|
||||
# avoids a single bad pose shifting the robust center enough to hide itself.
|
||||
while len(rejected) < maximum_rejections and len(active) > 6:
|
||||
active_robot = [robot_poses[index] for index in active]
|
||||
active_target = [target_poses[index] for index in active]
|
||||
candidates: list[tuple[float, str, np.ndarray, dict[str, Any]]] = []
|
||||
method_items = HAND_EYE_SOLVER_METHODS.items()
|
||||
if requested_solver in HAND_EYE_SOLVER_METHODS:
|
||||
method_items = [(requested_solver, HAND_EYE_SOLVER_METHODS[requested_solver])]
|
||||
for name, method in method_items:
|
||||
try:
|
||||
solution = solve_handeye_matrix(active_robot, active_target, eye_in_hand, method)
|
||||
consistency = fixed_target_consistency(active_robot, active_target, solution, eye_in_hand)
|
||||
candidates.append((consistency["score_m"], name, solution, consistency))
|
||||
except (ValueError, cv2.error, np.linalg.LinAlgError):
|
||||
continue
|
||||
if not candidates:
|
||||
raise ValueError("全部手眼求解器均失败,请增加姿态变化后重新采集")
|
||||
_, provisional_name, _, consistency = min(candidates, key=lambda item: item[0])
|
||||
trans = consistency["translation_errors_m"]
|
||||
rot = consistency["rotation_errors_rad"]
|
||||
trans_median = float(np.median(trans))
|
||||
rot_median = float(np.median(rot))
|
||||
trans_mad = float(np.median(np.abs(trans - trans_median)))
|
||||
rot_mad = float(np.median(np.abs(rot - rot_median)))
|
||||
trans_limit = max(
|
||||
HAND_EYE_OUTLIER_TRANSLATION_FLOOR_M,
|
||||
trans_median + 3.5 * 1.4826 * trans_mad,
|
||||
)
|
||||
rot_limit = max(
|
||||
HAND_EYE_OUTLIER_ROTATION_FLOOR_RAD,
|
||||
rot_median + 3.5 * 1.4826 * rot_mad,
|
||||
)
|
||||
severities = np.maximum(trans / trans_limit, rot / rot_limit)
|
||||
worst_local = int(np.argmax(severities))
|
||||
if float(severities[worst_local]) <= 1.0:
|
||||
break
|
||||
rejected.append({
|
||||
"input_index": int(active[worst_local]),
|
||||
"translation_error_m": float(trans[worst_local]),
|
||||
"rotation_error_rad": float(rot[worst_local]),
|
||||
"translation_limit_m": trans_limit,
|
||||
"rotation_limit_rad": rot_limit,
|
||||
"provisional_solver": provisional_name,
|
||||
})
|
||||
del active[worst_local]
|
||||
|
||||
active_robot = [robot_poses[index] for index in active]
|
||||
active_target = [target_poses[index] for index in active]
|
||||
reports: dict[str, dict[str, Any]] = {}
|
||||
solved: dict[str, np.ndarray] = {}
|
||||
for name, method in HAND_EYE_SOLVER_METHODS.items():
|
||||
try:
|
||||
solution = solve_handeye_matrix(active_robot, active_target, eye_in_hand, method)
|
||||
consistency = fixed_target_consistency(active_robot, active_target, solution, eye_in_hand)
|
||||
in_sample = {
|
||||
key: value for key, value in consistency.items()
|
||||
if key not in {"translation_errors_m", "rotation_errors_rad"}
|
||||
}
|
||||
try:
|
||||
cross_validation = leave_one_out_handeye_metrics(
|
||||
active_robot,
|
||||
active_target,
|
||||
eye_in_hand,
|
||||
method,
|
||||
)
|
||||
except (ValueError, cv2.error, np.linalg.LinAlgError):
|
||||
cross_validation = None
|
||||
reports[name] = {
|
||||
"status": "ok",
|
||||
"in_sample": in_sample,
|
||||
"leave_one_out": cross_validation,
|
||||
}
|
||||
solved[name] = solution
|
||||
except (ValueError, cv2.error, np.linalg.LinAlgError) as exc:
|
||||
reports[name] = {"status": "failed", "error": str(exc)}
|
||||
|
||||
available = [name for name in HAND_EYE_SOLVER_METHODS if name in solved]
|
||||
if not available:
|
||||
raise ValueError("异常样本筛选后全部手眼求解器均失败")
|
||||
if requested_solver in solved:
|
||||
selected_name = requested_solver
|
||||
else:
|
||||
def solver_rank(name: str) -> float:
|
||||
validation = reports[name].get("leave_one_out")
|
||||
if validation is not None:
|
||||
return float(validation["score_m"])
|
||||
return float(reports[name]["in_sample"]["score_m"])
|
||||
selected_name = min(available, key=solver_rank)
|
||||
solution = solved[selected_name]
|
||||
return {
|
||||
"solution": solution,
|
||||
"selected_solver": selected_name,
|
||||
"active_indices": active,
|
||||
"rejected": rejected,
|
||||
"solver_reports": reports,
|
||||
"consistency": fixed_target_consistency(active_robot, active_target, solution, eye_in_hand),
|
||||
"pair_metrics": ax_xb_all_pair_metrics(active_robot, active_target, solution, eye_in_hand),
|
||||
}
|
||||
324
scripts/handeye_refinement.py
Normal file
324
scripts/handeye_refinement.py
Normal file
@ -0,0 +1,324 @@
|
||||
"""Joint robot-world/hand-eye pixel refinement (new extension, not a phone port).
|
||||
|
||||
Related formulation: Tabb and Ahmad Yousef (2017), 'Solving the robot-world,
|
||||
hand-eye(s) calibration problem with iterative methods', reprojection class:
|
||||
https://doi.org/10.1007/s00138-017-0841-7 ; author manuscript with erratum:
|
||||
https://arxiv.org/abs/1907.12425 . This is an independent NumPy/OpenCV LM
|
||||
implementation, with fixed intrinsics, distortion and robot poses.
|
||||
|
||||
Column-vector T_parent_child matrices use metres. X is flange<-camera for
|
||||
eye-in-hand, base<-camera otherwise. Y is base<-target / flange<-target.
|
||||
Predicted camera<-target is inv(X) inv(G) Y / inv(X) G Y, respectively.
|
||||
All RMS values are sqrt(mean(||pixel residual||^2)), including outliers.
|
||||
Acceptance is a pixel consistency gate, never a hardware/mm accuracy claim.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from typing import Any
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
from handeye_math import solve_handeye_matrix
|
||||
|
||||
HUBER_PX = 1.5
|
||||
MAX_ITERATIONS = 80
|
||||
MAX_CONDITION = 1e6
|
||||
MAX_POINTS_PER_FRAME = 10000
|
||||
MAX_TOTAL_POINTS = 100000
|
||||
PARAMETER_SCALE = np.tile([1., 1., 1., .2, .2, .2], 2)
|
||||
|
||||
|
||||
def _array(value, shape, name):
|
||||
try:
|
||||
result = np.asarray(value, dtype=np.float64)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError(f'{name}: expected finite numeric array') from exc
|
||||
if result.size != math.prod(shape) or not np.all(np.isfinite(result)):
|
||||
raise ValueError(f'{name}: expected {math.prod(shape)} finite numbers')
|
||||
return result.reshape(shape)
|
||||
|
||||
|
||||
def _matrix(value, name):
|
||||
matrix = _array(value, (4, 4), name)
|
||||
r = matrix[:3, :3]
|
||||
if (not np.allclose(matrix[3], [0, 0, 0, 1], atol=1e-8, rtol=0)
|
||||
or not np.allclose(r.T @ r, np.eye(3), atol=1e-5, rtol=0)
|
||||
or abs(np.linalg.det(r)-1.) > 1e-5):
|
||||
raise ValueError(f'{name}: expected a proper SE(3) transform')
|
||||
return matrix.copy()
|
||||
|
||||
|
||||
def _inverse(t):
|
||||
result = np.eye(4)
|
||||
result[:3, :3] = t[:3, :3].T
|
||||
result[:3, 3] = -result[:3, :3] @ t[:3, 3]
|
||||
return result
|
||||
|
||||
|
||||
def _skew(points):
|
||||
p = np.asarray(points).reshape(-1, 3)
|
||||
result = np.zeros((len(p), 3, 3))
|
||||
result[:, 0, 1], result[:, 0, 2] = -p[:, 2], p[:, 1]
|
||||
result[:, 1, 0], result[:, 1, 2] = p[:, 2], -p[:, 0]
|
||||
result[:, 2, 0], result[:, 2, 1] = -p[:, 1], p[:, 0]
|
||||
return result
|
||||
|
||||
|
||||
def _increment(t, delta):
|
||||
"""Right multiplication by the SE(3) exponential; twist = [omega, v]."""
|
||||
omega, velocity = delta[:3], delta[3:]
|
||||
theta = float(np.linalg.norm(omega))
|
||||
w = _skew(omega)[0]
|
||||
if theta < 1e-6:
|
||||
a, b = .5-theta**2/24., 1./6.-theta**2/120.
|
||||
else:
|
||||
a, b = (1.-math.cos(theta))/theta**2, (theta-math.sin(theta))/theta**3
|
||||
exp = np.eye(4)
|
||||
exp[:3, :3] = cv2.Rodrigues(omega)[0]
|
||||
exp[:3, 3] = (np.eye(3)+a*w+b*w@w) @ velocity
|
||||
return t @ exp
|
||||
|
||||
|
||||
def _validated(robot_poses, observations, initial_matrix, eye_in_hand):
|
||||
if not isinstance(eye_in_hand, (bool, np.bool_)):
|
||||
raise ValueError('eye_in_hand must be boolean')
|
||||
if not isinstance(observations, (list, tuple)) or not 6 <= len(observations) <= 100:
|
||||
raise ValueError('Joint refinement requires 6..100 observations')
|
||||
if not isinstance(robot_poses, (list, tuple, np.ndarray)) or len(robot_poses) != len(observations):
|
||||
raise ValueError('Robot poses and observations must be paired')
|
||||
x = _matrix(initial_matrix, 'initial_matrix')
|
||||
robots, data, total = [], [], 0
|
||||
id_coordinates = {}
|
||||
for i, (pose, obs) in enumerate(zip(robot_poses, observations)):
|
||||
try:
|
||||
g = _matrix(pose, f'robot[{i}]')
|
||||
c = _matrix(obs['T_camera_target'], f'observation[{i}].T_camera_target')
|
||||
count = len(obs['object_points'])
|
||||
if not 6 <= count <= MAX_POINTS_PER_FRAME:
|
||||
raise ValueError('Each frame requires 6..10000 matched corners')
|
||||
total += count
|
||||
if total > MAX_TOTAL_POINTS:
|
||||
raise ValueError('Total corner count exceeds 100000')
|
||||
obj = _array(obs['object_points'], (count, 3), 'object_points')
|
||||
img = _array(obs['image_points'], (count, 2), 'image_points')
|
||||
ids = _array(obs['corner_ids'], (count,), 'corner_ids')
|
||||
if (np.shape(obs['object_points']) != (count, 3) or np.shape(obs['image_points']) != (count, 2)
|
||||
or np.shape(obs['corner_ids']) != (count,)):
|
||||
raise ValueError('Expected matched N x 3 object points, N x 2 image points and N corner IDs')
|
||||
if np.any(ids < 0) or np.any(ids > 2147483647) or np.any(ids != np.floor(ids)) or len(np.unique(ids)) != count:
|
||||
raise ValueError('corner_ids must be unique nonnegative integers')
|
||||
for corner_id, point in zip(ids, obj):
|
||||
previous = id_coordinates.setdefault(int(corner_id), point)
|
||||
if not np.allclose(previous, point, atol=1e-9, rtol=0):
|
||||
raise ValueError('A corner ID must refer to the same object point in every frame')
|
||||
centered = obj - obj.mean(axis=0)
|
||||
singular = np.linalg.svd(centered, compute_uv=False)
|
||||
if singular[1] <= max(1e-9, singular[0]*1e-6) or singular[2] > max(1e-9, singular[0]*1e-6):
|
||||
raise ValueError('Object points must be planar and noncollinear')
|
||||
if len(np.unique(obj, axis=0)) != count:
|
||||
raise ValueError('Duplicate object points')
|
||||
k = _array(obs['K'], (3, 3), 'K')
|
||||
if k[0,0] <= 0 or k[1,1] <= 0 or not np.allclose(k[2], [0,0,1], atol=1e-10, rtol=0) or abs(k[0,1])+abs(k[1,0]) > 1e-10:
|
||||
raise ValueError('K must have positive focal lengths and standard zero-skew form')
|
||||
d = np.asarray(obs['D'], dtype=np.float64).reshape(-1)
|
||||
if len(d) not in (0,4,5,8,12,14) or not np.all(np.isfinite(d)):
|
||||
raise ValueError('Invalid distortion coefficients')
|
||||
width, height = obs['width'], obs['height']
|
||||
if (isinstance(width, bool) or isinstance(height, bool) or int(width) != width or int(height) != height
|
||||
or min(width, height) < 2 or max(width, height) > 8192 or width*height > 32000000):
|
||||
raise ValueError('Invalid image dimensions')
|
||||
if np.any(img < 0) or np.any(img[:,0] >= width) or np.any(img[:,1] >= height):
|
||||
raise ValueError('Image corners must be inside the calibrated image')
|
||||
depths = (obj @ c[:3,:3].T + c[:3,3])[:,2]
|
||||
if np.min(depths) <= 1e-8:
|
||||
raise ValueError('All PnP corners must have positive depth')
|
||||
robots.append(g)
|
||||
data.append(dict(c=c, obj=obj, skew=_skew(obj), img=img, k=k, d=d,
|
||||
motion=_inverse(g) if eye_in_hand else g))
|
||||
except (KeyError, TypeError, OverflowError) as exc:
|
||||
raise ValueError(f'Invalid observation {i}: {exc}') from exc
|
||||
return robots, data, x
|
||||
|
||||
|
||||
def _initial_fixed(data, x):
|
||||
poses = [_inverse(o['motion']) @ x @ o['c'] for o in data]
|
||||
u, _, vt = np.linalg.svd(np.sum([p[:3,:3] for p in poses], axis=0))
|
||||
y = np.eye(4)
|
||||
y[:3,:3] = u @ np.diag([1., 1., np.linalg.det(u@vt)]) @ vt
|
||||
y[:3,3] = np.median([p[:3,3] for p in poses], axis=0)
|
||||
return y
|
||||
|
||||
|
||||
def _evaluate(data, x, y, jacobian=False):
|
||||
residuals, blocks = [], []
|
||||
xi = _inverse(x)
|
||||
for obs in data:
|
||||
prediction = xi @ obs['motion'] @ y
|
||||
pc = obs['obj'] @ prediction[:3,:3].T + prediction[:3,3]
|
||||
if not np.all(np.isfinite(pc)) or np.min(pc[:,2]) <= 1e-8:
|
||||
raise ValueError('Predicted corners violate positive depth')
|
||||
projected, camera_j = cv2.projectPoints(pc, np.zeros(3), np.zeros(3), obs['k'], obs['d'])
|
||||
residuals.append((projected.reshape(-1,2)-obs['img']).ravel())
|
||||
if jacobian:
|
||||
dp = camera_j[:,3:6].reshape(-1,2,3)
|
||||
geometric = np.concatenate((_skew(pc), np.broadcast_to(-np.eye(3), (len(pc),3,3)),
|
||||
-prediction[:3,:3] @ obs['skew'], np.broadcast_to(prediction[:3,:3], (len(pc),3,3))), axis=2)
|
||||
blocks.append((dp @ geometric).reshape(-1,12)*PARAMETER_SCALE)
|
||||
residual = np.concatenate(residuals)
|
||||
if not np.all(np.isfinite(residual)):
|
||||
raise ValueError('Nonfinite reprojection')
|
||||
return residual, np.vstack(blocks) if jacobian else None
|
||||
|
||||
|
||||
def _cost_weights(residual):
|
||||
norms = np.linalg.norm(residual.reshape(-1,2), axis=1)
|
||||
cost = np.sum(np.where(norms <= HUBER_PX, .5*norms**2, HUBER_PX*(norms-.5*HUBER_PX)))
|
||||
weights = np.repeat(np.minimum(1., HUBER_PX/np.maximum(norms, 1e-15)), 2)
|
||||
return float(cost), weights
|
||||
|
||||
|
||||
def _condition(jacobian, weights):
|
||||
weighted = jacobian*np.sqrt(weights[:,None])
|
||||
if not np.all(np.isfinite(weighted)):
|
||||
raise ValueError('Nonfinite joint Jacobian')
|
||||
singular = np.linalg.svd(weighted, compute_uv=False)
|
||||
if singular[-1] <= singular[0]/MAX_CONDITION or singular[0] <= 1e-12:
|
||||
raise ValueError('Joint Jacobian is rank deficient or poorly conditioned; increase robot pose diversity')
|
||||
return weighted, float(singular[0]/singular[-1])
|
||||
|
||||
|
||||
def _fit(data, x, y):
|
||||
x, y = x.copy(), y.copy()
|
||||
damping, converged, iterations = 1e-3, False, 0
|
||||
initial_residual, _ = _evaluate(data, x, y)
|
||||
initial_cost, _ = _cost_weights(initial_residual)
|
||||
for iteration in range(MAX_ITERATIONS):
|
||||
iterations = iteration+1
|
||||
residual, j = _evaluate(data, x, y, True)
|
||||
cost, weights = _cost_weights(residual)
|
||||
jw, condition = _condition(j, weights)
|
||||
h = jw.T @ jw
|
||||
gradient = j.T @ (weights*residual)
|
||||
diagonal = np.maximum(np.diag(h), 1e-12)
|
||||
if np.max(np.abs(gradient)/np.sqrt(diagonal)) < 1e-7:
|
||||
converged = True
|
||||
break
|
||||
accepted_step = False
|
||||
for _ in range(16):
|
||||
step = np.linalg.solve(h+damping*np.diag(diagonal), -gradient)
|
||||
# Bound trial motion to a local basin; translation scale is 0.2m.
|
||||
length = max(np.linalg.norm(step[:3]), np.linalg.norm(step[6:9]),
|
||||
np.linalg.norm(step[3:6]), np.linalg.norm(step[9:12]))
|
||||
if length > .3:
|
||||
step *= .3/length
|
||||
physical = step*PARAMETER_SCALE
|
||||
trial_x = _increment(x, physical[:6])
|
||||
trial_y = _increment(y, physical[6:])
|
||||
try:
|
||||
trial_residual, _ = _evaluate(data, trial_x, trial_y)
|
||||
trial_cost, _ = _cost_weights(trial_residual)
|
||||
except (ValueError, cv2.error):
|
||||
trial_cost = math.inf
|
||||
if trial_cost < cost:
|
||||
x, y = trial_x, trial_y
|
||||
accepted_step = True
|
||||
damping = max(damping/3., 1e-12)
|
||||
# Small progress alone is insufficient while heavily damped.
|
||||
if (np.linalg.norm(step) < 1e-9 or cost-trial_cost < 1e-10*max(1., cost)) and damping < 1e-3:
|
||||
converged = True
|
||||
break
|
||||
damping *= 10.
|
||||
if damping > 1e14:
|
||||
break
|
||||
if converged or not accepted_step:
|
||||
break
|
||||
residual, j = _evaluate(data, x, y, True)
|
||||
cost, weights = _cost_weights(residual)
|
||||
_, condition = _condition(j, weights)
|
||||
return dict(x=x, y=y, residual=residual, initial_residual=initial_residual,
|
||||
initial_cost=initial_cost, cost=cost, condition=condition,
|
||||
converged=converged, iterations=iterations)
|
||||
|
||||
|
||||
def _rms(residual):
|
||||
return float(np.sqrt(np.mean(np.sum(residual.reshape(-1,2)**2, axis=1))))
|
||||
|
||||
|
||||
def refine_joint(robot_poses, observations, initial_matrix, eye_in_hand) -> dict[str, Any]:
|
||||
"""Fit both transforms; reject quality failures without a successful fallback.
|
||||
|
||||
Invalid/degenerate input raises ValueError. Numerical nonconvergence and
|
||||
cross-validation failures return accepted=False and explicit quality_flags.
|
||||
Validation fits see only their training poses, PnP estimates and corners;
|
||||
neither the supplied initial matrix nor the full-fit matrices are reused.
|
||||
The robust loss must not increase (relative tolerance 1e-9); all-point RMS
|
||||
may rise by at most max(0.01px, 1% of initial RMS), and must be <=1.5px.
|
||||
Held-out all-point RMS must be <=3px with every frame validated exactly once.
|
||||
"""
|
||||
robots, data, x0 = _validated(robot_poses, observations, initial_matrix, eye_in_hand)
|
||||
y0 = _initial_fixed(data, x0)
|
||||
full = _fit(data, x0, y0)
|
||||
flags = []
|
||||
if not full['converged']:
|
||||
flags.append('refinement_not_converged')
|
||||
initial_rms, final_rms = _rms(full['initial_residual']), _rms(full['residual'])
|
||||
if full['cost'] > full['initial_cost']+1e-9*max(1., full['initial_cost']):
|
||||
flags.append('robust_objective_not_improved')
|
||||
if final_rms > initial_rms+max(.01, .01*initial_rms):
|
||||
flags.append('all_point_rms_increased')
|
||||
if final_rms > 1.5:
|
||||
flags.append('high_refinement_reprojection')
|
||||
n = len(data)
|
||||
folds = [list(range(i, n, 3)) for i in range(3)] if n >= 9 else [[i] for i in range(n)]
|
||||
heldout, fold_reports, validation_residuals = {}, [], []
|
||||
for fold_id, test in enumerate(folds):
|
||||
test_set = set(test)
|
||||
train = [i for i in range(n) if i not in test_set]
|
||||
report = dict(fold=fold_id, train_indices=train, held_out_indices=test, valid=False)
|
||||
try:
|
||||
train_data = [data[i] for i in train]
|
||||
train_x = _matrix(solve_handeye_matrix([robots[i] for i in train], [data[i]['c'] for i in train],
|
||||
eye_in_hand, cv2.CALIB_HAND_EYE_PARK), 'validation initialization')
|
||||
fit = _fit(train_data, train_x, _initial_fixed(train_data, train_x))
|
||||
if not fit['converged']:
|
||||
raise ValueError('Validation fit did not converge')
|
||||
fold_residuals = []
|
||||
for i in test:
|
||||
residual, _ = _evaluate([data[i]], fit['x'], fit['y'])
|
||||
fold_residuals.append((i, residual))
|
||||
for i, residual in fold_residuals:
|
||||
heldout[i] = _rms(residual)
|
||||
validation_residuals.append(residual)
|
||||
report.update(valid=True, rms_px=_rms(np.concatenate([r for _, r in fold_residuals])),
|
||||
iterations=fit['iterations'], jacobian_condition=fit['condition'])
|
||||
except (ValueError, cv2.error, np.linalg.LinAlgError) as exc:
|
||||
report['error'] = str(exc)
|
||||
fold_reports.append(report)
|
||||
validation_rms = _rms(np.concatenate(validation_residuals)) if validation_residuals else None
|
||||
if len(heldout) != n:
|
||||
flags.append('incomplete_cross_validation')
|
||||
if validation_rms is not None and validation_rms > 3.:
|
||||
flags.append('high_validation_reprojection')
|
||||
details, offset = [], 0
|
||||
for i, obs in enumerate(data):
|
||||
end = offset+2*len(obs['obj'])
|
||||
details.append(dict(input_index=i, used=True, corner_count=len(obs['obj']),
|
||||
initial_rms_px=_rms(full['initial_residual'][offset:end]),
|
||||
final_rms_px=_rms(full['residual'][offset:end]), validation_rms_px=heldout.get(i),
|
||||
validation_used=i in heldout))
|
||||
offset = end
|
||||
metrics = dict(initial_rms_px=initial_rms, final_rms_px=final_rms, validation_rms_px=validation_rms,
|
||||
validation_sample_count=len(heldout), validation_coverage=len(heldout)/n,
|
||||
validation_fold_count=len(folds), validation_point_count=sum(len(data[i]['obj']) for i in heldout),
|
||||
iterations=full['iterations'], jacobian_condition=full['condition'],
|
||||
initial_robust_cost=full['initial_cost'], final_robust_cost=full['cost'], huber_delta_px=HUBER_PX,
|
||||
final_rms_limit_px=1.5, validation_rms_limit_px=3., max_jacobian_condition=MAX_CONDITION,
|
||||
samples_total=n, samples_used=n, point_count=offset//2, accepted=not flags)
|
||||
return dict(matrix=full['x'].ravel().tolist(), fixed_matrix=full['y'].ravel().tolist(),
|
||||
initial_matrix=x0.ravel().tolist(), initial_fixed_matrix=y0.ravel().tolist(),
|
||||
matrix_name='T_flange_camera' if eye_in_hand else 'T_base_camera',
|
||||
fixed_matrix_name='T_base_target' if eye_in_hand else 'T_flange_target',
|
||||
method='joint_reprojection_lm', converged=full['converged'], accepted=not flags,
|
||||
metrics=metrics, quality_flags=flags, sample_diagnostics=details, validation_folds=fold_reports)
|
||||
331
scripts/handeye_worker.py
Normal file
331
scripts/handeye_worker.py
Normal file
@ -0,0 +1,331 @@
|
||||
"""Isolated OpenCV worker for Qt. One UTF-8 JSON request/reply per line.
|
||||
|
||||
Protocol 1 uses row-major 16-element SE(3) matrices, metres and radians.
|
||||
T_parent_child transforms child coordinates into parent coordinates. The
|
||||
worker never opens cameras or robots: every measurement comes from the caller.
|
||||
Detect supports a PNG in image_png_base64 or stride-aware frame planes.
|
||||
Solve requires paired T_base_flange/T_camera_target and reprojection_px.
|
||||
ok means the operation ran; valid (and metrics.accepted) controls acceptance.
|
||||
Phone provenance is listed in handeye_math.py and at the ported stages below.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# -I / embedded Python intentionally exclude the working directory and script
|
||||
# directory. Only add our explicitly deployed sibling algorithm modules.
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from handeye_math import (HAND_EYE_SOLVER_METHODS, dominant_rotation_axes,
|
||||
estimate_planar_pose, robust_handeye_calibration, rvec_tvec_to_matrix,
|
||||
ax_xb_all_pair_metrics, fixed_target_consistency)
|
||||
|
||||
PROTOCOL = 1
|
||||
MAX_DIMENSION = 8192
|
||||
MAX_PIXELS = 32_000_000
|
||||
MAX_LINE_BYTES = 180_000_000
|
||||
MAX_REPROJECTION_PX = 1.5
|
||||
MAX_PHOTO_BYTES = 2 * 1024 * 1024
|
||||
|
||||
|
||||
def capture_photo(image: np.ndarray) -> str:
|
||||
# Keep full frame coordinates for the measured corners; never resize.
|
||||
for quality in (90, 75, 55, 35):
|
||||
ok, encoded = cv2.imencode('.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, quality])
|
||||
if ok and encoded.nbytes <= MAX_PHOTO_BYTES:
|
||||
return base64.b64encode(encoded).decode('ascii')
|
||||
raise ValueError('采样照片编码失败或超过 2 MiB,请降低视频分辨率后重采')
|
||||
|
||||
|
||||
def finite_array(value: Any, shape: tuple[int, ...], name: str) -> np.ndarray:
|
||||
result = np.asarray(value, dtype=np.float64)
|
||||
if result.size != math.prod(shape) or not np.all(np.isfinite(result)):
|
||||
raise ValueError(f'{name}: expected {math.prod(shape)} finite numbers')
|
||||
return result.reshape(shape)
|
||||
|
||||
|
||||
def matrix(value: Any, name: str) -> np.ndarray:
|
||||
result = finite_array(value, (4, 4), name)
|
||||
rotation = result[:3, :3]
|
||||
if not np.allclose(result[3], [0,0,0,1], atol=1e-8, rtol=0):
|
||||
raise ValueError(f'{name}: invalid homogeneous bottom row')
|
||||
if not np.allclose(rotation.T @ rotation, np.eye(3), atol=1e-5, rtol=0) or abs(np.linalg.det(rotation)-1) > 1e-5:
|
||||
raise ValueError(f'{name}: rotation must be proper orthonormal SO(3)')
|
||||
return result
|
||||
|
||||
|
||||
def dimensions(width: Any, height: Any) -> tuple[int, int]:
|
||||
w,h=int(width),int(height)
|
||||
if w != width or h != height or min(w,h)<2 or max(w,h)>MAX_DIMENSION or w*h>MAX_PIXELS:
|
||||
raise ValueError('Invalid image dimensions (maximum 8192 per axis / 32 megapixels)')
|
||||
return w,h
|
||||
|
||||
|
||||
def decode_frame(request: dict) -> np.ndarray:
|
||||
w,h=dimensions(request['width'], request['height'])
|
||||
if 'frame' not in request:
|
||||
encoded=base64.b64decode(request['image_png_base64'],validate=True)
|
||||
# Check the PNG header before allowing OpenCV to allocate decoded pixels.
|
||||
if len(encoded)<24 or encoded[:8] != b'\x89PNG\r\n\x1a\n':
|
||||
raise ValueError('image_png_base64 must contain a PNG image')
|
||||
pw,ph=int.from_bytes(encoded[16:20],'big'),int.from_bytes(encoded[20:24],'big')
|
||||
if (pw,ph)!=(w,h): raise ValueError('PNG dimensions differ from calibrated width/height')
|
||||
image=cv2.imdecode(np.frombuffer(encoded,np.uint8),cv2.IMREAD_COLOR)
|
||||
if image is None: raise ValueError('Could not decode PNG image')
|
||||
return image
|
||||
frame=request['frame']
|
||||
if dimensions(frame['width'],frame['height'])!=(w,h):
|
||||
raise ValueError('Frame dimensions differ from calibrated width/height')
|
||||
fmt=frame['format'];planes=frame['planes']
|
||||
count={'RGBA':1,'I420':3,'NV12':2}.get(fmt)
|
||||
if count is None or len(planes)!=count: raise ValueError('Unsupported frame format or plane count')
|
||||
def plane(index: int, rows: int, row_bytes: int) -> np.ndarray:
|
||||
stride=int(frame.get(f'stride{index}',row_bytes))
|
||||
if stride<row_bytes or stride>row_bytes+65536: raise ValueError('Invalid plane stride')
|
||||
raw=base64.b64decode(planes[index],validate=True)
|
||||
# Trailing row padding may be omitted by frame producers.
|
||||
minimum=(rows-1)*stride+row_bytes
|
||||
if len(raw)<minimum or len(raw)>rows*stride: raise ValueError('Frame plane length does not match dimensions/stride')
|
||||
return np.ndarray((rows,row_bytes),dtype=np.uint8,buffer=raw,strides=(stride,1)).copy()
|
||||
if fmt=='RGBA': return cv2.cvtColor(plane(0,h,w*4).reshape(h,w,4),cv2.COLOR_RGBA2BGR)
|
||||
if w%2 or h%2: raise ValueError('I420/NV12 frames require even dimensions')
|
||||
y=plane(0,h,w)
|
||||
if fmt=='I420':
|
||||
packed=np.concatenate((y.ravel(),plane(1,h//2,w//2).ravel(),plane(2,h//2,w//2).ravel())).reshape(h*3//2,w)
|
||||
return cv2.cvtColor(packed,cv2.COLOR_YUV2BGR_I420)
|
||||
packed=np.vstack((y,plane(1,h//2,w)))
|
||||
return cv2.cvtColor(packed,cv2.COLOR_YUV2BGR_NV12)
|
||||
|
||||
|
||||
def detect(request: dict) -> dict:
|
||||
k=finite_array(request['K'],(3,3),'K')
|
||||
d=np.asarray(request.get('D',[]),dtype=np.float64).reshape(-1)
|
||||
if len(d) not in (0,4,5,8,12,14) or not np.all(np.isfinite(d)):
|
||||
raise ValueError('D requires 0, 4, 5, 8, 12 or 14 finite coefficients')
|
||||
if k[0,0]<=0 or k[1,1]<=0 or not np.allclose(k[2],[0,0,1],atol=1e-10):
|
||||
raise ValueError('Invalid calibrated camera matrix')
|
||||
image=decode_frame(request)
|
||||
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
|
||||
config=request['board'];kind=config['type']
|
||||
cols,rows=int(config['columns']),int(config['rows'])
|
||||
square=float(config['square_size_m'])
|
||||
if not 3<=cols<=100 or not 3<=rows<=100 or not math.isfinite(square) or square<=0:
|
||||
raise ValueError('Board requires 3..100 columns/rows and positive square_size_m')
|
||||
# Port of phone HandEyeApp.detect (1905-1952), object-point layout
|
||||
# (1644-1650), and _board (1584-1597), with stricter boundary validation.
|
||||
if kind=='chessboard':
|
||||
found,corners=False,None
|
||||
try:
|
||||
found,corners=cv2.findChessboardCornersSB(gray,(cols,rows),flags=cv2.CALIB_CB_EXHAUSTIVE|cv2.CALIB_CB_ACCURACY)
|
||||
except (AttributeError,cv2.error):
|
||||
pass
|
||||
if not found:
|
||||
found,corners=cv2.findChessboardCorners(gray,(cols,rows),flags=cv2.CALIB_CB_ADAPTIVE_THRESH|cv2.CALIB_CB_NORMALIZE_IMAGE)
|
||||
if found:
|
||||
corners=cv2.cornerSubPix(gray,corners,(5,5),(-1,-1),(cv2.TERM_CRITERIA_EPS|cv2.TERM_CRITERIA_MAX_ITER,40,1e-3))
|
||||
if not found or corners is None or len(corners)!=cols*rows:
|
||||
return dict(ok=True,valid=False,error=f'未检测到 {cols}×{rows} 棋盘格内角点',corners=[],axes=[],quality_flags=['board_not_found'])
|
||||
obj=np.zeros((cols*rows,3),np.float64)
|
||||
obj[:,:2]=np.mgrid[0:cols,0:rows].T.reshape(-1,2)*square
|
||||
img=np.asarray(corners,np.float64).reshape(-1,2)
|
||||
ids=np.arange(len(img))
|
||||
elif kind=='charuco':
|
||||
marker=float(config['marker_size_m']);name=config.get('dictionary','DICT_4X4_50')
|
||||
if not math.isfinite(marker) or not 0<marker<square:
|
||||
raise ValueError('marker_size_m must be positive and smaller than square_size_m')
|
||||
if not isinstance(name,str) or not name.startswith('DICT_') or not hasattr(cv2.aruco,name):
|
||||
raise ValueError('Unknown ArUco dictionary')
|
||||
dictionary=cv2.aruco.getPredefinedDictionary(getattr(cv2.aruco,name))
|
||||
board=cv2.aruco.CharucoBoard((cols,rows),square,marker,dictionary)
|
||||
corners,ids,_,_=cv2.aruco.CharucoDetector(board).detectBoard(gray)
|
||||
if ids is None or len(ids)<6:
|
||||
return dict(ok=True,valid=False,error='至少需要 6 个 ChArUco 角点',corners=[] if corners is None else corners.reshape(-1,2).tolist(),axes=[],quality_flags=['insufficient_corners'])
|
||||
obj,img=board.matchImagePoints(corners,ids)
|
||||
obj=np.asarray(obj,np.float64).reshape(-1,3);img=np.asarray(img,np.float64).reshape(-1,2)
|
||||
else: raise ValueError('board.type must be chessboard or charuco')
|
||||
rvec,tvec=estimate_planar_pose(obj,img,k,d)
|
||||
target=rvec_tvec_to_matrix(rvec,tvec)
|
||||
projected=cv2.projectPoints(obj,rvec,tvec,k,d)[0].reshape(-1,2)
|
||||
error=float(np.mean(np.linalg.norm(projected-img,axis=1)))
|
||||
axis=square*2
|
||||
axes=cv2.projectPoints(np.array([[0,0,0],[axis,0,0],[0,axis,0],[0,0,axis]],np.float64),rvec,tvec,k,d)[0].reshape(-1,2)
|
||||
valid=math.isfinite(error) and error<=MAX_REPROJECTION_PX
|
||||
result = dict(ok=True,valid=valid,T_camera_target=target.ravel().tolist(),corners=img.tolist(),ids=np.asarray(ids).ravel().tolist(),axes=axes.tolist(),reprojection_px=error,quality_flags=[] if valid else ['high_reprojection'],error='' if valid else '重投影误差超过 1.5 px',board_type=kind,
|
||||
image_points=img.tolist(),object_points=obj.tolist(),corner_ids=np.asarray(ids).ravel().tolist(),
|
||||
K=k.ravel().tolist(),D=d.tolist(),width=int(image.shape[1]),height=int(image.shape[0]))
|
||||
if valid and request.get('capture_photo') is True:
|
||||
result['photo_jpeg'] = capture_photo(image)
|
||||
return result
|
||||
|
||||
|
||||
def observable(robots: list[np.ndarray]) -> bool:
|
||||
# Rotation vectors must span two independent axes, rather than two bins
|
||||
# for one diagonal axis. Translation solve also needs full rank.
|
||||
vectors=[];translation_blocks=[]
|
||||
for i in range(len(robots)-1):
|
||||
for j in range(i+1,len(robots)):
|
||||
rotation=robots[i][:3,:3].T @ robots[j][:3,:3]
|
||||
vector=cv2.Rodrigues(rotation)[0].ravel()
|
||||
if np.linalg.norm(vector)>=math.radians(3): vectors.append(vector)
|
||||
translation_blocks.append(rotation-np.eye(3))
|
||||
if len(vectors)<2: return False
|
||||
values=np.linalg.svd(np.asarray(vectors),compute_uv=False)
|
||||
motion_values=np.linalg.svd(np.vstack(translation_blocks),compute_uv=False)
|
||||
return bool(values[1]>.03*values[0] and motion_values[-1]>.03*motion_values[0])
|
||||
|
||||
|
||||
def solve(request: dict) -> dict:
|
||||
optimization=request.get('optimization','pose_only')
|
||||
if optimization not in ('pose_only','joint_reprojection'):
|
||||
raise ValueError('Unknown optimization; expected pose_only or joint_reprojection')
|
||||
mode={'EyeInHand':'eye_in_hand','EyeToHand':'eye_to_hand'}.get(request.get('mode'),request.get('mode'))
|
||||
if mode not in ('eye_in_hand','eye_to_hand'): raise ValueError('Unknown hand-eye mode')
|
||||
method=request.get('method','auto')
|
||||
if method!='auto' and method not in HAND_EYE_SOLVER_METHODS: raise ValueError('Unknown hand-eye solver')
|
||||
samples=request['samples']
|
||||
if not isinstance(samples,list) or not 5<=len(samples)<=100:
|
||||
raise ValueError('手眼标定需要 5 到 100 组配对位姿,建议至少 12 组')
|
||||
robots=[];targets=[];errors=[]
|
||||
for index,sample in enumerate(samples):
|
||||
robots.append(matrix(sample['T_base_flange'],f'samples[{index}].T_base_flange'))
|
||||
target=matrix(sample['T_camera_target'],f'samples[{index}].T_camera_target')
|
||||
if target[2,3]<=0: raise ValueError(f'samples[{index}]: board origin must have positive camera depth')
|
||||
targets.append(target)
|
||||
error=float(sample['reprojection_px'])
|
||||
if not math.isfinite(error) or error<0: raise ValueError('Every sample requires finite nonnegative reprojection_px')
|
||||
errors.append(error)
|
||||
if not observable(robots): raise ValueError('姿态变化不足:需要至少两个独立旋转轴(超过 3°)')
|
||||
# Phone reprojection MAD filtering (2712-2748), but never retain a
|
||||
# >1.5px observation merely to reach the mathematical minimum.
|
||||
median=float(np.median(errors));mad=float(np.median(np.abs(np.asarray(errors)-median)))
|
||||
limit=min(MAX_REPROJECTION_PX,max(.65,median+3.5*1.4826*mad))
|
||||
original=[i for i,e in enumerate(errors) if e<=limit]
|
||||
if len(original)<5: raise ValueError('重投影质量合格样本不足 5 个(上限 1.5 px)')
|
||||
selected_robots=[robots[i] for i in original]
|
||||
if not observable(selected_robots): raise ValueError('剔除重投影异常后姿态变化不足')
|
||||
result=robust_handeye_calibration(selected_robots,[targets[i] for i in original],mode=='eye_in_hand',method)
|
||||
active=[original[i] for i in result['active_indices']]
|
||||
final=matrix(result['solution'],'solution')
|
||||
consistency=result['consistency'];pairs=result['pair_metrics']
|
||||
quality=[]
|
||||
if not observable([robots[i] for i in active]): quality.append('insufficient_rotation_excitation')
|
||||
# Phone's independent validation gates (3085-3094): 5 mm / 2 degrees.
|
||||
if pairs['translation_rms_m']>.005: quality.append('high_ax_xb_translation')
|
||||
if pairs['rotation_rms_rad']>math.radians(2): quality.append('high_ax_xb_rotation')
|
||||
if consistency['translation_max_m']>.005: quality.append('high_fixed_target_translation')
|
||||
if consistency['rotation_max_rad']>math.radians(2): quality.append('high_fixed_target_rotation')
|
||||
cv=result['solver_reports'][result['selected_solver']].get('leave_one_out')
|
||||
if cv is not None:
|
||||
if cv['translation_max_m']>.005: quality.append('high_cross_validation_translation')
|
||||
if cv['rotation_max_rad']>math.radians(2): quality.append('high_cross_validation_rotation')
|
||||
if cv['sample_count']!=len(active): quality.append('incomplete_cross_validation')
|
||||
metrics=dict(accepted=not quality,reprojection_mean_px=float(np.mean([errors[i] for i in active])),reprojection_max_px=max(errors[i] for i in active),ax_xb_translation_rms_m=pairs['translation_rms_m'],ax_xb_rotation_rms_rad=pairs['rotation_rms_rad'],fixed_target_translation_max_m=consistency['translation_max_m'],fixed_target_rotation_max_rad=consistency['rotation_max_rad'],pair_count=pairs['pair_count'],samples_total=len(samples),samples_used=len(active))
|
||||
active_set=set(active)
|
||||
rejected=sorted(set(range(len(samples)))-active_set)
|
||||
details=[]
|
||||
for i in range(len(samples)):
|
||||
detail=dict(input_index=i,used=i in active_set,reprojection_px=errors[i])
|
||||
if i in active_set:
|
||||
local=active.index(i)
|
||||
detail.update(fixed_pose_translation_error_m=float(consistency['translation_errors_m'][local]),fixed_pose_rotation_error_rad=float(consistency['rotation_errors_rad'][local]))
|
||||
else: detail['reason']='reprojection_outlier' if i not in original else 'transform_outlier'
|
||||
details.append(detail)
|
||||
response=dict(ok=True,valid=not quality,mode=mode,matrix=final.ravel().tolist(),matrix_name='T_flange_camera' if mode=='eye_in_hand' else 'T_base_camera',selected_solver=result['selected_solver'],active_indices=active,rejected_indices=rejected,sample_diagnostics=details,metrics=metrics,quality_flags=quality,ax_xb_all_pair_metrics=pairs,fixed_target_consistency={k:v for k,v in consistency.items() if not isinstance(v,np.ndarray)},solver_evaluations=result['solver_reports'],rotation_axis_coverage=sorted(dominant_rotation_axes([robots[i] for i in active])),reprojection_limit_px=limit,independent_validation_required=True,error='' if not quality else '标定质量未通过:'+', '.join(quality),optimization=optimization)
|
||||
if optimization=='pose_only':
|
||||
return response
|
||||
# This is a new joint reprojection stage, not a claim that the phone GUI
|
||||
# originally performed Robot-world calibration. Both fixed transforms are
|
||||
# variables; robot poses and each observation's intrinsics remain measured.
|
||||
from handeye_refinement import refine_joint
|
||||
if len(active)<6:
|
||||
raise ValueError('联合标定需要至少 6 组有效样本,以进行独立留出验证')
|
||||
active_robots=[robots[i] for i in active]
|
||||
active_targets=[targets[i] for i in active]
|
||||
refinement=refine_joint(active_robots,[samples[i] for i in active],final,mode=='eye_in_hand')
|
||||
refined=matrix(refinement['matrix'],'refined solution')
|
||||
pairs=ax_xb_all_pair_metrics(active_robots,active_targets,refined,mode=='eye_in_hand')
|
||||
consistency=fixed_target_consistency(active_robots,active_targets,refined,mode=='eye_in_hand')
|
||||
refined_quality=list(refinement.get('quality_flags',[]))
|
||||
if not refinement.get('converged'): refined_quality.append('joint_optimization_not_converged')
|
||||
if not refinement.get('accepted') and not refined_quality: refined_quality.append('joint_quality_rejected')
|
||||
if pairs['translation_rms_m']>.005: refined_quality.append('high_ax_xb_translation')
|
||||
if pairs['rotation_rms_rad']>math.radians(2): refined_quality.append('high_ax_xb_rotation')
|
||||
if consistency['translation_max_m']>.005: refined_quality.append('high_fixed_target_translation')
|
||||
if consistency['rotation_max_rad']>math.radians(2): refined_quality.append('high_fixed_target_rotation')
|
||||
refinement['quality_flags']=sorted(set(refined_quality))
|
||||
refinement['accepted']=not refined_quality
|
||||
refinement['metrics']['accepted']=not refined_quality
|
||||
refined_metrics=dict(metrics)
|
||||
refined_metrics.update(accepted=not refined_quality,
|
||||
ax_xb_translation_rms_m=pairs['translation_rms_m'],ax_xb_rotation_rms_rad=pairs['rotation_rms_rad'],
|
||||
fixed_target_translation_max_m=consistency['translation_max_m'],fixed_target_rotation_max_rad=consistency['rotation_max_rad'],
|
||||
joint_reprojection_rms_px=refinement['metrics']['final_rms_px'],
|
||||
validation_reprojection_rms_px=refinement['metrics']['validation_rms_px'])
|
||||
# Preserve sample indices in the original capture list, including removals
|
||||
# made by the phone's robust initialization stage.
|
||||
refined_details=refinement.get('sample_diagnostics',[])
|
||||
for detail in refined_details:
|
||||
detail['input_index']=active[detail['input_index']]
|
||||
for fold in refinement.get('validation_folds',[]):
|
||||
for field in ('train_indices','held_out_indices'):
|
||||
fold[field]=[active[i] for i in fold[field]]
|
||||
for local,index in enumerate(active):
|
||||
details[index]['fixed_pose_translation_error_m']=float(consistency['translation_errors_m'][local])
|
||||
details[index]['fixed_pose_rotation_error_rad']=float(consistency['rotation_errors_rad'][local])
|
||||
if local<len(refined_details): details[index]['joint']=refined_details[local]
|
||||
refinement['active_indices']=active
|
||||
response.update(matrix=refined.ravel().tolist(),refinement=refinement,
|
||||
valid=not refined_quality,quality_flags=refinement['quality_flags'],metrics=refined_metrics,
|
||||
initial_metrics=metrics,ax_xb_all_pair_metrics=pairs,
|
||||
fixed_target_consistency={k:v for k,v in consistency.items() if not isinstance(v,np.ndarray)},
|
||||
error='' if not refined_quality else '联合标定质量未通过:'+', '.join(refinement['quality_flags']))
|
||||
return response
|
||||
|
||||
|
||||
def handle_request(request: Any) -> dict:
|
||||
try:
|
||||
if not isinstance(request,dict): raise ValueError('Request must be a JSON object')
|
||||
operation=request.get('op')
|
||||
if operation=='check':
|
||||
# Import here as well so a partial deployment fails during preflight,
|
||||
# before users spend time collecting samples.
|
||||
from handeye_refinement import refine_joint
|
||||
result=dict(ok=True,valid=True,protocol=PROTOCOL,opencv_version=cv2.__version__,numpy_version=np.__version__,methods=['auto',*HAND_EYE_SOLVER_METHODS],capabilities=['chessboard','charuco','eye_in_hand','eye_to_hand','RGBA','I420','NV12','joint_reprojection','raw_corner_observations'],matrix_convention='T_parent_child; row-major; metres')
|
||||
elif operation=='detect': result=detect(request)
|
||||
elif operation=='solve': result=solve(request)
|
||||
else: raise ValueError('Unknown op; expected check, detect or solve')
|
||||
except Exception as exc:
|
||||
result=dict(ok=False,valid=False,error=str(exc),quality_flags=['operation_failed'])
|
||||
result.setdefault('protocol',PROTOCOL)
|
||||
if isinstance(request,dict) and 'id' in request: result['id']=request['id']
|
||||
return result
|
||||
|
||||
|
||||
def main() -> None:
|
||||
# cv2 diagnostics go to stderr; stdout remains strictly NDJSON.
|
||||
if hasattr(sys.stdin,'reconfigure'): sys.stdin.reconfigure(encoding='utf-8')
|
||||
if hasattr(sys.stdout,'reconfigure'): sys.stdout.reconfigure(encoding='utf-8')
|
||||
cv2.setNumThreads(2)
|
||||
while True:
|
||||
line=sys.stdin.readline(MAX_LINE_BYTES+1)
|
||||
if not line: break
|
||||
if len(line)>MAX_LINE_BYTES:
|
||||
# Discard this request's tail, then accept the next line.
|
||||
while line and not line.endswith('\n'): line=sys.stdin.readline(MAX_LINE_BYTES+1)
|
||||
result=dict(ok=False,valid=False,protocol=PROTOCOL,error='Request exceeds size limit')
|
||||
else:
|
||||
try: result=handle_request(json.loads(line))
|
||||
except (ValueError,TypeError) as exc: result=dict(ok=False,valid=False,protocol=PROTOCOL,error='Invalid JSON: '+str(exc))
|
||||
try: output=json.dumps(result,ensure_ascii=False,allow_nan=False,separators=(',',':'))
|
||||
except ValueError: output=json.dumps(dict(ok=False,valid=False,protocol=PROTOCOL,error='Nonfinite algorithm result'))
|
||||
print(output,flush=True)
|
||||
|
||||
|
||||
if __name__=='__main__': main()
|
||||
90
scripts/package_handeye_runtime.py
Normal file
90
scripts/package_handeye_runtime.py
Normal file
@ -0,0 +1,90 @@
|
||||
"""Build the application-local Windows x64 hand-eye runtime, without pip.
|
||||
|
||||
Run with the already validated Python 3.12 environment. Only NumPy/OpenCV
|
||||
packages and their licenses are copied; no venv/Anaconda paths are retained.
|
||||
The output is a fresh directory; deployment is handled by qmake/CMake.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.metadata
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import sysconfig
|
||||
import urllib.request
|
||||
import zipfile
|
||||
|
||||
VERSION = '3.12.4'
|
||||
ARCHIVE = f'python-{VERSION}-embed-amd64.zip'
|
||||
URL = f'https://www.python.org/ftp/python/{VERSION}/{ARCHIVE}'
|
||||
SHA256 = '15fea3c9367653a85086fe37216b4d1a1c78688fa5e1587e1db0b0f658856564'
|
||||
PACKAGES = {'numpy': '2.5.2', 'opencv-contrib-python': '4.11.0.86'}
|
||||
|
||||
|
||||
def main():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--output', type=Path, default=root/'third_party/handeye-runtime')
|
||||
parser.add_argument('--archive', type=Path, default=root/'third_party/handeye-downloads'/ARCHIVE)
|
||||
args = parser.parse_args()
|
||||
if os.name != 'nt' or sys.version_info[:2] != (3, 12) or struct.calcsize('P') != 8:
|
||||
parser.error('Use the validated Windows x64 Python 3.12 environment')
|
||||
if args.output.exists():
|
||||
parser.error('Output already exists; select a new --output directory for a rebuild')
|
||||
site = Path(sysconfig.get_path('purelib')).resolve()
|
||||
distributions = {}
|
||||
for name, version in PACKAGES.items():
|
||||
distribution = importlib.metadata.distribution(name)
|
||||
if distribution.version != version:
|
||||
parser.error(f'{name}: expected {version}, found {distribution.version}')
|
||||
metadata = [p for p in distribution.files if str(p).endswith('.dist-info/METADATA')]
|
||||
if len(metadata) != 1:
|
||||
parser.error(f'{name}: missing distribution metadata and licenses')
|
||||
distributions[name] = distribution.locate_file(metadata[0]).parent
|
||||
if not args.archive.exists():
|
||||
args.archive.parent.mkdir(parents=True, exist_ok=True)
|
||||
urllib.request.urlretrieve(URL, args.archive)
|
||||
if hashlib.sha256(args.archive.read_bytes()).hexdigest() != SHA256:
|
||||
parser.error('Python archive SHA256 mismatch')
|
||||
output = args.output.resolve()
|
||||
output.mkdir(parents=True)
|
||||
with zipfile.ZipFile(args.archive) as archive:
|
||||
# Official archive has flat paths; reject traversal before extracting.
|
||||
for name in archive.namelist():
|
||||
if not (output/name).resolve().is_relative_to(output):
|
||||
raise ValueError('Unsafe archive entry')
|
||||
archive.extractall(output)
|
||||
target = output/'Lib/site-packages'
|
||||
target.mkdir(parents=True)
|
||||
for name in ('numpy', 'numpy.libs', 'cv2'):
|
||||
shutil.copytree(site/name, target/name,
|
||||
ignore=shutil.ignore_patterns('__pycache__', '*.pyc', 'tests'))
|
||||
for metadata in distributions.values():
|
||||
shutil.copytree(metadata, target/metadata.name)
|
||||
# All paths resolve relative to python312.dll. Do not import site or run
|
||||
# user .pth files; dependency DLL loaders are part of NumPy/OpenCV.
|
||||
(output/'python312._pth').write_text('python312.zip\n.\nLib/site-packages\n', encoding='ascii')
|
||||
probe = ('import sys,json,numpy,cv2; '
|
||||
'assert hasattr(cv2,"aruco"); '
|
||||
'print(json.dumps(dict(python=sys.version,numpy=numpy.__version__,opencv=cv2.__version__)))')
|
||||
env = dict(os.environ, PYTHONHOME='invalid-external-python', PYTHONPATH='invalid-external-packages',
|
||||
PATH=os.path.join(os.environ['SystemRoot'], 'System32'))
|
||||
result = subprocess.run([str(output/'python.exe'), '-I', '-B', '-c', probe],
|
||||
cwd=output, env=env, check=True, capture_output=True, text=True)
|
||||
manifest = dict(schema=1, platform='windows-amd64', python=VERSION,
|
||||
python_archive_url=URL, python_archive_sha256=SHA256, packages=PACKAGES,
|
||||
probe=json.loads(result.stdout))
|
||||
manifest['files'] = {str(p.relative_to(output)).replace('\\', '/'):
|
||||
hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in sorted(output.rglob('*')) if p.is_file()}
|
||||
(output/'manifest.json').write_text(json.dumps(manifest, indent=2), encoding='utf-8')
|
||||
print(json.dumps(dict(runtime=str(output), files=len(manifest['files']),
|
||||
size_mb=round(sum(p.stat().st_size for p in output.rglob('*') if p.is_file())/1048576, 1))))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
345
src/agvmapviewwidget.cpp
Normal file
345
src/agvmapviewwidget.cpp
Normal file
@ -0,0 +1,345 @@
|
||||
#include "agvmapviewwidget.h"
|
||||
|
||||
#include <QLineF>
|
||||
#include <QMouseEvent>
|
||||
#include <QPainter>
|
||||
#include <QPainterPath>
|
||||
#include <QPaintEvent>
|
||||
#include <QPolygonF>
|
||||
#include <QWheelEvent>
|
||||
#include <QtMath>
|
||||
|
||||
namespace {
|
||||
constexpr double kMinimumZoom = 0.5;
|
||||
constexpr double kMaximumZoom = 8.0;
|
||||
constexpr int kMaximumTrajectoryPoints = 600;
|
||||
constexpr double kTrajectoryMinimumDistance = 0.03;
|
||||
}
|
||||
|
||||
AgvMapViewWidget::AgvMapViewWidget(QWidget *parent)
|
||||
: QWidget(parent)
|
||||
{
|
||||
setMinimumSize(420, 320);
|
||||
setMouseTracking(true);
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
setFocusPolicy(Qt::StrongFocus);
|
||||
setAutoFillBackground(false);
|
||||
}
|
||||
|
||||
void AgvMapViewWidget::setMapFrame(const QImage &image,
|
||||
const QVariantMap &metadata)
|
||||
{
|
||||
const QString nextMapId = metadata.value(QStringLiteral("mapId")).toString();
|
||||
if (!nextMapId.isEmpty() && nextMapId != m_mapId) {
|
||||
m_mapId = nextMapId;
|
||||
clearTrajectory();
|
||||
resetView();
|
||||
}
|
||||
m_image = image;
|
||||
m_metadata = metadata;
|
||||
update();
|
||||
}
|
||||
|
||||
void AgvMapViewWidget::updateRobotPose(double x, double y, double theta,
|
||||
bool localized)
|
||||
{
|
||||
m_robotX = x;
|
||||
m_robotY = y;
|
||||
m_robotTheta = theta;
|
||||
m_localized = localized;
|
||||
m_hasPose = qIsFinite(x) && qIsFinite(y) && qIsFinite(theta);
|
||||
|
||||
if (m_hasPose && localized && canProjectPose()) {
|
||||
const QPointF next(x, y);
|
||||
if (m_trajectory.isEmpty()
|
||||
|| QLineF(m_trajectory.constLast(), next).length()
|
||||
>= kTrajectoryMinimumDistance) {
|
||||
m_trajectory.append(next);
|
||||
if (m_trajectory.size() > kMaximumTrajectoryPoints)
|
||||
m_trajectory.remove(0, m_trajectory.size()
|
||||
- kMaximumTrajectoryPoints);
|
||||
}
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
void AgvMapViewWidget::setStreamMessage(const QString &message)
|
||||
{
|
||||
m_streamMessage = message;
|
||||
update();
|
||||
}
|
||||
|
||||
void AgvMapViewWidget::zoomIn()
|
||||
{
|
||||
changeZoom(1.25, rect().center());
|
||||
}
|
||||
|
||||
void AgvMapViewWidget::zoomOut()
|
||||
{
|
||||
changeZoom(0.8, rect().center());
|
||||
}
|
||||
|
||||
void AgvMapViewWidget::resetView()
|
||||
{
|
||||
m_zoom = 1.0;
|
||||
m_pan = QPointF();
|
||||
update();
|
||||
}
|
||||
|
||||
void AgvMapViewWidget::clearTrajectory()
|
||||
{
|
||||
m_trajectory.clear();
|
||||
update();
|
||||
}
|
||||
|
||||
bool AgvMapViewWidget::canProjectPose() const
|
||||
{
|
||||
return !m_image.isNull()
|
||||
&& m_metadata.value(QStringLiteral("dimension")).toInt() == 2
|
||||
&& m_metadata.value(QStringLiteral("resolution")).toDouble() > 0.0
|
||||
&& m_metadata.value(QStringLiteral("renderScale"), 1.0).toDouble() > 0.0;
|
||||
}
|
||||
|
||||
QPointF AgvMapViewWidget::worldToImage(double x, double y) const
|
||||
{
|
||||
const double originX = m_metadata.value(QStringLiteral("originX")).toDouble();
|
||||
const double originY = m_metadata.value(QStringLiteral("originY")).toDouble();
|
||||
const double originTheta = m_metadata.value(QStringLiteral("originTheta")).toDouble();
|
||||
const double resolution = m_metadata.value(QStringLiteral("resolution")).toDouble();
|
||||
const double renderScale = m_metadata.value(QStringLiteral("renderScale"), 1.0).toDouble();
|
||||
|
||||
const double dx = x - originX;
|
||||
const double dy = y - originY;
|
||||
const double cosine = qCos(originTheta);
|
||||
const double sine = qSin(originTheta);
|
||||
const double gridX = (cosine * dx + sine * dy) / resolution;
|
||||
const double gridY = (-sine * dx + cosine * dy) / resolution;
|
||||
return QPointF(gridX * renderScale,
|
||||
m_image.height() - gridY * renderScale);
|
||||
}
|
||||
|
||||
double AgvMapViewWidget::viewScale() const
|
||||
{
|
||||
if (m_image.isNull())
|
||||
return 1.0;
|
||||
const double horizontal = qMax(1, width() - 24)
|
||||
/ static_cast<double>(m_image.width());
|
||||
const double vertical = qMax(1, height() - 24)
|
||||
/ static_cast<double>(m_image.height());
|
||||
return qMin(horizontal, vertical) * m_zoom;
|
||||
}
|
||||
|
||||
QPointF AgvMapViewWidget::imageTopLeft() const
|
||||
{
|
||||
if (m_image.isNull())
|
||||
return QPointF();
|
||||
const double scale = viewScale();
|
||||
return QPointF((width() - m_image.width() * scale) * 0.5,
|
||||
(height() - m_image.height() * scale) * 0.5) + m_pan;
|
||||
}
|
||||
|
||||
QPointF AgvMapViewWidget::imageToWidget(const QPointF &point) const
|
||||
{
|
||||
return imageTopLeft() + point * viewScale();
|
||||
}
|
||||
|
||||
void AgvMapViewWidget::drawCoordinateAxes(QPainter &painter) const
|
||||
{
|
||||
constexpr double panelSize = 92.0;
|
||||
constexpr double panelMargin = 12.0;
|
||||
constexpr double arrowLength = 27.0;
|
||||
const QRectF panel(width() - panelMargin - panelSize,
|
||||
panelMargin, panelSize, panelSize);
|
||||
|
||||
painter.save();
|
||||
painter.setPen(QPen(QColor(QStringLiteral("#c9d4de")), 1));
|
||||
painter.setBrush(QColor(255, 255, 255, 232));
|
||||
painter.drawRoundedRect(panel, 8, 8);
|
||||
|
||||
const QPointF center = panel.center();
|
||||
const double originTheta = m_metadata.value(
|
||||
QStringLiteral("originTheta")).toDouble();
|
||||
const QPointF xDirection(qCos(originTheta), qSin(originTheta));
|
||||
const QPointF yDirection(qSin(originTheta), -qCos(originTheta));
|
||||
|
||||
const auto drawArrow = [&painter, center, arrowLength](
|
||||
const QPointF &direction,
|
||||
const QColor &color,
|
||||
const QString &label) {
|
||||
const QPointF normal(-direction.y(), direction.x());
|
||||
const QPointF tip = center + direction * arrowLength;
|
||||
painter.setPen(QPen(color, 2.4, Qt::SolidLine, Qt::RoundCap));
|
||||
painter.setBrush(color);
|
||||
painter.drawLine(center, tip);
|
||||
|
||||
QPolygonF arrowHead;
|
||||
arrowHead << tip
|
||||
<< tip - direction * 8.0 + normal * 4.5
|
||||
<< tip - direction * 8.0 - normal * 4.5;
|
||||
painter.setPen(Qt::NoPen);
|
||||
painter.drawPolygon(arrowHead);
|
||||
|
||||
const QPointF labelCenter = tip + direction * 9.0;
|
||||
const QRectF labelRect(labelCenter.x() - 9.0,
|
||||
labelCenter.y() - 9.0, 18.0, 18.0);
|
||||
QFont labelFont = painter.font();
|
||||
labelFont.setBold(true);
|
||||
painter.setFont(labelFont);
|
||||
painter.setPen(color);
|
||||
painter.drawText(labelRect, Qt::AlignCenter, label);
|
||||
};
|
||||
|
||||
drawArrow(xDirection, QColor(QStringLiteral("#d94a4a")),
|
||||
QStringLiteral("X"));
|
||||
drawArrow(yDirection, QColor(QStringLiteral("#2f9e69")),
|
||||
QStringLiteral("Y"));
|
||||
painter.setPen(Qt::NoPen);
|
||||
painter.setBrush(QColor(QStringLiteral("#374151")));
|
||||
painter.drawEllipse(center, 3.2, 3.2);
|
||||
painter.restore();
|
||||
}
|
||||
|
||||
void AgvMapViewWidget::paintEvent(QPaintEvent *event)
|
||||
{
|
||||
Q_UNUSED(event)
|
||||
QPainter painter(this);
|
||||
painter.setRenderHint(QPainter::Antialiasing);
|
||||
painter.fillRect(rect(), QColor(QStringLiteral("#eef2f6")));
|
||||
|
||||
if (m_image.isNull()) {
|
||||
painter.setPen(QColor(QStringLiteral("#71808e")));
|
||||
painter.drawText(rect(), Qt::AlignCenter,
|
||||
m_streamMessage.isEmpty()
|
||||
? QStringLiteral("等待 AGV 返回地图数据")
|
||||
: m_streamMessage);
|
||||
return;
|
||||
}
|
||||
|
||||
const double scale = viewScale();
|
||||
const QPointF topLeft = imageTopLeft();
|
||||
const QRectF target(topLeft,
|
||||
QSizeF(m_image.width() * scale,
|
||||
m_image.height() * scale));
|
||||
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
|
||||
painter.drawImage(target, m_image);
|
||||
painter.setPen(QPen(QColor(QStringLiteral("#c9d4de")), 1));
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
painter.drawRect(target);
|
||||
|
||||
if (canProjectPose() && m_trajectory.size() > 1) {
|
||||
QPainterPath path;
|
||||
path.moveTo(imageToWidget(worldToImage(
|
||||
m_trajectory.first().x(), m_trajectory.first().y())));
|
||||
for (int index = 1; index < m_trajectory.size(); ++index) {
|
||||
path.lineTo(imageToWidget(worldToImage(
|
||||
m_trajectory.at(index).x(), m_trajectory.at(index).y())));
|
||||
}
|
||||
painter.setPen(QPen(QColor(QStringLiteral("#2f6fed")), 2,
|
||||
Qt::DashLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.drawPath(path);
|
||||
}
|
||||
|
||||
if (canProjectPose() && m_hasPose) {
|
||||
const QPointF center = imageToWidget(worldToImage(m_robotX, m_robotY));
|
||||
const double originTheta = m_metadata.value(
|
||||
QStringLiteral("originTheta")).toDouble();
|
||||
const double angle = m_robotTheta - originTheta;
|
||||
const QPointF forward(qCos(angle), -qSin(angle));
|
||||
const QPointF lateral(-forward.y(), forward.x());
|
||||
const double size = 13.0;
|
||||
QPolygonF robot;
|
||||
robot << center + forward * size
|
||||
<< center - forward * size * 0.7 + lateral * size * 0.65
|
||||
<< center - forward * size * 0.7 - lateral * size * 0.65;
|
||||
|
||||
painter.setPen(Qt::NoPen);
|
||||
painter.setBrush(QColor(47, 111, 237, m_localized ? 48 : 24));
|
||||
painter.drawEllipse(center, 25, 25);
|
||||
painter.setBrush(m_localized
|
||||
? QColor(QStringLiteral("#2f6fed"))
|
||||
: QColor(QStringLiteral("#df8b24")));
|
||||
painter.drawPolygon(robot);
|
||||
painter.setPen(QColor(QStringLiteral("#ffffff")));
|
||||
painter.drawLine(center - forward * 2, center + forward * 7);
|
||||
|
||||
const QString poseText = QStringLiteral("(%1, %2, %3°)")
|
||||
.arg(m_robotX, 0, 'f', 2)
|
||||
.arg(m_robotY, 0, 'f', 2)
|
||||
.arg(qRadiansToDegrees(m_robotTheta), 0, 'f', 1);
|
||||
const QFontMetrics metrics(painter.font());
|
||||
QRectF labelRect = metrics.boundingRect(poseText);
|
||||
labelRect.adjust(-7, -4, 7, 4);
|
||||
labelRect.moveBottomLeft(center + QPointF(16, -14));
|
||||
painter.setPen(QPen(QColor(QStringLiteral("#b9c9dc")), 1));
|
||||
painter.setBrush(QColor(255, 255, 255, 238));
|
||||
painter.drawRoundedRect(labelRect, 6, 6);
|
||||
painter.setPen(QColor(QStringLiteral("#145da8")));
|
||||
painter.drawText(labelRect, Qt::AlignCenter, poseText);
|
||||
}
|
||||
|
||||
if (canProjectPose())
|
||||
drawCoordinateAxes(painter);
|
||||
|
||||
if (!m_streamMessage.isEmpty()) {
|
||||
const QRect messageRect(12, height() - 36, width() - 24, 24);
|
||||
painter.setPen(QColor(QStringLiteral("#5c6975")));
|
||||
painter.drawText(messageRect, Qt::AlignLeft | Qt::AlignVCenter,
|
||||
m_streamMessage);
|
||||
}
|
||||
}
|
||||
|
||||
void AgvMapViewWidget::changeZoom(double factor, const QPointF &anchor)
|
||||
{
|
||||
if (m_image.isNull())
|
||||
return;
|
||||
const double oldScale = viewScale();
|
||||
const QPointF imagePoint = (anchor - imageTopLeft()) / oldScale;
|
||||
m_zoom = qBound(kMinimumZoom, m_zoom * factor, kMaximumZoom);
|
||||
const double newScale = viewScale();
|
||||
const QPointF centeredTopLeft(
|
||||
(width() - m_image.width() * newScale) * 0.5,
|
||||
(height() - m_image.height() * newScale) * 0.5);
|
||||
m_pan = anchor - imagePoint * newScale - centeredTopLeft;
|
||||
update();
|
||||
}
|
||||
|
||||
void AgvMapViewWidget::wheelEvent(QWheelEvent *event)
|
||||
{
|
||||
changeZoom(event->angleDelta().y() > 0 ? 1.15 : 0.87, event->pos());
|
||||
event->accept();
|
||||
}
|
||||
|
||||
void AgvMapViewWidget::mousePressEvent(QMouseEvent *event)
|
||||
{
|
||||
if (event->button() == Qt::LeftButton) {
|
||||
m_dragging = true;
|
||||
m_lastMousePosition = event->pos();
|
||||
setCursor(Qt::ClosedHandCursor);
|
||||
event->accept();
|
||||
return;
|
||||
}
|
||||
QWidget::mousePressEvent(event);
|
||||
}
|
||||
|
||||
void AgvMapViewWidget::mouseMoveEvent(QMouseEvent *event)
|
||||
{
|
||||
if (m_dragging) {
|
||||
m_pan += event->pos() - m_lastMousePosition;
|
||||
m_lastMousePosition = event->pos();
|
||||
update();
|
||||
event->accept();
|
||||
return;
|
||||
}
|
||||
QWidget::mouseMoveEvent(event);
|
||||
}
|
||||
|
||||
void AgvMapViewWidget::mouseReleaseEvent(QMouseEvent *event)
|
||||
{
|
||||
if (event->button() == Qt::LeftButton && m_dragging) {
|
||||
m_dragging = false;
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
event->accept();
|
||||
return;
|
||||
}
|
||||
QWidget::mouseReleaseEvent(event);
|
||||
}
|
||||
59
src/agvmapviewwidget.h
Normal file
59
src/agvmapviewwidget.h
Normal file
@ -0,0 +1,59 @@
|
||||
#pragma once
|
||||
|
||||
#include <QImage>
|
||||
#include <QPoint>
|
||||
#include <QPointF>
|
||||
#include <QString>
|
||||
#include <QVariantMap>
|
||||
#include <QVector>
|
||||
#include <QWidget>
|
||||
|
||||
class QMouseEvent;
|
||||
class QPainter;
|
||||
class QPaintEvent;
|
||||
class QWheelEvent;
|
||||
|
||||
class AgvMapViewWidget final : public QWidget
|
||||
{
|
||||
public:
|
||||
explicit AgvMapViewWidget(QWidget *parent = nullptr);
|
||||
|
||||
void setMapFrame(const QImage &image, const QVariantMap &metadata);
|
||||
void updateRobotPose(double x, double y, double theta, bool localized);
|
||||
void setStreamMessage(const QString &message);
|
||||
void zoomIn();
|
||||
void zoomOut();
|
||||
void resetView();
|
||||
void clearTrajectory();
|
||||
|
||||
protected:
|
||||
void paintEvent(QPaintEvent *event) override;
|
||||
void wheelEvent(QWheelEvent *event) override;
|
||||
void mousePressEvent(QMouseEvent *event) override;
|
||||
void mouseMoveEvent(QMouseEvent *event) override;
|
||||
void mouseReleaseEvent(QMouseEvent *event) override;
|
||||
|
||||
private:
|
||||
bool canProjectPose() const;
|
||||
QPointF worldToImage(double x, double y) const;
|
||||
QPointF imageToWidget(const QPointF &point) const;
|
||||
double viewScale() const;
|
||||
QPointF imageTopLeft() const;
|
||||
void drawCoordinateAxes(QPainter &painter) const;
|
||||
void changeZoom(double factor, const QPointF &anchor);
|
||||
|
||||
QImage m_image;
|
||||
QVariantMap m_metadata;
|
||||
QVector<QPointF> m_trajectory;
|
||||
QString m_streamMessage;
|
||||
QString m_mapId;
|
||||
QPointF m_pan;
|
||||
QPoint m_lastMousePosition;
|
||||
double m_zoom = 1.0;
|
||||
double m_robotX = 0.0;
|
||||
double m_robotY = 0.0;
|
||||
double m_robotTheta = 0.0;
|
||||
bool m_localized = false;
|
||||
bool m_hasPose = false;
|
||||
bool m_dragging = false;
|
||||
};
|
||||
74
src/calibrationfile.h
Normal file
74
src/calibrationfile.h
Normal file
@ -0,0 +1,74 @@
|
||||
#pragma once
|
||||
#include "handeyestore.h"
|
||||
#include "tcptoolstore.h"
|
||||
#include <QFile>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QFileInfo>
|
||||
#include <cmath>
|
||||
|
||||
// File formats are explicit SI schemas; never infer units from magnitudes.
|
||||
namespace CalibrationFile {
|
||||
inline bool numbers(const QVariant &v,int size,QVariantList &out) {
|
||||
out=v.toList(); if(out.size()!=size) return false;
|
||||
for(const auto &x:out) if(x.type()!=QVariant::Double && x.type()!=QVariant::Int) return false;
|
||||
for(const auto &x:out) if(!std::isfinite(x.toDouble())) return false;
|
||||
return true;
|
||||
}
|
||||
inline bool read(const QString &path,QVariantMap &map,QString &error) {
|
||||
QFile f(path); if(!f.open(QIODevice::ReadOnly)) { error=f.errorString(); return false; }
|
||||
if(f.size()>8*1024*1024) { error=QStringLiteral("标定文件超过 8 MB"); return false; }
|
||||
QJsonParseError e; const auto doc=QJsonDocument::fromJson(f.readAll(),&e);
|
||||
if(e.error!=QJsonParseError::NoError||!doc.isObject()) { error=QStringLiteral("需要有效的 JSON 对象:")+e.errorString(); return false; }
|
||||
map=doc.object().toVariantMap(); return true;
|
||||
}
|
||||
inline bool tcp(const QVariantMap &m,TcpToolStore::Tool &out,QString &error) {
|
||||
TcpToolStore::Tool t; QVariantList p,r;
|
||||
if(!m.value("convention").toString().startsWith("T_flange_tcp")
|
||||
|| !m.value("aubo_pose_convention").toString().contains("metres")
|
||||
|| !m.value("aubo_pose_convention").toString().contains("ZYX")
|
||||
|| !m.value("aubo_pose_convention").toString().contains("radians")
|
||||
|| !numbers(m.value("translation_m"),3,p)||!numbers(m.value("orientation_rxyz"),3,r)) {
|
||||
error=QStringLiteral("TCP 文件需明确 T_flange_tcp、米和 ZYX 弧度,包含 translation_m / orientation_rxyz"); return false;
|
||||
}
|
||||
for(int i=0;i<3;++i) { t.offset[i]=p[i].toDouble(); t.offset[i+3]=r[i].toDouble(); }
|
||||
t.name=m.value("tool_name").toString().trimmed();
|
||||
if(t.name.isEmpty()||!TcpCalibration::validPose(t.offset)) { error=QStringLiteral("TCP 名称或位姿无效"); return false; }
|
||||
out=t; return true;
|
||||
}
|
||||
inline bool handEye(const QVariantMap &m,const QString &camera,HandEyeStore::Record &out,QString &error) {
|
||||
HandEyeStore::Record r; QVariantList matrix;
|
||||
if(m.contains("primary_result")) {
|
||||
const auto primary=m.value("primary_result").toString();
|
||||
const auto key=primary=="T_eef_camera"?QString("T_flange_camera"):primary;
|
||||
if(key!="T_flange_camera"&&key!="T_base_camera") { error=QStringLiteral("未知手眼矩阵方向"); return false; }
|
||||
const auto rows=m.value(key).toList();
|
||||
if(rows.size()!=4) { error=QStringLiteral("文件必须提供明确的 T_flange_camera 或 T_base_camera,不能推测 EEF 参考系"); return false; }
|
||||
for(const auto &row:rows) { QVariantList v; if(!numbers(row,4,v)) { error=QStringLiteral("矩阵必须是 4×4 有限数值"); return false; } matrix+=v; }
|
||||
r.mode=key=="T_flange_camera"?"eye_in_hand":"eye_to_hand";
|
||||
r.cameraId=m.value("cameraId",camera).toString(); r.name=m.value("name","导入手眼标定").toString();
|
||||
r.method=m.value("solver").toString(); r.createdAt=m.value("created_at").toString(); r.sampleCount=m.value("samples_used").toInt();
|
||||
for(const auto &key:{"mean_reprojection_error_px","ax_xb_translation_rms_m","ax_xb_rotation_rms_rad"}) {
|
||||
const auto v=m.value(key); if(v.type()!=QVariant::Double||!std::isfinite(v.toDouble())||v.toDouble()<0) { error=QStringLiteral("文件缺少有效质量指标:")+key; return false; }
|
||||
}
|
||||
const bool accepted=m.value("mean_reprojection_error_px").toDouble()<=1.5 && m.value("ax_xb_translation_rms_m").toDouble()<=.005 && m.value("ax_xb_rotation_rms_rad").toDouble()<=.0872664626;
|
||||
r.metrics={{"accepted",accepted},{"source","phone_file"},{"import_quality",m}};
|
||||
QVariantList k; const auto rowsK=m.value("camera_matrix").toList();
|
||||
if(rowsK.size()!=3) { error=QStringLiteral("缺少相机内参"); return false; }
|
||||
for(const auto &row:rowsK) { QVariantList v; if(!numbers(row,3,v)) { error=QStringLiteral("内参无效"); return false; } k+=v; }
|
||||
if(k[0].toDouble()<=0||k[4].toDouble()<=0) { error=QStringLiteral("焦距无效"); return false; }
|
||||
r.intrinsics={{"fx",k[0]},{"fy",k[4]},{"cx",k[2]},{"cy",k[5]},{"coeffs",m.value("dist_coeffs")}};
|
||||
} else {
|
||||
if(m.value("units").toString()!="m_rad"||!numbers(m.value("transformSI"),16,matrix)) { error=QStringLiteral("Qt 文件需包含 units=m_rad 和 transformSI[16]"); return false; }
|
||||
r.name=m.value("name").toString(); r.cameraId=m.value("cameraId").toString(); r.mode=m.value("mode").toString();
|
||||
r.cameraSerial=m.value("cameraSerial").toString(); r.cameraModel=m.value("cameraModel").toString();
|
||||
if(m.value("matrixDirection").toString()!=(r.mode=="eye_in_hand"?"Flange_T_Camera":"Base_T_Camera")) { error=QStringLiteral("手眼矩阵方向不匹配"); return false; }
|
||||
r.method=m.value("method").toString(); r.createdAt=m.value("createdAt").toString(); r.sampleCount=m.value("sampleCount").toInt();
|
||||
r.metrics=m.value("metrics").toMap(); r.intrinsics=m.value("intrinsics").toMap(); r.board=m.value("board").toMap();
|
||||
r.refinement=m.value("refinement").toMap(); r.observations=m.value("observations").toList();
|
||||
}
|
||||
for(int i=0;i<16;++i) r.transform[i]=matrix[i].toDouble();
|
||||
if(!HandEyeStore::validateRecord(r,error)) return false;
|
||||
out=r; return true;
|
||||
}
|
||||
}
|
||||
25
src/cameracapabilities.h
Normal file
25
src/cameracapabilities.h
Normal file
@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
#include <QVariantMap>
|
||||
|
||||
namespace CameraCapabilities {
|
||||
enum class Mode { Preview, Depth, Plane };
|
||||
inline bool known(const QVariantMap& c) {
|
||||
return c.value("version").toUInt()==1 && !c.value("serial").toString().isEmpty()
|
||||
&& c.value("sessionGeneration").toULongLong()>0;
|
||||
}
|
||||
inline Mode mode(const QVariantMap& c) {
|
||||
if(!known(c) || !c.value("rawImage").toBool() || !c.value("validIntrinsics").toBool()
|
||||
|| !c.value("captureTimestamp").toBool()) return Mode::Preview;
|
||||
return c.value("metricAlignedDepth").toBool() ? Mode::Depth : Mode::Plane;
|
||||
}
|
||||
inline bool matches(const QVariantMap& c,const QVariantMap& frame) {
|
||||
return known(c) && frame.value("cameraSerial")==c.value("serial")
|
||||
&& frame.value("cameraSessionGeneration").toULongLong()==c.value("sessionGeneration").toULongLong();
|
||||
}
|
||||
inline QString title(const QVariantMap& c) {
|
||||
const auto m=mode(c);
|
||||
return (c.value("model").toString().isEmpty()?QStringLiteral("相机"):c.value("model").toString())
|
||||
+QStringLiteral(" · ")+(m==Mode::Depth?QStringLiteral("RGBD 深度定位"):
|
||||
m==Mode::Plane?QStringLiteral("二维平面定位"):QStringLiteral("视频预览 / 参数待就绪"));
|
||||
}
|
||||
}
|
||||
149
src/handeyebridge.cpp
Normal file
149
src/handeyebridge.cpp
Normal file
@ -0,0 +1,149 @@
|
||||
#include "handeyebridge.h"
|
||||
#include <QJsonDocument>
|
||||
#include <QProcess>
|
||||
#include <QProcessEnvironment>
|
||||
#include <QFileInfo>
|
||||
#include <QThread>
|
||||
#include <QTimer>
|
||||
|
||||
class HandEyeProcessWorker : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
QProcess *process = nullptr;
|
||||
QTimer *timer = nullptr;
|
||||
QByteArray buffer, diagnostics;
|
||||
quint64 epoch = 0;
|
||||
bool pending = false;
|
||||
void dispose() {
|
||||
pending = false;
|
||||
if (timer) timer->stop();
|
||||
if (process) {
|
||||
process->disconnect(this);
|
||||
process->kill();
|
||||
process->waitForFinished(2000);
|
||||
delete process;
|
||||
process = nullptr;
|
||||
}
|
||||
buffer.clear(); diagnostics.clear();
|
||||
}
|
||||
void fail(const QString &message) {
|
||||
const auto current = epoch;
|
||||
dispose();
|
||||
emit error(current, message);
|
||||
}
|
||||
void launch(quint64 generation, const QString &python, const QString &script) {
|
||||
dispose(); epoch = generation;
|
||||
if (!timer) {
|
||||
timer = new QTimer(this); timer->setSingleShot(true);
|
||||
connect(timer, &QTimer::timeout, this, [this] { fail(QStringLiteral("标定计算超时,请重新开始预览。")); });
|
||||
}
|
||||
process = new QProcess(this);
|
||||
connect(process, &QProcess::readyReadStandardError, this, [this] {
|
||||
diagnostics = (diagnostics + process->readAllStandardError()).right(4096);
|
||||
});
|
||||
connect(process, &QProcess::readyReadStandardOutput, this, [this] {
|
||||
buffer += process->readAllStandardOutput();
|
||||
if (buffer.size() > 32*1024*1024) { fail(QStringLiteral("算法返回数据过大。")); return; }
|
||||
int lineEnd;
|
||||
while ((lineEnd = buffer.indexOf('\n')) >= 0) {
|
||||
const QByteArray line = buffer.left(lineEnd); buffer.remove(0, lineEnd+1);
|
||||
if (line.trimmed().isEmpty()) continue;
|
||||
QJsonParseError parse;
|
||||
const auto document = QJsonDocument::fromJson(line, &parse);
|
||||
if (parse.error != QJsonParseError::NoError || !document.isObject()) {
|
||||
fail(QStringLiteral("算法返回了无效协议数据。")); return;
|
||||
}
|
||||
if (!pending) continue;
|
||||
timer->stop(); pending = false;
|
||||
emit reply(epoch, document.toVariant().toMap());
|
||||
}
|
||||
});
|
||||
connect(process, &QProcess::errorOccurred, this, [this](QProcess::ProcessError) {
|
||||
const QString message = process->errorString();
|
||||
const auto generation=epoch; const auto original=process;
|
||||
// Defer destruction until QProcess finishes its signal emission.
|
||||
QTimer::singleShot(0, this, [this,message,generation,original] { if (process==original && epoch==generation) fail(QStringLiteral("无法运行手眼算法:")+message); });
|
||||
});
|
||||
connect(process, QOverload<int,QProcess::ExitStatus>::of(&QProcess::finished), this,
|
||||
[this](int code,QProcess::ExitStatus) {
|
||||
const QString detail = QString::fromUtf8(diagnostics);
|
||||
const auto generation=epoch; const auto original=process;
|
||||
QTimer::singleShot(0,this,[this,code,detail,generation,original] { if (process==original && epoch==generation) fail(QStringLiteral("手眼算法已退出(%1):%2").arg(code).arg(detail)); });
|
||||
});
|
||||
// Never inherit Python configuration or packages from the workstation.
|
||||
auto environment=QProcessEnvironment::systemEnvironment();
|
||||
for (const auto &key:environment.keys())
|
||||
if (key.startsWith(QStringLiteral("PYTHON"),Qt::CaseInsensitive)) environment.remove(key);
|
||||
process->setProcessEnvironment(environment);
|
||||
process->setWorkingDirectory(QFileInfo(python).absolutePath());
|
||||
process->start(python, {QStringLiteral("-I"),QStringLiteral("-B"),QStringLiteral("-u"),script});
|
||||
}
|
||||
void send(quint64 generation, QVariantMap request, const VideoFrame &frame) {
|
||||
if (generation != epoch) return;
|
||||
if (!process) { emit error(epoch,QStringLiteral("请先启动手眼算法。")); return; }
|
||||
if (pending) { fail(QStringLiteral("手眼算法请求重叠。")); return; }
|
||||
if (frame.isValid()) {
|
||||
QString format;
|
||||
switch (frame.format) {
|
||||
case VideoPixelFormat::I420: format=QStringLiteral("I420"); break;
|
||||
case VideoPixelFormat::NV12: format=QStringLiteral("NV12"); break;
|
||||
case VideoPixelFormat::RGBA: format=QStringLiteral("RGBA"); break;
|
||||
default: emit error(epoch,QStringLiteral("不支持的视频像素格式。")); return;
|
||||
}
|
||||
QVariantList planes;
|
||||
planes << QString::fromLatin1(frame.plane0.toBase64());
|
||||
if (!frame.plane1.isEmpty()) planes << QString::fromLatin1(frame.plane1.toBase64());
|
||||
if (!frame.plane2.isEmpty()) planes << QString::fromLatin1(frame.plane2.toBase64());
|
||||
request.insert(QStringLiteral("frame"),QVariantMap{
|
||||
{"format",format},{"width",frame.width},{"height",frame.height},
|
||||
{"stride0",frame.stride0},{"stride1",frame.stride1},{"stride2",frame.stride2},{"planes",planes}});
|
||||
}
|
||||
pending=true;
|
||||
timer->start(request.value("op").toString()==QStringLiteral("solve") ? 90000 : 12000);
|
||||
process->write(QJsonDocument::fromVariant(request).toJson(QJsonDocument::Compact)+'\n');
|
||||
}
|
||||
signals:
|
||||
void reply(quint64 generation,const QVariantMap &value);
|
||||
void error(quint64 generation,const QString &message);
|
||||
};
|
||||
|
||||
HandEyeBridge::HandEyeBridge(QObject *parent) : QObject(parent), m_thread(new QThread(this)), m_worker(new HandEyeProcessWorker)
|
||||
{
|
||||
m_worker->moveToThread(m_thread);
|
||||
connect(m_thread,&QThread::finished,m_worker,&QObject::deleteLater);
|
||||
connect(m_worker,&HandEyeProcessWorker::reply,this,[this](quint64 epoch,const QVariantMap &reply) {
|
||||
if (epoch!=m_epoch) return;
|
||||
m_busy=false; emit completed(reply);
|
||||
});
|
||||
connect(m_worker,&HandEyeProcessWorker::error,this,[this](quint64 epoch,const QString &message) {
|
||||
if (epoch!=m_epoch) return;
|
||||
m_busy=false; emit failed(message);
|
||||
});
|
||||
m_thread->start();
|
||||
}
|
||||
HandEyeBridge::~HandEyeBridge()
|
||||
{
|
||||
++m_epoch;
|
||||
QMetaObject::invokeMethod(m_worker,[this] { m_worker->dispose(); },Qt::BlockingQueuedConnection);
|
||||
m_thread->quit(); m_thread->wait();
|
||||
}
|
||||
void HandEyeBridge::start(const QString &python,const QString &script)
|
||||
{
|
||||
const auto epoch=++m_epoch; m_busy=false;
|
||||
QMetaObject::invokeMethod(m_worker,[=] { m_worker->launch(epoch,python,script); },Qt::QueuedConnection);
|
||||
}
|
||||
void HandEyeBridge::stop()
|
||||
{
|
||||
++m_epoch; m_busy=false;
|
||||
QMetaObject::invokeMethod(m_worker,[this] { m_worker->dispose(); },Qt::QueuedConnection);
|
||||
}
|
||||
bool HandEyeBridge::submit(const QVariantMap &request,const VideoFrame &frame)
|
||||
{
|
||||
if (m_busy) return false;
|
||||
m_busy=true; const auto epoch=m_epoch;
|
||||
QMetaObject::invokeMethod(m_worker,[=] { m_worker->send(epoch,request,frame); },Qt::QueuedConnection);
|
||||
return true;
|
||||
}
|
||||
|
||||
#include "handeyebridge.moc"
|
||||
30
src/handeyebridge.h
Normal file
30
src/handeyebridge.h
Normal file
@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include "videoframe.h"
|
||||
#include <QObject>
|
||||
#include <QVariantMap>
|
||||
|
||||
class QThread;
|
||||
class HandEyeProcessWorker;
|
||||
|
||||
// Persistent phone algorithm process. Image encoding and all process I/O live
|
||||
// on a worker thread; the process never opens a camera or robot connection.
|
||||
class HandEyeBridge : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit HandEyeBridge(QObject *parent = nullptr);
|
||||
~HandEyeBridge() override;
|
||||
void start(const QString &python, const QString &script);
|
||||
void stop();
|
||||
bool submit(const QVariantMap &request, const VideoFrame &frame = VideoFrame());
|
||||
bool busy() const { return m_busy; }
|
||||
signals:
|
||||
void completed(const QVariantMap &reply);
|
||||
void failed(const QString &message);
|
||||
private:
|
||||
QThread *m_thread;
|
||||
HandEyeProcessWorker *m_worker;
|
||||
quint64 m_epoch = 0;
|
||||
bool m_busy = false;
|
||||
};
|
||||
391
src/handeyemotionwidget.cpp
Normal file
391
src/handeyemotionwidget.cpp
Normal file
@ -0,0 +1,391 @@
|
||||
#include "handeyemotionwidget.h"
|
||||
#include "handeyeurdf.h"
|
||||
#include <QCheckBox>
|
||||
#include <QFileDialog>
|
||||
#include <QFileInfo>
|
||||
#include <QDir>
|
||||
#include <QComboBox>
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QFrame>
|
||||
#include <QGridLayout>
|
||||
#include <QLabel>
|
||||
#include <QLineEdit>
|
||||
#include <QMessageBox>
|
||||
#include <QPushButton>
|
||||
#include <QSettings>
|
||||
#include <QScrollArea>
|
||||
#include <QSignalBlocker>
|
||||
#include <QTimer>
|
||||
#include <QVBoxLayout>
|
||||
#include <cmath>
|
||||
|
||||
HandEyeMotionWidget::HandEyeMotionWidget(QWidget *parent) : QWidget(parent)
|
||||
{
|
||||
setObjectName(QStringLiteral("handEyeMotionPanel"));
|
||||
auto *outer = new QVBoxLayout(this);
|
||||
outer->setContentsMargins(0,0,0,0);
|
||||
auto *frame = new QFrame;
|
||||
frame->setObjectName(QStringLiteral("panel"));
|
||||
auto *scroll = new QScrollArea(this);
|
||||
scroll->setFrameShape(QFrame::NoFrame);
|
||||
scroll->setWidgetResizable(true);
|
||||
scroll->setWidget(frame);
|
||||
outer->addWidget(scroll);
|
||||
auto *layout = new QVBoxLayout(frame);
|
||||
layout->setSizeConstraint(QLayout::SetMinimumSize);
|
||||
layout->setContentsMargins(16,14,16,14);
|
||||
layout->setSpacing(10);
|
||||
auto *title = new QLabel(QStringLiteral("视觉标定"));
|
||||
title->setObjectName(QStringLiteral("eyebrow"));
|
||||
layout->addWidget(title);
|
||||
auto *row = new QHBoxLayout;
|
||||
m_records = new QComboBox;
|
||||
m_records->setObjectName(QStringLiteral("handEyeMotionProfiles"));
|
||||
m_records->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
|
||||
m_records->setMinimumContentsLength(18);
|
||||
m_records->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Fixed);
|
||||
row->addWidget(new QLabel(QStringLiteral("标定结果")));
|
||||
row->addWidget(m_records,1);
|
||||
auto *reloadButton = new QPushButton(QStringLiteral("重新加载"));
|
||||
reloadButton->setObjectName(QStringLiteral("handEyeMotionReload"));
|
||||
row->addWidget(reloadButton);
|
||||
layout->addLayout(row);
|
||||
m_recordInfo = new QLabel; m_recordInfo->setObjectName(QStringLiteral("handEyeSelectedResult"));
|
||||
m_recordInfo->setWordWrap(true); layout->addWidget(m_recordInfo);
|
||||
m_identityConfirmed=new QCheckBox(QStringLiteral("已确认旧标定属于当前相机")); m_identityConfirmed->hide(); layout->addWidget(m_identityConfirmed);
|
||||
connect(m_identityConfirmed,&QCheckBox::toggled,this,[this] { invalidate(); refresh(); });
|
||||
auto *grid = new QGridLayout;
|
||||
grid->addWidget(new QLabel(QStringLiteral("相机点")),1,0);
|
||||
grid->addWidget(new QLabel(QStringLiteral("基座点")),2,0);
|
||||
for (int i=0;i<3;++i) {
|
||||
grid->addWidget(new QLabel(QString(QChar('X'+i))+QStringLiteral(" (mm)")),0,i+1);
|
||||
auto *input = new QDoubleSpinBox;
|
||||
input->setObjectName(QStringLiteral("handEyeCameraPoint%1").arg(i));
|
||||
input->setRange(-1000000,1000000);
|
||||
input->setDecimals(3);
|
||||
input->setButtonSymbols(QAbstractSpinBox::NoButtons);
|
||||
input->setKeyboardTracking(false);
|
||||
input->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Fixed);
|
||||
m_inputs.append(input);
|
||||
grid->addWidget(input,1,i+1);
|
||||
auto *result = new QLineEdit;
|
||||
result->setObjectName(QStringLiteral("handEyeBasePoint%1").arg(i));
|
||||
result->setReadOnly(true);
|
||||
result->setPlaceholderText(QStringLiteral("待转换 · mm"));
|
||||
m_results.append(result);
|
||||
grid->addWidget(result,2,i+1);
|
||||
grid->setColumnStretch(i+1,1);
|
||||
connect(input,QOverload<double>::of(&QDoubleSpinBox::valueChanged),this,[this] { invalidate(); refresh(); });
|
||||
// Editing text invalidates immediately, before a spin box commits its value.
|
||||
connect(input->findChild<QLineEdit *>(),&QLineEdit::textEdited,this,[this] { invalidate(); refresh(); });
|
||||
}
|
||||
layout->addLayout(grid);
|
||||
auto *actions = new QHBoxLayout;
|
||||
m_status = new QLabel;
|
||||
m_status->setObjectName(QStringLiteral("mutedLabel"));
|
||||
m_status->setWordWrap(true);
|
||||
actions->addWidget(m_status,1);
|
||||
m_convert = new QPushButton(QStringLiteral("转换为基座坐标"));
|
||||
m_convert->setObjectName(QStringLiteral("handEyeConvert"));
|
||||
actions->addWidget(m_convert);
|
||||
layout->addLayout(actions);
|
||||
m_convert->setToolTip(QStringLiteral("仅转换坐标,不发送运动指令。"));
|
||||
auto *urdfTitle = new QLabel(QStringLiteral("URDF 标定更新"));
|
||||
urdfTitle->setObjectName(QStringLiteral("sectionTitle")); layout->addWidget(urdfTitle);
|
||||
auto *fileRow = new QHBoxLayout;
|
||||
m_urdfPath = new QLineEdit; m_urdfPath->setReadOnly(true);
|
||||
m_urdfPath->setObjectName(QStringLiteral("handEyeUrdfPath"));
|
||||
m_urdfPath->setPlaceholderText(QStringLiteral("选择机器人 URDF"));
|
||||
auto *current = new QPushButton(QStringLiteral("当前模型"));
|
||||
auto *browse = new QPushButton(QStringLiteral("选择"));
|
||||
fileRow->addWidget(m_urdfPath,1); fileRow->addWidget(current); fileRow->addWidget(browse);
|
||||
layout->addLayout(fileRow);
|
||||
auto *mapping = new QGridLayout;
|
||||
m_urdfReference=new QComboBox; m_urdfReference->setObjectName(QStringLiteral("handEyeUrdfReference"));
|
||||
m_urdfCamera=new QComboBox; m_urdfCamera->setObjectName(QStringLiteral("handEyeUrdfCamera"));
|
||||
m_urdfCamera->setEditable(true); m_urdfCamera->setInsertPolicy(QComboBox::NoInsert);
|
||||
for (auto *combo : {m_urdfReference,m_urdfCamera})
|
||||
combo->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Fixed);
|
||||
m_urdfCamera->lineEdit()->setPlaceholderText(QStringLiteral("选择或输入相机坐标系"));
|
||||
mapping->addWidget(new QLabel(QStringLiteral("参考 Link")),0,0); mapping->addWidget(m_urdfReference,0,1);
|
||||
mapping->addWidget(new QLabel(QStringLiteral("相机 Link")),1,0); mapping->addWidget(m_urdfCamera,1,1);
|
||||
mapping->setColumnStretch(1,1); layout->addLayout(mapping);
|
||||
m_urdfConfirmed = new QCheckBox; m_urdfConfirmed->setObjectName(QStringLiteral("handEyeUrdfConfirmed"));
|
||||
m_urdfConfirmed->setToolTip(QStringLiteral("参考 Link 必须与标定的基座/法兰坐标一致;相机 Link 必须为标定使用的光学坐标系,而非未经换算的相机外壳坐标系。新相机 Link 将作为固定子节点添加。"));
|
||||
layout->addWidget(m_urdfConfirmed);
|
||||
m_updateUrdf=new QPushButton(QStringLiteral("导出并加载 URDF"));
|
||||
m_updateUrdf->setObjectName(QStringLiteral("handEyeUpdateUrdf"));
|
||||
m_updateUrdf->setToolTip(QStringLiteral("根据选中标定更新相机固定关节并保存为新文件,保留原模型。建议保存在原模型目录以保持 package:// 资源解析。"));
|
||||
layout->addWidget(m_updateUrdf);
|
||||
connect(current,&QPushButton::clicked,this,&HandEyeMotionWidget::currentUrdfRequested);
|
||||
connect(browse,&QPushButton::clicked,this,[this] {
|
||||
const QString path=QFileDialog::getOpenFileName(this,QStringLiteral("选择 URDF"),m_urdfSource,QStringLiteral("URDF (*.urdf)"));
|
||||
if (!path.isEmpty()) setUrdfFile(path);
|
||||
});
|
||||
connect(m_urdfReference,QOverload<int>::of(&QComboBox::currentIndexChanged),this,[this] { m_urdfConfirmed->setChecked(false); refresh(); });
|
||||
connect(m_urdfCamera,&QComboBox::currentTextChanged,this,[this] { m_urdfConfirmed->setChecked(false); refresh(); });
|
||||
connect(m_urdfConfirmed,&QCheckBox::toggled,this,[this] { refresh(); });
|
||||
connect(m_updateUrdf,&QPushButton::clicked,this,&HandEyeMotionWidget::chooseUrdfOutput);
|
||||
m_timeout = new QTimer(this);
|
||||
m_timeout->setSingleShot(true);
|
||||
m_timeout->setInterval(6000);
|
||||
connect(m_timeout,&QTimer::timeout,this,[this] {
|
||||
if (!m_pendingToken) return;
|
||||
invalidate(); refresh();
|
||||
reportError(QStringLiteral("读取实时位姿超时,请检查机械臂连接后重试"));
|
||||
});
|
||||
connect(m_records,QOverload<int>::of(&QComboBox::currentIndexChanged),this,&HandEyeMotionWidget::selectRecord);
|
||||
connect(reloadButton,&QPushButton::clicked,this,[this] { reload(); });
|
||||
connect(m_convert,&QPushButton::clicked,this,&HandEyeMotionWidget::convert);
|
||||
refresh();
|
||||
}
|
||||
|
||||
void HandEyeMotionWidget::setContext(const QString &endpoint, const QString &device,
|
||||
bool connected, bool demo, bool referenceConfirmed,
|
||||
const TcpCalibration::Pose &activeOffset)
|
||||
{
|
||||
const bool scopeChanged = m_endpoint != endpoint || m_device != device;
|
||||
const bool changed = scopeChanged || m_connected != connected || m_demo != demo
|
||||
|| m_referenceConfirmed != referenceConfirmed || m_activeOffset != activeOffset;
|
||||
m_endpoint=endpoint; m_device=device; m_connected=connected; m_demo=demo;
|
||||
m_referenceConfirmed=referenceConfirmed; m_activeOffset=activeOffset;
|
||||
if (!changed) return;
|
||||
invalidate();
|
||||
if (scopeChanged) {
|
||||
m_urdfSource.clear(); m_urdfPath->clear(); m_urdfReference->clear(); m_urdfCamera->clear();
|
||||
m_urdfConfirmed->setChecked(false); reload();
|
||||
}
|
||||
else refresh();
|
||||
}
|
||||
|
||||
void HandEyeMotionWidget::reload(const QString &preferredName)
|
||||
{
|
||||
invalidate();
|
||||
m_loading=true;
|
||||
m_selected=-1;
|
||||
m_snapshot=HandEyeStore::Snapshot{};
|
||||
m_records->clear();
|
||||
QString error;
|
||||
bool loaded=true;
|
||||
if (!m_endpoint.trimmed().isEmpty() && !m_device.trimmed().isEmpty()) {
|
||||
QSettings settings;
|
||||
loaded=HandEyeStore::load(settings,m_endpoint,m_device,m_snapshot,error);
|
||||
}
|
||||
int selected=-1;
|
||||
const QString wanted=preferredName.isEmpty() ? m_snapshot.current : preferredName;
|
||||
if(m_cameraScoped && !m_cameraSerial.isEmpty()) {
|
||||
for(auto i=m_snapshot.records.begin();i!=m_snapshot.records.end();) {
|
||||
if(!i->cameraSerial.isEmpty()&&i->cameraSerial!=m_cameraSerial) i=m_snapshot.records.erase(i); else ++i;
|
||||
}
|
||||
}
|
||||
for (const auto &record : m_snapshot.records) {
|
||||
const QString mode=record.mode==QStringLiteral("eye_in_hand")
|
||||
? QStringLiteral("眼在手上") : QStringLiteral("眼在手外");
|
||||
m_records->addItem(QStringLiteral("%1 · %2 · %3").arg(record.name,record.cameraId,mode),record.name);
|
||||
if (record.name==wanted) selected=m_records->count()-1;
|
||||
}
|
||||
if (selected<0 && !m_snapshot.records.isEmpty()) selected=0;
|
||||
m_records->setCurrentIndex(selected);
|
||||
m_loading=false;
|
||||
if (loaded && selected>=0) selectRecord(selected);
|
||||
else refresh();
|
||||
if (!loaded) reportError(error);
|
||||
}
|
||||
|
||||
void HandEyeMotionWidget::invalidate()
|
||||
{
|
||||
++m_serial;
|
||||
m_pendingToken=0;
|
||||
m_resultValid=false;
|
||||
if (m_timeout) m_timeout->stop();
|
||||
for (auto *result : m_results) result->clear();
|
||||
}
|
||||
|
||||
void HandEyeMotionWidget::setCameraCapabilities(const QString&,const QVariantMap& caps) {
|
||||
const auto serial=caps.value("serial").toString();
|
||||
const auto generation=caps.value("sessionGeneration").toULongLong();
|
||||
if(m_cameraScoped && serial==m_cameraSerial && generation==m_cameraGeneration) return;
|
||||
m_cameraScoped=true; m_cameraSerial=serial; m_cameraGeneration=generation; m_identityConfirmed->setChecked(false); reload();
|
||||
}
|
||||
|
||||
void HandEyeMotionWidget::selectRecord(int index)
|
||||
{
|
||||
if (m_loading) return;
|
||||
invalidate();
|
||||
m_urdfConfirmed->setChecked(false);
|
||||
m_identityConfirmed->setChecked(false);
|
||||
m_selected=-1;
|
||||
if (index>=0 && index<m_snapshot.records.size()) {
|
||||
QSettings settings; QString error;
|
||||
if (!HandEyeStore::select(settings,m_endpoint,m_device,m_snapshot.records.at(index).name,error)) {
|
||||
refresh(); reportError(error); return;
|
||||
}
|
||||
m_selected=index;
|
||||
}
|
||||
refresh();
|
||||
}
|
||||
|
||||
bool HandEyeMotionWidget::canConvert() const
|
||||
{
|
||||
if (m_selected<0 || m_selected>=m_snapshot.records.size() || m_pendingToken) return false;
|
||||
if(m_cameraScoped && m_connected && !m_demo) {
|
||||
if(m_cameraSerial.isEmpty()) return false;
|
||||
const auto serial=m_snapshot.records.at(m_selected).cameraSerial;
|
||||
if(serial.isEmpty()&&!m_identityConfirmed->isChecked()) return false;
|
||||
if(!serial.isEmpty()&&serial!=m_cameraSerial) return false;
|
||||
}
|
||||
if (m_snapshot.records.at(m_selected).mode==QStringLiteral("eye_to_hand")) return true;
|
||||
return m_connected && !m_demo && m_referenceConfirmed && TcpCalibration::validPose(m_activeOffset);
|
||||
}
|
||||
|
||||
void HandEyeMotionWidget::refresh()
|
||||
{
|
||||
const bool selected=m_selected>=0 && m_selected<m_snapshot.records.size();
|
||||
m_identityConfirmed->setVisible(m_cameraScoped && selected && m_snapshot.records[m_selected].cameraSerial.isEmpty());
|
||||
m_identityConfirmed->setToolTip(QStringLiteral("确认该旧格式标定与当前相机序列号 %1 匹配;切换相机后需重新确认。").arg(m_cameraSerial));
|
||||
const bool eyeInHand=selected && m_snapshot.records[m_selected].mode==QStringLiteral("eye_in_hand");
|
||||
m_urdfConfirmed->setText(eyeInHand ? QStringLiteral("已核对:法兰 / 相机光学坐标系")
|
||||
: QStringLiteral("已核对:基座 / 相机光学坐标系"));
|
||||
m_updateUrdf->setEnabled(selected && !m_pendingToken && !m_urdfSource.isEmpty()
|
||||
&& !m_urdfReference->currentData().toString().isEmpty() && !m_urdfCamera->currentText().trimmed().isEmpty()
|
||||
&& m_urdfConfirmed->isChecked());
|
||||
if (selected) {
|
||||
const auto &r=m_snapshot.records[m_selected]; TcpCalibration::Pose p{};
|
||||
TcpCalibration::matrixPose(r.transform,p);
|
||||
m_recordInfo->setText(QStringLiteral("%1 · %2\nXYZ:%3 / %4 / %5 mm")
|
||||
.arg(r.cameraId,eyeInHand?QStringLiteral("相机 → 法兰"):QStringLiteral("相机 → 基座"))
|
||||
.arg(p[0]*1000,0,'f',3).arg(p[1]*1000,0,'f',3).arg(p[2]*1000,0,'f',3));
|
||||
} else m_recordInfo->clear();
|
||||
m_convert->setEnabled(canConvert());
|
||||
m_records->setEnabled(!m_snapshot.records.isEmpty());
|
||||
QString status, tooltip;
|
||||
if (m_selected<0) status=QStringLiteral("当前机械臂暂无可用手眼标定");
|
||||
else {
|
||||
const bool onHand=m_snapshot.records.at(m_selected).mode==QStringLiteral("eye_in_hand");
|
||||
tooltip=onHand ? QStringLiteral("Flange_T_Camera:相机 → 法兰;Base_T_Camera = Base_T_Flange × Flange_T_Camera;内部单位 m / rad")
|
||||
: QStringLiteral("Base_T_Camera:相机 → 基座;内部单位 m / rad");
|
||||
if (m_pendingToken) status=QStringLiteral("正在读取真实位姿…");
|
||||
else if (m_resultValid) status=QStringLiteral("基座点已就绪 · 未发送运动");
|
||||
else if (onHand && !canConvert()) status=QStringLiteral("请连接真实机械臂并核对活动 TCP 偏移");
|
||||
else status=onHand ? QStringLiteral("转换时读取当前法兰位姿") : QStringLiteral("使用固定相机到基座的标定变换");
|
||||
}
|
||||
m_status->setText(status);
|
||||
m_records->setToolTip(tooltip);
|
||||
for (auto *result : m_results) result->setToolTip(tooltip);
|
||||
}
|
||||
|
||||
void HandEyeMotionWidget::setUrdfFile(const QString &path)
|
||||
{
|
||||
m_urdfConfirmed->setChecked(false);
|
||||
m_urdfSource.clear(); m_urdfPath->clear(); m_urdfReference->clear(); m_urdfCamera->clear();
|
||||
QStringList links; QList<HandEyeUrdf::FixedJoint> joints; QString error;
|
||||
if (!HandEyeUrdf::readUrdf(path,links,joints,error)) { refresh(); reportError(error); return; }
|
||||
m_urdfSource=QFileInfo(path).absoluteFilePath();
|
||||
m_urdfPath->setText(QDir::toNativeSeparators(m_urdfSource)); m_urdfPath->setToolTip(m_urdfPath->text());
|
||||
m_urdfReference->addItem(QStringLiteral("选择基座 / 法兰坐标系"),QString());
|
||||
for (const auto &link:links) m_urdfReference->addItem(link,link);
|
||||
m_urdfCamera->addItems(links); m_urdfCamera->setCurrentIndex(-1); m_urdfCamera->setEditText(QString());
|
||||
refresh();
|
||||
}
|
||||
|
||||
bool HandEyeMotionWidget::exportUrdf(const QString &target,QString &error)
|
||||
{
|
||||
if (!m_updateUrdf->isEnabled()) { error=QStringLiteral("请选择标定结果、URDF 和坐标系,并确认坐标关系。"); return false; }
|
||||
const auto record=m_snapshot.records[m_selected];
|
||||
if (!HandEyeUrdf::update(m_urdfSource,target,m_urdfReference->currentData().toString(),
|
||||
m_urdfCamera->currentText().trimmed(),record,error)) return false;
|
||||
emit logMessage(QStringLiteral("OK"),QStringLiteral("已导出标定 URDF:%1 · %2").arg(record.name,target));
|
||||
emit urdfUpdated(m_endpoint,m_device,QFileInfo(target).absoluteFilePath());
|
||||
return true;
|
||||
}
|
||||
|
||||
void HandEyeMotionWidget::chooseUrdfOutput()
|
||||
{
|
||||
if (!m_updateUrdf->isEnabled()) return;
|
||||
const QString endpoint=m_endpoint,device=m_device,name=m_snapshot.records[m_selected].name,source=m_urdfSource;
|
||||
const QFileInfo file(source);
|
||||
const QString target=QFileDialog::getSaveFileName(this,QStringLiteral("导出标定 URDF(新文件)"),
|
||||
file.dir().filePath(file.completeBaseName()+QStringLiteral("_calibrated.urdf")),QStringLiteral("URDF (*.urdf)"));
|
||||
if (target.isEmpty()) return;
|
||||
if (endpoint!=m_endpoint || device!=m_device || source!=m_urdfSource || m_selected<0
|
||||
|| name!=m_snapshot.records[m_selected].name) { reportError(QStringLiteral("设备或标定结果已变化,请重新选择。")); return; }
|
||||
QString error;
|
||||
if (!exportUrdf(target,error)) reportError(error);
|
||||
}
|
||||
|
||||
void HandEyeMotionWidget::convert()
|
||||
{
|
||||
if (!canConvert()) return;
|
||||
for (auto *input : m_inputs) input->interpretText();
|
||||
invalidate();
|
||||
if (m_snapshot.records.at(m_selected).mode==QStringLiteral("eye_to_hand")) {
|
||||
prepare({}); return;
|
||||
}
|
||||
m_pendingToken=(quint64(1)<<61) | (m_serial & ((quint64(1)<<61)-1));
|
||||
m_timeout->start();
|
||||
refresh();
|
||||
emit captureRequested(m_device,m_pendingToken);
|
||||
}
|
||||
|
||||
void HandEyeMotionWidget::acceptPose(quint64 requestId, const QString &deviceId,
|
||||
const QVariantMap &pose, const QVariantMap &state,
|
||||
bool success, const QString &detail)
|
||||
{
|
||||
if (!m_pendingToken || requestId!=m_pendingToken || deviceId!=m_device) return;
|
||||
m_pendingToken=0;
|
||||
m_timeout->stop();
|
||||
refresh();
|
||||
if (!success) {
|
||||
reportError(detail.isEmpty() ? QStringLiteral("读取真实位姿失败") : detail); return;
|
||||
}
|
||||
if (!canConvert() || state.value("connected").type()!=QVariant::Bool
|
||||
|| state.value("moving").type()!=QVariant::Bool || state.value("fault").type()!=QVariant::Bool
|
||||
|| !state.value("connected").toBool() || state.value("moving").toBool() || state.value("fault").toBool()) {
|
||||
reportError(QStringLiteral("机械臂状态不可用于转换,请停稳并重新核对")); return;
|
||||
}
|
||||
TcpCalibration::Pose tcp{}, flange{};
|
||||
const char *keys[]={"x","y","z","rx","ry","rz"};
|
||||
for (int i=0;i<6;++i) {
|
||||
const QVariant value=pose.value(QLatin1String(keys[i]));
|
||||
bool valid=false;
|
||||
tcp[size_t(i)]=value.toDouble(&valid);
|
||||
if (value.type()==QVariant::Bool || !valid || !std::isfinite(tcp[size_t(i)])) {
|
||||
reportError(QStringLiteral("实时 TCP 位姿包含缺失或无效数值")); return;
|
||||
}
|
||||
}
|
||||
QString error;
|
||||
if (!TcpCalibration::flangePose(tcp,m_activeOffset,flange,&error)) {
|
||||
reportError(QStringLiteral("无法由活动 TCP 换算法兰位姿:%1").arg(error)); return;
|
||||
}
|
||||
prepare(flange);
|
||||
}
|
||||
|
||||
void HandEyeMotionWidget::prepare(const TcpCalibration::Pose &baseFlange)
|
||||
{
|
||||
if (m_selected<0 || m_selected>=m_snapshot.records.size()) return;
|
||||
const auto record=m_snapshot.records.at(m_selected);
|
||||
std::array<double,3> point{}, base{};
|
||||
for (int i=0;i<3;++i) point[size_t(i)]=m_inputs.at(i)->value()/1000.0;
|
||||
QString error;
|
||||
if (!HandEyeStore::cameraPointToBase(record,baseFlange,point,base,error)) {
|
||||
refresh(); reportError(error); return;
|
||||
}
|
||||
QVariantList values;
|
||||
for (int i=0;i<3;++i) {
|
||||
m_results.at(i)->setText(QStringLiteral("%1 mm").arg(base[size_t(i)]*1000.0,0,'f',3));
|
||||
values.append(base[size_t(i)]);
|
||||
}
|
||||
m_resultValid=true;
|
||||
refresh();
|
||||
emit logMessage(QStringLiteral("OK"),QStringLiteral("相机点已转换为基座坐标 · %1 · %2 · 仅坐标转换")
|
||||
.arg(record.cameraId,record.name));
|
||||
// TODO: Integrate only after a visual-target motion pipeline and explicit
|
||||
// target orientation semantics exist. A point alone must never command motion.
|
||||
emit basePointPrepared(record.cameraId,record.name,values);
|
||||
}
|
||||
|
||||
void HandEyeMotionWidget::reportError(const QString &message)
|
||||
{
|
||||
emit logMessage(QStringLiteral("WARN"),message);
|
||||
QMessageBox::warning(this,QStringLiteral("手眼坐标转换"),message);
|
||||
}
|
||||
67
src/handeyemotionwidget.h
Normal file
67
src/handeyemotionwidget.h
Normal file
@ -0,0 +1,67 @@
|
||||
#pragma once
|
||||
|
||||
#include "handeyestore.h"
|
||||
#include <QWidget>
|
||||
|
||||
class QComboBox;
|
||||
class QDoubleSpinBox;
|
||||
class QLabel;
|
||||
class QLineEdit;
|
||||
class QPushButton;
|
||||
class QTimer;
|
||||
class QCheckBox;
|
||||
|
||||
// Prepares only a camera point in the robot base frame; never commands motion.
|
||||
class HandEyeMotionWidget : public QWidget {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit HandEyeMotionWidget(QWidget *parent = nullptr);
|
||||
void setContext(const QString &endpoint, const QString &device, bool connected,
|
||||
bool demo, bool referenceConfirmed, const TcpCalibration::Pose &activeOffset);
|
||||
void reload(const QString &preferredName = QString());
|
||||
void setUrdfFile(const QString &path);
|
||||
bool exportUrdf(const QString &target, QString &error);
|
||||
public slots:
|
||||
void setCameraCapabilities(const QString &camera,const QVariantMap &capabilities);
|
||||
void acceptPose(quint64 requestId, const QString &deviceId, const QVariantMap &pose,
|
||||
const QVariantMap &state, bool success, const QString &detail);
|
||||
signals:
|
||||
void captureRequested(const QString &deviceId, quint64 requestId);
|
||||
void logMessage(const QString &level, const QString &message);
|
||||
void basePointPrepared(const QString &cameraId, const QString &profileName,
|
||||
const QVariantList &baseXYZmetres);
|
||||
void currentUrdfRequested();
|
||||
void urdfUpdated(const QString &endpoint, const QString &deviceId, const QString &filePath);
|
||||
private:
|
||||
void invalidate();
|
||||
void refresh();
|
||||
void selectRecord(int index);
|
||||
void convert();
|
||||
void prepare(const TcpCalibration::Pose &baseFlange);
|
||||
void reportError(const QString &message);
|
||||
void chooseUrdfOutput();
|
||||
bool canConvert() const;
|
||||
QString m_endpoint, m_device;
|
||||
bool m_connected = false, m_demo = true, m_referenceConfirmed = false;
|
||||
bool m_loading = false, m_resultValid = false;
|
||||
TcpCalibration::Pose m_activeOffset{};
|
||||
HandEyeStore::Snapshot m_snapshot;
|
||||
int m_selected = -1;
|
||||
quint64 m_serial = 0, m_pendingToken = 0;
|
||||
QComboBox *m_records = nullptr;
|
||||
QString m_cameraSerial;
|
||||
QCheckBox *m_identityConfirmed = nullptr;
|
||||
bool m_cameraScoped=false;
|
||||
quint64 m_cameraGeneration=0;
|
||||
QList<QDoubleSpinBox *> m_inputs;
|
||||
QList<QLineEdit *> m_results;
|
||||
QLabel *m_status = nullptr;
|
||||
QPushButton *m_convert = nullptr;
|
||||
QTimer *m_timeout = nullptr;
|
||||
QString m_urdfSource;
|
||||
QLineEdit *m_urdfPath = nullptr;
|
||||
QComboBox *m_urdfReference = nullptr, *m_urdfCamera = nullptr;
|
||||
QCheckBox *m_urdfConfirmed = nullptr;
|
||||
QPushButton *m_updateUrdf = nullptr;
|
||||
QLabel *m_recordInfo = nullptr;
|
||||
};
|
||||
389
src/handeyestore.cpp
Normal file
389
src/handeyestore.cpp
Normal file
@ -0,0 +1,389 @@
|
||||
#include "handeyestore.h"
|
||||
#include <QCryptographicHash>
|
||||
#include <QSettings>
|
||||
#include <QSet>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
namespace HandEyeStore {
|
||||
namespace {
|
||||
bool fail(QString &error, const char *message)
|
||||
{
|
||||
error = QString::fromUtf8(message);
|
||||
return false;
|
||||
}
|
||||
bool validText(const QString &value)
|
||||
{
|
||||
return !value.trimmed().isEmpty() && value == value.trimmed()
|
||||
&& !value.contains(QChar::Null);
|
||||
}
|
||||
QString key(const QString &endpoint, const QString &device)
|
||||
{
|
||||
QByteArray identity = endpoint.trimmed().toUtf8();
|
||||
identity.append('\0');
|
||||
identity.append(device.trimmed().toUtf8());
|
||||
return QStringLiteral("handEyeCalibration/v1/") + QString::fromLatin1(
|
||||
QCryptographicHash::hash(identity, QCryptographicHash::Sha256).toHex());
|
||||
}
|
||||
QString direction(const QString &mode)
|
||||
{
|
||||
return mode == QStringLiteral("eye_in_hand")
|
||||
? QStringLiteral("Flange_T_Camera") : QStringLiteral("Base_T_Camera");
|
||||
}
|
||||
bool numeric(const QVariant &value)
|
||||
{
|
||||
return value.type() == QVariant::Double || value.userType() == QMetaType::Float || value.type() == QVariant::Int
|
||||
|| value.type() == QVariant::UInt || value.type() == QVariant::LongLong
|
||||
|| value.type() == QVariant::ULongLong;
|
||||
}
|
||||
bool finiteMetadata(const QVariant &value, int depth = 0)
|
||||
{
|
||||
if (depth > 32) return false;
|
||||
if (numeric(value)) return std::isfinite(value.toDouble());
|
||||
if (value.type() == QVariant::Map) {
|
||||
const auto map = value.toMap();
|
||||
for (auto it = map.cbegin(); it != map.cend(); ++it)
|
||||
if (!finiteMetadata(it.value(), depth + 1)) return false;
|
||||
} else if (value.type() == QVariant::List) {
|
||||
for (const auto &entry : value.toList())
|
||||
if (!finiteMetadata(entry, depth + 1)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool finiteNumber(const QVariant &value)
|
||||
{
|
||||
return numeric(value) && std::isfinite(value.toDouble());
|
||||
}
|
||||
bool integerInRange(const QVariant &value, int minimum, int maximum)
|
||||
{
|
||||
if (!finiteNumber(value)) return false;
|
||||
const double number = value.toDouble();
|
||||
return number >= minimum && number <= maximum && std::floor(number) == number;
|
||||
}
|
||||
bool numericList(const QVariant &value, int size)
|
||||
{
|
||||
if (value.type() != QVariant::List || value.toList().size() != size) return false;
|
||||
for (const auto &entry : value.toList()) if (!finiteNumber(entry)) return false;
|
||||
return true;
|
||||
}
|
||||
bool rigidMatrix(const QVariant &value, TcpCalibration::Matrix *output = nullptr)
|
||||
{
|
||||
if (!numericList(value,16)) return false;
|
||||
const auto values = value.toList();
|
||||
TcpCalibration::Matrix matrix{};
|
||||
for (int i = 0; i < 16; ++i) matrix[size_t(i)] = values.at(i).toDouble();
|
||||
TcpCalibration::Pose ignored{};
|
||||
if (!TcpCalibration::matrixPose(matrix,ignored)) return false;
|
||||
if (output) *output = matrix;
|
||||
return true;
|
||||
}
|
||||
bool validObservations(const Record &record, QString &error)
|
||||
{
|
||||
if (record.observations.isEmpty()) return true;
|
||||
const int minimum = record.refinement.isEmpty() ? 5 : 6;
|
||||
if (record.observations.size() < minimum || record.observations.size() > 100
|
||||
|| record.sampleCount > record.observations.size())
|
||||
return fail(error,"原始观测须包含全部有效样本,最多 100 组;位姿解至少 5 组,联合优化至少 6 组");
|
||||
for (const auto &value : record.observations) {
|
||||
if (value.type() != QVariant::Map || !finiteMetadata(value))
|
||||
return fail(error,"原始观测必须是对象且不能包含非有限数值");
|
||||
const auto observation = value.toMap();
|
||||
if (!rigidMatrix(observation.value("T_base_flange"))
|
||||
|| !rigidMatrix(observation.value("T_camera_target")))
|
||||
return fail(error,"原始观测的法兰或标定板位姿不是有效刚体变换");
|
||||
if (!finiteNumber(observation.value("reprojection_px"))
|
||||
|| observation.value("reprojection_px").toDouble() < 0.)
|
||||
return fail(error,"原始观测的重投影误差必须是非负有限数值");
|
||||
if (!integerInRange(observation.value("width"),2,8192)
|
||||
|| !integerInRange(observation.value("height"),2,8192))
|
||||
return fail(error,"原始观测图像尺寸必须是 2 至 8192 的整数");
|
||||
if (!numericList(observation.value("K"),9))
|
||||
return fail(error,"原始观测相机内参必须包含 9 个有限数值");
|
||||
const auto k = observation.value("K").toList();
|
||||
if (k.at(0).toDouble() <= 0. || k.at(4).toDouble() <= 0.
|
||||
|| std::abs(k.at(6).toDouble()) > 1e-12 || std::abs(k.at(7).toDouble()) > 1e-12
|
||||
|| std::abs(k.at(8).toDouble()-1.) > 1e-12)
|
||||
return fail(error,"原始观测相机焦距必须为正且内参末行为 [0,0,1]");
|
||||
const int distortionSize = observation.value("D").toList().size();
|
||||
if ((distortionSize != 0 && distortionSize != 4 && distortionSize != 5
|
||||
&& distortionSize != 8 && distortionSize != 12 && distortionSize != 14)
|
||||
|| !numericList(observation.value("D"),distortionSize))
|
||||
return fail(error,"原始观测畸变参数数量或数值无效");
|
||||
for (const auto &field : {"image_points","object_points","corner_ids"})
|
||||
if (observation.value(QLatin1String(field)).type() != QVariant::List)
|
||||
return fail(error,"原始观测缺少角点、物点或角点编号列表");
|
||||
const auto pixels = observation.value("image_points").toList();
|
||||
const auto objects = observation.value("object_points").toList();
|
||||
const auto ids = observation.value("corner_ids").toList();
|
||||
if (pixels.size() < 6 || pixels.size() > 10000 || pixels.size() != objects.size()
|
||||
|| pixels.size() != ids.size())
|
||||
return fail(error,"原始观测需要 6 至 10000 个配对的角点、物点与编号");
|
||||
QSet<int> uniqueIds;
|
||||
for (int i = 0; i < pixels.size(); ++i) {
|
||||
if (!numericList(pixels.at(i),2) || !numericList(objects.at(i),3)
|
||||
|| !integerInRange(ids.at(i),0,std::numeric_limits<int>::max()))
|
||||
return fail(error,"原始观测坐标必须是有限数值且角点编号必须是非负整数");
|
||||
const int id = ids.at(i).toInt();
|
||||
if (uniqueIds.contains(id)) return fail(error,"原始观测角点编号不能重复");
|
||||
uniqueIds.insert(id);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool validRefinement(const Record &record, QString &error)
|
||||
{
|
||||
if (record.refinement.isEmpty()) return true;
|
||||
const auto &refinement = record.refinement;
|
||||
if (record.observations.isEmpty() || record.sampleCount < 6)
|
||||
return fail(error,"联合优化结果必须保留原始观测且至少有 6 组有效样本");
|
||||
if (!finiteMetadata(refinement)
|
||||
|| refinement.value("method").type() != QVariant::String
|
||||
|| refinement.value("method").toString() != QStringLiteral("joint_reprojection_lm"))
|
||||
return fail(error,"联合优化方法或结果数值无效");
|
||||
for (const auto &field : {"accepted","converged"})
|
||||
if (refinement.value(QLatin1String(field)).type() != QVariant::Bool
|
||||
|| !refinement.value(QLatin1String(field)).toBool())
|
||||
return fail(error,"联合优化必须已收敛且通过质量检查");
|
||||
const bool inHand = record.mode == QStringLiteral("eye_in_hand");
|
||||
if (refinement.value("matrix_name").type() != QVariant::String
|
||||
|| refinement.value("fixed_matrix_name").type() != QVariant::String
|
||||
|| refinement.value("matrix_name").toString() != (inHand ? "T_flange_camera" : "T_base_camera")
|
||||
|| refinement.value("fixed_matrix_name").toString() != (inHand ? "T_base_target" : "T_flange_target"))
|
||||
return fail(error,"联合优化矩阵方向与安装方式不一致");
|
||||
TcpCalibration::Matrix refined{};
|
||||
if (!rigidMatrix(refinement.value("matrix"),&refined)
|
||||
|| !rigidMatrix(refinement.value("fixed_matrix"))
|
||||
|| !rigidMatrix(refinement.value("initial_matrix"))
|
||||
|| !rigidMatrix(refinement.value("initial_fixed_matrix")))
|
||||
return fail(error,"联合优化的初始或最终矩阵不是有效刚体变换");
|
||||
for (size_t i = 0; i < refined.size(); ++i)
|
||||
if (std::abs(refined[i]-record.transform[i]) > 1e-12)
|
||||
return fail(error,"联合优化最终矩阵与保存的变换不一致");
|
||||
if (refinement.value("metrics").type() != QVariant::Map
|
||||
|| refinement.value("quality_flags").type() != QVariant::List)
|
||||
return fail(error,"联合优化缺少质量指标或质量标记列表");
|
||||
if (!refinement.value("quality_flags").toList().isEmpty())
|
||||
return fail(error,"联合优化仍有质量警告,禁止保存与转换");
|
||||
const auto metrics = refinement.value("metrics").toMap();
|
||||
for (const auto &field : {"initial_rms_px","final_rms_px","validation_rms_px","jacobian_condition"})
|
||||
if (!finiteNumber(metrics.value(QLatin1String(field)))
|
||||
|| metrics.value(QLatin1String(field)).toDouble() < 0.)
|
||||
return fail(error,"联合优化误差与条件数必须是非负有限数值");
|
||||
if (metrics.value("final_rms_px").toDouble() > 1.5
|
||||
|| metrics.value("validation_rms_px").toDouble() > 3.
|
||||
|| !integerInRange(metrics.value("validation_sample_count"),record.sampleCount,record.sampleCount)
|
||||
|| !integerInRange(metrics.value("iterations"),0,std::numeric_limits<int>::max()))
|
||||
return fail(error,"联合优化误差超限或验证样本数、迭代次数无效");
|
||||
return true;
|
||||
}
|
||||
bool write(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
const Snapshot &snapshot, QString &error)
|
||||
{
|
||||
QVariantList records;
|
||||
for (const auto &r : snapshot.records) {
|
||||
QVariantList matrix;
|
||||
for (double value : r.transform) matrix.append(value);
|
||||
QVariantMap entry{{"name",r.name},{"cameraId",r.cameraId},{"mode",r.mode},
|
||||
{"method",r.method},{"createdAt",r.createdAt},{"transformSI",matrix},
|
||||
{"matrixDirection",direction(r.mode)},{"sampleCount",r.sampleCount},
|
||||
{"metrics",r.metrics},{"board",r.board},{"intrinsics",r.intrinsics}};
|
||||
if (!r.refinement.isEmpty()) entry.insert("refinement",r.refinement);
|
||||
if (!r.cameraSerial.isEmpty()) entry.insert("cameraSerial",r.cameraSerial);
|
||||
if (!r.cameraModel.isEmpty()) entry.insert("cameraModel",r.cameraModel);
|
||||
if (!r.observations.isEmpty()) entry.insert("observations",r.observations);
|
||||
records.append(entry);
|
||||
}
|
||||
const QString storageKey = key(endpoint, device);
|
||||
const bool existed = settings.contains(storageKey);
|
||||
const QVariant previous = settings.value(storageKey);
|
||||
settings.setValue(storageKey, QVariantMap{{"schemaVersion",1},{"units","m_rad"},
|
||||
{"endpoint",endpoint.trimmed()},{"device",device.trimmed()},
|
||||
{"current",snapshot.current},{"records",records}});
|
||||
settings.sync();
|
||||
if (settings.status() != QSettings::NoError) {
|
||||
// Restore the pending value as well; QSettings can retry on destruction.
|
||||
if (existed) settings.setValue(storageKey, previous);
|
||||
else settings.remove(storageKey);
|
||||
error = QStringLiteral("本机手眼标定设置写入失败,请检查配置位置权限:%1").arg(settings.fileName());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool readRecord(const QVariant &value, Record &record, QString &error)
|
||||
{
|
||||
if (value.type() != QVariant::Map)
|
||||
return fail(error,"本机手眼标定记录必须是对象,未覆盖原配置");
|
||||
const auto map = value.toMap();
|
||||
for (const auto &field : {"name","cameraId","mode","method","createdAt","matrixDirection"})
|
||||
if (map.value(QLatin1String(field)).type() != QVariant::String)
|
||||
return fail(error,"本机手眼标定记录缺少文本字段或字段类型错误,未覆盖原配置");
|
||||
for (const auto &field : {"metrics","board","intrinsics"})
|
||||
if (map.value(QLatin1String(field)).type() != QVariant::Map)
|
||||
return fail(error,"本机手眼标定记录缺少质量、标定板或内参对象,未覆盖原配置");
|
||||
if (map.value("sampleCount").type() != QVariant::Int
|
||||
|| map.value("transformSI").type() != QVariant::List)
|
||||
return fail(error,"本机手眼标定采样数或变换矩阵类型错误,未覆盖原配置");
|
||||
record.name = map.value("name").toString();
|
||||
record.cameraId = map.value("cameraId").toString();
|
||||
for(const auto& field:{"cameraSerial","cameraModel"})
|
||||
if(map.contains(field) && map.value(field).type()!=QVariant::String) return fail(error,"相机身份字段必须是文本");
|
||||
record.cameraSerial = map.value("cameraSerial").toString();
|
||||
record.cameraModel = map.value("cameraModel").toString();
|
||||
record.mode = map.value("mode").toString();
|
||||
record.method = map.value("method").toString();
|
||||
record.createdAt = map.value("createdAt").toString();
|
||||
record.sampleCount = map.value("sampleCount").toInt();
|
||||
record.metrics = map.value("metrics").toMap();
|
||||
record.board = map.value("board").toMap();
|
||||
record.intrinsics = map.value("intrinsics").toMap();
|
||||
if ((map.contains("refinement") && map.value("refinement").type() != QVariant::Map)
|
||||
|| (map.contains("observations") && map.value("observations").type() != QVariant::List))
|
||||
return fail(error,"本机手眼联合优化或原始观测字段类型错误,未覆盖原配置");
|
||||
record.refinement = map.value("refinement").toMap();
|
||||
record.observations = map.value("observations").toList();
|
||||
if (map.value("matrixDirection").toString() != direction(record.mode))
|
||||
return fail(error,"本机手眼标定矩阵方向与安装方式不一致,未覆盖原配置");
|
||||
const auto matrix = map.value("transformSI").toList();
|
||||
if (matrix.size() != 16)
|
||||
return fail(error,"本机手眼标定变换矩阵必须包含 16 个数值,未覆盖原配置");
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
if (!numeric(matrix.at(i)))
|
||||
return fail(error,"本机手眼标定变换矩阵包含非数值,未覆盖原配置");
|
||||
record.transform[size_t(i)] = matrix.at(i).toDouble();
|
||||
}
|
||||
return validateRecord(record,error);
|
||||
}
|
||||
}
|
||||
|
||||
bool validateRecord(const Record &record, QString &error)
|
||||
{
|
||||
error.clear();
|
||||
if (!validText(record.name) || record.name.size() > 80)
|
||||
return fail(error,"标定名称不能为空、包含空字符或首尾空格,长度不能超过 80 个字符");
|
||||
if (!validText(record.cameraId)) return fail(error,"相机 ID 不能为空或包含首尾空格、空字符");
|
||||
if((!record.cameraSerial.isEmpty() && !validText(record.cameraSerial)) || (!record.cameraModel.isEmpty() && !validText(record.cameraModel)))
|
||||
return fail(error,"相机序列号或型号包含非法字符");
|
||||
if (record.mode != QStringLiteral("eye_in_hand") && record.mode != QStringLiteral("eye_to_hand"))
|
||||
return fail(error,"手眼安装方式必须是 eye_in_hand 或 eye_to_hand");
|
||||
if (!validText(record.method) || !validText(record.createdAt))
|
||||
return fail(error,"标定方法与创建时间不能为空或包含首尾空格、空字符");
|
||||
if (record.sampleCount < 5) return fail(error,"手眼标定至少需要 5 组有效样本");
|
||||
if (record.metrics.value("accepted").type() != QVariant::Bool
|
||||
|| !record.metrics.value("accepted").toBool())
|
||||
return fail(error,"手眼标定缺少合格质量标记或质量检查未通过,禁止保存与转换");
|
||||
if (!finiteMetadata(record.metrics) || !finiteMetadata(record.board) || !finiteMetadata(record.intrinsics))
|
||||
return fail(error,"质量指标、标定板或相机内参包含非有限数值或嵌套层级过深");
|
||||
TcpCalibration::Pose ignored{};
|
||||
if (!TcpCalibration::matrixPose(record.transform,ignored))
|
||||
return fail(error,"变换矩阵必须有限、末行为 [0,0,0,1],旋转正交且行列式为 +1");
|
||||
return validObservations(record,error) && validRefinement(record,error);
|
||||
}
|
||||
|
||||
bool load(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
Snapshot &snapshot, QString &error)
|
||||
{
|
||||
snapshot = Snapshot{};
|
||||
error.clear();
|
||||
if (!validText(endpoint.trimmed()) || !validText(device.trimmed()))
|
||||
return fail(error,"服务器地址和机械臂设备 ID 不能为空或包含空字符");
|
||||
settings.sync();
|
||||
if (settings.status() != QSettings::NoError) {
|
||||
error = QStringLiteral("无法读取本机手眼标定设置:%1").arg(settings.fileName());
|
||||
return false;
|
||||
}
|
||||
const QString storageKey = key(endpoint,device);
|
||||
if (!settings.contains(storageKey)) return true;
|
||||
const QVariant value = settings.value(storageKey);
|
||||
const auto map = value.toMap();
|
||||
if (value.type() != QVariant::Map || map.value("schemaVersion").type() != QVariant::Int
|
||||
|| map.value("schemaVersion").toInt() != 1
|
||||
|| map.value("units").type() != QVariant::String || map.value("units").toString() != QStringLiteral("m_rad")
|
||||
|| map.value("endpoint").type() != QVariant::String || map.value("endpoint").toString() != endpoint.trimmed()
|
||||
|| map.value("device").type() != QVariant::String || map.value("device").toString() != device.trimmed()
|
||||
|| map.value("current").type() != QVariant::String || map.value("records").type() != QVariant::List)
|
||||
return fail(error,"本机手眼标定配置格式、版本、单位或设备身份无效,未覆盖原配置");
|
||||
Snapshot result;
|
||||
QSet<QString> names;
|
||||
for (const auto &entry : map.value("records").toList()) {
|
||||
Record record;
|
||||
if (!readRecord(entry,record,error)) return false;
|
||||
if (names.contains(record.name)) return fail(error,"本机手眼标定记录重名,未覆盖原配置");
|
||||
names.insert(record.name);
|
||||
result.records.append(record);
|
||||
}
|
||||
result.current = map.value("current").toString();
|
||||
if (!result.current.isEmpty() && !names.contains(result.current))
|
||||
return fail(error,"当前本机手眼标定引用不存在,未覆盖原配置");
|
||||
snapshot = result;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool save(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
const Record &record, bool replace, QString &error)
|
||||
{
|
||||
if (!validateRecord(record,error)) return false;
|
||||
Snapshot snapshot;
|
||||
if (!load(settings,endpoint,device,snapshot,error)) return false;
|
||||
int index = -1;
|
||||
for (int i = 0; i < snapshot.records.size(); ++i)
|
||||
if (snapshot.records.at(i).name == record.name) index = i;
|
||||
if (index >= 0 && !replace) return fail(error,"标定名称已存在,请确认覆盖或更换名称");
|
||||
if (index >= 0) snapshot.records[index] = record;
|
||||
else snapshot.records.append(record);
|
||||
snapshot.current = record.name;
|
||||
return write(settings,endpoint,device,snapshot,error);
|
||||
}
|
||||
|
||||
bool select(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
const QString &name, QString &error)
|
||||
{
|
||||
Snapshot snapshot;
|
||||
if (!load(settings,endpoint,device,snapshot,error)) return false;
|
||||
bool found = name.isEmpty();
|
||||
for (const auto &r : snapshot.records) found |= r.name == name;
|
||||
if (!found) return fail(error,"本机手眼标定记录不存在");
|
||||
snapshot.current = name;
|
||||
return write(settings,endpoint,device,snapshot,error);
|
||||
}
|
||||
|
||||
bool remove(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
const QString &name, QString &error)
|
||||
{
|
||||
Snapshot snapshot;
|
||||
if (!load(settings,endpoint,device,snapshot,error)) return false;
|
||||
for (int i = 0; i < snapshot.records.size(); ++i) {
|
||||
if (snapshot.records.at(i).name != name) continue;
|
||||
snapshot.records.removeAt(i);
|
||||
if (snapshot.current == name) snapshot.current.clear();
|
||||
return write(settings,endpoint,device,snapshot,error);
|
||||
}
|
||||
return fail(error,"本机手眼标定记录不存在");
|
||||
}
|
||||
|
||||
bool cameraPointToBase(const Record &record, const TcpCalibration::Pose &baseFlange,
|
||||
const std::array<double,3> &cameraPoint,
|
||||
std::array<double,3> &basePoint, QString &error)
|
||||
{
|
||||
if (!validateRecord(record,error)) return false;
|
||||
for (double value : cameraPoint)
|
||||
if (!std::isfinite(value)) return fail(error,"相机点坐标必须是有限的米制数值");
|
||||
TcpCalibration::Matrix matrix = record.transform;
|
||||
if (record.mode == QStringLiteral("eye_in_hand")) {
|
||||
TcpCalibration::Matrix flange{};
|
||||
if (!TcpCalibration::poseMatrix(baseFlange,flange))
|
||||
return fail(error,"基座到法兰位姿必须是有限数值,单位为米和弧度");
|
||||
matrix.fill(0.0);
|
||||
for (int r = 0; r < 4; ++r) for (int c = 0; c < 4; ++c)
|
||||
for (int k = 0; k < 4; ++k)
|
||||
matrix[size_t(r*4+c)] += flange[size_t(r*4+k)] * record.transform[size_t(k*4+c)];
|
||||
}
|
||||
std::array<double,3> result{};
|
||||
for (int r = 0; r < 3; ++r) {
|
||||
result[size_t(r)] = matrix[size_t(r*4+3)];
|
||||
for (int c = 0; c < 3; ++c) result[size_t(r)] += matrix[size_t(r*4+c)] * cameraPoint[size_t(c)];
|
||||
if (!std::isfinite(result[size_t(r)])) return fail(error,"坐标转换溢出,结果不是有限数值");
|
||||
}
|
||||
basePoint = result;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
42
src/handeyestore.h
Normal file
42
src/handeyestore.h
Normal file
@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
|
||||
#include "tcpcalibration.h"
|
||||
#include <QList>
|
||||
#include <QString>
|
||||
#include <QVariantMap>
|
||||
|
||||
class QSettings;
|
||||
|
||||
// Local results only; no controller configuration or automatic robot movement.
|
||||
namespace HandEyeStore {
|
||||
struct Record {
|
||||
QString name, cameraId, mode, method, createdAt;
|
||||
QString cameraSerial, cameraModel;
|
||||
// Row-major, metres. eye_in_hand: Flange_T_Camera;
|
||||
// eye_to_hand: Base_T_Camera. Pose angles use ZYX radians.
|
||||
TcpCalibration::Matrix transform{};
|
||||
QVariantMap metrics, board, intrinsics;
|
||||
// Optional joint-refinement result and original phone observations (SI).
|
||||
// Empty fields preserve compatibility with pose-only v1 records.
|
||||
QVariantMap refinement;
|
||||
QVariantList observations;
|
||||
int sampleCount = 0;
|
||||
};
|
||||
struct Snapshot {
|
||||
QList<Record> records;
|
||||
QString current;
|
||||
};
|
||||
bool validateRecord(const Record &record, QString &error);
|
||||
bool load(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
Snapshot &snapshot, QString &error);
|
||||
bool save(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
const Record &record, bool replace, QString &error);
|
||||
bool select(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
const QString &name, QString &error);
|
||||
bool remove(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
const QString &name, QString &error);
|
||||
// Output is unchanged on failure. eye_to_hand does not use baseFlange.
|
||||
bool cameraPointToBase(const Record &record, const TcpCalibration::Pose &baseFlange,
|
||||
const std::array<double, 3> &cameraPoint,
|
||||
std::array<double, 3> &basePoint, QString &error);
|
||||
}
|
||||
188
src/handeyeurdf.cpp
Normal file
188
src/handeyeurdf.cpp
Normal file
@ -0,0 +1,188 @@
|
||||
#include "handeyeurdf.h"
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QHash>
|
||||
#include <QRegularExpression>
|
||||
#include <QSaveFile>
|
||||
#include <QSet>
|
||||
#include <QXmlStreamReader>
|
||||
#include <QXmlStreamWriter>
|
||||
#include <cmath>
|
||||
|
||||
namespace {
|
||||
using Matrix = TcpCalibration::Matrix;
|
||||
struct Joint {
|
||||
QString name, type, parent, child;
|
||||
TcpCalibration::Pose origin{};
|
||||
int parents = 0, children = 0, origins = 0;
|
||||
};
|
||||
struct Model { QByteArray xml; QStringList links; QList<Joint> joints; QHash<QString,int> incoming; };
|
||||
bool fail(QString &error, const QString &message) { error = message; return false; }
|
||||
bool triple(const QString &s, TcpCalibration::Pose &pose, int offset)
|
||||
{
|
||||
if (s.isEmpty()) return true;
|
||||
const auto values = s.split(QRegularExpression("\\s+"),QString::SkipEmptyParts);
|
||||
if (values.size()!=3) return false;
|
||||
for (int i=0;i<3;++i) { bool ok=false; const double v=values[i].toDouble(&ok);
|
||||
if (!ok || !std::isfinite(v)) return false;
|
||||
pose[offset+i]=v;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool parse(const QString &path, Model &model, QString &error)
|
||||
{
|
||||
QFile file(path);
|
||||
if (!file.open(QIODevice::ReadOnly)) return fail(error,file.errorString());
|
||||
model.xml=file.readAll();
|
||||
QXmlStreamReader reader(model.xml);
|
||||
int depth=0, jointIndex=-1; QSet<QString> jointNames;
|
||||
while (!reader.atEnd()) {
|
||||
reader.readNext();
|
||||
if (reader.isDTD() || reader.isEntityReference()) return fail(error,"DTD/entity URDF is not supported.");
|
||||
if (reader.isStartElement()) {
|
||||
++depth;
|
||||
const QString name=reader.name().toString(); const auto a=reader.attributes();
|
||||
if (!reader.namespaceUri().isEmpty() || reader.qualifiedName().contains(':'))
|
||||
return fail(error,"Expand Xacro/namespaced XML before exporting URDF.");
|
||||
for (const auto &attr:a) if (attr.value().contains("${") || attr.value().contains("$("))
|
||||
return fail(error,"Unexpanded Xacro expressions are not supported.");
|
||||
if (depth==1 && name!="robot") return fail(error,"Expected a URDF robot root.");
|
||||
if (name=="mimic") return fail(error,"Mimic joints are not supported by this exporter.");
|
||||
if (depth==2 && name=="link") {
|
||||
const QString link=a.value("name").toString();
|
||||
if (link.isEmpty() || model.links.contains(link)) return fail(error,"Missing or duplicate link name.");
|
||||
model.links.append(link);
|
||||
}
|
||||
if (depth==2 && name=="joint") {
|
||||
Joint j; j.name=a.value("name").toString(); j.type=a.value("type").toString();
|
||||
if (j.name.isEmpty() || jointNames.contains(j.name)) return fail(error,"Missing or duplicate joint name.");
|
||||
if (!QStringList{"fixed","revolute","continuous","prismatic","floating","planar"}.contains(j.type))
|
||||
return fail(error,"Unknown or missing joint type.");
|
||||
jointNames.insert(j.name); model.joints.append(j); jointIndex=model.joints.size()-1;
|
||||
} else if (depth==3 && jointIndex>=0) {
|
||||
Joint &j=model.joints[jointIndex];
|
||||
if (name=="parent") { j.parent=a.value("link").toString(); ++j.parents; }
|
||||
if (name=="child") { j.child=a.value("link").toString(); ++j.children; }
|
||||
if (name=="origin") { ++j.origins;
|
||||
if (!triple(a.value("xyz").toString(),j.origin,0) || !triple(a.value("rpy").toString(),j.origin,3))
|
||||
return fail(error,"Joint origin must contain finite xyz/rpy triples."); }
|
||||
}
|
||||
} else if (reader.isEndElement()) { if (depth==2) jointIndex=-1; --depth; }
|
||||
}
|
||||
if (reader.hasError()) return fail(error,reader.errorString());
|
||||
if (model.links.isEmpty()) return fail(error,"URDF contains no links.");
|
||||
for (int i=0;i<model.joints.size();++i) {
|
||||
const Joint &j=model.joints[i];
|
||||
if (j.parents!=1 || j.children!=1 || j.origins>1 || !model.links.contains(j.parent)
|
||||
|| !model.links.contains(j.child) || j.parent==j.child || model.incoming.contains(j.child))
|
||||
return fail(error,"Invalid or ambiguous joint parent/child structure.");
|
||||
model.incoming.insert(j.child,i);
|
||||
}
|
||||
QSet<QString> roots;
|
||||
for (const QString &link:model.links) {
|
||||
QString current=link; QSet<QString> seen;
|
||||
while (model.incoming.contains(current)) {
|
||||
if (seen.contains(current)) return fail(error,"URDF joint cycle detected.");
|
||||
seen.insert(current); current=model.joints[model.incoming.value(current)].parent;
|
||||
}
|
||||
roots.insert(current);
|
||||
}
|
||||
if (roots.size()!=1) return fail(error,"URDF links are disconnected.");
|
||||
error.clear(); return true;
|
||||
}
|
||||
Matrix product(const Matrix &a,const Matrix &b) {
|
||||
Matrix c{}; for(int i=0;i<4;++i) for(int j=0;j<4;++j) for(int k=0;k<4;++k) c[4*i+j]+=a[4*i+k]*b[4*k+j]; return c;
|
||||
}
|
||||
Matrix inverse(const Matrix &a) {
|
||||
Matrix b{}; b[15]=1; for(int i=0;i<3;++i) { for(int j=0;j<3;++j) b[4*i+j]=a[4*j+i];
|
||||
for(int j=0;j<3;++j) b[4*i+3]-=b[4*i+j]*a[4*j+3]; } return b;
|
||||
}
|
||||
QString tripleText(const TcpCalibration::Pose &p,int offset) {
|
||||
return QString("%1 %2 %3").arg(QString::number(p[offset],'g',17),QString::number(p[offset+1],'g',17),QString::number(p[offset+2],'g',17));
|
||||
}
|
||||
void origin(QXmlStreamWriter &w,const TcpCalibration::Pose &p) {
|
||||
w.writeEmptyElement("origin"); w.writeAttribute("xyz",tripleText(p,0)); w.writeAttribute("rpy",tripleText(p,3));
|
||||
}
|
||||
}
|
||||
namespace HandEyeUrdf {
|
||||
bool readUrdf(const QString &path, QStringList &links, QList<FixedJoint> &fixedJoints, QString &error)
|
||||
{
|
||||
Model model; if (!parse(path,model,error)) return false;
|
||||
QList<FixedJoint> candidates;
|
||||
for (const auto &j:model.joints) if (j.type=="fixed") candidates.append({j.name,j.parent,j.child});
|
||||
links=model.links; fixedJoints=candidates; return true;
|
||||
}
|
||||
bool update(const QString &source,const QString &target,const QString &referenceLink,
|
||||
const QString &cameraLink,const HandEyeStore::Record &record,QString &error)
|
||||
{
|
||||
if (!HandEyeStore::validateRecord(record,error)) return false;
|
||||
if (target.trimmed().isEmpty() || QFileInfo::exists(target)
|
||||
|| QFileInfo(source).absoluteFilePath().compare(QFileInfo(target).absoluteFilePath(),Qt::CaseInsensitive)==0)
|
||||
return fail(error,"Export requires a new file; the source and existing files are never overwritten.");
|
||||
Model model; if (!parse(source,model,error)) return false;
|
||||
if (!model.links.contains(referenceLink) || cameraLink==referenceLink)
|
||||
return fail(error,"Choose a valid reference link distinct from the camera frame.");
|
||||
const bool add=!model.links.contains(cameraLink);
|
||||
if (add && !QRegularExpression("^[A-Za-z_][A-Za-z0-9_.-]*$").match(cameraLink).hasMatch())
|
||||
return fail(error,"A new camera link needs a simple nonempty identifier.");
|
||||
QString jointName=cameraLink+"_handeye_fixed";
|
||||
Matrix transform=record.transform;
|
||||
if (!add) {
|
||||
if (!model.incoming.contains(cameraLink)) return fail(error,"The camera link has no incoming fixed joint.");
|
||||
const Joint &camera=model.joints[model.incoming.value(cameraLink)]; jointName=camera.name;
|
||||
if (camera.type!="fixed") return fail(error,"Camera joint must be fixed.");
|
||||
Matrix preceding{}; TcpCalibration::poseMatrix(TcpCalibration::Pose{},preceding);
|
||||
QString current=camera.parent;
|
||||
while (current!=referenceLink) {
|
||||
if (!model.incoming.contains(current)) return fail(error,"Reference must be an ancestor of the camera through fixed joints.");
|
||||
const Joint &j=model.joints[model.incoming.value(current)];
|
||||
if (j.type!="fixed") return fail(error,"Reference-to-camera chain includes a moving joint.");
|
||||
Matrix local{}; if (!TcpCalibration::poseMatrix(j.origin,local,&error)) return false;
|
||||
preceding=product(local,preceding); current=j.parent;
|
||||
}
|
||||
transform=product(inverse(preceding),record.transform);
|
||||
} else {
|
||||
QSet<QString> names; for(const auto &j:model.joints) names.insert(j.name);
|
||||
while(names.contains(jointName)) jointName+="_";
|
||||
}
|
||||
TcpCalibration::Pose pose{}; if (!TcpCalibration::matrixPose(transform,pose,&error)) return false;
|
||||
QByteArray bytes; QXmlStreamReader r(model.xml); QXmlStreamWriter w(&bytes);
|
||||
int depth=0; bool selected=false, hasOrigin=false;
|
||||
while (!r.atEnd()) {
|
||||
r.readNext();
|
||||
if (r.isStartElement()) {
|
||||
++depth; const QString name=r.name().toString();
|
||||
if (depth==2 && name=="joint") { selected=!add && r.attributes().value("name")==jointName; hasOrigin=false; }
|
||||
const bool replaceOrigin=selected && depth==3 && name=="origin";
|
||||
const bool resource=(name=="mesh" || name=="texture") && r.attributes().hasAttribute("filename");
|
||||
if (replaceOrigin || resource) {
|
||||
w.writeStartElement(r.qualifiedName().toString());
|
||||
for (const auto &ns:r.namespaceDeclarations()) w.writeNamespace(ns.namespaceUri().toString(),ns.prefix().toString());
|
||||
for (const auto &a:r.attributes()) {
|
||||
QString value=a.value().toString();
|
||||
if (replaceOrigin && (a.name()=="xyz" || a.name()=="rpy")) continue;
|
||||
if (resource && a.name()=="filename" && !value.contains("://") && !QFileInfo(value).isAbsolute())
|
||||
value=QDir::cleanPath(QFileInfo(source).dir().absoluteFilePath(value));
|
||||
w.writeAttribute(a.qualifiedName().toString(),value);
|
||||
}
|
||||
if (replaceOrigin) { hasOrigin=true; w.writeAttribute("xyz",tripleText(pose,0)); w.writeAttribute("rpy",tripleText(pose,3)); }
|
||||
} else w.writeCurrentToken(r);
|
||||
} else if (r.isEndElement()) {
|
||||
if (depth==2 && selected) { if(!hasOrigin) origin(w,pose); selected=false; }
|
||||
if (depth==1 && add) {
|
||||
w.writeEmptyElement("link"); w.writeAttribute("name",cameraLink);
|
||||
w.writeStartElement("joint"); w.writeAttribute("name",jointName); w.writeAttribute("type","fixed");
|
||||
w.writeEmptyElement("parent"); w.writeAttribute("link",referenceLink);
|
||||
w.writeEmptyElement("child"); w.writeAttribute("link",cameraLink);
|
||||
origin(w,pose); w.writeEndElement();
|
||||
}
|
||||
w.writeCurrentToken(r); --depth;
|
||||
} else w.writeCurrentToken(r);
|
||||
}
|
||||
if (r.hasError() || w.hasError()) return fail(error,"Could not serialize URDF.");
|
||||
QSaveFile out(target); out.setDirectWriteFallback(false);
|
||||
if (!out.open(QIODevice::WriteOnly) || out.write(bytes)!=bytes.size() || !out.commit()) return fail(error,out.errorString());
|
||||
error.clear(); return true;
|
||||
}
|
||||
}
|
||||
18
src/handeyeurdf.h
Normal file
18
src/handeyeurdf.h
Normal file
@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
#include "handeyestore.h"
|
||||
#include <QStringList>
|
||||
|
||||
// File-only export. Caller confirms the selected reference is the calibrated
|
||||
// flange (eye_in_hand) or base (eye_to_hand), and camera is the measured frame.
|
||||
namespace HandEyeUrdf {
|
||||
struct FixedJoint { QString name, parentLink, childLink; };
|
||||
bool readUrdf(const QString &path, QStringList &links,
|
||||
QList<FixedJoint> &fixedJoints, QString &error);
|
||||
// Existing camera: replace its incoming fixed joint; all joints between the
|
||||
// reference and camera must be fixed. New camera: add a fixed leaf.
|
||||
// Target must be a new file distinct from source. Relative mesh/texture paths
|
||||
// become absolute. package:// and other URI paths remain unchanged.
|
||||
bool update(const QString &source, const QString &target,
|
||||
const QString &referenceLink, const QString &cameraLink,
|
||||
const HandEyeStore::Record &record, QString &error);
|
||||
}
|
||||
805
src/jointfloweditor.cpp
Normal file
805
src/jointfloweditor.cpp
Normal file
@ -0,0 +1,805 @@
|
||||
#include "jointfloweditor.h"
|
||||
#include "uiicons.h"
|
||||
|
||||
#include <QGraphicsItem>
|
||||
#include <QGraphicsScene>
|
||||
#include <QGraphicsSceneHoverEvent>
|
||||
#include <QGraphicsSceneMouseEvent>
|
||||
#include <QGraphicsView>
|
||||
#include <QComboBox>
|
||||
#include <QDialog>
|
||||
#include <QDialogButtonBox>
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QEvent>
|
||||
#include <QFormLayout>
|
||||
#include <QFrame>
|
||||
#include <QJsonObject>
|
||||
#include <QHBoxLayout>
|
||||
#include <QLabel>
|
||||
#include <QLineEdit>
|
||||
#include <QMouseEvent>
|
||||
#include <QPainter>
|
||||
#include <QPen>
|
||||
#include <QPushButton>
|
||||
#include <QScrollBar>
|
||||
#include <QSignalBlocker>
|
||||
#include <QSpinBox>
|
||||
#include <QTimer>
|
||||
#include <QVBoxLayout>
|
||||
#include <QUuid>
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
|
||||
namespace {
|
||||
constexpr qreal kNodeWidth = 190.0;
|
||||
constexpr qreal kNodeHeight = 76.0;
|
||||
|
||||
class NodeEditDialog final : public QDialog
|
||||
{
|
||||
public:
|
||||
NodeEditDialog(const QString &title, QWidget *parent)
|
||||
: QDialog(parent, Qt::Tool | Qt::FramelessWindowHint)
|
||||
{
|
||||
setObjectName(QStringLiteral("jointFlowChildDialog"));
|
||||
setAttribute(Qt::WA_TranslucentBackground);
|
||||
QVBoxLayout *outerLayout = new QVBoxLayout(this);
|
||||
outerLayout->setContentsMargins(12, 12, 12, 12);
|
||||
outerLayout->setSpacing(0);
|
||||
QFrame *surface = new QFrame(this);
|
||||
surface->setObjectName(QStringLiteral("jointFlowChildSurface"));
|
||||
QVBoxLayout *surfaceLayout = new QVBoxLayout(surface);
|
||||
surfaceLayout->setContentsMargins(0, 0, 0, 0);
|
||||
surfaceLayout->setSpacing(0);
|
||||
m_titleBar = new QWidget(surface);
|
||||
m_titleBar->setObjectName(QStringLiteral("jointFlowChildTitleBar"));
|
||||
m_titleBar->setFixedHeight(44);
|
||||
QHBoxLayout *titleLayout = new QHBoxLayout(m_titleBar);
|
||||
titleLayout->setContentsMargins(12, 0, 0, 0);
|
||||
titleLayout->setSpacing(9);
|
||||
QLabel *mark = new QLabel(QStringLiteral("C"), m_titleBar);
|
||||
mark->setObjectName(QStringLiteral("jointFlowDialogMark"));
|
||||
mark->setAlignment(Qt::AlignCenter);
|
||||
mark->setFixedSize(24, 24);
|
||||
QLabel *titleLabel = new QLabel(title, m_titleBar);
|
||||
titleLabel->setObjectName(QStringLiteral("jointFlowDialogTitle"));
|
||||
QPushButton *closeButton = new QPushButton(m_titleBar);
|
||||
closeButton->setObjectName(QStringLiteral("jointFlowDialogCloseButton"));
|
||||
closeButton->setFixedSize(46, 43);
|
||||
closeButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/x.svg"),
|
||||
QColor(QStringLiteral("#4f5964")), QColor(QStringLiteral("#4f5964"))));
|
||||
titleLayout->addWidget(mark);
|
||||
titleLayout->addWidget(titleLabel);
|
||||
titleLayout->addStretch(1);
|
||||
titleLayout->addWidget(closeButton);
|
||||
surfaceLayout->addWidget(m_titleBar);
|
||||
QWidget *content = new QWidget(surface);
|
||||
content->setObjectName(QStringLiteral("jointFlowChildContent"));
|
||||
m_contentLayout = new QVBoxLayout(content);
|
||||
m_contentLayout->setContentsMargins(18, 16, 18, 16);
|
||||
m_contentLayout->setSpacing(12);
|
||||
surfaceLayout->addWidget(content, 1);
|
||||
outerLayout->addWidget(surface);
|
||||
m_titleBar->installEventFilter(this);
|
||||
titleLabel->installEventFilter(this);
|
||||
mark->installEventFilter(this);
|
||||
connect(closeButton, &QPushButton::clicked, this, &QDialog::reject);
|
||||
}
|
||||
|
||||
QVBoxLayout *contentLayout() const { return m_contentLayout; }
|
||||
|
||||
protected:
|
||||
bool eventFilter(QObject *watched, QEvent *event) override
|
||||
{
|
||||
if ((watched == m_titleBar || (watched && watched->parent() == m_titleBar)) && event) {
|
||||
if (event->type() == QEvent::MouseButtonPress) {
|
||||
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
|
||||
if (mouseEvent->button() == Qt::LeftButton) {
|
||||
m_dragging = true;
|
||||
m_dragOffset = mouseEvent->globalPos() - frameGeometry().topLeft();
|
||||
return true;
|
||||
}
|
||||
} else if (event->type() == QEvent::MouseMove && m_dragging) {
|
||||
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
|
||||
move(mouseEvent->globalPos() - m_dragOffset);
|
||||
return true;
|
||||
} else if (event->type() == QEvent::MouseButtonRelease) {
|
||||
m_dragging = false;
|
||||
}
|
||||
}
|
||||
return QDialog::eventFilter(watched, event);
|
||||
}
|
||||
|
||||
private:
|
||||
QWidget *m_titleBar = nullptr;
|
||||
QVBoxLayout *m_contentLayout = nullptr;
|
||||
QPoint m_dragOffset;
|
||||
bool m_dragging = false;
|
||||
};
|
||||
|
||||
class FlowGraphicsView final : public QGraphicsView
|
||||
{
|
||||
public:
|
||||
explicit FlowGraphicsView(QGraphicsScene *scene, QWidget *parent = nullptr)
|
||||
: QGraphicsView(scene, parent)
|
||||
{
|
||||
}
|
||||
|
||||
protected:
|
||||
void mousePressEvent(QMouseEvent *event) override
|
||||
{
|
||||
if (event->button() == Qt::RightButton) {
|
||||
m_panning = true;
|
||||
m_lastPosition = event->pos();
|
||||
viewport()->setCursor(Qt::ClosedHandCursor);
|
||||
event->accept();
|
||||
return;
|
||||
}
|
||||
QGraphicsView::mousePressEvent(event);
|
||||
}
|
||||
|
||||
void mouseMoveEvent(QMouseEvent *event) override
|
||||
{
|
||||
if (m_panning) {
|
||||
const QPoint delta = event->pos() - m_lastPosition;
|
||||
m_lastPosition = event->pos();
|
||||
horizontalScrollBar()->setValue(horizontalScrollBar()->value() - delta.x());
|
||||
verticalScrollBar()->setValue(verticalScrollBar()->value() - delta.y());
|
||||
event->accept();
|
||||
return;
|
||||
}
|
||||
QGraphicsView::mouseMoveEvent(event);
|
||||
}
|
||||
|
||||
void mouseReleaseEvent(QMouseEvent *event) override
|
||||
{
|
||||
if (event->button() == Qt::RightButton && m_panning) {
|
||||
m_panning = false;
|
||||
viewport()->unsetCursor();
|
||||
event->accept();
|
||||
return;
|
||||
}
|
||||
QGraphicsView::mouseReleaseEvent(event);
|
||||
}
|
||||
|
||||
private:
|
||||
bool m_panning = false;
|
||||
QPoint m_lastPosition;
|
||||
};
|
||||
|
||||
class FlowCardItem final : public QGraphicsItem
|
||||
{
|
||||
public:
|
||||
FlowCardItem(QString id, QString title, QString subtitle, bool loop, bool active,
|
||||
bool collapsed,
|
||||
std::function<void(const QString &, const QPointF &)> moved,
|
||||
std::function<void(const QString &)> edit,
|
||||
std::function<void(const QString &)> toggleCollapsed)
|
||||
: m_id(std::move(id)), m_title(std::move(title)), m_subtitle(std::move(subtitle)),
|
||||
m_loop(loop), m_active(active), m_collapsed(collapsed),
|
||||
m_moved(std::move(moved)), m_edit(std::move(edit)),
|
||||
m_toggleCollapsed(std::move(toggleCollapsed))
|
||||
{
|
||||
setFlags(ItemIsMovable | ItemIsSelectable | ItemSendsGeometryChanges);
|
||||
setAcceptHoverEvents(true);
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
setZValue(2.0);
|
||||
}
|
||||
|
||||
QRectF boundingRect() const override { return QRectF(0, 0, kNodeWidth, kNodeHeight); }
|
||||
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override
|
||||
{
|
||||
painter->setRenderHint(QPainter::Antialiasing);
|
||||
const QColor fill = m_loop ? QColor("#f4efff") : QColor("#ffffff");
|
||||
const QColor border = m_active ? QColor("#20a36a")
|
||||
: (isSelected() ? QColor("#1b6ef3") : QColor("#cbd6e2"));
|
||||
painter->setPen(QPen(border, m_active ? 3.0 : 1.5));
|
||||
painter->setBrush(fill);
|
||||
painter->drawRoundedRect(boundingRect().adjusted(1, 1, -1, -1), 10, 10);
|
||||
painter->setPen(QColor("#25313d"));
|
||||
QFont titleFont = painter->font();
|
||||
titleFont.setBold(true);
|
||||
painter->setFont(titleFont);
|
||||
painter->drawText(QRectF(14, 10, kNodeWidth - (m_loop ? 58 : 28), 25),
|
||||
Qt::AlignLeft | Qt::AlignVCenter,
|
||||
m_title);
|
||||
if (m_loop) {
|
||||
const QColor buttonFill = m_collapsePressed ? QColor("#d8e9ff")
|
||||
: m_collapseHovered ? QColor("#e8f2ff") : QColor("#ffffff");
|
||||
const QColor buttonBorder = m_collapseHovered || m_collapsePressed
|
||||
? QColor("#1b6ef3") : QColor("#b8c7d8");
|
||||
painter->setPen(QPen(buttonBorder, 1.4));
|
||||
painter->setBrush(buttonFill);
|
||||
painter->drawRoundedRect(collapseButtonRect(), 5, 5);
|
||||
painter->setPen(QPen(QColor("#286fc2"), 1.8,
|
||||
Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
const QPointF center = collapseButtonRect().center();
|
||||
QPolygonF arrow;
|
||||
if (m_collapsed) {
|
||||
arrow << QPointF(center.x() - 3.5, center.y() - 5)
|
||||
<< QPointF(center.x() + 2.0, center.y())
|
||||
<< QPointF(center.x() - 3.5, center.y() + 5);
|
||||
} else {
|
||||
arrow << QPointF(center.x() - 5, center.y() - 3.0)
|
||||
<< QPointF(center.x(), center.y() + 2.5)
|
||||
<< QPointF(center.x() + 5, center.y() - 3.0);
|
||||
}
|
||||
painter->drawPolyline(arrow);
|
||||
}
|
||||
painter->setFont(QFont());
|
||||
painter->setPen(QColor("#687684"));
|
||||
painter->drawText(QRectF(14, 38, kNodeWidth - 28, 26), Qt::AlignLeft | Qt::AlignVCenter,
|
||||
m_subtitle);
|
||||
}
|
||||
|
||||
protected:
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event) override
|
||||
{
|
||||
if (m_loop && event->button() == Qt::LeftButton
|
||||
&& collapseButtonRect().contains(event->pos())) {
|
||||
m_collapsePressed = true;
|
||||
update(collapseButtonRect().adjusted(-2, -2, 2, 2));
|
||||
event->accept();
|
||||
return;
|
||||
}
|
||||
setCursor(Qt::ClosedHandCursor);
|
||||
QGraphicsItem::mousePressEvent(event);
|
||||
}
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override
|
||||
{
|
||||
if (m_collapsePressed) {
|
||||
const bool activate = collapseButtonRect().contains(event->pos());
|
||||
m_collapsePressed = false;
|
||||
update(collapseButtonRect().adjusted(-2, -2, 2, 2));
|
||||
if (activate && m_toggleCollapsed)
|
||||
m_toggleCollapsed(m_id);
|
||||
event->accept();
|
||||
return;
|
||||
}
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
QGraphicsItem::mouseReleaseEvent(event);
|
||||
if (m_moved)
|
||||
m_moved(m_id, pos());
|
||||
}
|
||||
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override
|
||||
{
|
||||
if (m_edit)
|
||||
m_edit(m_id);
|
||||
event->accept();
|
||||
}
|
||||
void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override
|
||||
{
|
||||
const bool overButton = m_loop && collapseButtonRect().contains(event->pos());
|
||||
if (m_collapseHovered != overButton) {
|
||||
m_collapseHovered = overButton;
|
||||
update(collapseButtonRect().adjusted(-2, -2, 2, 2));
|
||||
}
|
||||
setCursor(overButton ? Qt::PointingHandCursor : Qt::OpenHandCursor);
|
||||
QGraphicsItem::hoverMoveEvent(event);
|
||||
}
|
||||
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override
|
||||
{
|
||||
if (m_collapseHovered) {
|
||||
m_collapseHovered = false;
|
||||
update(collapseButtonRect().adjusted(-2, -2, 2, 2));
|
||||
}
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
QGraphicsItem::hoverLeaveEvent(event);
|
||||
}
|
||||
|
||||
private:
|
||||
QRectF collapseButtonRect() const { return QRectF(kNodeWidth - 34, 9, 22, 22); }
|
||||
|
||||
QString m_id;
|
||||
QString m_title;
|
||||
QString m_subtitle;
|
||||
bool m_loop = false;
|
||||
bool m_active = false;
|
||||
bool m_collapsed = false;
|
||||
bool m_collapseHovered = false;
|
||||
bool m_collapsePressed = false;
|
||||
std::function<void(const QString &, const QPointF &)> m_moved;
|
||||
std::function<void(const QString &)> m_edit;
|
||||
std::function<void(const QString &)> m_toggleCollapsed;
|
||||
};
|
||||
}
|
||||
|
||||
JointFlowEditor::JointFlowEditor(QWidget *parent) : QWidget(parent)
|
||||
{
|
||||
setObjectName(QStringLiteral("jointFlowEditor"));
|
||||
QVBoxLayout *layout = new QVBoxLayout(this);
|
||||
layout->setContentsMargins(0, 0, 0, 0);
|
||||
m_scene = new QGraphicsScene(this);
|
||||
m_scene->setBackgroundBrush(QColor("#f4f7fa"));
|
||||
m_view = new FlowGraphicsView(m_scene, this);
|
||||
m_view->setObjectName(QStringLiteral("jointFlowCanvas"));
|
||||
m_view->setRenderHint(QPainter::Antialiasing);
|
||||
m_view->setDragMode(QGraphicsView::RubberBandDrag);
|
||||
m_view->setMinimumHeight(230);
|
||||
layout->addWidget(m_view);
|
||||
connect(m_scene, &QGraphicsScene::selectionChanged, this, [this]() {
|
||||
for (QGraphicsItem *item : m_scene->selectedItems()) {
|
||||
const QString id = item->data(0).toString();
|
||||
if (!id.isEmpty()) {
|
||||
m_selectedNodeId = id;
|
||||
if (const Node *selected = nodeById(id))
|
||||
m_insertionParentId = selected->parentId;
|
||||
notifyInsertionContext();
|
||||
return;
|
||||
}
|
||||
}
|
||||
m_selectedNodeId.clear();
|
||||
notifyInsertionContext();
|
||||
});
|
||||
}
|
||||
|
||||
JointFlowEditor::~JointFlowEditor()
|
||||
{
|
||||
// The scene is deleted by QObject after our selection/node members are gone.
|
||||
// Do not let its selectionChanged callback access those destroyed members.
|
||||
disconnect(m_scene, nullptr, this, nullptr);
|
||||
}
|
||||
|
||||
void JointFlowEditor::addSingleNode(const QString &nodeName, const QString &pointName,
|
||||
double intervalSeconds)
|
||||
{
|
||||
if (nodeName.trimmed().isEmpty() || pointName.isEmpty())
|
||||
return;
|
||||
Node node;
|
||||
node.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
|
||||
node.type = SingleNode;
|
||||
node.nodeName = nodeName.trimmed();
|
||||
node.pointName = pointName;
|
||||
node.intervalSeconds = qMax(0.0, intervalSeconds);
|
||||
const Node *insertionParent = nodeById(m_insertionParentId);
|
||||
node.parentId = insertionParent && insertionParent->type == LoopNode
|
||||
? insertionParent->id : QString();
|
||||
node.order = insertionOrder(node.parentId);
|
||||
makeRoomForInsertion(node.parentId, node.order);
|
||||
node.position = QPointF(40 + node.order * 220, 40 + (node.parentId.isEmpty() ? 0 : 100));
|
||||
m_nodes.append(node);
|
||||
m_selectedNodeId = node.id;
|
||||
layoutSiblings(QString());
|
||||
rebuildScene();
|
||||
emit changed();
|
||||
}
|
||||
|
||||
void JointFlowEditor::addLoopNode(const QString &nodeName, int loopCount,
|
||||
double intervalSeconds)
|
||||
{
|
||||
if (nodeName.trimmed().isEmpty())
|
||||
return;
|
||||
Node node;
|
||||
node.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
|
||||
node.type = LoopNode;
|
||||
node.nodeName = nodeName.trimmed();
|
||||
node.loopCount = qMax(1, loopCount);
|
||||
node.intervalSeconds = qMax(0.0, intervalSeconds);
|
||||
const Node *insertionParent = nodeById(m_insertionParentId);
|
||||
node.parentId = insertionParent && insertionParent->type == LoopNode
|
||||
? insertionParent->id : QString();
|
||||
node.order = insertionOrder(node.parentId);
|
||||
makeRoomForInsertion(node.parentId, node.order);
|
||||
node.position = QPointF(40 + node.order * 220, 40 + (node.parentId.isEmpty() ? 0 : 100));
|
||||
m_nodes.append(node);
|
||||
m_selectedNodeId = node.id;
|
||||
layoutSiblings(QString());
|
||||
rebuildScene();
|
||||
emit changed();
|
||||
}
|
||||
|
||||
void JointFlowEditor::removeSelectedNode()
|
||||
{
|
||||
const QString id = selectedNodeId();
|
||||
if (id.isEmpty())
|
||||
return;
|
||||
QStringList removing{id};
|
||||
for (int i = 0; i < removing.size(); ++i) {
|
||||
for (const Node &node : m_nodes)
|
||||
if (node.parentId == removing.at(i))
|
||||
removing.append(node.id);
|
||||
}
|
||||
QString parentId;
|
||||
if (const Node *node = nodeById(id))
|
||||
parentId = node->parentId;
|
||||
for (int i = m_nodes.size() - 1; i >= 0; --i)
|
||||
if (removing.contains(m_nodes.at(i).id))
|
||||
m_nodes.removeAt(i);
|
||||
if (removing.contains(m_insertionParentId))
|
||||
setInsertionAtRoot();
|
||||
m_selectedNodeId.clear();
|
||||
normalizeOrders(parentId);
|
||||
layoutSiblings(QString());
|
||||
rebuildScene();
|
||||
emit changed();
|
||||
}
|
||||
|
||||
void JointFlowEditor::removePointReferences(const QStringList &pointNames)
|
||||
{
|
||||
for (int i = m_nodes.size() - 1; i >= 0; --i)
|
||||
if (m_nodes.at(i).type == SingleNode && pointNames.contains(m_nodes.at(i).pointName))
|
||||
m_nodes.removeAt(i);
|
||||
rebuildScene();
|
||||
emit changed();
|
||||
}
|
||||
|
||||
bool JointFlowEditor::isEmpty() const { return m_nodes.isEmpty(); }
|
||||
|
||||
QList<JointFlowEditor::ExecutionStep> JointFlowEditor::expandedSteps(
|
||||
QString *error, int maximumSteps) const
|
||||
{
|
||||
QList<ExecutionStep> result;
|
||||
for (const Node *node : childrenOf(QString())) {
|
||||
if (!appendExecution(*node, result, error, maximumSteps))
|
||||
return {};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool JointFlowEditor::appendExecution(const Node &node, QList<ExecutionStep> &steps,
|
||||
QString *error, int maximumSteps) const
|
||||
{
|
||||
if (node.type == SingleNode) {
|
||||
if (steps.size() >= maximumSteps) {
|
||||
if (error) *error = QStringLiteral("展开后的流程超过 %1 步").arg(maximumSteps);
|
||||
return false;
|
||||
}
|
||||
steps.append({node.pointName, node.intervalSeconds, node.id});
|
||||
return true;
|
||||
}
|
||||
const QList<const Node *> children = childrenOf(node.id);
|
||||
if (children.isEmpty()) {
|
||||
if (error) *error = QStringLiteral("存在没有子节点的循环节点");
|
||||
return false;
|
||||
}
|
||||
for (int repeat = 0; repeat < node.loopCount; ++repeat)
|
||||
for (const Node *child : children)
|
||||
if (!appendExecution(*child, steps, error, maximumSteps)) return false;
|
||||
if (!steps.isEmpty())
|
||||
steps.last().intervalSeconds += node.intervalSeconds;
|
||||
return true;
|
||||
}
|
||||
|
||||
QJsonArray JointFlowEditor::toJson() const
|
||||
{
|
||||
QJsonArray array;
|
||||
for (const Node &node : m_nodes)
|
||||
appendJsonNode(array, node);
|
||||
return array;
|
||||
}
|
||||
|
||||
void JointFlowEditor::appendJsonNode(QJsonArray &target, const Node &node) const
|
||||
{
|
||||
QJsonObject object;
|
||||
object.insert(QStringLiteral("id"), node.id);
|
||||
object.insert(QStringLiteral("type"), node.type == LoopNode ? QStringLiteral("loop")
|
||||
: QStringLiteral("single"));
|
||||
object.insert(QStringLiteral("nodeName"), node.nodeName);
|
||||
object.insert(QStringLiteral("pointName"), node.pointName);
|
||||
object.insert(QStringLiteral("loopCount"), node.loopCount);
|
||||
object.insert(QStringLiteral("intervalSeconds"), node.intervalSeconds);
|
||||
object.insert(QStringLiteral("parentId"), node.parentId);
|
||||
object.insert(QStringLiteral("order"), node.order);
|
||||
object.insert(QStringLiteral("x"), node.position.x());
|
||||
object.insert(QStringLiteral("y"), node.position.y());
|
||||
object.insert(QStringLiteral("collapsed"), node.collapsed);
|
||||
target.append(object);
|
||||
}
|
||||
|
||||
bool JointFlowEditor::fromJson(const QJsonArray &array)
|
||||
{
|
||||
QList<Node> loaded;
|
||||
for (const QJsonValue &value : array) {
|
||||
const QJsonObject object = value.toObject();
|
||||
Node node;
|
||||
node.id = object.value(QStringLiteral("id")).toString();
|
||||
if (node.id.isEmpty()) return false;
|
||||
node.type = object.value(QStringLiteral("type")).toString() == QStringLiteral("loop")
|
||||
? LoopNode : SingleNode;
|
||||
node.nodeName = object.value(QStringLiteral("nodeName")).toString().trimmed();
|
||||
node.pointName = object.value(QStringLiteral("pointName")).toString();
|
||||
if (node.nodeName.isEmpty())
|
||||
node.nodeName = node.type == LoopNode ? QStringLiteral("循环节点") : node.pointName;
|
||||
node.loopCount = qMax(1, object.value(QStringLiteral("loopCount")).toInt(1));
|
||||
node.intervalSeconds = qMax(0.0, object.value(QStringLiteral("intervalSeconds")).toDouble());
|
||||
node.parentId = object.value(QStringLiteral("parentId")).toString();
|
||||
node.order = object.value(QStringLiteral("order")).toInt();
|
||||
node.position = QPointF(object.value(QStringLiteral("x")).toDouble(),
|
||||
object.value(QStringLiteral("y")).toDouble());
|
||||
node.collapsed = object.value(QStringLiteral("collapsed")).toBool(false);
|
||||
loaded.append(node);
|
||||
}
|
||||
m_nodes = loaded;
|
||||
m_selectedNodeId.clear();
|
||||
m_insertionParentId.clear();
|
||||
rebuildScene();
|
||||
return true;
|
||||
}
|
||||
|
||||
void JointFlowEditor::clear()
|
||||
{
|
||||
m_nodes.clear();
|
||||
m_selectedNodeId.clear();
|
||||
m_insertionParentId.clear();
|
||||
rebuildScene();
|
||||
}
|
||||
void JointFlowEditor::setActiveNode(const QString &nodeId) { m_activeNodeId = nodeId; rebuildScene(); }
|
||||
|
||||
void JointFlowEditor::setAvailablePointNames(const QStringList &pointNames)
|
||||
{
|
||||
m_availablePointNames = pointNames;
|
||||
m_availablePointNames.removeDuplicates();
|
||||
}
|
||||
|
||||
void JointFlowEditor::setInsertionAtRoot()
|
||||
{
|
||||
const QSignalBlocker sceneBlocker(m_scene);
|
||||
m_scene->clearSelection();
|
||||
m_selectedNodeId.clear();
|
||||
m_insertionParentId.clear();
|
||||
notifyInsertionContext();
|
||||
}
|
||||
|
||||
bool JointFlowEditor::useSelectedLoopAsInsertionParent()
|
||||
{
|
||||
const Node *selected = nodeById(selectedNodeId());
|
||||
if (!selected || selected->type != LoopNode)
|
||||
return false;
|
||||
const QSignalBlocker sceneBlocker(m_scene);
|
||||
m_scene->clearSelection();
|
||||
m_insertionParentId = selected->id;
|
||||
m_selectedNodeId.clear();
|
||||
notifyInsertionContext();
|
||||
return true;
|
||||
}
|
||||
|
||||
JointFlowEditor::Node *JointFlowEditor::nodeById(const QString &id)
|
||||
{ for (Node &node : m_nodes) if (node.id == id) return &node; return nullptr; }
|
||||
const JointFlowEditor::Node *JointFlowEditor::nodeById(const QString &id) const
|
||||
{ for (const Node &node : m_nodes) if (node.id == id) return &node; return nullptr; }
|
||||
|
||||
QList<const JointFlowEditor::Node *> JointFlowEditor::childrenOf(const QString &parentId) const
|
||||
{
|
||||
QList<const Node *> result;
|
||||
for (const Node &node : m_nodes) if (node.parentId == parentId) result.append(&node);
|
||||
std::sort(result.begin(), result.end(), [](const Node *a, const Node *b) {
|
||||
return a->order < b->order;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
QString JointFlowEditor::selectedNodeId() const
|
||||
{
|
||||
for (QGraphicsItem *item : m_scene->selectedItems())
|
||||
if (!item->data(0).toString().isEmpty()) return item->data(0).toString();
|
||||
return m_selectedNodeId;
|
||||
}
|
||||
|
||||
void JointFlowEditor::editNode(const QString &id)
|
||||
{
|
||||
Node *node = nodeById(id);
|
||||
if (!node) return;
|
||||
|
||||
NodeEditDialog dialog(node->type == SingleNode
|
||||
? QStringLiteral("编辑单步节点") : QStringLiteral("编辑循环节点"), this);
|
||||
dialog.setMinimumWidth(420);
|
||||
QVBoxLayout *dialogLayout = dialog.contentLayout();
|
||||
QFormLayout *form = new QFormLayout;
|
||||
QLineEdit *nameEdit = new QLineEdit(node->nodeName, &dialog);
|
||||
form->addRow(QStringLiteral("节点名称"), nameEdit);
|
||||
|
||||
QComboBox *pointCombo = nullptr;
|
||||
QSpinBox *loopCountSpin = nullptr;
|
||||
if (node->type == SingleNode) {
|
||||
QStringList pointNames = m_availablePointNames;
|
||||
if (!pointNames.contains(node->pointName))
|
||||
pointNames.prepend(node->pointName);
|
||||
pointCombo = new QComboBox(&dialog);
|
||||
pointCombo->addItems(pointNames);
|
||||
pointCombo->setCurrentText(node->pointName);
|
||||
form->addRow(QStringLiteral("执行点位"), pointCombo);
|
||||
} else {
|
||||
loopCountSpin = new QSpinBox(&dialog);
|
||||
loopCountSpin->setRange(1, 10000);
|
||||
loopCountSpin->setValue(node->loopCount);
|
||||
form->addRow(QStringLiteral("循环次数"), loopCountSpin);
|
||||
}
|
||||
QDoubleSpinBox *intervalSpin = new QDoubleSpinBox(&dialog);
|
||||
intervalSpin->setRange(0.0, 3600.0);
|
||||
intervalSpin->setDecimals(1);
|
||||
intervalSpin->setSingleStep(0.1);
|
||||
intervalSpin->setSuffix(QStringLiteral(" s"));
|
||||
intervalSpin->setValue(node->intervalSeconds);
|
||||
form->addRow(node->type == LoopNode ? QStringLiteral("循环结束后等待")
|
||||
: QStringLiteral("执行结束后等待"),
|
||||
intervalSpin);
|
||||
dialogLayout->addLayout(form);
|
||||
|
||||
QDialogButtonBox *buttons = new QDialogButtonBox(
|
||||
QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);
|
||||
buttons->button(QDialogButtonBox::Ok)->setText(QStringLiteral("保存"));
|
||||
buttons->button(QDialogButtonBox::Cancel)->setText(QStringLiteral("取消"));
|
||||
connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
|
||||
connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
|
||||
dialogLayout->addWidget(buttons);
|
||||
|
||||
if (dialog.exec() != QDialog::Accepted || nameEdit->text().trimmed().isEmpty())
|
||||
return;
|
||||
node->nodeName = nameEdit->text().trimmed();
|
||||
if (pointCombo)
|
||||
node->pointName = pointCombo->currentText();
|
||||
if (loopCountSpin)
|
||||
node->loopCount = loopCountSpin->value();
|
||||
node->intervalSeconds = intervalSpin->value();
|
||||
rebuildScene();
|
||||
emit changed();
|
||||
}
|
||||
|
||||
void JointFlowEditor::toggleLoopCollapsed(const QString &id)
|
||||
{
|
||||
Node *node = nodeById(id);
|
||||
if (!node || node->type != LoopNode)
|
||||
return;
|
||||
node->collapsed = !node->collapsed;
|
||||
QTimer::singleShot(0, this, [this]() {
|
||||
rebuildScene();
|
||||
emit changed();
|
||||
});
|
||||
}
|
||||
|
||||
void JointFlowEditor::moveNode(const QString &id, const QPointF &position)
|
||||
{
|
||||
Node *node = nodeById(id);
|
||||
if (!node) return;
|
||||
const QString parentId = node->parentId;
|
||||
const qreal droppedCenterX = position.x() + kNodeWidth / 2.0;
|
||||
QList<Node *> siblings;
|
||||
for (Node &candidate : m_nodes)
|
||||
if (candidate.parentId == parentId && candidate.id != id)
|
||||
siblings.append(&candidate);
|
||||
std::sort(siblings.begin(), siblings.end(), [](const Node *a, const Node *b) {
|
||||
return a->order < b->order;
|
||||
});
|
||||
|
||||
int targetOrder = 0;
|
||||
for (const Node *sibling : siblings) {
|
||||
if (droppedCenterX > sibling->position.x() + kNodeWidth / 2.0)
|
||||
++targetOrder;
|
||||
}
|
||||
siblings.insert(targetOrder, node);
|
||||
for (int order = 0; order < siblings.size(); ++order)
|
||||
siblings.at(order)->order = order;
|
||||
layoutSiblings(QString());
|
||||
rebuildScene();
|
||||
emit changed();
|
||||
}
|
||||
|
||||
int JointFlowEditor::insertionOrder(const QString &parentId) const
|
||||
{
|
||||
const Node *selected = nodeById(selectedNodeId());
|
||||
if (selected && selected->parentId == parentId)
|
||||
return selected->order + 1;
|
||||
return childrenOf(parentId).size();
|
||||
}
|
||||
|
||||
void JointFlowEditor::makeRoomForInsertion(const QString &parentId, int order)
|
||||
{
|
||||
for (Node &candidate : m_nodes)
|
||||
if (candidate.parentId == parentId && candidate.order >= order)
|
||||
++candidate.order;
|
||||
}
|
||||
|
||||
qreal JointFlowEditor::layoutSiblings(const QString &parentId)
|
||||
{
|
||||
QList<Node *> siblings;
|
||||
for (Node &candidate : m_nodes)
|
||||
if (candidate.parentId == parentId)
|
||||
siblings.append(&candidate);
|
||||
std::sort(siblings.begin(), siblings.end(), [](const Node *a, const Node *b) {
|
||||
return a->order < b->order;
|
||||
});
|
||||
qreal startX = 40.0;
|
||||
qreal y = 40.0;
|
||||
if (!parentId.isEmpty()) {
|
||||
const Node *parent = nodeById(parentId);
|
||||
if (parent) {
|
||||
startX = parent->position.x() + 40.0;
|
||||
y = parent->position.y() + 112.0;
|
||||
} else {
|
||||
y = 140.0;
|
||||
}
|
||||
}
|
||||
qreal right = startX;
|
||||
for (int order = 0; order < siblings.size(); ++order) {
|
||||
Node *sibling = siblings.at(order);
|
||||
sibling->order = order;
|
||||
sibling->position = QPointF(startX, y);
|
||||
right = startX + kNodeWidth;
|
||||
// Reserve the entire subtree before placing the next sibling, so
|
||||
// adjacent expanded loops cannot put their child cards on top of each other.
|
||||
if (sibling->type == LoopNode)
|
||||
right = qMax(right, layoutSiblings(sibling->id));
|
||||
startX = right + 30.0;
|
||||
}
|
||||
return right;
|
||||
}
|
||||
|
||||
void JointFlowEditor::notifyInsertionContext()
|
||||
{
|
||||
const Node *parent = nodeById(m_insertionParentId);
|
||||
const QString container = parent && parent->type == LoopNode
|
||||
? parent->nodeName : QStringLiteral("根流程");
|
||||
const Node *selected = nodeById(selectedNodeId());
|
||||
if (selected && selected->parentId == (parent ? parent->id : QString())) {
|
||||
emit insertionContextChanged(QStringLiteral("%1(插入到“%2”之后)")
|
||||
.arg(container, selected->nodeName));
|
||||
return;
|
||||
}
|
||||
emit insertionContextChanged(QStringLiteral("%1(末尾)").arg(container));
|
||||
}
|
||||
|
||||
void JointFlowEditor::normalizeOrders(const QString &parentId)
|
||||
{
|
||||
int order = 0;
|
||||
for (const Node *child : childrenOf(parentId))
|
||||
if (Node *node = nodeById(child->id)) node->order = order++;
|
||||
}
|
||||
|
||||
void JointFlowEditor::rebuildScene()
|
||||
{
|
||||
const QSignalBlocker sceneBlocker(m_scene);
|
||||
m_scene->clear();
|
||||
QHash<QString, FlowCardItem *> cards;
|
||||
for (const Node &node : m_nodes) {
|
||||
bool hiddenByCollapsedAncestor = false;
|
||||
const Node *ancestor = node.parentId.isEmpty() ? nullptr : nodeById(node.parentId);
|
||||
while (ancestor) {
|
||||
if (ancestor->collapsed) {
|
||||
hiddenByCollapsedAncestor = true;
|
||||
break;
|
||||
}
|
||||
ancestor = ancestor->parentId.isEmpty() ? nullptr : nodeById(ancestor->parentId);
|
||||
}
|
||||
if (hiddenByCollapsedAncestor)
|
||||
continue;
|
||||
const QString title = node.nodeName;
|
||||
const QString executionUnit = node.type == LoopNode
|
||||
? QStringLiteral("循环 × %1").arg(node.loopCount) : node.pointName;
|
||||
const QString subtitle = QStringLiteral("执行:%1 · 等待 %2 s")
|
||||
.arg(executionUnit).arg(node.intervalSeconds, 0, 'f', 1);
|
||||
auto *card = new FlowCardItem(node.id, title, subtitle, node.type == LoopNode,
|
||||
node.id == m_activeNodeId, node.collapsed,
|
||||
[this](const QString &id, const QPointF &pos) { moveNode(id, pos); },
|
||||
[this](const QString &id) { editNode(id); },
|
||||
[this](const QString &id) { toggleLoopCollapsed(id); });
|
||||
card->setData(0, node.id);
|
||||
card->setPos(node.position);
|
||||
m_scene->addItem(card);
|
||||
if (node.id == m_selectedNodeId)
|
||||
card->setSelected(true);
|
||||
cards.insert(node.id, card);
|
||||
}
|
||||
for (const Node &node : m_nodes) {
|
||||
if (node.parentId.isEmpty() || !cards.contains(node.parentId) || !cards.contains(node.id))
|
||||
continue;
|
||||
const QPointF from = cards.value(node.parentId)->sceneBoundingRect().center();
|
||||
const QPointF to = cards.value(node.id)->sceneBoundingRect().center();
|
||||
m_scene->addLine(QLineF(from, to), QPen(QColor("#9aabc0"), 2.0));
|
||||
}
|
||||
QStringList parentIds{QString()};
|
||||
for (const Node &node : m_nodes)
|
||||
if (!parentIds.contains(node.parentId)) parentIds.append(node.parentId);
|
||||
for (const QString &parentId : parentIds) {
|
||||
const QList<const Node *> siblings = childrenOf(parentId);
|
||||
for (int i = 1; i < siblings.size(); ++i) {
|
||||
const Node *previous = siblings.at(i - 1);
|
||||
const Node *current = siblings.at(i);
|
||||
if (!cards.contains(previous->id) || !cards.contains(current->id)) continue;
|
||||
const QPointF from = cards.value(previous->id)->sceneBoundingRect().center();
|
||||
const QPointF to = cards.value(current->id)->sceneBoundingRect().center();
|
||||
m_scene->addLine(QLineF(from, to), QPen(QColor("#5a91cf"), 1.5, Qt::DashLine));
|
||||
}
|
||||
}
|
||||
m_scene->setSceneRect(m_scene->itemsBoundingRect().adjusted(-60, -60, 60, 60));
|
||||
notifyInsertionContext();
|
||||
}
|
||||
83
src/jointfloweditor.h
Normal file
83
src/jointfloweditor.h
Normal file
@ -0,0 +1,83 @@
|
||||
#pragma once
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QList>
|
||||
#include <QPointF>
|
||||
#include <QWidget>
|
||||
|
||||
class QGraphicsScene;
|
||||
class QGraphicsView;
|
||||
|
||||
class JointFlowEditor : public QWidget
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
struct ExecutionStep {
|
||||
QString pointName;
|
||||
double intervalSeconds = 0.0;
|
||||
QString nodeId;
|
||||
};
|
||||
|
||||
explicit JointFlowEditor(QWidget *parent = nullptr);
|
||||
~JointFlowEditor() override;
|
||||
|
||||
void addSingleNode(const QString &nodeName, const QString &pointName,
|
||||
double intervalSeconds);
|
||||
void addLoopNode(const QString &nodeName, int loopCount, double intervalSeconds);
|
||||
void removeSelectedNode();
|
||||
void removePointReferences(const QStringList &pointNames);
|
||||
bool isEmpty() const;
|
||||
QList<ExecutionStep> expandedSteps(QString *error = nullptr,
|
||||
int maximumSteps = 100000) const;
|
||||
QJsonArray toJson() const;
|
||||
bool fromJson(const QJsonArray &array);
|
||||
void clear();
|
||||
void setActiveNode(const QString &nodeId);
|
||||
void setAvailablePointNames(const QStringList &pointNames);
|
||||
void setInsertionAtRoot();
|
||||
bool useSelectedLoopAsInsertionParent();
|
||||
|
||||
signals:
|
||||
void changed();
|
||||
void insertionContextChanged(const QString &description);
|
||||
|
||||
private:
|
||||
enum NodeType { SingleNode, LoopNode };
|
||||
struct Node {
|
||||
QString id;
|
||||
NodeType type = SingleNode;
|
||||
QString nodeName;
|
||||
QString pointName;
|
||||
int loopCount = 1;
|
||||
double intervalSeconds = 0.0;
|
||||
QString parentId;
|
||||
int order = 0;
|
||||
QPointF position;
|
||||
bool collapsed = false;
|
||||
};
|
||||
|
||||
Node *nodeById(const QString &id);
|
||||
const Node *nodeById(const QString &id) const;
|
||||
QList<const Node *> childrenOf(const QString &parentId) const;
|
||||
QString selectedNodeId() const;
|
||||
void editNode(const QString &id);
|
||||
void toggleLoopCollapsed(const QString &id);
|
||||
void moveNode(const QString &id, const QPointF &position);
|
||||
int insertionOrder(const QString &parentId) const;
|
||||
void makeRoomForInsertion(const QString &parentId, int order);
|
||||
qreal layoutSiblings(const QString &parentId);
|
||||
void notifyInsertionContext();
|
||||
void normalizeOrders(const QString &parentId);
|
||||
void rebuildScene();
|
||||
void appendJsonNode(QJsonArray &target, const Node &node) const;
|
||||
bool appendExecution(const Node &node, QList<ExecutionStep> &steps,
|
||||
QString *error, int maximumSteps) const;
|
||||
|
||||
QList<Node> m_nodes;
|
||||
QGraphicsScene *m_scene = nullptr;
|
||||
QGraphicsView *m_view = nullptr;
|
||||
QString m_activeNodeId;
|
||||
QString m_selectedNodeId;
|
||||
QString m_insertionParentId;
|
||||
QStringList m_availablePointNames;
|
||||
};
|
||||
113
src/main.cpp
113
src/main.cpp
@ -4,6 +4,7 @@
|
||||
|
||||
#include <QApplication>
|
||||
#include <QCheckBox>
|
||||
#include <QComboBox>
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QLineEdit>
|
||||
@ -11,8 +12,94 @@
|
||||
#include <QTimer>
|
||||
#include <QTextStream>
|
||||
|
||||
#ifdef Q_OS_WIN
|
||||
#include <windows.h>
|
||||
#include <dbghelp.h>
|
||||
|
||||
namespace {
|
||||
|
||||
LONG WINAPI writeCrashDump(EXCEPTION_POINTERS *exceptionPointers)
|
||||
{
|
||||
static LONG handlingCrash = 0;
|
||||
if (InterlockedCompareExchange(&handlingCrash, 1, 0) != 0)
|
||||
return EXCEPTION_EXECUTE_HANDLER;
|
||||
|
||||
wchar_t executablePath[MAX_PATH] = {};
|
||||
GetModuleFileNameW(nullptr, executablePath, MAX_PATH);
|
||||
wchar_t *lastSeparator = wcsrchr(executablePath, L'\\');
|
||||
if (lastSeparator)
|
||||
*lastSeparator = L'\0';
|
||||
|
||||
wchar_t dumpDirectory[MAX_PATH] = {};
|
||||
_snwprintf(dumpDirectory, MAX_PATH - 1, L"%ls\\crash_dumps", executablePath);
|
||||
CreateDirectoryW(dumpDirectory, nullptr);
|
||||
|
||||
SYSTEMTIME time = {};
|
||||
GetLocalTime(&time);
|
||||
wchar_t baseName[96] = {};
|
||||
_snwprintf(baseName, 95,
|
||||
L"CmvrControlStation_%04u%02u%02u_%02u%02u%02u_%lu",
|
||||
time.wYear, time.wMonth, time.wDay,
|
||||
time.wHour, time.wMinute, time.wSecond,
|
||||
GetCurrentProcessId());
|
||||
|
||||
wchar_t dumpPath[MAX_PATH] = {};
|
||||
_snwprintf(dumpPath, MAX_PATH - 1, L"%ls\\%ls.dmp", dumpDirectory, baseName);
|
||||
HANDLE dumpFile = CreateFileW(dumpPath, GENERIC_WRITE, FILE_SHARE_READ, nullptr,
|
||||
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (dumpFile != INVALID_HANDLE_VALUE) {
|
||||
MINIDUMP_EXCEPTION_INFORMATION exceptionInfo = {};
|
||||
exceptionInfo.ThreadId = GetCurrentThreadId();
|
||||
exceptionInfo.ExceptionPointers = exceptionPointers;
|
||||
exceptionInfo.ClientPointers = FALSE;
|
||||
const MINIDUMP_TYPE dumpType = static_cast<MINIDUMP_TYPE>(
|
||||
MiniDumpWithDataSegs | MiniDumpWithHandleData |
|
||||
MiniDumpWithThreadInfo | MiniDumpWithIndirectlyReferencedMemory);
|
||||
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), dumpFile,
|
||||
dumpType, &exceptionInfo, nullptr, nullptr);
|
||||
FlushFileBuffers(dumpFile);
|
||||
CloseHandle(dumpFile);
|
||||
}
|
||||
|
||||
wchar_t summaryPath[MAX_PATH] = {};
|
||||
_snwprintf(summaryPath, MAX_PATH - 1, L"%ls\\%ls.txt", dumpDirectory, baseName);
|
||||
HANDLE summaryFile = CreateFileW(summaryPath, GENERIC_WRITE, FILE_SHARE_READ, nullptr,
|
||||
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (summaryFile != INVALID_HANDLE_VALUE) {
|
||||
const DWORD exceptionCode = exceptionPointers && exceptionPointers->ExceptionRecord
|
||||
? exceptionPointers->ExceptionRecord->ExceptionCode : 0;
|
||||
const void *exceptionAddress = exceptionPointers && exceptionPointers->ExceptionRecord
|
||||
? exceptionPointers->ExceptionRecord->ExceptionAddress : nullptr;
|
||||
char summary[512] = {};
|
||||
const int length = _snprintf(summary, sizeof(summary) - 1,
|
||||
"Application: CmvrControlStation.exe\r\n"
|
||||
"Timestamp: %04u-%02u-%02u %02u:%02u:%02u\r\n"
|
||||
"Exception code: 0x%08lX\r\n"
|
||||
"Exception address: %p\r\n"
|
||||
"Process ID: %lu\r\nThread ID: %lu\r\n"
|
||||
"Dump: %ls\r\n",
|
||||
time.wYear, time.wMonth, time.wDay,
|
||||
time.wHour, time.wMinute, time.wSecond,
|
||||
exceptionCode, exceptionAddress,
|
||||
GetCurrentProcessId(), GetCurrentThreadId(), dumpPath);
|
||||
DWORD written = 0;
|
||||
if (length > 0)
|
||||
WriteFile(summaryFile, summary, static_cast<DWORD>(length), &written, nullptr);
|
||||
FlushFileBuffers(summaryFile);
|
||||
CloseHandle(summaryFile);
|
||||
}
|
||||
|
||||
return EXCEPTION_EXECUTE_HANDLER;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
#endif
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
#ifdef Q_OS_WIN
|
||||
SetUnhandledExceptionFilter(writeCrashDump);
|
||||
#endif
|
||||
QApplication app(argc, argv);
|
||||
app.setApplicationName(QStringLiteral("CMVR Control Station"));
|
||||
app.setOrganizationName(QStringLiteral("CMVR"));
|
||||
@ -117,16 +204,15 @@ int main(int argc, char *argv[])
|
||||
QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection,
|
||||
Q_ARG(int, 2));
|
||||
QCheckBox *demoCheck = window.findChild<QCheckBox *>(QStringLiteral("demoCheck"));
|
||||
QLineEdit *cameraIdEdit =
|
||||
window.findChild<QLineEdit *>(QStringLiteral("cameraIdEdit"));
|
||||
QPushButton *connectButton =
|
||||
window.findChild<QPushButton *>(QStringLiteral("connectButton"));
|
||||
if (!demoCheck || !cameraIdEdit || !connectButton) {
|
||||
QComboBox *cameraDeviceCombo =
|
||||
window.findChild<QComboBox *>(QStringLiteral("cameraDeviceCombo"));
|
||||
if (!demoCheck || !cameraDeviceCombo) {
|
||||
finishSmoke(3, QStringLiteral("未找到相机自检所需控件"));
|
||||
return;
|
||||
}
|
||||
demoCheck->setChecked(true);
|
||||
cameraIdEdit->setText(QStringLiteral("demo_camera_1,demo_camera_2"));
|
||||
cameraDeviceCombo->addItem(QStringLiteral("demo_camera_1"),
|
||||
QStringLiteral("demo_camera_1"));
|
||||
appendCameraSmokeLog(QStringLiteral("STEP 等待应用自动连接 Demo"));
|
||||
|
||||
QTimer::singleShot(1500, &window,
|
||||
@ -149,19 +235,22 @@ int main(int argc, char *argv[])
|
||||
return;
|
||||
}
|
||||
streamButton->click();
|
||||
appendCameraSmokeLog(QStringLiteral("STEP 已请求双路预览"));
|
||||
appendCameraSmokeLog(QStringLiteral("STEP 已请求单相机预览"));
|
||||
|
||||
QTimer::singleShot(1200, &window,
|
||||
[&window, streamButton, finishSmoke, appendCameraSmokeLog]() {
|
||||
appendCameraSmokeLog(QStringLiteral("STEP 检查双路视频帧"));
|
||||
const QList<VideoRenderWidget *> renders =
|
||||
window.findChildren<VideoRenderWidget *>();
|
||||
appendCameraSmokeLog(QStringLiteral("STEP 检查相机视频帧"));
|
||||
QWidget *cameraPreview = window.findChild<QWidget *>(
|
||||
QStringLiteral("cameraPreviewContainer"));
|
||||
const QList<VideoRenderWidget *> renders = cameraPreview
|
||||
? cameraPreview->findChildren<VideoRenderWidget *>()
|
||||
: QList<VideoRenderWidget *>();
|
||||
int renderersWithFrames = 0;
|
||||
for (VideoRenderWidget *render : renders) {
|
||||
if (render->hasFrame())
|
||||
++renderersWithFrames;
|
||||
}
|
||||
if (renders.size() != 2 || renderersWithFrames != 2 ||
|
||||
if (renders.size() != 1 || renderersWithFrames != 1 ||
|
||||
streamButton->text() != QStringLiteral("停止全部预览")) {
|
||||
finishSmoke(5,
|
||||
QStringLiteral("预览校验失败:渲染器=%1,有帧=%2,按钮=%3")
|
||||
@ -181,7 +270,7 @@ int main(int argc, char *argv[])
|
||||
return;
|
||||
}
|
||||
finishSmoke(0,
|
||||
QStringLiteral("双路 Demo 均收到视频帧,停止全部成功"));
|
||||
QStringLiteral("单相机 Demo 收到视频帧,停止预览成功"));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
1691
src/mainwindow.cpp
1691
src/mainwindow.cpp
File diff suppressed because it is too large
Load Diff
150
src/mainwindow.h
150
src/mainwindow.h
@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <QImage>
|
||||
#include <QJsonArray>
|
||||
#include <QHash>
|
||||
#include <QList>
|
||||
#include <QMainWindow>
|
||||
@ -9,6 +10,7 @@
|
||||
#include <QStringList>
|
||||
#include <QVariantList>
|
||||
#include <QVariantMap>
|
||||
#include <QVector>
|
||||
|
||||
#include "videoframe.h"
|
||||
|
||||
@ -25,6 +27,7 @@ class QLineEdit;
|
||||
class QProgressBar;
|
||||
class QPushButton;
|
||||
class QResizeEvent;
|
||||
class QSettings;
|
||||
class QSlider;
|
||||
class QSpinBox;
|
||||
class QStackedWidget;
|
||||
@ -39,6 +42,14 @@ class QuicTestServer;
|
||||
class UrdfViewerWidget;
|
||||
class AudioStreamManager;
|
||||
class VideoRenderWidget;
|
||||
class TcpCalibrationWidget;
|
||||
class TouchOperationWidget;
|
||||
class TcpJogController;
|
||||
class HandEyeCalibrationWidget;
|
||||
class HandEyeMotionWidget;
|
||||
class AgvMapViewWidget;
|
||||
class TactileHeatmapWidget;
|
||||
class JointFlowEditor;
|
||||
|
||||
class MainWindow : public QMainWindow
|
||||
{
|
||||
@ -50,6 +61,7 @@ public:
|
||||
|
||||
protected:
|
||||
bool nativeEvent(const QByteArray &eventType, void *message, long *result) override;
|
||||
bool eventFilter(QObject *watched, QEvent *event) override;
|
||||
void changeEvent(QEvent *event) override;
|
||||
void resizeEvent(QResizeEvent *event) override;
|
||||
|
||||
@ -71,6 +83,12 @@ private slots:
|
||||
void updateCameraStreamState(const QString &cameraId, bool running,
|
||||
const QString &detail);
|
||||
void updateCameraRecordingState(bool recording, const QString &detail);
|
||||
void updateDexHandStatus(const QString &deviceId, bool initialized,
|
||||
bool hasTactileFeedback,
|
||||
const QString &model,
|
||||
const QVariantList &freedoms);
|
||||
void updateDexHandTactile(const QString &deviceId, int rows, int cols,
|
||||
const QVariantList &values, quint64 frameCount);
|
||||
void updateAgvState(const QVariantMap &state, const QVariantMap &navigation);
|
||||
void updateAgvInventory(const QStringList &maps, const QVariantList &stations);
|
||||
void handleCommand(const QString &command, bool success, const QString &detail);
|
||||
@ -80,12 +98,20 @@ private slots:
|
||||
void appendQuicLog(const QString &level, const QString &message);
|
||||
void sendMoveJ();
|
||||
void sendMoveJPose();
|
||||
void recordCurrentJointPoint();
|
||||
void executeSelectedJointPoint();
|
||||
void startJointPointLoop();
|
||||
void stopJointPointLoop(const QString &reason = QString());
|
||||
void advanceJointPointLoop();
|
||||
void refreshRecordedJointPoints();
|
||||
void refreshJointFlowTable();
|
||||
void saveSnapshot();
|
||||
|
||||
private:
|
||||
QWidget *createSystemPage();
|
||||
QWidget *createArmPage();
|
||||
QWidget *createCameraPage();
|
||||
QWidget *createDexHandPage();
|
||||
QStringList configuredCameraIds() const;
|
||||
void rebuildCameraPreviewGrid(const QStringList &cameraIds);
|
||||
void refreshCameraStreamControls();
|
||||
@ -96,20 +122,47 @@ private:
|
||||
QWidget *createDiagnosticsPage();
|
||||
void loadSettings();
|
||||
void saveSettings();
|
||||
void loadJointPrograms(QSettings &legacySettings);
|
||||
void saveJointPrograms();
|
||||
void storeCurrentJointProgramGroup();
|
||||
void activateJointProgramGroup(int index);
|
||||
QString jointProgramsFilePath() const;
|
||||
void setControlsEnabled(bool enabled);
|
||||
void updateWindowChrome();
|
||||
void ensureArmModelLoaded();
|
||||
void rebuildArmJointTables(const QStringList &jointNames);
|
||||
void rebuildArmJogControls();
|
||||
void refreshArmJogAvailability();
|
||||
void setArmTelemetryEnabled(bool enabled);
|
||||
void startJointJog(int jointIndex, int direction);
|
||||
void startCartesianJog(int axisIndex, int direction);
|
||||
void stopArmJog();
|
||||
void refreshTcpChoices(const QString &savedName = QString());
|
||||
void updateArmPoseFrames();
|
||||
bool selectedLocalTcp() const;
|
||||
void setupHandEye();
|
||||
void setupTouchOperation();
|
||||
void syncHandEyeContext();
|
||||
void startAgvManualMotion(double vx, double vy, double wz);
|
||||
void stopAgvManualMotion(bool sendStop = true);
|
||||
void restartAgvMapStream(const QString &mapName = QString());
|
||||
void presentPendingAgvMapFrame();
|
||||
void updateArmAlert(const QString &deviceId, const QString &alertKey,
|
||||
const QString &level, const QString &summary,
|
||||
const QString &detail = QString());
|
||||
QString endpoint() const;
|
||||
|
||||
RobotClient *m_client = nullptr;
|
||||
TcpCalibrationWidget *m_tcpCalibration = nullptr;
|
||||
TcpJogController *m_tcpJog = nullptr;
|
||||
HandEyeCalibrationWidget *m_handEye = nullptr;
|
||||
HandEyeMotionWidget *m_handEyeMotion = nullptr;
|
||||
QString m_handEyeOwnedCamera;
|
||||
TouchOperationWidget *m_touchOperation = nullptr;
|
||||
QString m_touchOwnedCamera;
|
||||
QString m_tcpChoiceEndpoint, m_tcpChoiceDevice;
|
||||
QStringList m_controllerTcpFrames;
|
||||
QLabel *m_armPoseSubtitle = nullptr;
|
||||
AudioStreamManager *m_audioManager = nullptr;
|
||||
QuicTestServer *m_quicServer = nullptr;
|
||||
QStackedWidget *m_pages = nullptr;
|
||||
@ -168,8 +221,11 @@ private:
|
||||
QTableWidget *m_jointTable = nullptr;
|
||||
QTableWidget *m_motionTable = nullptr;
|
||||
QList<QDoubleSpinBox *> m_targetSpins;
|
||||
QList<QDoubleSpinBox *> m_targetRadianSpins;
|
||||
QPushButton *m_syncCurrentToTargetButton = nullptr;
|
||||
QDoubleSpinBox *m_moveJVelocitySpin = nullptr;
|
||||
QDoubleSpinBox *m_moveJAccelerationSpin = nullptr;
|
||||
QStringList m_activeArmJointNames;
|
||||
QTabWidget *m_motionCommandTabs = nullptr;
|
||||
QList<QDoubleSpinBox *> m_moveJPoseSpins;
|
||||
QComboBox *m_moveJPoseBaseLinkCombo = nullptr;
|
||||
QPushButton *m_copyCurrentPoseButton = nullptr;
|
||||
@ -188,6 +244,7 @@ private:
|
||||
QComboBox *m_tcpFrameCombo = nullptr;
|
||||
QSlider *m_jogSpeedSlider = nullptr;
|
||||
QLabel *m_jogSpeedValue = nullptr;
|
||||
QLabel *m_jogReadyLabel = nullptr;
|
||||
QPushButton *m_jogStopButton = nullptr;
|
||||
QHash<QString, double> m_previousJointVelocities;
|
||||
qint64 m_lastArmTelemetryMs = 0;
|
||||
@ -215,11 +272,58 @@ private:
|
||||
QString m_teachSelectedJoint;
|
||||
QString m_pendingUrdfPath;
|
||||
bool m_armModelLoadScheduled = false;
|
||||
struct RecordedJointPoint {
|
||||
QString name;
|
||||
QString side;
|
||||
QString deviceId;
|
||||
QStringList jointNames;
|
||||
QVector<double> positions;
|
||||
};
|
||||
struct JointProgramGroup {
|
||||
QString name;
|
||||
QList<RecordedJointPoint> points;
|
||||
QJsonArray flow;
|
||||
double moveJVelocity = 0.1;
|
||||
double moveJAcceleration = 0.1;
|
||||
};
|
||||
QList<JointProgramGroup> m_jointProgramGroups;
|
||||
int m_activeJointProgramGroup = -1;
|
||||
bool m_updatingJointProgramGroup = false;
|
||||
QList<RecordedJointPoint> m_recordedJointPoints;
|
||||
QComboBox *m_jointProgramGroupCombo = nullptr;
|
||||
QHash<QString, double> m_latestArmJointPositions;
|
||||
QLineEdit *m_jointPointNameEdit = nullptr;
|
||||
QTableWidget *m_jointPointTable = nullptr;
|
||||
QLabel *m_jointPointDetailLabel = nullptr;
|
||||
QSpinBox *m_jointPointLoopCount = nullptr;
|
||||
QDoubleSpinBox *m_jointPointInterval = nullptr;
|
||||
QDoubleSpinBox *m_jointFlowVelocitySpin = nullptr;
|
||||
QDoubleSpinBox *m_jointFlowAccelerationSpin = nullptr;
|
||||
QSpinBox *m_jointFlowGroupCount = nullptr;
|
||||
JointFlowEditor *m_jointFlowEditor = nullptr;
|
||||
QDialog *m_jointFlowDialog = nullptr;
|
||||
QPushButton *m_recordJointPointButton = nullptr;
|
||||
QPushButton *m_runJointPointButton = nullptr;
|
||||
QPushButton *m_deleteJointPointButton = nullptr;
|
||||
QPushButton *m_startJointPointLoopButton = nullptr;
|
||||
QPushButton *m_stopJointPointLoopButton = nullptr;
|
||||
QLabel *m_jointPointLoopStatus = nullptr;
|
||||
QVector<int> m_jointPointLoopRows;
|
||||
QVector<double> m_jointPointExecutionWaits;
|
||||
QStringList m_jointPointExecutionNodeIds;
|
||||
int m_jointPointLoopCursor = 0;
|
||||
int m_jointPointLoopsCompleted = 0;
|
||||
int m_jointPointLoopTarget = 0;
|
||||
bool m_jointPointLoopActive = false;
|
||||
bool m_jointPointMovePending = false;
|
||||
quint64 m_jointPointLoopGeneration = 0;
|
||||
bool m_jointPointDispatching = false;
|
||||
|
||||
QLineEdit *m_cameraIdEdit = nullptr;
|
||||
QComboBox *m_cameraDeviceCombo = nullptr;
|
||||
VideoRenderWidget *m_videoRender = nullptr;
|
||||
QLabel *m_imageMetaLabel = nullptr;
|
||||
QPushButton *m_snapshotButton = nullptr;
|
||||
QPushButton *m_depthSnapshotButton = nullptr;
|
||||
QPushButton *m_cameraStreamButton = nullptr;
|
||||
QPushButton *m_saveImageButton = nullptr;
|
||||
QComboBox *m_cameraCodecCombo = nullptr;
|
||||
@ -237,15 +341,39 @@ private:
|
||||
QLabel *meta = nullptr;
|
||||
};
|
||||
QHash<QString, CameraPreviewTile> m_cameraPreviewTiles;
|
||||
QHash<QString, QString> m_cameraStreamModes;
|
||||
QSet<QString> m_runningCameraIds;
|
||||
QString m_activeCameraId;
|
||||
QVariantMap m_activeCameraCapabilities;
|
||||
quint64 m_cameraCapabilitiesToken=0;
|
||||
bool m_cameraCapabilityInFlight=false;
|
||||
QImage m_lastImage;
|
||||
bool m_lastImageIsDepth = false;
|
||||
bool m_cameraStreaming = false;
|
||||
bool m_cameraRecording = false;
|
||||
|
||||
QComboBox *m_dexHandDeviceCombo = nullptr;
|
||||
QLabel *m_dexHandStateLabel = nullptr;
|
||||
QTableWidget *m_dexHandStateTable = nullptr;
|
||||
QTabWidget *m_dexHandCommandTabs = nullptr;
|
||||
QList<QDoubleSpinBox *> m_dexHandAngleSpins;
|
||||
QList<QDoubleSpinBox *> m_dexHandPositionSpins;
|
||||
QList<QDoubleSpinBox *> m_dexHandSpeedSpins;
|
||||
QList<QDoubleSpinBox *> m_dexHandForceSpins;
|
||||
QTimer *m_dexHandRefreshTimer = nullptr;
|
||||
QWidget *m_dexHandTactilePanel = nullptr;
|
||||
TactileHeatmapWidget *m_dexHandTactileHeatmap = nullptr;
|
||||
QLabel *m_dexHandTactileStateLabel = nullptr;
|
||||
QPushButton *m_dexHandTactileStartButton = nullptr;
|
||||
QPushButton *m_dexHandTactileStopButton = nullptr;
|
||||
bool m_dexHandHasTactileFeedback = false;
|
||||
qint64 m_lastDexHandTactileUiUpdateMs = 0;
|
||||
|
||||
QLineEdit *m_agvIdEdit = nullptr;
|
||||
QDialog *m_agvStatusDialog = nullptr;
|
||||
QCheckBox *m_agvStatusSwitch = nullptr;
|
||||
QTimer *m_agvStatusRefreshTimer = nullptr;
|
||||
QTimer *m_agvManualVelocityTimer = nullptr;
|
||||
QTimer *m_agvMapRefreshTimer = nullptr;
|
||||
QLabel *m_agvConnectionValue = nullptr;
|
||||
QLabel *m_agvPoseValue = nullptr;
|
||||
QLabel *m_agvMotionValue = nullptr;
|
||||
@ -261,6 +389,10 @@ private:
|
||||
QLabel *m_agvMapOverview = nullptr;
|
||||
QLabel *m_agvMappingPreview = nullptr;
|
||||
QLabel *m_agvMappingStateLabel = nullptr;
|
||||
AgvMapViewWidget *m_agvMapView = nullptr;
|
||||
QWidget *m_agvControlWorkspace = nullptr;
|
||||
QPushButton *m_agvDeleteMapButton = nullptr;
|
||||
QPushButton *m_agvStopMappingButton = nullptr;
|
||||
QProgressBar *m_agvProgress = nullptr;
|
||||
QDoubleSpinBox *m_agvXSpin = nullptr;
|
||||
QDoubleSpinBox *m_agvYSpin = nullptr;
|
||||
@ -270,9 +402,21 @@ private:
|
||||
QDoubleSpinBox *m_agvVySpin = nullptr;
|
||||
QDoubleSpinBox *m_agvWzSpin = nullptr;
|
||||
QComboBox *m_agvMapCombo = nullptr;
|
||||
QComboBox *m_agvMapRefreshCombo = nullptr;
|
||||
QComboBox *m_agvStationCombo = nullptr;
|
||||
QTableWidget *m_agvStationTable = nullptr;
|
||||
QString m_agvDownloadPath;
|
||||
QVariantMap m_latestAgvState;
|
||||
QImage m_pendingAgvMapImage;
|
||||
QVariantMap m_pendingAgvMapMetadata;
|
||||
QString m_pendingAgvMapDetail;
|
||||
double m_agvManualVx = 0.0;
|
||||
double m_agvManualVy = 0.0;
|
||||
double m_agvManualWz = 0.0;
|
||||
bool m_agvManualMotionActive = false;
|
||||
bool m_agvMapStreamActive = false;
|
||||
bool m_agvMapFramePending = false;
|
||||
bool m_agvStopMappingRetryPending = false;
|
||||
QList<QPushButton *> m_serviceButtons;
|
||||
QPushButton *m_speakerStreamStartButton = nullptr;
|
||||
QPushButton *m_speakerStreamStopButton = nullptr;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
1167
src/robotclient.cpp
1167
src/robotclient.cpp
File diff suppressed because it is too large
Load Diff
@ -30,6 +30,10 @@ public slots:
|
||||
void disconnectFromServer();
|
||||
void setArmTelemetry(const QString &deviceId, bool enabled);
|
||||
void requestArmInfo(const QString &deviceId);
|
||||
void requestTcpCalibrationPose(const QString &deviceId, quint64 requestId);
|
||||
void requestControllerTcpOffset(const QString &deviceId, quint64 requestId);
|
||||
void requestTcpJogMove(const QString &deviceId, const QVariantMap &pose,
|
||||
double velocity, double acceleration, quint64 token);
|
||||
void requestArmFrames(const QString &deviceId);
|
||||
void setArmTelemetryFrames(const QString &deviceId, const QString &baseFrame,
|
||||
const QString &tcpFrame);
|
||||
@ -47,6 +51,17 @@ public slots:
|
||||
void requestArmClearFault(const QString &deviceId);
|
||||
void requestArmCalibrateZero(const QString &deviceId, const QString &jointName);
|
||||
void requestSnapshot(const QString &cameraId);
|
||||
void requestHandEyeImage(const QString &cameraId, quint64 token);
|
||||
void requestTouchRgbdImage(const QString &cameraId, quint64 token);
|
||||
void requestTouchImage(const QString &cameraId, quint64 token);
|
||||
void requestCameraCapabilities(const QString &cameraId, quint64 token);
|
||||
void requestDepthSnapshot(const QString &cameraId);
|
||||
void requestCameraStatus(const QString &cameraId);
|
||||
void requestDexHandStatus(const QString &deviceId);
|
||||
void requestDexHandCommand(const QString &deviceId, const QString &command,
|
||||
const QVariantList &values);
|
||||
void startDexHandTactileStream(const QString &deviceId);
|
||||
void stopDexHandTactileStream();
|
||||
void startCameraStream(const QString &cameraId, const QString &codec,
|
||||
const QString &mode = QStringLiteral("rgb"));
|
||||
void setCameraStreamCodec(const QString &codec);
|
||||
@ -56,6 +71,8 @@ public slots:
|
||||
void requestSystemRefresh();
|
||||
void requestSystemStopAll(const QString &deviceId);
|
||||
void requestAgvRefresh(const QString &deviceId);
|
||||
void requestAgvRelocalize(const QString &deviceId, double x, double y,
|
||||
double theta);
|
||||
void requestAgvNavigatePose(const QString &deviceId, double x, double y,
|
||||
double theta, double maxSpeed);
|
||||
void requestAgvNavigateStation(const QString &deviceId, const QString &stationId,
|
||||
@ -86,10 +103,20 @@ public slots:
|
||||
const QString &expectedRevision);
|
||||
|
||||
signals:
|
||||
// Synchronous arbitration before manual arm commands enter the worker queue.
|
||||
void armCommandStarting(const QString &deviceId);
|
||||
// Emitted synchronously before a command that may select another active TCP.
|
||||
void tcpReferenceInvalidated(const QString &deviceId);
|
||||
void connectRequested(const QString &host, int port, bool demoMode);
|
||||
void disconnectRequested();
|
||||
void armTelemetryRequested(const QString &deviceId, bool enabled);
|
||||
void armInfoRequested(const QString &deviceId);
|
||||
void tcpCalibrationPoseRequested(const QString &deviceId, quint64 requestId);
|
||||
void controllerTcpOffsetRequested(const QString &deviceId, quint64 requestId);
|
||||
void controllerTcpOffsetReceived(quint64 requestId, const QString &deviceId,
|
||||
const QVariantMap &offset, bool success, const QString &detail);
|
||||
void tcpJogMoveRequested(const QString &deviceId, const QVariantMap &pose,
|
||||
double velocity, double acceleration, quint64 token);
|
||||
void armFramesRequested(const QString &deviceId);
|
||||
void armTelemetryFramesRequested(const QString &deviceId, const QString &baseFrame,
|
||||
const QString &tcpFrame);
|
||||
@ -107,6 +134,19 @@ signals:
|
||||
void armClearFaultRequested(const QString &deviceId);
|
||||
void armCalibrateZeroRequested(const QString &deviceId, const QString &jointName);
|
||||
void snapshotRequested(const QString &cameraId);
|
||||
void handEyeImageRequested(const QString &cameraId, quint64 token);
|
||||
void touchRgbdImageRequested(const QString &cameraId, quint64 token);
|
||||
void touchImageRequested(const QString &cameraId, quint64 token);
|
||||
void cameraCapabilitiesRequested(const QString &cameraId, quint64 token);
|
||||
void cameraCapabilitiesReceived(quint64 token,const QString &cameraId,
|
||||
const QVariantMap &capabilities,bool success,const QString &detail);
|
||||
void depthSnapshotRequested(const QString &cameraId);
|
||||
void cameraStatusRequested(const QString &cameraId);
|
||||
void dexHandStatusRequested(const QString &deviceId);
|
||||
void dexHandCommandRequested(const QString &deviceId, const QString &command,
|
||||
const QVariantList &values);
|
||||
void dexHandTactileStreamStartRequested(const QString &deviceId);
|
||||
void dexHandTactileStreamStopRequested();
|
||||
void cameraStreamStartRequested(const QString &cameraId, const QString &codec,
|
||||
const QString &mode);
|
||||
void cameraStreamCodecRequested(const QString &codec);
|
||||
@ -116,6 +156,8 @@ signals:
|
||||
void systemRefreshRequested();
|
||||
void systemStopAllRequested(const QString &deviceId);
|
||||
void agvRefreshRequested(const QString &deviceId);
|
||||
void agvRelocalizeRequested(const QString &deviceId, double x, double y,
|
||||
double theta);
|
||||
void agvNavigatePoseRequested(const QString &deviceId, double x, double y,
|
||||
double theta, double maxSpeed);
|
||||
void agvNavigateStationRequested(const QString &deviceId, const QString &stationId,
|
||||
@ -148,6 +190,10 @@ signals:
|
||||
|
||||
void connectionChanged(bool connected, int latencyMs, const QString &detail);
|
||||
void armInfoReceived(const QString &deviceId, const QVariantMap &info);
|
||||
// Raw active TCP in the driver's base frame; this is not a flange pose.
|
||||
void tcpCalibrationPoseReceived(quint64 requestId, const QString &deviceId,
|
||||
const QVariantMap &pose, const QVariantMap &state,
|
||||
bool success, const QString &detail);
|
||||
void armFramesReceived(const QString &deviceId, const QStringList &baseFrames,
|
||||
const QStringList &tcpFrames);
|
||||
void telemetryReceived(const QString &deviceId, const QVariantList &joints,
|
||||
@ -158,6 +204,23 @@ signals:
|
||||
const QVariantList &devices);
|
||||
void systemInfoReceived(const QVariantMap &info);
|
||||
void imageReceived(const QImage &image, const QString &detail);
|
||||
// success validates image/intrinsics only. Pairing must additionally check
|
||||
// metadata.captureTimestampAvailable and its captureUtcNs against robot poses.
|
||||
void handEyeImageReceived(quint64 token, const QString &cameraId,
|
||||
const QImage &image, const QVariantMap &intrinsics,
|
||||
const QVariantMap &metadata, bool success,
|
||||
const QString &detail);
|
||||
void touchRgbdImageReceived(quint64 token, const QString &cameraId,
|
||||
const QImage &image, const QVariantMap &intrinsics,
|
||||
const QVariantMap &metadata, bool success, const QString &detail);
|
||||
void cameraStatusReceived(const QString &cameraId, const QVariantMap &state);
|
||||
void dexHandStatusReceived(const QString &deviceId, bool initialized,
|
||||
bool hasTactileFeedback,
|
||||
const QString &model,
|
||||
const QVariantList &freedoms);
|
||||
void dexHandTactileReceived(const QString &deviceId, int rows, int cols,
|
||||
const QVariantList &values, quint64 frameCount);
|
||||
void dexHandTactileStreamStateChanged(bool running, const QString &detail);
|
||||
void videoFrameReceived(const QString &cameraId, const VideoFrame &frame,
|
||||
const QString &detail);
|
||||
void cameraStreamStateChanged(const QString &cameraId, bool running,
|
||||
@ -165,7 +228,8 @@ signals:
|
||||
void cameraRecordingStateChanged(bool recording, const QString &detail);
|
||||
void agvStateReceived(const QVariantMap &state, const QVariantMap &navigation);
|
||||
void agvInventoryReceived(const QStringList &maps, const QVariantList &stations);
|
||||
void agvMapFrameReceived(const QImage &image, const QString &detail);
|
||||
void agvMapFrameReceived(const QImage &image, const QVariantMap &metadata,
|
||||
const QString &detail);
|
||||
void agvMapStreamStateChanged(bool running, const QString &detail);
|
||||
void rpcFinished(const QString &serviceName, const QString &methodName,
|
||||
bool success, const QString &responseJson);
|
||||
|
||||
87
src/tactileheatmapwidget.cpp
Normal file
87
src/tactileheatmapwidget.cpp
Normal file
@ -0,0 +1,87 @@
|
||||
#include "tactileheatmapwidget.h"
|
||||
|
||||
#include <QLinearGradient>
|
||||
#include <QPainter>
|
||||
#include <QPaintEvent>
|
||||
#include <QtMath>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace {
|
||||
QColor forceColor(double normalized)
|
||||
{
|
||||
normalized = qBound(0.0, normalized, 1.0);
|
||||
if (normalized < 0.25)
|
||||
return QColor::fromRgbF(0.10, 0.32 + normalized * 1.6, 0.88);
|
||||
if (normalized < 0.55) {
|
||||
const double t = (normalized - 0.25) / 0.30;
|
||||
return QColor::fromRgbF(0.10 + t * 0.85, 0.72 + t * 0.20, 0.88 - t * 0.72);
|
||||
}
|
||||
const double t = (normalized - 0.55) / 0.45;
|
||||
return QColor::fromRgbF(0.95, 0.92 - t * 0.78, 0.16 - t * 0.08);
|
||||
}
|
||||
}
|
||||
|
||||
TactileHeatmapWidget::TactileHeatmapWidget(QWidget *parent)
|
||||
: QWidget(parent)
|
||||
{
|
||||
setMinimumSize(260, 360);
|
||||
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
|
||||
}
|
||||
|
||||
void TactileHeatmapWidget::setTactileData(int rows, int cols,
|
||||
const QVector<int> &values)
|
||||
{
|
||||
if (rows <= 0 || cols <= 0 || values.size() < rows * cols)
|
||||
return;
|
||||
m_rows = rows;
|
||||
m_cols = cols;
|
||||
m_values = values.mid(0, rows * cols);
|
||||
update();
|
||||
}
|
||||
|
||||
void TactileHeatmapWidget::paintEvent(QPaintEvent *event)
|
||||
{
|
||||
Q_UNUSED(event)
|
||||
QPainter painter(this);
|
||||
painter.setRenderHint(QPainter::Antialiasing);
|
||||
painter.fillRect(rect(), QColor(20, 25, 36));
|
||||
|
||||
const int legendWidth = 22;
|
||||
const QRectF gridArea = rect().adjusted(18, 18, -50, -18);
|
||||
const double cellWidth = gridArea.width() / m_cols;
|
||||
const double cellHeight = gridArea.height() / m_rows;
|
||||
const int peak = m_values.isEmpty()
|
||||
? 0 : *std::max_element(m_values.cbegin(), m_values.cend());
|
||||
const double scale = qMax(25, peak);
|
||||
|
||||
for (int row = 0; row < m_rows; ++row) {
|
||||
// AP001 reports matrix rows from the finger base towards the tip.
|
||||
// Draw the tip at the top of the widget to match the physical finger.
|
||||
const int sourceRow = m_rows - 1 - row;
|
||||
for (int col = 0; col < m_cols; ++col) {
|
||||
const int value = m_values.value(sourceRow * m_cols + col);
|
||||
QRectF cell(gridArea.left() + col * cellWidth + 2,
|
||||
gridArea.top() + row * cellHeight + 2,
|
||||
cellWidth - 4, cellHeight - 4);
|
||||
painter.setPen(QPen(QColor(255, 255, 255, 35), 1));
|
||||
painter.setBrush(forceColor(value / scale));
|
||||
painter.drawRoundedRect(cell, 5, 5);
|
||||
painter.setPen(value / scale > 0.65 ? Qt::white : QColor(235, 242, 255));
|
||||
painter.drawText(cell, Qt::AlignCenter, QString::number(value));
|
||||
}
|
||||
}
|
||||
|
||||
const QRectF legend(gridArea.right() + 15, gridArea.top(), legendWidth,
|
||||
gridArea.height());
|
||||
QLinearGradient gradient(legend.bottomLeft(), legend.topLeft());
|
||||
gradient.setColorAt(0.0, forceColor(0.0));
|
||||
gradient.setColorAt(0.5, forceColor(0.5));
|
||||
gradient.setColorAt(1.0, forceColor(1.0));
|
||||
painter.fillRect(legend, gradient);
|
||||
painter.setPen(QColor(220, 228, 240));
|
||||
painter.drawText(QRectF(legend.right() + 3, legend.top() - 7, 30, 18),
|
||||
Qt::AlignLeft, QString::number(peak));
|
||||
painter.drawText(QRectF(legend.right() + 3, legend.bottom() - 10, 30, 18),
|
||||
Qt::AlignLeft, QStringLiteral("0"));
|
||||
}
|
||||
20
src/tactileheatmapwidget.h
Normal file
20
src/tactileheatmapwidget.h
Normal file
@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include <QVector>
|
||||
#include <QWidget>
|
||||
|
||||
class TactileHeatmapWidget final : public QWidget
|
||||
{
|
||||
public:
|
||||
explicit TactileHeatmapWidget(QWidget *parent = nullptr);
|
||||
|
||||
void setTactileData(int rows, int cols, const QVector<int> &values);
|
||||
|
||||
protected:
|
||||
void paintEvent(QPaintEvent *event) override;
|
||||
|
||||
private:
|
||||
int m_rows = 12;
|
||||
int m_cols = 5;
|
||||
QVector<int> m_values = QVector<int>(60, 0);
|
||||
};
|
||||
269
src/tcpcalibration.cpp
Normal file
269
src/tcpcalibration.cpp
Normal file
@ -0,0 +1,269 @@
|
||||
#include "tcpcalibration.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
namespace TcpCalibration {
|
||||
namespace {
|
||||
constexpr double pi = 3.14159265358979323846;
|
||||
bool fail(QString *error, const char *message)
|
||||
{
|
||||
if (error) *error = QString::fromUtf8(message);
|
||||
return false;
|
||||
}
|
||||
void clearError(QString *error) { if (error) error->clear(); }
|
||||
Matrix multiply(const Matrix &a, const Matrix &b)
|
||||
{
|
||||
Matrix out{};
|
||||
for (int r=0;r<4;++r) for (int c=0;c<4;++c)
|
||||
for (int k=0;k<4;++k) out[r*4+c]+=a[r*4+k]*b[k*4+c];
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
bool validPose(const Pose &pose)
|
||||
{
|
||||
return std::all_of(pose.begin(),pose.end(),[](double x){return std::isfinite(x);});
|
||||
}
|
||||
|
||||
bool poseMatrix(const Pose &p, Matrix &matrix, QString *error)
|
||||
{
|
||||
if (!validPose(p)) return fail(error,"Pose must contain six finite values.");
|
||||
const double cx=std::cos(p[3]), sx=std::sin(p[3]);
|
||||
const double cy=std::cos(p[4]), sy=std::sin(p[4]);
|
||||
const double cz=std::cos(p[5]), sz=std::sin(p[5]);
|
||||
matrix={{cz*cy,cz*sy*sx-sz*cx,cz*sy*cx+sz*sx,p[0],
|
||||
sz*cy,sz*sy*sx+cz*cx,sz*sy*cx-cz*sx,p[1],
|
||||
-sy,cy*sx,cy*cx,p[2],0,0,0,1}};
|
||||
clearError(error); return true;
|
||||
}
|
||||
|
||||
bool matrixPose(const Matrix &m, Pose &pose, QString *error)
|
||||
{
|
||||
for (double v:m) if (!std::isfinite(v)) return fail(error,"Transform contains non-finite values.");
|
||||
constexpr double tolerance=1e-6;
|
||||
if (std::abs(m[12])>tolerance || std::abs(m[13])>tolerance ||
|
||||
std::abs(m[14])>tolerance || std::abs(m[15]-1)>tolerance)
|
||||
return fail(error,"Transform must have homogeneous last row [0,0,0,1].");
|
||||
for (int a=0;a<3;++a) for (int b=0;b<3;++b) {
|
||||
double dot=0;
|
||||
for (int r=0;r<3;++r) dot+=m[r*4+a]*m[r*4+b];
|
||||
if (std::abs(dot-(a==b?1.0:0.0))>tolerance)
|
||||
return fail(error,"Transform rotation must be orthonormal.");
|
||||
}
|
||||
const double determinant=m[0]*(m[5]*m[10]-m[6]*m[9])
|
||||
-m[1]*(m[4]*m[10]-m[6]*m[8])+m[2]*(m[4]*m[9]-m[5]*m[8]);
|
||||
if (std::abs(determinant-1)>tolerance)
|
||||
return fail(error,"Transform rotation must be proper (determinant +1).");
|
||||
const double cy=std::hypot(m[0],m[4]);
|
||||
Pose out{{m[3],m[7],m[11],0,std::atan2(-m[8],cy),0}};
|
||||
// Same gimbal-lock branch as phone/scripts/robot_pose_math.py.
|
||||
if (cy>1e-9) {out[3]=std::atan2(m[9],m[10]); out[5]=std::atan2(m[4],m[0]);}
|
||||
else out[3]=std::atan2(-m[6],m[5]);
|
||||
pose=out; clearError(error); return true;
|
||||
}
|
||||
|
||||
bool toolPose(const Pose &baseFlange, const Pose &flangeTcp, Pose &baseTcp, QString *error)
|
||||
{
|
||||
Matrix a{},b{};
|
||||
if (!poseMatrix(baseFlange,a,error) || !poseMatrix(flangeTcp,b,error)) return false;
|
||||
return matrixPose(multiply(a,b),baseTcp,error);
|
||||
}
|
||||
|
||||
bool flangePose(const Pose &baseTcp, const Pose &flangeTcp, Pose &baseFlange, QString *error)
|
||||
{
|
||||
Matrix a{},b{},inverse{};
|
||||
if (!poseMatrix(baseTcp,a,error) || !poseMatrix(flangeTcp,b,error)) return false;
|
||||
for (int r=0;r<3;++r) {
|
||||
for (int c=0;c<3;++c) inverse[r*4+c]=b[c*4+r];
|
||||
for (int c=0;c<3;++c) inverse[r*4+3]-=inverse[r*4+c]*b[c*4+3];
|
||||
}
|
||||
inverse[15]=1;
|
||||
return matrixPose(multiply(a,inverse),baseFlange,error);
|
||||
}
|
||||
|
||||
bool jogTarget(const Pose &baseActive, const Pose &flangeActive, const Pose &flangeSelected,
|
||||
int axis, double increment, Pose &target, QString *error)
|
||||
{
|
||||
if (axis < 0 || axis >= 6 || !std::isfinite(increment)
|
||||
|| std::abs(increment) > (axis < 3 ? .002 : .005))
|
||||
return fail(error, "TCP jog increment is outside the bounded step range.");
|
||||
Pose flange{}, selected{}, delta{}, nextSelected{}, nextFlange{};
|
||||
if (!flangePose(baseActive, flangeActive, flange, error)
|
||||
|| !toolPose(flange, flangeSelected, selected, error)) return false;
|
||||
delta[size_t(axis)] = increment;
|
||||
return toolPose(selected, delta, nextSelected, error)
|
||||
&& flangePose(nextSelected, flangeSelected, nextFlange, error)
|
||||
&& toolPose(nextFlange, flangeActive, target, error);
|
||||
}
|
||||
|
||||
bool tooSimilar(const Pose &previous, const Pose ¤t)
|
||||
{
|
||||
Matrix a{},b{};
|
||||
if (!poseMatrix(previous,a) || !poseMatrix(current,b)) return false;
|
||||
const double distance=std::hypot(std::hypot(current[0]-previous[0],
|
||||
current[1]-previous[1]),current[2]-previous[2])*1000;
|
||||
double trace=0;
|
||||
for (int r=0;r<3;++r) for (int c=0;c<3;++c) trace+=a[r*4+c]*b[r*4+c];
|
||||
const double angle=std::acos(std::max(-1.0,std::min(1.0,(trace-1)/2)))*180/pi;
|
||||
return distance<1.0 && angle<3.0;
|
||||
}
|
||||
|
||||
namespace {
|
||||
bool solvePosition(const std::vector<Pose> &poses, Result &result, QString *error)
|
||||
{
|
||||
if (poses.size()<3) return fail(error,"TCP position calibration needs at least three flange poses.");
|
||||
std::vector<Matrix> transforms;
|
||||
std::vector<std::array<double,6>> a;
|
||||
std::vector<double> b;
|
||||
for (const Pose &pose:poses) {
|
||||
Matrix m{};
|
||||
if (!poseMatrix(pose,m,error)) return false;
|
||||
transforms.push_back(m);
|
||||
for (int r=0;r<3;++r) {
|
||||
std::array<double,6> row{{m[r*4],m[r*4+1],m[r*4+2],0,0,0}};
|
||||
row[3+r]=-1; a.push_back(row); b.push_back(-m[r*4+3]);
|
||||
}
|
||||
}
|
||||
// One-sided Jacobi SVD: orthogonalize A's six columns directly. Never form
|
||||
// A^T*A (which would square the condition number). A becomes U*Sigma;
|
||||
// V accumulates the right rotations, so x=V*Sigma^-1*U^T*b.
|
||||
std::array<std::array<double,6>,6> v{};
|
||||
for (int i=0;i<6;++i) v[i][i]=1;
|
||||
const double epsilon=std::numeric_limits<double>::epsilon();
|
||||
bool converged=false;
|
||||
for (int sweep=0;sweep<100;++sweep) {
|
||||
bool changed=false;
|
||||
for (int p=0;p<5;++p) for (int q=p+1;q<6;++q) {
|
||||
double alpha=0,beta=0,gamma=0;
|
||||
for (const auto &row:a) {alpha+=row[p]*row[p];beta+=row[q]*row[q];gamma+=row[p]*row[q];}
|
||||
if (std::abs(gamma)<=16*epsilon*std::sqrt(alpha)*std::sqrt(beta)) continue;
|
||||
changed=true;
|
||||
const double zeta=(beta-alpha)/(2*gamma);
|
||||
const double tangent=std::copysign(1.0,zeta)/(std::abs(zeta)+std::hypot(1.0,zeta));
|
||||
const double cosine=1/std::hypot(1.0,tangent), sine=cosine*tangent;
|
||||
for (auto &row:a) {const double x=row[p],y=row[q];row[p]=cosine*x-sine*y;row[q]=sine*x+cosine*y;}
|
||||
for (auto &row:v) {const double x=row[p],y=row[q];row[p]=cosine*x-sine*y;row[q]=sine*x+cosine*y;}
|
||||
}
|
||||
if (!changed) {converged=true;break;}
|
||||
}
|
||||
if (!converged) return fail(error,"TCP least-squares decomposition did not converge.");
|
||||
std::array<double,6> singular{};
|
||||
for (int c=0;c<6;++c) for (const auto &row:a) singular[c]=std::hypot(singular[c],row[c]);
|
||||
const double largest=*std::max_element(singular.begin(),singular.end());
|
||||
const double smallest=*std::min_element(singular.begin(),singular.end());
|
||||
// NumPy lstsq(rcond=None): epsilon * max(M,N) * largest singular value.
|
||||
if (smallest<=epsilon*double(std::max(size_t(6),a.size()))*largest)
|
||||
return fail(error,"Insufficient rotation diversity: TCP system rank is below six.");
|
||||
// Additional explicit numerical guard, absent from the phone implementation.
|
||||
if (smallest<largest/1e8)
|
||||
return fail(error,"TCP poses are ill-conditioned; increase wrist rotation diversity.");
|
||||
std::array<double,6> solution{};
|
||||
for (int c=0;c<6;++c) {
|
||||
double projection=0;
|
||||
for (size_t r=0;r<a.size();++r) projection+=(a[r][c]/singular[c])*b[r];
|
||||
const double coefficient=projection/singular[c];
|
||||
for (int j=0;j<6;++j) solution[j]+=v[j][c]*coefficient;
|
||||
}
|
||||
Result out;
|
||||
for (int i=0;i<3;++i) {out.offset[i]=solution[i];out.fixedPoint[i]=solution[i+3];}
|
||||
for (double value:solution) if (!std::isfinite(value))
|
||||
return fail(error,"TCP solution is non-finite.");
|
||||
double residualNorm=0;
|
||||
for (const Matrix &m:transforms) {
|
||||
double distance=0;
|
||||
for (int r=0;r<3;++r) {
|
||||
double delta=m[r*4+3]-out.fixedPoint[r];
|
||||
for (int c=0;c<3;++c) delta+=m[r*4+c]*out.offset[c];
|
||||
distance=std::hypot(distance,delta);
|
||||
}
|
||||
const double mm=distance*1000;
|
||||
if (!std::isfinite(mm)) return fail(error,"TCP residual is non-finite.");
|
||||
out.residualsMm.push_back(mm); residualNorm=std::hypot(residualNorm,mm);
|
||||
}
|
||||
out.rmsMm=residualNorm/std::sqrt(double(poses.size()));
|
||||
if (!std::isfinite(out.rmsMm)) return fail(error,"TCP RMS is non-finite.");
|
||||
result=out; clearError(error); return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool solve(const std::vector<Pose> &poses, Result &result, QString *error)
|
||||
{
|
||||
if (poses.size()<4) return fail(error,"TCP calibration needs at least four flange poses.");
|
||||
return solvePosition(poses,result,error);
|
||||
}
|
||||
|
||||
bool solveSixPoint(const std::vector<Pose> &poses, DirectionMethod method,
|
||||
Result &result, QString *error)
|
||||
{
|
||||
if (poses.size()!=6) return fail(error,"Six-point TCP calibration needs exactly six flange poses.");
|
||||
if (method!=DirectionMethod::XZ && method!=DirectionMethod::XY)
|
||||
return fail(error,"Unknown six-point direction method.");
|
||||
Result out;
|
||||
if (!solvePosition(std::vector<Pose>(poses.begin(),poses.begin()+3),out,error)) return false;
|
||||
std::array<Matrix,3> direction{};
|
||||
std::array<std::array<double,3>,3> tip{};
|
||||
for (int i=0;i<3;++i) {
|
||||
if (!poseMatrix(poses[size_t(i+3)],direction[i],error)) return false;
|
||||
const auto &m=direction[i];
|
||||
for (int r=0;r<3;++r) {
|
||||
tip[i][r]=m[r*4+3];
|
||||
for (int c=0;c<3;++c) tip[i][r]+=m[r*4+c]*out.offset[c];
|
||||
if (!std::isfinite(tip[i][r])) return fail(error,"Direction TCP position is non-finite.");
|
||||
}
|
||||
if (i) {
|
||||
double trace=0;
|
||||
for(int r=0;r<3;++r) for(int c=0;c<3;++c) trace+=direction[0][r*4+c]*m[r*4+c];
|
||||
const double angle=std::acos(std::max(-1.0,std::min(1.0,(trace-1)/2)))*180/pi;
|
||||
out.directionOrientationDriftDeg=std::max(out.directionOrientationDriftDeg,angle);
|
||||
if (angle>.2+1e-9)
|
||||
return fail(error,"Direction poses must keep flange orientation fixed (maximum drift 0.2 degrees).");
|
||||
}
|
||||
}
|
||||
using Vector=std::array<double,3>;
|
||||
std::array<Vector,2> vectors{};
|
||||
for (int i=0;i<2;++i) {
|
||||
double length=0;
|
||||
for (int r=0;r<3;++r) {
|
||||
vectors[i][r]=tip[i+1][r]-tip[0][r];
|
||||
length=std::hypot(length,vectors[i][r]);
|
||||
}
|
||||
// Conservative numerical floor; vendor-specific larger travel guidance
|
||||
// belongs in the teaching instructions, not a universal algorithm gate.
|
||||
if (!std::isfinite(length) || length<.01)
|
||||
return fail(error,"Direction teaching baseline must be at least 10 mm and finite.");
|
||||
out.directionBaselineMm[i]=length*1000;
|
||||
if (!std::isfinite(out.directionBaselineMm[i]))
|
||||
return fail(error,"Direction baseline is non-finite.");
|
||||
for(double &value:vectors[i]) value/=length;
|
||||
}
|
||||
const Vector x=vectors[0];
|
||||
double dot=0;
|
||||
for(int r=0;r<3;++r) dot+=x[r]*vectors[1][r];
|
||||
dot=std::max(-1.0,std::min(1.0,dot));
|
||||
out.directionAngleDeg=std::acos(dot)*180/pi;
|
||||
if (out.directionAngleDeg<5 || out.directionAngleDeg>175)
|
||||
return fail(error,"Direction vectors are nearly collinear; separation must be 5 to 175 degrees.");
|
||||
Vector secondary{};
|
||||
double norm=0;
|
||||
for(int r=0;r<3;++r) { secondary[r]=vectors[1][r]-dot*x[r]; norm=std::hypot(norm,secondary[r]); }
|
||||
for(double &value:secondary) value/=norm;
|
||||
auto cross=[](const Vector &a,const Vector &b)->Vector {
|
||||
return {{a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]}};
|
||||
};
|
||||
Vector y{},z{};
|
||||
if (method==DirectionMethod::XZ) { z=secondary; y=cross(z,x); }
|
||||
else { y=secondary; z=cross(x,y); }
|
||||
const std::array<Vector,3> axes{{x,y,z}};
|
||||
Matrix flangeTool{}; flangeTool[15]=1;
|
||||
// Directions were taught in base coordinates. Persist flange-relative
|
||||
// rotation R_flange_tool = transpose(R_base_flange_origin) * R_base_tool.
|
||||
for(int r=0;r<3;++r) {
|
||||
flangeTool[r*4+3]=out.offset[r];
|
||||
for(int c=0;c<3;++c) for(int k=0;k<3;++k)
|
||||
flangeTool[r*4+c]+=direction[0][k*4+r]*axes[c][k];
|
||||
}
|
||||
if (!matrixPose(flangeTool,out.offset,error)) return false;
|
||||
result=out; clearError(error); return true;
|
||||
}
|
||||
}
|
||||
46
src/tcpcalibration.h
Normal file
46
src/tcpcalibration.h
Normal file
@ -0,0 +1,46 @@
|
||||
#ifndef TCPCALIBRATION_H
|
||||
#define TCPCALIBRATION_H
|
||||
|
||||
#include <QString>
|
||||
#include <array>
|
||||
#include <vector>
|
||||
|
||||
namespace TcpCalibration {
|
||||
// AUBO convention: metres, radians; R = Rz(rz) * Ry(ry) * Rx(rx).
|
||||
using Pose = std::array<double, 6>;
|
||||
using Matrix = std::array<double, 16>; // Row-major homogeneous transform.
|
||||
struct Result {
|
||||
Pose offset{}; // Flange-to-tool; solve() leaves rotation zero/unmeasured.
|
||||
std::array<double, 3> fixedPoint{};
|
||||
std::vector<double> residualsMm;
|
||||
double rmsMm = 0;
|
||||
std::array<double, 2> directionBaselineMm{};
|
||||
double directionAngleDeg = 0;
|
||||
double directionOrientationDriftDeg = 0; // Maximum relative to direction origin.
|
||||
};
|
||||
bool validPose(const Pose &pose);
|
||||
bool poseMatrix(const Pose &pose, Matrix &matrix, QString *error = nullptr);
|
||||
bool matrixPose(const Matrix &matrix, Pose &pose, QString *error = nullptr);
|
||||
bool flangePose(const Pose &baseTcp, const Pose &flangeTcp, Pose &baseFlange,
|
||||
QString *error = nullptr);
|
||||
bool toolPose(const Pose &baseFlange, const Pose &flangeTcp, Pose &baseTcp,
|
||||
QString *error = nullptr);
|
||||
// Same fixed-point least squares and RMS as phone's solve_tcp_offset.
|
||||
// Unlike the Python original, also rejects condition numbers above 1e8.
|
||||
// A high RMS still returns a result; the caller applies the 2 mm quality gate.
|
||||
bool solve(const std::vector<Pose> &flangePoses, Result &result, QString *error = nullptr);
|
||||
enum class DirectionMethod { XZ, XY };
|
||||
// Exactly six flange poses: three fixed-tip rotations, then origin, +X,
|
||||
// and +Z (XZ) or +Y (XY), keeping the last three flange orientations fixed.
|
||||
// Direction gates: >=10 mm baseline, >=5 deg from collinearity, <=0.2 deg
|
||||
// flange drift. These are numerical quality limits, not vendor travel advice.
|
||||
// Position RMS/residuals describe only the first three observations.
|
||||
bool solveSixPoint(const std::vector<Pose> &flangePoses, DirectionMethod method,
|
||||
Result &result, QString *error = nullptr);
|
||||
bool tooSimilar(const Pose &previous, const Pose ¤t);
|
||||
// Increment in the selected tool's axes, with rotation about its own origin.
|
||||
// Returns the target of the controller's existing active TCP (base coordinates).
|
||||
bool jogTarget(const Pose &baseActive, const Pose &flangeActive, const Pose &flangeSelected,
|
||||
int axis, double increment, Pose &target, QString *error = nullptr);
|
||||
}
|
||||
#endif
|
||||
650
src/tcpcalibrationwidget.cpp
Normal file
650
src/tcpcalibrationwidget.cpp
Normal file
@ -0,0 +1,650 @@
|
||||
#include "tcpcalibrationwidget.h"
|
||||
|
||||
#include <QCheckBox>
|
||||
#include <QComboBox>
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QFrame>
|
||||
#include <QGridLayout>
|
||||
#include <QHeaderView>
|
||||
#include <QLabel>
|
||||
#include <QLineEdit>
|
||||
#include <QMessageBox>
|
||||
#include <QPushButton>
|
||||
#include <QScrollArea>
|
||||
#include <QSettings>
|
||||
#include <QSignalBlocker>
|
||||
#include <QTableWidget>
|
||||
#include <QTimer>
|
||||
#include <QVBoxLayout>
|
||||
#include <QtMath>
|
||||
#include <cmath>
|
||||
|
||||
namespace {
|
||||
QVBoxLayout *panel(QBoxLayout *parent, const QString &title)
|
||||
{
|
||||
auto *frame = new QFrame;
|
||||
frame->setObjectName(QStringLiteral("panel"));
|
||||
auto *layout = new QVBoxLayout(frame);
|
||||
layout->setContentsMargins(14, 12, 14, 12);
|
||||
layout->setSpacing(8);
|
||||
auto *label = new QLabel(title);
|
||||
label->setObjectName(QStringLiteral("sectionTitle"));
|
||||
layout->addWidget(label);
|
||||
parent->addWidget(frame);
|
||||
return layout;
|
||||
}
|
||||
QLabel *hint(const QString &text)
|
||||
{
|
||||
auto *label = new QLabel(text);
|
||||
label->setObjectName(QStringLiteral("mutedLabel"));
|
||||
label->setWordWrap(true);
|
||||
return label;
|
||||
}
|
||||
const char *keys[] = {"x", "y", "z", "rx", "ry", "rz"};
|
||||
QString axis(int i) { return QString::fromLatin1(keys[i]).toUpper(); }
|
||||
double fromDisplay(double value, int axisIndex)
|
||||
{
|
||||
return axisIndex < 3 ? value / 1000.0 : qDegreesToRadians(value);
|
||||
}
|
||||
double toDisplay(double value, int axisIndex)
|
||||
{
|
||||
return axisIndex < 3 ? value * 1000.0 : qRadiansToDegrees(value);
|
||||
}
|
||||
}
|
||||
|
||||
TcpCalibrationWidget::TcpCalibrationWidget(QWidget *parent) : QWidget(parent)
|
||||
{
|
||||
setObjectName(QStringLiteral("tcpCalibrationPage"));
|
||||
buildUi();
|
||||
m_captureTimer = new QTimer(this);
|
||||
m_captureTimer->setSingleShot(true);
|
||||
m_captureTimer->setInterval(6000);
|
||||
connect(m_captureTimer, &QTimer::timeout, this, [this] {
|
||||
if (m_pendingRow < 0) return;
|
||||
++m_serial;
|
||||
m_pendingRow = -1;
|
||||
refresh();
|
||||
reportError(QStringLiteral("读取实时位姿超时,请检查机械臂连接后重试"));
|
||||
});
|
||||
resizeSamples(4);
|
||||
}
|
||||
|
||||
void TcpCalibrationWidget::buildUi()
|
||||
{
|
||||
auto *outer = new QVBoxLayout(this);
|
||||
outer->setContentsMargins(12, 10, 12, 10);
|
||||
auto *scroll = new QScrollArea(this);
|
||||
scroll->setWidgetResizable(true);
|
||||
scroll->setFrameShape(QFrame::NoFrame);
|
||||
auto *content = new QWidget;
|
||||
auto *layout = new QVBoxLayout(content);
|
||||
layout->setContentsMargins(0, 0, 0, 0);
|
||||
layout->setSpacing(10);
|
||||
scroll->setWidget(content);
|
||||
outer->addWidget(scroll);
|
||||
|
||||
auto *configuration = new QHBoxLayout;
|
||||
configuration->setSpacing(10);
|
||||
layout->addLayout(configuration);
|
||||
auto *toolPanel = panel(configuration, QStringLiteral("工具信息"));
|
||||
auto *toolGrid = new QGridLayout;
|
||||
toolGrid->setHorizontalSpacing(12);
|
||||
m_toolCombo = new QComboBox;
|
||||
m_toolCombo->setObjectName(QStringLiteral("tcpLocalTools"));
|
||||
m_toolCombo->addItem(QStringLiteral("新建工具"));
|
||||
m_name = new QLineEdit;
|
||||
m_name->setObjectName(QStringLiteral("tcpToolName"));
|
||||
m_name->setMaxLength(80);
|
||||
m_name->setPlaceholderText(QStringLiteral("输入工具名称"));
|
||||
m_name->setToolTip(QStringLiteral("保存至当前机械臂,并同步至工具坐标列表。"));
|
||||
m_reload = new QPushButton(QStringLiteral("刷新"));
|
||||
m_delete = new QPushButton(QStringLiteral("删除"));
|
||||
m_delete->setObjectName(QStringLiteral("tcpDelete"));
|
||||
toolGrid->addWidget(new QLabel(QStringLiteral("工具")), 0, 0);
|
||||
toolGrid->addWidget(m_toolCombo, 0, 1);
|
||||
toolGrid->addWidget(new QLabel(QStringLiteral("名称")), 1, 0);
|
||||
toolGrid->addWidget(m_name, 1, 1, 1, 3);
|
||||
toolGrid->addWidget(m_reload, 0, 2);
|
||||
toolGrid->addWidget(m_delete, 0, 3);
|
||||
toolGrid->setColumnStretch(1, 1);
|
||||
toolPanel->addLayout(toolGrid);
|
||||
m_currentTool = hint(QStringLiteral("正在标定:新工具"));
|
||||
toolPanel->addWidget(m_currentTool);
|
||||
toolPanel->addStretch();
|
||||
auto *sourcePanel = panel(configuration, QStringLiteral("控制器 TCP 偏移"));
|
||||
sourcePanel->parentWidget()->setToolTip(QStringLiteral("与示教器当前活动 TCP 一致,用于还原法兰位姿。仅零偏移工具可填全零;采样期间不得切换。"));
|
||||
configuration->setStretch(0,1); configuration->setStretch(1,1);
|
||||
auto *sourceGrid = new QGridLayout;
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
auto *spin = new QDoubleSpinBox;
|
||||
spin->setObjectName(QStringLiteral("tcpSource%1").arg(i));
|
||||
spin->setRange(i < 3 ? -10000 : -360, i < 3 ? 10000 : 360);
|
||||
spin->setDecimals(4);
|
||||
spin->setSuffix(i < 3 ? QStringLiteral(" mm") : QStringLiteral(" °"));
|
||||
m_source.append(spin);
|
||||
sourceGrid->addWidget(new QLabel(axis(i)), i/3, (i%3)*2);
|
||||
sourceGrid->addWidget(spin, i/3, (i%3)*2+1);
|
||||
sourceGrid->setColumnStretch((i%3)*2+1,1);
|
||||
connect(spin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this,
|
||||
[this](double) { updateSource(); });
|
||||
}
|
||||
sourcePanel->addLayout(sourceGrid);
|
||||
m_sourceConfirmed = new QCheckBox(QStringLiteral(
|
||||
"已确认控制器 TCP 偏移"));
|
||||
m_sourceConfirmed->setToolTip(QStringLiteral("RX/RY/RZ 为 ZYX 欧拉角,非旋转向量。偏移必须与控制器当前活动工具一致。"));
|
||||
m_sourceConfirmed->setObjectName(QStringLiteral("tcpSourceConfirmed"));
|
||||
sourcePanel->addWidget(m_sourceConfirmed);
|
||||
m_readOffset = new QPushButton(QStringLiteral("从控制器读取"));
|
||||
m_readOffset->setObjectName(QStringLiteral("tcpReadControllerOffset"));
|
||||
sourcePanel->addWidget(m_readOffset);
|
||||
connect(m_readOffset, &QPushButton::clicked, this, [this] {
|
||||
if (!m_connected || m_demo || m_device.isEmpty() || m_offsetPending) return;
|
||||
invalidateReference();
|
||||
m_offsetPending = true;
|
||||
const quint64 request = ++m_offsetSerial;
|
||||
refresh();
|
||||
emit controllerOffsetRequested(m_device, request);
|
||||
QTimer::singleShot(6000, this, [this, request] {
|
||||
if (!m_offsetPending || request != m_offsetSerial) return;
|
||||
acceptControllerOffset(request, m_device, {}, false, QStringLiteral("读取控制器 TCP 偏移超时"));
|
||||
});
|
||||
});
|
||||
connect(m_sourceConfirmed, &QCheckBox::toggled, this, [this](bool) {
|
||||
resetCalibration();
|
||||
refresh();
|
||||
emit referenceChanged();
|
||||
});
|
||||
|
||||
auto *pointsPanel = panel(layout, QStringLiteral("TCP 采样"));
|
||||
m_instructions = hint(QString());
|
||||
pointsPanel->addWidget(m_instructions);
|
||||
auto *pointActions = new QHBoxLayout;
|
||||
m_method = new QComboBox;
|
||||
m_method->setObjectName(QStringLiteral("tcpCalibrationMethod"));
|
||||
m_method->addItem(QStringLiteral("四点法"),QStringLiteral("four_point"));
|
||||
m_method->addItem(QStringLiteral("六点法 · XZ"),QStringLiteral("six_point_xz"));
|
||||
m_method->addItem(QStringLiteral("六点法 · XY"),QStringLiteral("six_point_xy"));
|
||||
pointActions->addWidget(new QLabel(QStringLiteral("标定方式")));
|
||||
pointActions->addWidget(m_method);
|
||||
pointActions->addStretch();
|
||||
auto *restart = new QPushButton(QStringLiteral("重新标定"));
|
||||
restart->setObjectName(QStringLiteral("tcpClear"));
|
||||
pointActions->addWidget(restart);
|
||||
pointsPanel->addLayout(pointActions);
|
||||
m_table = new QTableWidget(0, 10);
|
||||
m_table->setObjectName(QStringLiteral("tcpSamples"));
|
||||
m_table->setHorizontalHeaderLabels({QStringLiteral("点位"), QStringLiteral("状态"),
|
||||
QStringLiteral("X mm"), QStringLiteral("Y mm"), QStringLiteral("Z mm"),
|
||||
QStringLiteral("RX °"), QStringLiteral("RY °"), QStringLiteral("RZ °"),
|
||||
QStringLiteral("残差 mm"), QStringLiteral("操作")});
|
||||
m_table->setEditTriggers(QAbstractItemView::NoEditTriggers);
|
||||
m_table->setSelectionMode(QAbstractItemView::NoSelection);
|
||||
m_table->setAlternatingRowColors(true);
|
||||
m_table->verticalHeader()->hide();
|
||||
m_table->verticalHeader()->setDefaultSectionSize(36);
|
||||
m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
|
||||
m_table->setMinimumHeight(180);
|
||||
pointsPanel->addWidget(m_table);
|
||||
connect(m_method, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this] {
|
||||
resizeSamples(m_method->currentIndex()==0 ? 4 : 6);
|
||||
for (auto *spin : m_orientation) spin->setValue(0);
|
||||
});
|
||||
connect(restart, &QPushButton::clicked, this, &TcpCalibrationWidget::resetCalibration);
|
||||
|
||||
auto *resultPanel = panel(layout, QStringLiteral("TCP 参数(相对法兰)"));
|
||||
auto *resultGrid = new QGridLayout;
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
auto *axisLabel = new QLabel(axis(i) + (i < 3 ? QStringLiteral(" mm") : QStringLiteral(" °(手动)")));
|
||||
resultGrid->addWidget(axisLabel, 0, i);
|
||||
if (i>=3) m_orientationLabels.append(axisLabel);
|
||||
if (i < 3) {
|
||||
auto *value = new QLabel(QStringLiteral("--"));
|
||||
value->setObjectName(QStringLiteral("tcpResult%1").arg(i));
|
||||
value->setTextInteractionFlags(Qt::TextSelectableByMouse);
|
||||
m_results.append(value);
|
||||
resultGrid->addWidget(value, 1, i);
|
||||
} else {
|
||||
auto *spin = new QDoubleSpinBox;
|
||||
spin->setObjectName(QStringLiteral("tcpOrientation%1").arg(i));
|
||||
spin->setRange(-360, 360);
|
||||
spin->setDecimals(4);
|
||||
spin->setSuffix(QStringLiteral(" °"));
|
||||
m_orientation.append(spin);
|
||||
resultGrid->addWidget(spin, 1, i);
|
||||
connect(spin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this,
|
||||
[this](double) { refresh(); });
|
||||
}
|
||||
}
|
||||
resultPanel->addLayout(resultGrid);
|
||||
for (auto *spin : m_orientation) spin->setToolTip(QStringLiteral("固定点法仅求解平移;工具姿态需手动设置,采用 ZYX 欧拉角。"));
|
||||
m_rms = new QLabel(QStringLiteral("固定点 RMS:--(合格上限 2.000 mm)"));
|
||||
m_rms->setObjectName(QStringLiteral("tcpRms"));
|
||||
resultPanel->addWidget(m_rms);
|
||||
m_preview = hint(QStringLiteral("基座下工具位姿:--"));
|
||||
m_preview->setObjectName(QStringLiteral("tcpToolPreview"));
|
||||
resultPanel->addWidget(m_preview);
|
||||
auto *actions = new QHBoxLayout;
|
||||
m_status = hint(QStringLiteral("等待采样"));
|
||||
m_status->setObjectName(QStringLiteral("tcpStatus"));
|
||||
actions->addWidget(m_status, 1);
|
||||
m_calculate = new QPushButton(QStringLiteral("TCP 标定"));
|
||||
m_calculate->setObjectName(QStringLiteral("primaryButton"));
|
||||
m_calculate->setProperty("tcpAction", QStringLiteral("calculate"));
|
||||
m_save = new QPushButton(QStringLiteral("保存工具"));
|
||||
m_save->setObjectName(QStringLiteral("tcpSave"));
|
||||
actions->addWidget(m_calculate);
|
||||
actions->addWidget(m_save);
|
||||
outer->addLayout(actions);
|
||||
layout->addStretch();
|
||||
connect(m_calculate, &QPushButton::clicked, this, &TcpCalibrationWidget::calculate);
|
||||
connect(m_save, &QPushButton::clicked, this, &TcpCalibrationWidget::saveTool);
|
||||
connect(m_name, &QLineEdit::textChanged, this, [this](const QString &) { refresh(); });
|
||||
connect(m_toolCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &TcpCalibrationWidget::selectTool);
|
||||
connect(m_reload, &QPushButton::clicked, this, [this] { reloadTools(); });
|
||||
connect(m_delete, &QPushButton::clicked, this, &TcpCalibrationWidget::deleteTool);
|
||||
}
|
||||
|
||||
void TcpCalibrationWidget::setContext(const QString &endpoint, const QString &deviceId,
|
||||
bool connected, bool demoMode)
|
||||
{
|
||||
const bool identityChanged = endpoint != m_endpoint || deviceId != m_device;
|
||||
const bool sessionChanged = connected != m_connected || demoMode != m_demo;
|
||||
m_endpoint = endpoint;
|
||||
m_device = deviceId;
|
||||
m_connected = connected;
|
||||
m_demo = demoMode;
|
||||
if (identityChanged || sessionChanged) {
|
||||
++m_offsetSerial;
|
||||
m_offsetPending = false;
|
||||
const QSignalBlocker blocker(m_sourceConfirmed);
|
||||
m_sourceConfirmed->setChecked(false);
|
||||
resetCalibration();
|
||||
if (identityChanged) {
|
||||
m_loading = true;
|
||||
for (auto *spin : m_source) spin->setValue(0);
|
||||
m_loading = false;
|
||||
}
|
||||
reloadTools();
|
||||
}
|
||||
refresh();
|
||||
emit referenceChanged();
|
||||
}
|
||||
|
||||
bool TcpCalibrationWidget::referenceConfirmed() const
|
||||
{
|
||||
return m_connected && !m_demo && !m_device.trimmed().isEmpty() && m_sourceConfirmed->isChecked();
|
||||
}
|
||||
|
||||
void TcpCalibrationWidget::invalidateReference()
|
||||
{
|
||||
++m_offsetSerial;
|
||||
m_offsetPending = false;
|
||||
const QSignalBlocker blocker(m_sourceConfirmed);
|
||||
m_sourceConfirmed->setChecked(false);
|
||||
resetCalibration();
|
||||
emit referenceChanged();
|
||||
}
|
||||
|
||||
bool TcpCalibrationWidget::hasSamples() const
|
||||
{
|
||||
for (const auto &sample : m_samples) if (sample.captured) return true;
|
||||
return false;
|
||||
}
|
||||
void TcpCalibrationWidget::invalidateResult()
|
||||
{
|
||||
m_resultValid = false;
|
||||
m_loadedResult = false;
|
||||
m_result = TcpCalibration::Result{};
|
||||
for (auto *label : m_results) label->setText(QStringLiteral("--"));
|
||||
m_rms->setText(QStringLiteral("固定点 RMS:--(合格上限 2.000 mm)"));
|
||||
m_preview->setText(QStringLiteral("基座下工具位姿:--"));
|
||||
}
|
||||
void TcpCalibrationWidget::resetCalibration()
|
||||
{
|
||||
++m_serial;
|
||||
m_pendingRow = -1;
|
||||
if (m_captureTimer) m_captureTimer->stop();
|
||||
for (auto &sample : m_samples) sample = Sample{};
|
||||
invalidateResult();
|
||||
refresh();
|
||||
emit logMessage(QStringLiteral("INFO"), QStringLiteral("TCP 标定临时采样已重置,已保存工具保持不变"));
|
||||
}
|
||||
void TcpCalibrationWidget::resizeSamples(int count)
|
||||
{
|
||||
++m_serial;
|
||||
m_pendingRow = -1;
|
||||
if (m_captureTimer) m_captureTimer->stop();
|
||||
m_samples.assign(size_t(count),Sample{});
|
||||
invalidateResult();
|
||||
m_table->setRowCount(count);
|
||||
m_table->setMinimumHeight(count*36+40);
|
||||
for (int row = 0; row < count; ++row) {
|
||||
for (int col = 0; col < 9; ++col)
|
||||
if (!m_table->item(row, col)) m_table->setItem(row, col, new QTableWidgetItem);
|
||||
if (!m_table->cellWidget(row, 9)) {
|
||||
auto *button = new QPushButton(QStringLiteral("采集"));
|
||||
button->setObjectName(QStringLiteral("tcpCapture%1").arg(row));
|
||||
m_table->setCellWidget(row, 9, button);
|
||||
connect(button, &QPushButton::clicked, this, [this, row] { capture(row); });
|
||||
}
|
||||
}
|
||||
refresh();
|
||||
}
|
||||
TcpCalibration::Pose TcpCalibrationWidget::serverOffset() const
|
||||
{
|
||||
TcpCalibration::Pose pose{};
|
||||
for (int i = 0; i < 6; ++i) pose[size_t(i)] = fromDisplay(m_source.at(i)->value(), i);
|
||||
return pose;
|
||||
}
|
||||
void TcpCalibrationWidget::updateSource()
|
||||
{
|
||||
if (m_loading) return;
|
||||
++m_offsetSerial;
|
||||
m_offsetPending = false;
|
||||
const QSignalBlocker blocker(m_sourceConfirmed);
|
||||
m_sourceConfirmed->setChecked(false);
|
||||
resetCalibration();
|
||||
emit referenceChanged();
|
||||
}
|
||||
void TcpCalibrationWidget::refresh()
|
||||
{
|
||||
if (!m_table) return;
|
||||
if (m_readOffset) {
|
||||
m_readOffset->setEnabled(m_connected && !m_demo && !m_device.isEmpty()
|
||||
&& !m_offsetPending && m_pendingRow < 0);
|
||||
m_readOffset->setText(m_offsetPending ? QStringLiteral("读取中…") : QStringLiteral("从控制器读取"));
|
||||
}
|
||||
int captured = 0;
|
||||
const bool busy = m_pendingRow >= 0;
|
||||
const bool six = m_method->currentIndex()>0;
|
||||
const bool xz = m_method->currentData().toString()=="six_point_xz";
|
||||
m_instructions->setText(six
|
||||
? QStringLiteral("1–3:固定尖端位置并改变姿态;4:方向原点;5:+X;6:+%1。后三点保持相同姿态。").arg(xz?"Z":"Y")
|
||||
: QStringLiteral("保持尖端位置不变,以四个不同姿态采样;工具方向手动设置。"));
|
||||
m_instructions->setToolTip(six ? QStringLiteral("方向点从原点沿所需工具正轴平移,返回原点姿态后采下一轴。程序不会自动移动机器人。最小方向基线 10 mm;建议在安全行程内增加基线。") : QString());
|
||||
const bool ready = m_connected && !m_demo && !m_device.trimmed().isEmpty()
|
||||
&& m_sourceConfirmed->isChecked() && !busy;
|
||||
for (int row = 0; row < int(m_samples.size()); ++row) {
|
||||
const auto &sample = m_samples[size_t(row)];
|
||||
captured += sample.captured;
|
||||
const QString purpose=!six ? QStringLiteral("固定点") : row<3 ? QStringLiteral("接近点")
|
||||
: row==3 ? QStringLiteral("方向原点") : row==4 ? QStringLiteral("+X") : xz?QStringLiteral("+Z"):QStringLiteral("+Y");
|
||||
m_table->item(row, 0)->setText(QStringLiteral("%1 · %2").arg(row+1).arg(purpose));
|
||||
m_table->item(row, 1)->setText(row == m_pendingRow ? QStringLiteral("读取中")
|
||||
: sample.captured ? QStringLiteral("已采集") : QStringLiteral("未采集"));
|
||||
for (int i = 0; i < 6; ++i) m_table->item(row, 2 + i)->setText(sample.captured
|
||||
? QString::number(toDisplay(sample.flange[size_t(i)], i), 'f', 3) : QStringLiteral("--"));
|
||||
m_table->item(row, 8)->setText(m_resultValid && !m_loadedResult
|
||||
&& row < int(m_result.residualsMm.size())
|
||||
? QString::number(m_result.residualsMm[size_t(row)], 'f', 3) : QStringLiteral("--"));
|
||||
auto *button = qobject_cast<QPushButton *>(m_table->cellWidget(row, 9));
|
||||
button->setText(sample.captured ? QStringLiteral("重新采集") : QStringLiteral("采集"));
|
||||
button->setEnabled(ready);
|
||||
}
|
||||
m_method->setEnabled(!busy);
|
||||
for (int i=0;i<m_orientation.size();++i) {
|
||||
m_orientation[i]->setReadOnly(six); m_orientation[i]->setButtonSymbols(six?QAbstractSpinBox::NoButtons:QAbstractSpinBox::UpDownArrows);
|
||||
m_orientationLabels[i]->setText(axis(i+3)+(six?QStringLiteral(" °(计算)"):QStringLiteral(" °(手动)")));
|
||||
m_orientation[i]->setToolTip(six?QStringLiteral("由方向原点、+X 与第二方向点计算,ZYX 欧拉角。"):QStringLiteral("四点法仅求平移;工具方向手动设置,ZYX 欧拉角。"));
|
||||
}
|
||||
m_toolCombo->setEnabled(!busy);
|
||||
m_name->setEnabled(!busy);
|
||||
m_reload->setEnabled(!busy && !m_device.isEmpty());
|
||||
m_delete->setEnabled(!busy && m_toolCombo->currentIndex() > 0);
|
||||
for (auto *spin : m_source) spin->setEnabled(!busy && !m_offsetPending);
|
||||
m_sourceConfirmed->setEnabled(!busy && !m_offsetPending && m_connected && !m_demo);
|
||||
m_calculate->setEnabled(!busy && captured >= 4 && captured == int(m_samples.size()));
|
||||
m_save->setEnabled(!busy && m_resultValid && m_result.rmsMm <= 2.0
|
||||
&& !m_name->text().trimmed().isEmpty());
|
||||
m_status->setText(busy ? QStringLiteral("正在读取真实位姿…") : m_resultValid
|
||||
? (m_result.rmsMm > 2.0 ? QStringLiteral("误差超限,禁止保存,请重新采样")
|
||||
: m_loadedResult ? (six ? QStringLiteral("已加载六点标定结果") : QStringLiteral("已加载标定结果,可修改名称或手动方向"))
|
||||
: QStringLiteral("已计算,尚未保存"))
|
||||
: QStringLiteral("已采集 %1 / %2 点%3").arg(captured).arg(m_samples.size())
|
||||
.arg(!m_sourceConfirmed->isChecked() ? QStringLiteral(" · 请先核对活动 TCP 偏移") : QString()));
|
||||
}
|
||||
|
||||
void TcpCalibrationWidget::capture(int index)
|
||||
{
|
||||
if (index < 0 || index >= int(m_samples.size()) || m_pendingRow >= 0) return;
|
||||
if (!m_connected || m_demo || !m_sourceConfirmed->isChecked() || m_device.isEmpty()) {
|
||||
reportError(QStringLiteral("请连接真实机械臂并核对服务端活动 TCP 偏移"));
|
||||
return;
|
||||
}
|
||||
invalidateResult();
|
||||
// A failed replacement must not silently reuse the previous observation.
|
||||
m_samples[size_t(index)] = Sample{};
|
||||
m_pendingRow = index;
|
||||
++m_serial;
|
||||
m_captureTimer->start();
|
||||
refresh();
|
||||
emit captureRequested(m_device, m_serial);
|
||||
}
|
||||
void TcpCalibrationWidget::acceptControllerOffset(quint64 requestId, const QString &deviceId,
|
||||
const QVariantMap &offset, bool success,
|
||||
const QString &detail)
|
||||
{
|
||||
if (!m_offsetPending || requestId != m_offsetSerial || deviceId != m_device) return;
|
||||
m_offsetPending = false;
|
||||
TcpCalibration::Pose pose{};
|
||||
bool valid = success && readPose(offset, pose);
|
||||
for (int i = 0; valid && i < 6; ++i) {
|
||||
const double value = toDisplay(pose[size_t(i)], i);
|
||||
valid = value >= m_source[i]->minimum() && value <= m_source[i]->maximum();
|
||||
}
|
||||
if (!valid) {
|
||||
refresh();
|
||||
reportError(detail.isEmpty() ? QStringLiteral("控制器 TCP 偏移无效或超出显示范围") : detail);
|
||||
return;
|
||||
}
|
||||
m_loading = true;
|
||||
for (int i = 0; i < 6; ++i) m_source[i]->setValue(toDisplay(pose[size_t(i)], i));
|
||||
m_loading = false;
|
||||
m_sourceConfirmed->setChecked(true);
|
||||
refresh();
|
||||
emit logMessage(QStringLiteral("INFO"), QStringLiteral("已读取机械臂 %1 的活动 TCP 偏移(相对法兰)").arg(deviceId));
|
||||
}
|
||||
|
||||
bool TcpCalibrationWidget::readPose(const QVariantMap &map, TcpCalibration::Pose &pose) const
|
||||
{
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
const QString name = QString::fromLatin1(keys[i]);
|
||||
bool ok = false;
|
||||
pose[size_t(i)] = map.value(name).toDouble(&ok);
|
||||
if (!map.contains(name) || !ok || !std::isfinite(pose[size_t(i)])) return false;
|
||||
}
|
||||
return TcpCalibration::validPose(pose);
|
||||
}
|
||||
void TcpCalibrationWidget::acceptPose(quint64 requestId, const QString &deviceId,
|
||||
const QVariantMap &pose, const QVariantMap &state,
|
||||
bool success, const QString &detail)
|
||||
{
|
||||
if (requestId != m_serial || deviceId != m_device || m_pendingRow < 0) return;
|
||||
const int row = m_pendingRow;
|
||||
m_pendingRow = -1;
|
||||
m_captureTimer->stop();
|
||||
if (!success) { refresh(); reportError(detail); return; }
|
||||
if (!m_connected || m_demo || !m_sourceConfirmed->isChecked()
|
||||
|| !state.value(QStringLiteral("connected")).toBool()
|
||||
|| state.value(QStringLiteral("moving"), true).toBool()
|
||||
|| state.value(QStringLiteral("fault"), true).toBool()) {
|
||||
refresh(); reportError(QStringLiteral("机械臂状态不可用于采点,请停稳并重新核对")); return;
|
||||
}
|
||||
TcpCalibration::Pose tcp{}, flange{};
|
||||
QString error;
|
||||
if (!readPose(pose, tcp) || !TcpCalibration::flangePose(tcp, serverOffset(), flange, &error)) {
|
||||
refresh(); reportError(QStringLiteral("位姿数据无效:%1").arg(error)); return;
|
||||
}
|
||||
for (int i = 0; i < int(m_samples.size()); ++i) {
|
||||
// Direction origin may legitimately repeat one of the position poses.
|
||||
if (m_method->currentIndex()>0 && ((i<3)!=(row<3))) continue;
|
||||
if (i != row && m_samples[size_t(i)].captured
|
||||
&& TcpCalibration::tooSimilar(m_samples[size_t(i)].flange, flange)) {
|
||||
refresh(); reportError(QStringLiteral("与点位 %1 姿态过于接近,请改变腕部姿态后采集").arg(i + 1)); return;
|
||||
}
|
||||
}
|
||||
m_samples[size_t(row)].flange = flange;
|
||||
m_samples[size_t(row)].captured = true;
|
||||
if (m_toolCombo->currentIndex() > 0 && m_toolCombo->currentIndex() <= m_tools.tools.size()) {
|
||||
TcpCalibration::Pose preview{};
|
||||
if (TcpCalibration::toolPose(flange, m_tools.tools.at(m_toolCombo->currentIndex() - 1).offset, preview)) {
|
||||
QStringList values;
|
||||
for (int i = 0; i < 6; ++i) values << QString::number(toDisplay(preview[size_t(i)], i), 'f', 3);
|
||||
m_preview->setText(QStringLiteral("基座下工具位姿(mm / °):%1").arg(values.join(QStringLiteral(", "))));
|
||||
}
|
||||
}
|
||||
refresh();
|
||||
emit logMessage(QStringLiteral("OK"), QStringLiteral("TCP 点位 %1 已采集 · %2 · 法兰位姿 m/rad,活动 TCP 偏移已换算")
|
||||
.arg(row + 1).arg(m_device));
|
||||
}
|
||||
void TcpCalibrationWidget::calculate()
|
||||
{
|
||||
std::vector<TcpCalibration::Pose> poses;
|
||||
for (const auto &sample : m_samples) {
|
||||
if (!sample.captured) { reportError(QStringLiteral("请先完成所有点位采集")); return; }
|
||||
poses.push_back(sample.flange);
|
||||
}
|
||||
invalidateResult();
|
||||
QString error;
|
||||
const bool solved=m_method->currentIndex()==0 ? TcpCalibration::solve(poses,m_result,&error)
|
||||
: TcpCalibration::solveSixPoint(poses,m_method->currentData().toString()=="six_point_xz"
|
||||
? TcpCalibration::DirectionMethod::XZ : TcpCalibration::DirectionMethod::XY,m_result,&error);
|
||||
if (!solved) {
|
||||
refresh(); reportError(error); return;
|
||||
}
|
||||
m_resultValid = true;
|
||||
showResult(m_result.offset, m_result.rmsMm, false);
|
||||
refresh();
|
||||
emit logMessage(m_result.rmsMm <= 2.0 ? QStringLiteral("OK") : QStringLiteral("WARN"),
|
||||
QStringLiteral("TCP 计算完成,%1 点,RMS %2 mm%3").arg(poses.size())
|
||||
.arg(m_result.rmsMm, 0, 'f', 3)
|
||||
.arg(m_result.rmsMm > 2.0 ? QStringLiteral(",超过 2 mm,禁止保存") : QString()));
|
||||
}
|
||||
void TcpCalibrationWidget::showResult(const TcpCalibration::Pose &offset, double rmsMm, bool loaded)
|
||||
{
|
||||
for (int i = 0; i < 3; ++i) m_results.at(i)->setText(QString::number(offset[size_t(i)] * 1000, 'f', 3));
|
||||
if (m_method->currentIndex()>0)
|
||||
for (int i=0;i<3;++i) m_orientation[i]->setValue(qRadiansToDegrees(offset[size_t(i+3)]));
|
||||
m_rms->setText(QStringLiteral("固定点 RMS:%1 mm · %2%3").arg(rmsMm, 0, 'f', 3)
|
||||
.arg(rmsMm <= 2.0 ? QStringLiteral("合格(≤ 2.000 mm)") : QStringLiteral("超限,禁止保存"))
|
||||
.arg(loaded ? QStringLiteral(" · 已保存结果") : QString()));
|
||||
}
|
||||
void TcpCalibrationWidget::reportError(const QString &message)
|
||||
{
|
||||
emit logMessage(QStringLiteral("ERROR"), QStringLiteral("TCP 标定:%1").arg(message));
|
||||
QMessageBox::warning(this, QStringLiteral("工具坐标标定"), message);
|
||||
}
|
||||
void TcpCalibrationWidget::saveTool()
|
||||
{
|
||||
if (!m_resultValid || !std::isfinite(m_result.rmsMm) || m_result.rmsMm > 2.0) {
|
||||
reportError(QStringLiteral("请先得到 RMS 不超过 2 mm 的有效标定结果")); return;
|
||||
}
|
||||
TcpToolStore::Tool tool;
|
||||
tool.name = m_name->text().trimmed();
|
||||
tool.offset = m_result.offset;
|
||||
if (m_method->currentIndex()==0)
|
||||
for (int i = 0; i < 3; ++i) tool.offset[size_t(i + 3)] = qDegreesToRadians(m_orientation.at(i)->value());
|
||||
tool.rmsMm = m_result.rmsMm;
|
||||
tool.sampleCount = m_loadedResult ? m_loadedSampleCount : int(m_samples.size());
|
||||
tool.method = m_loadedResult ? m_loadedMethod : m_method->currentData().toString();
|
||||
bool replace = false;
|
||||
for (const auto &saved : m_tools.tools) if (saved.name == tool.name) replace = true;
|
||||
if (replace && QMessageBox::question(this, QStringLiteral("覆盖工具"),
|
||||
QStringLiteral("当前机械臂的工具“%1”已存在,是否覆盖?").arg(tool.name),
|
||||
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) return;
|
||||
QSettings settings;
|
||||
QString error;
|
||||
// TODO(controller TCP): ArmService currently has only ListTCPFrame;
|
||||
// there is no Get/Set/Create/Delete TCP-offset RPC to call or verify.
|
||||
// Keep local records distinct until actual persistent controller APIs exist.
|
||||
if (!TcpToolStore::save(settings, m_endpoint, m_device, tool, replace, error)) {
|
||||
reportError(error); return;
|
||||
}
|
||||
reloadTools(tool.name);
|
||||
emit toolsChanged(m_endpoint, m_device, tool.name);
|
||||
emit logMessage(QStringLiteral("OK"), QStringLiteral("TCP 本机工具“%1”已保存 · %2 / %3")
|
||||
.arg(tool.name, m_endpoint, m_device));
|
||||
QMessageBox::information(this, QStringLiteral("保存成功"),
|
||||
QStringLiteral("已保存到当前机器人的工具配置,并同步到机械臂的工具坐标列表。选择该工具后可进行 TCP 点动。"));
|
||||
}
|
||||
void TcpCalibrationWidget::reloadTools(const QString &preferred)
|
||||
{
|
||||
if (m_device.trimmed().isEmpty() || m_endpoint.trimmed().isEmpty()) {
|
||||
m_tools = TcpToolStore::Snapshot{};
|
||||
const QSignalBlocker blocker(m_toolCombo);
|
||||
m_toolCombo->clear();
|
||||
m_toolCombo->addItem(QStringLiteral("新建工具"));
|
||||
selectTool(0);
|
||||
m_currentTool->setText(QStringLiteral("请先选择机械臂"));
|
||||
return;
|
||||
}
|
||||
QSettings settings;
|
||||
QString error;
|
||||
TcpToolStore::Snapshot snapshot;
|
||||
if (!TcpToolStore::load(settings, m_endpoint, m_device, snapshot, error)) {
|
||||
emit logMessage(QStringLiteral("ERROR"), error);
|
||||
m_currentTool->setText(error);
|
||||
m_tools = TcpToolStore::Snapshot{};
|
||||
const QSignalBlocker blocker(m_toolCombo);
|
||||
m_toolCombo->clear(); m_toolCombo->addItem(QStringLiteral("配置读取失败"));
|
||||
resetCalibration();
|
||||
return;
|
||||
}
|
||||
m_tools = snapshot;
|
||||
const QString wanted = preferred.isEmpty() ? snapshot.current : preferred;
|
||||
int selected = 0;
|
||||
{
|
||||
const QSignalBlocker blocker(m_toolCombo);
|
||||
m_toolCombo->clear();
|
||||
m_toolCombo->addItem(QStringLiteral("新建工具"));
|
||||
for (const auto &tool : snapshot.tools) {
|
||||
m_toolCombo->addItem(tool.name);
|
||||
if (tool.name == wanted) selected = m_toolCombo->count() - 1;
|
||||
}
|
||||
m_toolCombo->setCurrentIndex(selected);
|
||||
}
|
||||
selectTool(selected);
|
||||
}
|
||||
void TcpCalibrationWidget::selectTool(int index)
|
||||
{
|
||||
resetCalibration();
|
||||
m_loading = true;
|
||||
if (index <= 0 || index > m_tools.tools.size()) {
|
||||
m_name->clear();
|
||||
for (auto *spin : m_orientation) spin->setValue(0);
|
||||
m_currentTool->setText(QStringLiteral("新工具 · 未保存"));
|
||||
} else {
|
||||
const auto &tool = m_tools.tools.at(index - 1);
|
||||
{ const QSignalBlocker blocker(m_method);
|
||||
m_method->setCurrentIndex(qMax(0,m_method->findData(tool.method))); }
|
||||
resizeSamples(m_method->currentIndex()==0 ? 4 : 6);
|
||||
m_name->setText(tool.name);
|
||||
m_result.offset = tool.offset;
|
||||
m_result.rmsMm = tool.rmsMm;
|
||||
m_loadedSampleCount = tool.sampleCount;
|
||||
m_loadedMethod = tool.method;
|
||||
m_resultValid = true;
|
||||
m_loadedResult = true;
|
||||
for (int i = 0; i < 3; ++i) m_orientation.at(i)->setValue(qRadiansToDegrees(tool.offset[size_t(i + 3)]));
|
||||
showResult(tool.offset, tool.rmsMm, true);
|
||||
m_currentTool->setText(QStringLiteral("%1 · %2 点标定").arg(tool.name).arg(tool.sampleCount));
|
||||
emit logMessage(QStringLiteral("INFO"), QStringLiteral("已加载工具标定结果:%1").arg(tool.name));
|
||||
}
|
||||
m_loading = false;
|
||||
refresh();
|
||||
}
|
||||
void TcpCalibrationWidget::deleteTool()
|
||||
{
|
||||
const int index = m_toolCombo->currentIndex() - 1;
|
||||
if (index < 0 || index >= m_tools.tools.size()) return;
|
||||
const QString name = m_tools.tools.at(index).name;
|
||||
if (QMessageBox::question(this, QStringLiteral("删除工具"),
|
||||
QStringLiteral("删除当前机械臂的工具“%1”?对应的工具坐标选项也将移除。").arg(name),
|
||||
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) return;
|
||||
QSettings settings;
|
||||
QString error;
|
||||
if (!TcpToolStore::remove(settings, m_endpoint, m_device, name, error)) { reportError(error); return; }
|
||||
reloadTools();
|
||||
emit toolsChanged(m_endpoint, m_device, QString());
|
||||
emit logMessage(QStringLiteral("INFO"), QStringLiteral("已删除本机 TCP 工具:%1").arg(name));
|
||||
}
|
||||
89
src/tcpcalibrationwidget.h
Normal file
89
src/tcpcalibrationwidget.h
Normal file
@ -0,0 +1,89 @@
|
||||
#pragma once
|
||||
|
||||
#include "tcpcalibration.h"
|
||||
#include "tcptoolstore.h"
|
||||
#include <QVariantMap>
|
||||
#include <QWidget>
|
||||
#include <vector>
|
||||
|
||||
class QCheckBox;
|
||||
class QComboBox;
|
||||
class QDoubleSpinBox;
|
||||
class QLabel;
|
||||
class QLineEdit;
|
||||
class QPushButton;
|
||||
class QTableWidget;
|
||||
class QTimer;
|
||||
|
||||
// Content of the existing tool-calibration navigation slot. No robot motion.
|
||||
class TcpCalibrationWidget : public QWidget
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit TcpCalibrationWidget(QWidget *parent = nullptr);
|
||||
void setContext(const QString &endpoint, const QString &deviceId,
|
||||
bool connected, bool demoMode);
|
||||
bool referenceConfirmed() const;
|
||||
TcpCalibration::Pose activeOffset() const { return serverOffset(); }
|
||||
public slots:
|
||||
void acceptControllerOffset(quint64 requestId, const QString &deviceId,
|
||||
const QVariantMap &offset, bool success, const QString &detail);
|
||||
void invalidateReference();
|
||||
void acceptPose(quint64 requestId, const QString &deviceId,
|
||||
const QVariantMap &pose, const QVariantMap &state,
|
||||
bool success, const QString &detail);
|
||||
signals:
|
||||
void controllerOffsetRequested(const QString &deviceId, quint64 requestId);
|
||||
void captureRequested(const QString &deviceId, quint64 requestId);
|
||||
void logMessage(const QString &level, const QString &message);
|
||||
void referenceChanged();
|
||||
void toolsChanged(const QString &endpoint, const QString &deviceId, const QString &savedName);
|
||||
private:
|
||||
struct Sample {
|
||||
bool captured = false;
|
||||
TcpCalibration::Pose flange{};
|
||||
};
|
||||
void buildUi();
|
||||
void resetCalibration();
|
||||
void invalidateResult();
|
||||
void refresh();
|
||||
void resizeSamples(int count);
|
||||
void capture(int index);
|
||||
void calculate();
|
||||
void saveTool();
|
||||
void reloadTools(const QString &preferred = QString());
|
||||
void selectTool(int index);
|
||||
void deleteTool();
|
||||
void updateSource();
|
||||
bool readPose(const QVariantMap &map, TcpCalibration::Pose &pose) const;
|
||||
TcpCalibration::Pose serverOffset() const;
|
||||
void showResult(const TcpCalibration::Pose &offset, double rmsMm, bool loaded);
|
||||
void reportError(const QString &message);
|
||||
bool hasSamples() const;
|
||||
|
||||
QString m_endpoint, m_device;
|
||||
bool m_connected = false, m_demo = true, m_resultValid = false;
|
||||
bool m_loading = false, m_loadedResult = false;
|
||||
quint64 m_serial = 0;
|
||||
quint64 m_offsetSerial = 0;
|
||||
bool m_offsetPending = false;
|
||||
QPushButton *m_readOffset = nullptr;
|
||||
int m_pendingRow = -1;
|
||||
int m_loadedSampleCount = 0;
|
||||
QString m_loadedMethod;
|
||||
TcpCalibration::Result m_result;
|
||||
std::vector<Sample> m_samples;
|
||||
TcpToolStore::Snapshot m_tools;
|
||||
QLabel *m_status = nullptr, *m_rms = nullptr;
|
||||
QLabel *m_currentTool = nullptr, *m_preview = nullptr, *m_instructions = nullptr;
|
||||
QComboBox *m_toolCombo = nullptr, *m_method = nullptr;
|
||||
QLineEdit *m_name = nullptr;
|
||||
QCheckBox *m_sourceConfirmed = nullptr;
|
||||
QList<QDoubleSpinBox *> m_source, m_orientation;
|
||||
QList<QLabel *> m_results;
|
||||
QList<QLabel *> m_orientationLabels;
|
||||
QTableWidget *m_table = nullptr;
|
||||
QPushButton *m_calculate = nullptr, *m_save = nullptr, *m_delete = nullptr;
|
||||
QPushButton *m_reload = nullptr;
|
||||
QTimer *m_captureTimer = nullptr;
|
||||
};
|
||||
103
src/tcpjogcontroller.cpp
Normal file
103
src/tcpjogcontroller.cpp
Normal file
@ -0,0 +1,103 @@
|
||||
#include "tcpjogcontroller.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
TcpJogController::TcpJogController(QObject *parent) : QObject(parent)
|
||||
{
|
||||
m_timeout.setSingleShot(true);
|
||||
m_holdLimit.setSingleShot(true);
|
||||
connect(&m_timeout, &QTimer::timeout, this, [this] { fail(QStringLiteral("TCP 点动反馈超时,已请求停止")); });
|
||||
connect(&m_holdLimit, &QTimer::timeout, this, &TcpJogController::stop);
|
||||
}
|
||||
QString TcpJogController::commandName(quint64 token)
|
||||
{
|
||||
return QStringLiteral("TCPJog/%1").arg(token);
|
||||
}
|
||||
void TcpJogController::setContext(const QString &endpoint, const QString &device, bool ready,
|
||||
const TcpCalibration::Pose &offset)
|
||||
{
|
||||
if (m_endpoint != endpoint || m_device != device || m_ready != ready || m_activeOffset != offset)
|
||||
stop();
|
||||
m_endpoint = endpoint; m_device = device; m_ready = ready;
|
||||
m_activeOffset = offset;
|
||||
}
|
||||
bool TcpJogController::start(const TcpCalibration::Pose &tool, int axis, int direction,
|
||||
double speed, double acceleration)
|
||||
{
|
||||
if (m_running) return false;
|
||||
if (!m_ready || m_endpoint.isEmpty() || m_device.isEmpty()
|
||||
|| !TcpCalibration::validPose(tool) || !TcpCalibration::validPose(m_activeOffset)
|
||||
|| axis < 0 || axis >= 6 || (direction != -1 && direction != 1)
|
||||
|| !std::isfinite(speed) || speed <= 0 || !std::isfinite(acceleration) || acceleration <= 0) {
|
||||
emit errorOccurred(QStringLiteral("请连接当前机械臂,并在 TCP 标定页核对活动 TCP 偏移后点动"));
|
||||
return false;
|
||||
}
|
||||
m_toolOffset = tool; m_axis = axis; m_direction = direction;
|
||||
// Local TCP uses bounded steps, not a long-running velocity command.
|
||||
m_speed = std::min(speed, axis < 3 ? .02 : .05);
|
||||
m_acceleration = std::min(acceleration, .5);
|
||||
m_running = true;
|
||||
m_holdLimit.start(30000);
|
||||
readNext();
|
||||
return true;
|
||||
}
|
||||
void TcpJogController::readNext()
|
||||
{
|
||||
if (!m_running) return;
|
||||
++m_token; m_waitingMove = false;
|
||||
m_timeout.start(6000);
|
||||
emit captureRequested(m_device, m_token);
|
||||
}
|
||||
void TcpJogController::stop()
|
||||
{
|
||||
const bool wasRunning = m_running;
|
||||
m_running = false; m_waitingMove = false; ++m_token;
|
||||
m_timeout.stop(); m_holdLimit.stop();
|
||||
if (wasRunning) emit stopRequested(m_device);
|
||||
}
|
||||
void TcpJogController::fail(const QString &message)
|
||||
{
|
||||
stop();
|
||||
emit errorOccurred(message);
|
||||
}
|
||||
void TcpJogController::acceptPose(quint64 token, const QString &device, const QVariantMap &pose,
|
||||
const QVariantMap &state, bool success, const QString &detail)
|
||||
{
|
||||
if (!m_running || m_waitingMove || token != m_token || device != m_device) return;
|
||||
if (!success) { fail(detail); return; }
|
||||
if (!state.value("connected").toBool() || state.value("moving",true).toBool()
|
||||
|| state.value("fault",true).toBool()) {
|
||||
fail(QStringLiteral("机械臂未停稳或状态异常,停止 TCP 点动")); return;
|
||||
}
|
||||
const char *keys[]={"x","y","z","rx","ry","rz"};
|
||||
TcpCalibration::Pose actual{}, target{};
|
||||
for(int i=0;i<6;++i) {
|
||||
bool ok=false; actual[size_t(i)]=pose.value(keys[i]).toDouble(&ok);
|
||||
if (!ok || !std::isfinite(actual[size_t(i)])) { fail(QStringLiteral("TCP 点动位姿无效")); return; }
|
||||
}
|
||||
QString error;
|
||||
double limit = m_axis < 3 ? .002 : .005;
|
||||
if (m_axis >= 3) {
|
||||
double radiusSquared = 0;
|
||||
for (int i=0;i<3;++i) radiusSquared += std::pow(m_toolOffset[size_t(i)]-m_activeOffset[size_t(i)],2);
|
||||
// Bound the active TCP's translation too, even for long tools.
|
||||
limit = std::min(limit, .002 / std::max(.001,std::sqrt(radiusSquared)));
|
||||
}
|
||||
const double step = m_direction * std::min(m_speed * .1, limit);
|
||||
if (!TcpCalibration::jogTarget(actual,m_activeOffset,m_toolOffset,m_axis,step,target,&error)) {
|
||||
fail(error); return;
|
||||
}
|
||||
QVariantMap output;
|
||||
for(int i=0;i<6;++i) output.insert(keys[i],target[size_t(i)]);
|
||||
m_waitingMove = true; m_timeout.start(10000);
|
||||
emit moveRequested(m_device,output,m_speed,m_acceleration,m_token);
|
||||
}
|
||||
void TcpJogController::acceptCommand(const QString &command, bool success, const QString &detail)
|
||||
{
|
||||
if (!m_running || !m_waitingMove || command != commandName(m_token)) return;
|
||||
m_timeout.stop();
|
||||
if (!success) { fail(detail); return; }
|
||||
m_waitingMove = false;
|
||||
const auto token=++m_token; // invalidate both duplicate read and completion replies
|
||||
QTimer::singleShot(50,this,[this,token] { if(m_running && token==m_token) readNext(); });
|
||||
}
|
||||
40
src/tcpjogcontroller.h
Normal file
40
src/tcpjogcontroller.h
Normal file
@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
#include "tcpcalibration.h"
|
||||
#include <QObject>
|
||||
#include <QTimer>
|
||||
#include <QVariantMap>
|
||||
|
||||
// Small, cancellable read -> finite MoveL -> read loop. No communication channel.
|
||||
class TcpJogController : public QObject {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit TcpJogController(QObject *parent = nullptr);
|
||||
void setContext(const QString &endpoint, const QString &device, bool ready,
|
||||
const TcpCalibration::Pose &activeOffset);
|
||||
bool start(const TcpCalibration::Pose &toolOffset, int axis, int direction,
|
||||
double speed, double acceleration);
|
||||
bool running() const { return m_running; }
|
||||
static QString commandName(quint64 token);
|
||||
public slots:
|
||||
void stop();
|
||||
void acceptPose(quint64 token, const QString &device, const QVariantMap &pose,
|
||||
const QVariantMap &state, bool success, const QString &detail);
|
||||
void acceptCommand(const QString &command, bool success, const QString &detail);
|
||||
signals:
|
||||
void captureRequested(const QString &device, quint64 token);
|
||||
void moveRequested(const QString &device, const QVariantMap &target,
|
||||
double speed, double acceleration, quint64 token);
|
||||
void stopRequested(const QString &device);
|
||||
void errorOccurred(const QString &message);
|
||||
private:
|
||||
void readNext();
|
||||
void fail(const QString &message);
|
||||
QString m_endpoint, m_device;
|
||||
TcpCalibration::Pose m_activeOffset{}, m_toolOffset{};
|
||||
bool m_ready = false, m_running = false, m_waitingMove = false;
|
||||
// Calibration uses the low token range; no cross-delivery between consumers.
|
||||
quint64 m_token = quint64(1) << 63;
|
||||
int m_axis = 0, m_direction = 1;
|
||||
double m_speed = 0, m_acceleration = 0;
|
||||
QTimer m_timeout, m_holdLimit;
|
||||
};
|
||||
159
src/tcptoolstore.cpp
Normal file
159
src/tcptoolstore.cpp
Normal file
@ -0,0 +1,159 @@
|
||||
#include "tcptoolstore.h"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QSettings>
|
||||
#include <QVariantMap>
|
||||
#include <cmath>
|
||||
|
||||
namespace TcpToolStore {
|
||||
namespace {
|
||||
QString key(const QString &endpoint, const QString &device)
|
||||
{
|
||||
QByteArray identity = endpoint.trimmed().toUtf8();
|
||||
identity.append('\0');
|
||||
identity.append(device.trimmed().toUtf8());
|
||||
return QStringLiteral("tcpCalibration/v1/") + QString::fromLatin1(
|
||||
QCryptographicHash::hash(identity, QCryptographicHash::Sha256).toHex());
|
||||
}
|
||||
bool valid(const Tool &tool)
|
||||
{
|
||||
return !tool.name.trimmed().isEmpty() && tool.name == tool.name.trimmed()
|
||||
&& tool.name.size() <= 80 && !tool.name.contains(QChar::Null)
|
||||
&& TcpCalibration::validPose(tool.offset) && std::isfinite(tool.rmsMm)
|
||||
&& tool.rmsMm >= 0.0 && tool.rmsMm <= 2.0
|
||||
&& tool.sampleCount >= 4 && tool.sampleCount <= 30
|
||||
&& (tool.method == "fixed_point" || (tool.method == "four_point" && tool.sampleCount == 4)
|
||||
|| ((tool.method == "six_point_xz" || tool.method == "six_point_xy") && tool.sampleCount == 6));
|
||||
}
|
||||
bool write(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
const Snapshot &snapshot, QString &error)
|
||||
{
|
||||
QVariantList records;
|
||||
for (const Tool &tool : snapshot.tools) {
|
||||
QVariantList pose;
|
||||
for (double value : tool.offset) pose.append(value);
|
||||
records.append(QVariantMap{{QStringLiteral("name"), tool.name},
|
||||
{QStringLiteral("offsetSI"), pose}, {QStringLiteral("rmsMm"), tool.rmsMm},
|
||||
{QStringLiteral("samples"), tool.sampleCount}, {QStringLiteral("method"),tool.method}});
|
||||
}
|
||||
settings.setValue(key(endpoint, device), QVariantMap{
|
||||
{QStringLiteral("endpoint"), endpoint.trimmed()},
|
||||
{QStringLiteral("device"), device.trimmed()},
|
||||
{QStringLiteral("current"), snapshot.current},
|
||||
{QStringLiteral("tools"), records}});
|
||||
settings.sync();
|
||||
if (settings.status() != QSettings::NoError) {
|
||||
error = QStringLiteral("本机设置写入失败,请检查配置位置权限:%1").arg(settings.fileName());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
bool load(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
Snapshot &snapshot, QString &error)
|
||||
{
|
||||
snapshot = Snapshot{};
|
||||
error.clear();
|
||||
if (endpoint.trimmed().isEmpty() || device.trimmed().isEmpty()) {
|
||||
error = QStringLiteral("服务器地址和机械臂设备 ID 不能为空");
|
||||
return false;
|
||||
}
|
||||
settings.sync();
|
||||
if (settings.status() != QSettings::NoError) {
|
||||
error = QStringLiteral("无法读取本机设置:%1").arg(settings.fileName());
|
||||
return false;
|
||||
}
|
||||
if (!settings.contains(key(endpoint, device))) return true;
|
||||
const QVariantMap value = settings.value(key(endpoint, device)).toMap();
|
||||
if (value.value(QStringLiteral("endpoint")).toString() != endpoint.trimmed()
|
||||
|| value.value(QStringLiteral("device")).toString() != device.trimmed()
|
||||
|| value.value(QStringLiteral("tools")).type() != QVariant::List) {
|
||||
error = QStringLiteral("本机 TCP 配置格式无效,未覆盖原配置");
|
||||
return false;
|
||||
}
|
||||
for (const QVariant &record : value.value(QStringLiteral("tools")).toList()) {
|
||||
const QVariantMap map = record.toMap();
|
||||
const QVariantList pose = map.value(QStringLiteral("offsetSI")).toList();
|
||||
Tool tool;
|
||||
tool.name = map.value(QStringLiteral("name")).toString();
|
||||
tool.method = map.value(QStringLiteral("method"),QStringLiteral("fixed_point")).toString();
|
||||
bool rmsOk = false, countOk = false, poseOk = pose.size() == 6;
|
||||
tool.rmsMm = map.value(QStringLiteral("rmsMm")).toDouble(&rmsOk);
|
||||
tool.sampleCount = map.value(QStringLiteral("samples")).toInt(&countOk);
|
||||
for (int i = 0; poseOk && i < 6; ++i) {
|
||||
bool ok = false;
|
||||
tool.offset[size_t(i)] = pose.at(i).toDouble(&ok);
|
||||
poseOk = poseOk && ok;
|
||||
}
|
||||
bool duplicate = false;
|
||||
for (const Tool &existing : snapshot.tools) duplicate |= existing.name == tool.name;
|
||||
if (!rmsOk || !countOk || !poseOk || !valid(tool) || duplicate) {
|
||||
snapshot = Snapshot{};
|
||||
error = QStringLiteral("本机 TCP 记录无效或重名,未覆盖原配置");
|
||||
return false;
|
||||
}
|
||||
snapshot.tools.append(tool);
|
||||
}
|
||||
snapshot.current = value.value(QStringLiteral("current")).toString();
|
||||
if (!snapshot.current.isEmpty()) {
|
||||
bool found = false;
|
||||
for (const Tool &tool : snapshot.tools) found |= tool.name == snapshot.current;
|
||||
if (!found) {
|
||||
error = QStringLiteral("当前本机工具引用不存在");
|
||||
snapshot = Snapshot{};
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool save(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
const Tool &tool, bool replace, QString &error)
|
||||
{
|
||||
if (!valid(tool)) {
|
||||
error = QStringLiteral("工具名称、TCP 数值、采点数量或 RMS 不合法");
|
||||
return false;
|
||||
}
|
||||
Snapshot snapshot;
|
||||
if (!load(settings, endpoint, device, snapshot, error)) return false;
|
||||
int index = -1;
|
||||
for (int i = 0; i < snapshot.tools.size(); ++i)
|
||||
if (snapshot.tools.at(i).name == tool.name) index = i;
|
||||
if (index >= 0 && !replace) {
|
||||
error = QStringLiteral("本机工具名称已存在,请确认覆盖或更换名称");
|
||||
return false;
|
||||
}
|
||||
if (index >= 0) snapshot.tools[index] = tool;
|
||||
else snapshot.tools.append(tool);
|
||||
snapshot.current = tool.name;
|
||||
return write(settings, endpoint, device, snapshot, error);
|
||||
}
|
||||
bool select(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
const QString &name, QString &error)
|
||||
{
|
||||
Snapshot snapshot;
|
||||
if (!load(settings, endpoint, device, snapshot, error)) return false;
|
||||
if (name.isEmpty()) {
|
||||
snapshot.current.clear();
|
||||
return write(settings,endpoint,device,snapshot,error);
|
||||
}
|
||||
for (const Tool &tool : snapshot.tools) if (tool.name == name) {
|
||||
snapshot.current = name;
|
||||
return write(settings, endpoint, device, snapshot, error);
|
||||
}
|
||||
error = QStringLiteral("本机工具不存在");
|
||||
return false;
|
||||
}
|
||||
bool remove(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
const QString &name, QString &error)
|
||||
{
|
||||
Snapshot snapshot;
|
||||
if (!load(settings, endpoint, device, snapshot, error)) return false;
|
||||
for (int i = 0; i < snapshot.tools.size(); ++i) if (snapshot.tools.at(i).name == name) {
|
||||
snapshot.tools.removeAt(i);
|
||||
if (snapshot.current == name) snapshot.current.clear();
|
||||
return write(settings, endpoint, device, snapshot, error);
|
||||
}
|
||||
error = QStringLiteral("本机工具不存在");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
30
src/tcptoolstore.h
Normal file
30
src/tcptoolstore.h
Normal file
@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include "tcpcalibration.h"
|
||||
#include <QList>
|
||||
#include <QString>
|
||||
|
||||
class QSettings;
|
||||
|
||||
// Local calibration records only. These are not controller frame identifiers.
|
||||
namespace TcpToolStore {
|
||||
struct Tool {
|
||||
QString name;
|
||||
TcpCalibration::Pose offset{}; // m, ZYX radians
|
||||
double rmsMm = 0.0;
|
||||
int sampleCount = 0;
|
||||
QString method = QStringLiteral("fixed_point"); // Legacy records have manual orientation.
|
||||
};
|
||||
struct Snapshot {
|
||||
QList<Tool> tools;
|
||||
QString current;
|
||||
};
|
||||
bool load(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
Snapshot &snapshot, QString &error);
|
||||
bool save(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
const Tool &tool, bool replace, QString &error);
|
||||
bool select(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
const QString &name, QString &error);
|
||||
bool remove(QSettings &settings, const QString &endpoint, const QString &device,
|
||||
const QString &name, QString &error);
|
||||
}
|
||||
704
src/touchoperationwidget.cpp
Normal file
704
src/touchoperationwidget.cpp
Normal file
@ -0,0 +1,704 @@
|
||||
#include "touchoperationwidget.h"
|
||||
#include "touchvideowidget.h"
|
||||
#include "calibrationfile.h"
|
||||
#include <QFileDialog>
|
||||
#include <QShowEvent>
|
||||
#include <QCheckBox>
|
||||
#include <QComboBox>
|
||||
#include <QCryptographicHash>
|
||||
#include <QDateTime>
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QFrame>
|
||||
#include <QGridLayout>
|
||||
#include <QHeaderView>
|
||||
#include <QHideEvent>
|
||||
#include <QJsonDocument>
|
||||
#include <QSaveFile>
|
||||
#include <QLabel>
|
||||
#include <QMessageBox>
|
||||
#include <QPushButton>
|
||||
#include <QScrollArea>
|
||||
#include <QSettings>
|
||||
#include <QSignalBlocker>
|
||||
#include <QSpinBox>
|
||||
#include <QTableWidget>
|
||||
#include <QVBoxLayout>
|
||||
#include <cmath>
|
||||
|
||||
namespace {
|
||||
using Pose=TcpCalibration::Pose;
|
||||
constexpr quint64 kPosePrefix=quint64(1)<<58;
|
||||
constexpr quint64 kImagePrefix=quint64(1)<<57;
|
||||
QVariantList values(const Pose &pose) { QVariantList result; for(double v:pose) result<<v; return result; }
|
||||
bool poseFrom(const QVariant &value,Pose &pose) {
|
||||
auto list=value.toList(); if(list.size()!=6) return false;
|
||||
for(int i=0;i<6;++i) { bool ok=false; pose[i]=list[i].toDouble(&ok); if(!ok) return false; }
|
||||
return TcpCalibration::validPose(pose);
|
||||
}
|
||||
bool decodePose(const QVariantMap &map,Pose &pose) {
|
||||
QVariantList list; for(const auto &key:QStringList{"x","y","z","rx","ry","rz"}) list<<map.value(key);
|
||||
return poseFrom(list,pose);
|
||||
}
|
||||
bool nearPose(const Pose &a,const Pose &b) {
|
||||
TcpCalibration::Matrix x{},y{};
|
||||
if(!TcpCalibration::poseMatrix(a,x)||!TcpCalibration::poseMatrix(b,y)) return false;
|
||||
double distance=0,trace=0;
|
||||
for(int i=0;i<3;++i) { distance+=std::pow(a[i]-b[i],2); for(int j=0;j<3;++j) trace+=x[i*4+j]*y[i*4+j]; }
|
||||
return distance<=.0005*.0005 && std::acos(qBound(-1.0,(trace-1)/2,1.0))<=.2*3.141592653589793/180;
|
||||
}
|
||||
QString poseText(const Pose &pose) {
|
||||
QStringList result; for(int i=0;i<6;++i) result<<QString::number(pose[i]*(i<3?1000:180/3.141592653589793),'f',2);
|
||||
return result.join(" / ");
|
||||
}
|
||||
QVBoxLayout *panel(QBoxLayout *parent,const QString &title) {
|
||||
auto *frame=new QFrame; frame->setObjectName("panel"); parent->addWidget(frame);
|
||||
auto *layout=new QVBoxLayout(frame); layout->setContentsMargins(12,12,12,12); layout->setSpacing(8);
|
||||
auto *label=new QLabel(title); label->setObjectName("sectionTitle"); layout->addWidget(label); return layout;
|
||||
}
|
||||
}
|
||||
|
||||
TouchOperationWidget::TouchOperationWidget(QWidget *parent):QWidget(parent),
|
||||
m_sequence(new TouchSequenceController(this)),m_video(new TouchVideoWidget(this))
|
||||
{
|
||||
setObjectName("touchOperationPage");
|
||||
m_video->setMaxPoints(2);
|
||||
auto *outer=new QVBoxLayout(this); outer->setContentsMargins(12,10,12,10); outer->setSpacing(8);
|
||||
auto *scroll=new QScrollArea; scroll->setWidgetResizable(true); scroll->setFrameShape(QFrame::NoFrame);
|
||||
auto *content=new QWidget; scroll->setWidget(content); outer->addWidget(scroll);
|
||||
auto *root=new QVBoxLayout(content); root->setContentsMargins(0,0,0,0); root->setSpacing(10);
|
||||
auto *top=new QHBoxLayout; top->setSpacing(10); root->addLayout(top);
|
||||
auto *vision=panel(top,QStringLiteral("视觉取点"));
|
||||
m_video->setMinimumWidth(320); m_video->setMaximumWidth(QWIDGETSIZE_MAX); m_video->setFrameAspectLayoutEnabled(true);
|
||||
vision->setAlignment(Qt::AlignTop);
|
||||
vision->addWidget(m_video);
|
||||
auto *videoActions=new QHBoxLayout;
|
||||
m_previewButton=new QPushButton(QStringLiteral("开始视频")); m_stopPreviewButton=new QPushButton(QStringLiteral("停止视频"));
|
||||
m_lockButton=new QPushButton(QStringLiteral("锁定观察画面")); m_liveButton=new QPushButton(QStringLiteral("恢复实时"));
|
||||
for(auto *b:{m_previewButton,m_stopPreviewButton,m_lockButton,m_liveButton}) videoActions->addWidget(b);
|
||||
vision->addLayout(videoActions);
|
||||
m_pickingStatus=new QLabel; m_pickingStatus->setObjectName("touchPickingStatus");
|
||||
m_pickingStatus->setProperty("class",QStringLiteral("mutedLabel"));
|
||||
m_pickingStatus->setWordWrap(true); vision->addWidget(m_pickingStatus);
|
||||
connect(m_video,&TouchVideoWidget::selectionBlocked,this,[this] {
|
||||
const QString blocker=pickingBlocker();
|
||||
m_pickingStatus->setText(blocker.isEmpty()
|
||||
? QStringLiteral("请先点击“锁定观察画面”,再选择 A / B 目标点。") : blocker);
|
||||
m_status->setText(m_pickingStatus->text());
|
||||
if(!m_cameraConfirmed->isChecked() && ready() && handEye() && observationValid())
|
||||
m_cameraConfirmed->setFocus(Qt::OtherFocusReason);
|
||||
});
|
||||
auto *config=panel(top,QStringLiteral("任务配置")); top->setStretch(0,7); top->setStretch(1,3);
|
||||
auto *grid=new QGridLayout; config->addLayout(grid);
|
||||
m_handEyeChoice=new QComboBox; m_handEyeChoice->setObjectName("touchHandEye");
|
||||
m_toolChoice=new QComboBox; m_toolChoice->setObjectName("touchTcp");
|
||||
for(auto *c:{m_handEyeChoice,m_toolChoice}) { c->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Fixed); c->setMinimumWidth(130); }
|
||||
m_cameraName=new QLabel; m_cameraName->setWordWrap(true);
|
||||
grid->setColumnStretch(1,1);
|
||||
m_handSource=new QComboBox; m_toolSource=new QComboBox;
|
||||
for(auto *source:{m_handSource,m_toolSource}) source->addItems({QStringLiteral("已有标定"),QStringLiteral("本地文件")});
|
||||
m_handFileButton=new QPushButton(QStringLiteral("导入文件")); m_toolFileButton=new QPushButton(QStringLiteral("导入文件"));
|
||||
m_handFileLabel=new QLabel(QStringLiteral("未导入")); m_toolFileLabel=new QLabel(QStringLiteral("未导入"));
|
||||
for(auto *label:{m_handFileLabel,m_toolFileLabel}) label->setWordWrap(true);
|
||||
grid->addWidget(new QLabel(QStringLiteral("手眼标定")),0,0); grid->addWidget(m_handSource,0,1); grid->addWidget(m_handFileButton,0,2);
|
||||
grid->addWidget(m_handEyeChoice,1,0,1,3); grid->addWidget(m_handFileLabel,2,0,1,3);
|
||||
grid->addWidget(new QLabel(QStringLiteral("工具 TCP")),3,0); grid->addWidget(m_toolSource,3,1); grid->addWidget(m_toolFileButton,3,2);
|
||||
grid->addWidget(m_toolChoice,4,0,1,3); grid->addWidget(m_toolFileLabel,5,0,1,3);
|
||||
m_cameraChoice=new QComboBox; grid->addWidget(new QLabel(QStringLiteral("相机")),6,0); grid->addWidget(m_cameraChoice,6,1); m_cameraName->hide();
|
||||
m_reloadButton=new QPushButton(QStringLiteral("刷新标定")); grid->addWidget(m_reloadButton,6,2);
|
||||
connect(m_cameraChoice,QOverload<int>::of(&QComboBox::currentIndexChanged),this,[this]{ if(m_loading) return; stopPreview(); m_cameraConfirmed->setChecked(false); autoPreview(); });
|
||||
connect(m_handFileButton,&QPushButton::clicked,this,[this]{ importCalibration(true); });
|
||||
connect(m_toolFileButton,&QPushButton::clicked,this,[this]{ importCalibration(false); });
|
||||
for(auto *source:{m_handSource,m_toolSource}) connect(source,QOverload<int>::of(&QComboBox::currentIndexChanged),this,[this]{ stopPreview(); m_observed=false; m_cameraConfirmed->setChecked(false); refresh(); autoPreview(); });
|
||||
m_cameraConfirmed=new QCheckBox(QStringLiteral("已核对相机、标定归属与内参"));
|
||||
m_cameraMode=new QLabel; m_cameraMode->setObjectName("touchCameraMode"); m_cameraMode->setWordWrap(true); config->addWidget(m_cameraMode);
|
||||
m_planeStatus=new QLabel; m_planeStatus->setWordWrap(true); config->addWidget(m_planeStatus);
|
||||
auto *planeRow=new QHBoxLayout; config->addLayout(planeRow);
|
||||
m_planeImport=new QPushButton(QStringLiteral("导入平面参数")); m_planeTemplate=new QPushButton(QStringLiteral("导出平面模板"));
|
||||
planeRow->addWidget(m_planeImport); planeRow->addWidget(m_planeTemplate);
|
||||
connect(m_planeImport,&QPushButton::clicked,this,&TouchOperationWidget::importPlane);
|
||||
connect(m_planeTemplate,&QPushButton::clicked,this,&TouchOperationWidget::exportPlaneTemplate);
|
||||
auto *forceStatus=new QLabel(QStringLiteral("力传感器:未接入")); forceStatus->setObjectName("touchForceStatus"); config->addWidget(forceStatus);
|
||||
m_cameraConfirmed->setToolTip(QStringLiteral("使用该相机 RGB 光学坐标系及标准 Brown 畸变模型;服务与上位机时钟同步,目标保持静止;深度单位及配准由服务提供。")); config->addWidget(m_cameraConfirmed);
|
||||
m_teachObservation=new QPushButton(QStringLiteral("录入当前观察位")); m_teachObservation->setObjectName("touchTeachObservation");
|
||||
m_returnButton=new QPushButton(QStringLiteral("回观察位"));
|
||||
auto *teachRow=new QHBoxLayout; teachRow->addWidget(m_teachObservation,1); teachRow->addWidget(m_returnButton); config->addLayout(teachRow);
|
||||
m_observationText=new QLabel; m_observationText->setWordWrap(true); m_observationText->setObjectName("mutedLabel"); config->addWidget(m_observationText);
|
||||
config->addSpacing(8);
|
||||
auto *actionTitle=new QLabel(QStringLiteral("动作参数")); actionTitle->setObjectName("sectionTitle"); config->addWidget(actionTitle);
|
||||
auto *params=new QGridLayout; params->setHorizontalSpacing(8); params->setVerticalSpacing(8);
|
||||
params->setColumnStretch(0,1); params->setColumnStretch(1,1); config->addLayout(params);
|
||||
m_action=new QComboBox; m_action->setObjectName("touchAction"); m_action->addItems({QStringLiteral("单击"),QStringLiteral("双击"),QStringLiteral("滑动")});
|
||||
params->addWidget(new QLabel(QStringLiteral("动作")),0,0); params->addWidget(m_action,0,1);
|
||||
auto addSpin=[params](const QString &label,int row,int col,double value,double min,double max,const QString &suffix) {
|
||||
auto *spin=new QDoubleSpinBox; spin->setRange(min,max); spin->setDecimals(2); spin->setValue(value); spin->setSuffix(suffix); spin->setKeyboardTracking(false);
|
||||
params->addWidget(new QLabel(label),row*2-1,col/2); params->addWidget(spin,row*2,col/2); return spin;
|
||||
};
|
||||
m_approach=addSpin(QStringLiteral("接近高度"),1,0,10,1,50," mm");
|
||||
m_press=addSpin(QStringLiteral("接触偏移"),1,2,0,0,2," mm");
|
||||
m_lift=addSpin(QStringLiteral("双击抬笔"),4,0,1,1,20," mm");
|
||||
m_speed=addSpin(QStringLiteral("移动速度"),2,0,30,5,50," mm/s");
|
||||
m_contactSpeed=addSpin(QStringLiteral("接触速度"),2,2,10,5,30," mm/s");
|
||||
m_travel=addSpin(QStringLiteral("运动范围"),3,0,300,10,1000," mm");
|
||||
m_dwell=new QSpinBox; m_dwell->setRange(0,2000); m_dwell->setValue(50); m_dwell->setSuffix(" ms");
|
||||
params->addWidget(new QLabel(QStringLiteral("接触停留")),5,1); params->addWidget(m_dwell,6,1);
|
||||
m_gap=new QSpinBox; m_gap->setRange(20,500); m_gap->setValue(50); m_gap->setSuffix(" ms");
|
||||
params->addWidget(new QLabel(QStringLiteral("双击间隔")),7,1); params->addWidget(m_gap,8,1);
|
||||
config->addStretch();
|
||||
m_press->setToolTip(QStringLiteral("沿相机 +Z 方向的几何位移,不是力控。首次验证建议为 0。"));
|
||||
m_travel->setToolTip(QStringLiteral("相对观察位的最大位移与每段最大行程;不代替碰撞检查。"));
|
||||
m_gap->setToolTip(QStringLiteral("抬笔到位后的停留;实际两次触点间隔还包含机械臂运动时间。"));
|
||||
auto *bottom=new QHBoxLayout; root->addLayout(bottom);
|
||||
auto *targetPanel=panel(bottom,QStringLiteral("目标点坐标换算结果"));
|
||||
m_conversionStatus=new QLabel; m_conversionStatus->setObjectName("touchConversionStatus"); m_conversionStatus->setWordWrap(true);
|
||||
m_conversionStatus->setToolTip(QStringLiteral("显示深度测量目标点,尚未叠加接触偏移;控制器 TCP 的实际运动目标见执行路径。"));
|
||||
targetPanel->addWidget(m_conversionStatus);
|
||||
m_targets=new QTableWidget(0,4); m_targets->setObjectName("touchTargets");
|
||||
m_targets->setHorizontalHeaderLabels({QStringLiteral("点"),QStringLiteral("像素 · px"),QStringLiteral("相机 XYZ · mm"),QStringLiteral("基座 XYZ · mm")}); targetPanel->addWidget(m_targets);
|
||||
auto *pathPanel=panel(bottom,QStringLiteral("执行路径"));
|
||||
m_steps=new QTableWidget(0,3); m_steps->setObjectName("touchSteps"); m_steps->setHorizontalHeaderLabels({QStringLiteral("步骤"),QStringLiteral("控制器 TCP · XYZ mm / RxRyRz °"),QStringLiteral("速度 mm/s")}); pathPanel->addWidget(m_steps);
|
||||
for(auto *table:{m_targets,m_steps}) { table->verticalHeader()->hide(); table->setEditTriggers(QAbstractItemView::NoEditTriggers); table->setMinimumHeight(150); table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); table->horizontalHeader()->setStretchLastSection(true); }
|
||||
m_targets->setMinimumHeight(188); m_targets->setMaximumHeight(230); m_targets->setWordWrap(false);
|
||||
m_steps->setMinimumHeight(188); m_steps->setMaximumHeight(260);
|
||||
for(auto *table:{m_targets,m_steps}) { table->setAlternatingRowColors(true); table->setShowGrid(false); }
|
||||
m_targets->horizontalHeader()->setSectionResizeMode(2,QHeaderView::Stretch);
|
||||
m_targets->horizontalHeader()->setSectionResizeMode(3,QHeaderView::Stretch);
|
||||
bottom->setStretch(0,1); bottom->setStretch(1,1);
|
||||
root->addStretch(1);
|
||||
auto *footer=new QHBoxLayout; outer->addLayout(footer);
|
||||
m_status=new QLabel; m_status->setWordWrap(true); m_status->setObjectName("mutedLabel"); outer->insertWidget(1,m_status);
|
||||
m_pathConfirmed=new QCheckBox(QStringLiteral("已核对目标、笔姿及路径净空")); footer->addWidget(m_pathConfirmed);
|
||||
footer->addStretch(1);
|
||||
m_calculateButton=new QPushButton(QStringLiteral("转换 / 预览")); m_executeButton=new QPushButton(QStringLiteral("执行动作")); m_executeButton->setObjectName("primaryButton");
|
||||
auto *stopButton=new QPushButton(QStringLiteral("停止")); stopButton->setObjectName("dangerOutlineButton");
|
||||
footer->addWidget(m_calculateButton); footer->addWidget(m_executeButton); footer->addWidget(stopButton);
|
||||
m_timeout.setSingleShot(true); m_timeout.setInterval(12000);
|
||||
connect(&m_timeout,&QTimer::timeout,this,[this] { fail(QStringLiteral("读取超时,请检查连接后重试。")); });
|
||||
connect(m_previewButton,&QPushButton::clicked,this,&TouchOperationWidget::startPreview);
|
||||
connect(m_stopPreviewButton,&QPushButton::clicked,this,&TouchOperationWidget::stopPreview);
|
||||
connect(m_lockButton,&QPushButton::clicked,this,&TouchOperationWidget::lockFrame);
|
||||
connect(m_liveButton,&QPushButton::clicked,this,[this] { invalidateFrame(); refresh(); });
|
||||
connect(m_teachObservation,&QPushButton::clicked,this,[this] { teach(Phase::Observation); });
|
||||
connect(m_returnButton,&QPushButton::clicked,this,[this] { teach(Phase::Return); });
|
||||
connect(m_calculateButton,&QPushButton::clicked,this,&TouchOperationWidget::calculate);
|
||||
connect(m_executeButton,&QPushButton::clicked,this,&TouchOperationWidget::execute);
|
||||
connect(stopButton,&QPushButton::clicked,this,[this] {
|
||||
const bool active=running(); stop();
|
||||
if(!active&&!m_device.isEmpty()) emit stopRequested(m_device);
|
||||
});
|
||||
connect(m_reloadButton,&QPushButton::clicked,this,&TouchOperationWidget::reloadCalibrations);
|
||||
connect(m_video,&TouchVideoWidget::pointsChanged,this,[this] { invalidatePlan(); refresh(); });
|
||||
connect(m_cameraConfirmed,&QCheckBox::toggled,this,[this] { invalidateFrame(); refresh(); });
|
||||
connect(m_pathConfirmed,&QCheckBox::toggled,this,[this] { refresh(); });
|
||||
connect(m_handEyeChoice,QOverload<int>::of(&QComboBox::currentIndexChanged),this,[this] { if(m_loading) return; stopPreview(); invalidateFrame(); m_cameraConfirmed->setChecked(false); saveTeaching(); refresh(); autoPreview(); });
|
||||
connect(m_toolChoice,QOverload<int>::of(&QComboBox::currentIndexChanged),this,[this] { if(m_loading) return; stop(); m_observed=false; saveTeaching(); refresh(); });
|
||||
connect(m_action,QOverload<int>::of(&QComboBox::currentIndexChanged),this,[this] { invalidatePlan(); refresh(); });
|
||||
for(auto *spin:{m_approach,m_press,m_lift,m_speed,m_contactSpeed,m_travel}) connect(spin,QOverload<double>::of(&QDoubleSpinBox::valueChanged),this,[this] { invalidatePlan(); refresh(); });
|
||||
for(auto *spin:{m_dwell,m_gap}) connect(spin,QOverload<int>::of(&QSpinBox::valueChanged),this,[this] { invalidatePlan(); refresh(); });
|
||||
connect(m_sequence,&TouchSequenceController::captureRequested,this,&TouchOperationWidget::captureRequested);
|
||||
connect(m_sequence,&TouchSequenceController::moveRequested,this,&TouchOperationWidget::moveRequested);
|
||||
connect(m_sequence,&TouchSequenceController::stopRequested,this,&TouchOperationWidget::stopRequested);
|
||||
connect(m_sequence,&TouchSequenceController::progressChanged,this,[this](int step,int count,const QString &label) { m_status->setText(QStringLiteral("执行 %1 / %2 · %3").arg(step).arg(count).arg(label)); refresh(); });
|
||||
connect(m_sequence,&TouchSequenceController::errorOccurred,this,[this](const QString &error) { emit logMessage("ERROR",error); });
|
||||
connect(m_sequence,&TouchSequenceController::finished,this,[this](bool success,const QString &detail) { invalidateFrame(); refresh(); m_status->setText(detail); emit logMessage(success?"OK":"WARN",QStringLiteral("末端操作:%1").arg(detail)); });
|
||||
refresh();
|
||||
}
|
||||
|
||||
bool TouchOperationWidget::running() const { return m_sequence->running(); }
|
||||
bool TouchOperationWidget::observationValid() const {
|
||||
Pose selected{};
|
||||
return m_observed && selectedTool(selected) && selected==m_observationTool && m_activeOffset==m_teachingOffset;
|
||||
}
|
||||
bool TouchOperationWidget::ready() const { return m_connected&&!m_demo&&m_reference&&!m_device.isEmpty()&&TcpCalibration::validPose(m_activeOffset); }
|
||||
QString TouchOperationWidget::pickingBlocker() const {
|
||||
if(m_capabilitiesReceived && CameraCapabilities::mode(m_cameraCapabilities)==CameraCapabilities::Mode::Preview)
|
||||
return QStringLiteral("相机仅可预览:请检查驱动、内参和采集时间戳");
|
||||
if(CameraCapabilities::mode(m_cameraCapabilities)==CameraCapabilities::Mode::Plane && !validPlaneBinding())
|
||||
return QStringLiteral("取点准备:请导入与当前相机及手眼结果匹配的平面参数");
|
||||
Pose tool{};
|
||||
if(!m_connected||m_demo) return QStringLiteral("取点准备:请连接真实机器人服务");
|
||||
if(!m_reference||!TcpCalibration::validPose(m_activeOffset)||m_device.isEmpty())
|
||||
return QStringLiteral("取点准备:请在 TCP 标定页读取或确认控制器 TCP 偏移");
|
||||
if(!selectedTool(tool)) return QStringLiteral("取点准备:请选择或导入触控笔 TCP 标定");
|
||||
if(!handEye()) return QStringLiteral("取点准备:请选择或导入手眼标定");
|
||||
if(!observationValid()) return QStringLiteral("取点准备:请录入当前 TCP 的观察位");
|
||||
if(!m_preview) return QStringLiteral("取点准备:请启动相机视频");
|
||||
if(!m_cameraConfirmed->isChecked())
|
||||
return QStringLiteral("取点准备:请确认当前相机、标定归属与内参");
|
||||
if(running()||m_phase!=Phase::Idle) return QStringLiteral("正在读取数据或执行动作,请等待完成");
|
||||
return {};
|
||||
}
|
||||
const HandEyeStore::Record *TouchOperationWidget::handEye() const {
|
||||
const HandEyeStore::Record *r=nullptr;
|
||||
if(m_handSource->currentIndex()==1) r=m_hasFileHand?&m_fileHand:nullptr;
|
||||
else { const int i=m_handEyeChoice->currentData().toInt(); if(m_handEyeChoice->currentIndex()>=0&&i>=0&&i<m_handEyes.records.size()) r=&m_handEyes.records[i]; }
|
||||
if(r && CameraCapabilities::known(m_cameraCapabilities) && !r->cameraSerial.isEmpty()
|
||||
&& r->cameraSerial!=m_cameraCapabilities.value("serial").toString()) return nullptr;
|
||||
return r;
|
||||
}
|
||||
QString TouchOperationWidget::cameraId() const { if(m_capabilitiesReceived) return m_cameraChoice->currentText(); auto *r=handEye(); return r?r->cameraId:m_cameraChoice->currentText(); }
|
||||
bool TouchOperationWidget::selectedTool(Pose &offset) const {
|
||||
if(m_toolSource->currentIndex()==1) { if(!m_hasFileTool) return false; offset=m_fileTool.offset; return true; }
|
||||
int i=m_toolChoice->currentIndex(); if(i<0||i>=m_tools.tools.size()) return false;
|
||||
offset=m_tools.tools[i].offset; return true;
|
||||
}
|
||||
void TouchOperationWidget::setContext(const QString &endpoint,const QString &device,bool connected,bool demo,bool reference,const Pose &offset) {
|
||||
bool scope=endpoint!=m_endpoint||device!=m_device;
|
||||
if(!scope&&offset!=m_activeOffset) { m_observed=false; }
|
||||
if(scope||connected!=m_connected||demo!=m_demo||reference!=m_reference||offset!=m_activeOffset) {
|
||||
stopPreview(); stop(); m_cameraConfirmed->setChecked(false);
|
||||
}
|
||||
m_endpoint=endpoint; m_device=device; m_connected=connected; m_demo=demo; m_reference=reference; m_activeOffset=offset;
|
||||
if(scope) {
|
||||
m_hasPlane=false; m_planeRecord={}; QSettings settings; QString error;
|
||||
if(CameraCapabilities::known(m_cameraCapabilities)) m_hasPlane=TouchPlaneStore::load(settings,m_endpoint,m_device,
|
||||
m_cameraCapabilities.value("serial").toString(),m_planeRecord,error);
|
||||
}
|
||||
if(scope) { m_observed=false; m_hasFileHand=false; m_hasFileTool=false; { const QSignalBlocker h(m_handSource),t(m_toolSource); m_handSource->setCurrentIndex(0); m_toolSource->setCurrentIndex(0); } m_handFileLabel->setText(QStringLiteral("未导入")); m_toolFileLabel->setText(QStringLiteral("未导入")); reloadCalibrations(); loadTeaching(); }
|
||||
if(m_observed&&m_reference&&m_teachingOffset!=m_activeOffset) { m_observed=false; }
|
||||
m_sequence->setContext(endpoint,device,ready(),offset); refresh(); autoPreview();
|
||||
}
|
||||
void TouchOperationWidget::reloadCalibrations() {
|
||||
stopPreview(); stop();
|
||||
const QString oldHand=m_handEyeChoice->currentText(),oldTool=m_toolChoice->currentText();
|
||||
m_loading=true; m_handEyeChoice->clear(); m_toolChoice->clear(); m_handEyes={}; m_tools={};
|
||||
QSettings settings; QString error;
|
||||
bool ok=m_endpoint.isEmpty()||m_device.isEmpty()||
|
||||
(HandEyeStore::load(settings,m_endpoint,m_device,m_handEyes,error)&&TcpToolStore::load(settings,m_endpoint,m_device,m_tools,error));
|
||||
if(ok) {
|
||||
for(int i=0;i<m_handEyes.records.size();++i) {
|
||||
const auto& r=m_handEyes.records[i];
|
||||
if(!CameraCapabilities::known(m_cameraCapabilities)||r.cameraSerial.isEmpty()||r.cameraSerial==m_cameraCapabilities.value("serial").toString()) m_handEyeChoice->addItem(r.name,i);
|
||||
}
|
||||
for(const auto &t:m_tools.tools) m_toolChoice->addItem(t.name);
|
||||
int h=m_handEyeChoice->findText(oldHand),t=m_toolChoice->findText(oldTool);
|
||||
if(h>=0) m_handEyeChoice->setCurrentIndex(h);
|
||||
if(t>=0) m_toolChoice->setCurrentIndex(t);
|
||||
}
|
||||
m_loading=false;
|
||||
if(m_observed&&!observationValid()) { m_observed=false; saveTeaching(); }
|
||||
m_cameraConfirmed->setChecked(false); refresh(); if(!ok) fail(error); else autoPreview();
|
||||
}
|
||||
void TouchOperationWidget::invalidatePlan() { m_planValid=false; m_plan={}; m_pathConfirmed->setChecked(false); m_steps->setRowCount(0); }
|
||||
void TouchOperationWidget::invalidateFrame() {
|
||||
invalidatePlan(); m_lockedAt=0; m_pendingImage={}; m_depth={}; m_video->unlock(); m_video->clearSelection();
|
||||
}
|
||||
void TouchOperationWidget::stop() {
|
||||
m_sequence->stop(); ++m_serial; m_poseToken=0; m_imageToken=0; m_phase=Phase::Idle; m_timeout.stop(); invalidateFrame(); refresh();
|
||||
}
|
||||
void TouchOperationWidget::fail(const QString &message) {
|
||||
stop(); m_status->setText(message); emit logMessage("ERROR",QStringLiteral("末端操作:%1").arg(message));
|
||||
QMessageBox::warning(this,QStringLiteral("末端操作"),message);
|
||||
}
|
||||
void TouchOperationWidget::setCameraIds(const QStringList &ids) {
|
||||
QStringList old; for(int i=0;i<m_cameraChoice->count();++i) old<<m_cameraChoice->itemText(i);
|
||||
if(old==ids) return;
|
||||
const QString previous=m_cameraChoice->currentText(); const QSignalBlocker block(m_cameraChoice);
|
||||
m_cameraChoice->clear(); m_cameraChoice->addItems(ids); int index=ids.indexOf(previous); if(index>=0) m_cameraChoice->setCurrentIndex(index);
|
||||
if(m_preview && !ids.contains(m_previewCamera)) stopPreview();
|
||||
autoPreview();
|
||||
}
|
||||
void TouchOperationWidget::autoPreview() {
|
||||
if(isVisible() && !m_preview && m_connected && !m_demo && m_cameraChoice->findText(cameraId())>=0) startPreview();
|
||||
}
|
||||
void TouchOperationWidget::showEvent(QShowEvent *event) { m_previewReconnects=0; QWidget::showEvent(event); QTimer::singleShot(0,this,[this]{ autoPreview(); }); }
|
||||
void TouchOperationWidget::importCalibration(bool hand) {
|
||||
if(m_endpoint.isEmpty()||m_device.isEmpty()) { fail(QStringLiteral("请先选择机械臂")); return; }
|
||||
const QString path=QFileDialog::getOpenFileName(this,QStringLiteral("导入标定文件"),QString(),"JSON (*.json)"); if(path.isEmpty()) return;
|
||||
QVariantMap map; QString error;
|
||||
if(!CalibrationFile::read(path,map,error)) { fail(error); return; }
|
||||
if((map.contains("device")&&map.value("device").toString()!=m_device)||(map.contains("endpoint")&&map.value("endpoint").toString()!=m_endpoint)) { fail(QStringLiteral("文件所属机械臂或服务器与当前选择不一致")); return; }
|
||||
if(hand) {
|
||||
HandEyeStore::Record value;
|
||||
if(!CalibrationFile::handEye(map,m_cameraChoice->currentText(),value,error)) { fail(error); return; }
|
||||
if(m_cameraChoice->findText(value.cameraId)<0) { fail(QStringLiteral("文件相机不在当前设备列表中")); return; }
|
||||
m_fileHand=value; m_hasFileHand=true; m_handFileLabel->setText(QFileInfo(path).fileName()); m_handFileLabel->setToolTip(path); m_handSource->setCurrentIndex(1);
|
||||
} else {
|
||||
TcpToolStore::Tool value; if(!CalibrationFile::tcp(map,value,error)) { fail(error); return; }
|
||||
m_fileTool=value; m_hasFileTool=true; m_toolFileLabel->setText(QFileInfo(path).fileName()); m_toolFileLabel->setToolTip(path); m_toolSource->setCurrentIndex(1);
|
||||
}
|
||||
stopPreview(); m_observed=false; m_cameraConfirmed->setChecked(false); refresh(); autoPreview();
|
||||
emit logMessage("OK",QStringLiteral("已为当前机械臂载入本地标定:%1").arg(path));
|
||||
}
|
||||
void TouchOperationWidget::hideEvent(QHideEvent *event) { stopPreview(); stop(); QWidget::hideEvent(event); }
|
||||
void TouchOperationWidget::startPreview() {
|
||||
if(!m_connected||m_demo||cameraId().isEmpty()) { fail(QStringLiteral("请连接机器人服务并选择相机。")); return; }
|
||||
stopPreview(); m_previewCamera=cameraId(); m_preview=true; emit previewRequested(m_previewCamera,true); refresh();
|
||||
}
|
||||
void TouchOperationWidget::stopPreview() {
|
||||
const QString camera=m_previewCamera; bool active=m_preview; m_preview=false; m_previewCamera.clear();
|
||||
if(active) emit previewRequested(camera,false);
|
||||
stop(); m_video->clearFrame();
|
||||
}
|
||||
void TouchOperationWidget::acceptFrame(const QString &camera,const VideoFrame &frame,const QString &) {
|
||||
if(!m_preview||camera!=m_previewCamera||!frame.isValid()) return;
|
||||
if(m_capabilitiesReceived && CameraCapabilities::known(m_cameraCapabilities)
|
||||
&& !CameraCapabilities::matches(m_cameraCapabilities,frame.metadata)) return;
|
||||
if(frame.metadata.value("kind").toString()!="rgb") { m_status->setText(QStringLiteral("当前流不是 RGB,请在相机页面切换为彩色视频。")); return; }
|
||||
m_previewReconnects=0;
|
||||
auto geometry=frame.intrinsics; geometry.insert("width",frame.width); geometry.insert("height",frame.height);
|
||||
const QString signature=TouchPlaneStore::fingerprint(geometry);
|
||||
if(!m_previewGeometry.isEmpty() && signature!=m_previewGeometry) { stop(); invalidateFrame(); m_cameraConfirmed->setChecked(false); refresh(); }
|
||||
m_previewGeometry=signature;
|
||||
m_video->present(frame);
|
||||
|
||||
}
|
||||
void TouchOperationWidget::acceptStreamState(const QString &camera,bool active,const QString &detail) {
|
||||
if(m_preview&&camera==m_previewCamera&&!active) {
|
||||
stopPreview(); m_status->setText(QStringLiteral("视频已停止:%1").arg(detail));
|
||||
// A previous page may finish stopping a borrowed stream after we enter.
|
||||
// Retry only the preview; stopPreview cancels any sampling/motion first.
|
||||
if(isVisible()&&m_connected&&!m_demo&&m_previewReconnects<3) {
|
||||
++m_previewReconnects; const quint64 generation=m_serial;
|
||||
m_status->setText(QStringLiteral("正在重新接入视频(%1/3)…").arg(m_previewReconnects));
|
||||
QTimer::singleShot(800,this,[this,generation] {
|
||||
if(generation==m_serial) autoPreview();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
void TouchOperationWidget::teach(Phase phase) {
|
||||
Pose offset{};
|
||||
if(!ready()||running()||m_phase!=Phase::Idle||!selectedTool(offset)) { fail(QStringLiteral("请先连接机械臂、选择 TCP 标定并核对控制器偏移。")); return; }
|
||||
if(phase==Phase::Return&&!observationValid()) return;
|
||||
invalidateFrame(); m_phase=phase; readPose();
|
||||
}
|
||||
void TouchOperationWidget::readPose() {
|
||||
m_poseToken=kPosePrefix|++m_serial; m_requestAt=QDateTime::currentMSecsSinceEpoch(); m_timeout.start();
|
||||
emit captureRequested(m_device,m_poseToken); refresh();
|
||||
}
|
||||
void TouchOperationWidget::lockFrame() {
|
||||
const QString blocker=pickingBlocker();
|
||||
if(!blocker.isEmpty()) { m_pickingStatus->setText(blocker); return; }
|
||||
invalidateFrame(); m_phase=Phase::LockBefore; readPose();
|
||||
}
|
||||
void TouchOperationWidget::acceptPose(quint64 token,const QString &device,const QVariantMap &map,const QVariantMap &state,bool success,const QString &detail) {
|
||||
m_sequence->acceptPose(token,device,map,state,success,detail);
|
||||
if(!m_poseToken||token!=m_poseToken||device!=m_device) return;
|
||||
m_poseToken=0; Pose pose{},tool{},flange{},selected{};
|
||||
const qint64 requested=state.value("requestedAtMs").toLongLong(),received=state.value("receivedAtMs").toLongLong();
|
||||
const qint64 now=QDateTime::currentMSecsSinceEpoch();
|
||||
if(!success||!ready()||!decodePose(map,pose)||(m_phase!=Phase::Observation&&!selectedTool(tool))||requested<m_requestAt||received<requested||received>now||now-received>1500
|
||||
||!state.value("connected").toBool()||state.value("moving",true).toBool()||state.value("fault",true).toBool()
|
||||
||state.value("protectiveStopped",true).toBool()||state.value("emergencyStopped",true).toBool()
|
||||
||state.value("source").toString()!=QStringLiteral("getRobotState.actual_tcp_pose")) { fail(QStringLiteral("实时位姿不可用:%1").arg(detail)); return; }
|
||||
if(!TcpCalibration::flangePose(pose,m_activeOffset,flange)||!TcpCalibration::toolPose(flange,tool,selected)) { fail(QStringLiteral("TCP 位姿转换失败。")); return; }
|
||||
const auto phase=m_phase;
|
||||
if(phase==Phase::LockBefore) {
|
||||
if(!nearPose(pose,m_observation)) { fail(QStringLiteral("机械臂不在观察位,请先回观察位并停稳。")); return; }
|
||||
m_before=pose; m_beforeAt=received; m_phase=Phase::LockImage; m_imageToken=kImagePrefix|++m_serial;
|
||||
requestLockImage(); refresh(); return;
|
||||
}
|
||||
if(phase==Phase::LockAfter) {
|
||||
if(requested<m_captureAt||!nearPose(m_before,pose)||!nearPose(pose,m_observation)||received-m_beforeAt>10000) { fail(QStringLiteral("取图期间位姿变化或时间窗无效,请停稳后重试。")); return; }
|
||||
TcpCalibration::flangePose(m_before,m_activeOffset,m_lockedFlange);
|
||||
if(!(m_video->lockImage(m_pendingImage))) { fail(QStringLiteral("观察图像无效。")); return; }
|
||||
m_pendingImage={}; m_lockedAt=QDateTime::currentMSecsSinceEpoch();
|
||||
} else if(phase==Phase::Observation) {
|
||||
const auto joints=state.value("jointPositions").toList();
|
||||
if(joints.isEmpty()) { fail(QStringLiteral("观察位缺少同次采集的关节角,请更新状态接口")); return; }
|
||||
for(const auto &v:joints) { bool ok=false; const double a=v.toDouble(&ok); if(!ok||!std::isfinite(a)) { fail(QStringLiteral("观察位关节角无效")); return; } }
|
||||
Pose flange{},tip{},tool{};
|
||||
if(!selectedTool(tool)||!TcpCalibration::flangePose(pose,m_activeOffset,flange)||!TcpCalibration::toolPose(flange,tool,tip)) { fail(QStringLiteral("无法换算观察位的触控笔 TCP 位姿")); return; }
|
||||
m_observationJoints=joints; m_observationTip=tip; m_observationTool=tool;
|
||||
m_observation=pose; m_observed=true; m_teachingOffset=m_activeOffset; saveTeaching();
|
||||
} else if(phase==Phase::Return) {
|
||||
m_phase=Phase::Idle; m_timeout.stop(); returnObservation(pose); return;
|
||||
}
|
||||
m_phase=Phase::Idle; m_timeout.stop(); refresh(); emit logMessage("OK",QStringLiteral("末端操作:已录入位姿 / 锁定观察图像"));
|
||||
}
|
||||
void TouchOperationWidget::acceptImage(quint64 token,const QString &camera,const QImage &image,const QVariantMap &intrinsics,const QVariantMap &metadata,bool success,const QString &detail) {
|
||||
if(!m_imageToken||token!=m_imageToken||camera!=cameraId()||m_phase!=Phase::LockImage) return;
|
||||
m_imageToken=0; QString error;
|
||||
if(!success) { fail(QStringLiteral("读取定位图像失败:%1").arg(detail)); return; }
|
||||
if(m_capabilitiesReceived && !CameraCapabilities::matches(m_cameraCapabilities,metadata)) {
|
||||
fail(QStringLiteral("相机已替换或采集会话变化,请重新锁定画面")); return;
|
||||
}
|
||||
const bool planeMode=CameraCapabilities::mode(m_cameraCapabilities)==CameraCapabilities::Mode::Plane;
|
||||
const qint64 colorAt=metadata.value("captureUtcNs").toLongLong()/1000000;
|
||||
const qint64 depthAt=planeMode?colorAt:metadata.value("depthCaptureUtcNs").toLongLong()/1000000;
|
||||
const qint64 earliestColor=metadata.value("captureEarliestLocalNs",metadata.value("captureUtcNs")).toLongLong()/1000000;
|
||||
const qint64 earliestDepth=planeMode?earliestColor:metadata.value("depthCaptureEarliestLocalNs",metadata.value("depthCaptureUtcNs")).toLongLong()/1000000;
|
||||
const qint64 now=QDateTime::currentMSecsSinceEpoch();
|
||||
if((!planeMode && (!metadata.value("alignedToColor").toBool()||!metadata.value("colorAxialZ").toBool()
|
||||
||metadata.value("byteOrder").toString()!="little"))||colorAt<=0||depthAt<=0
|
||||
||std::abs(colorAt-depthAt)>33||colorAt>now||depthAt>now) {
|
||||
fail(QStringLiteral("RGBD 缺少有效配准、深度单位或同步时间戳,请更新相机服务。")); return;
|
||||
}
|
||||
if(earliestColor>colorAt||earliestDepth>depthAt) {
|
||||
fail(QStringLiteral("RGBD 时间区间无效,请重新取图。")); return;
|
||||
}
|
||||
if(earliestColor<m_beforeAt||earliestDepth<m_beforeAt||now-qMin(earliestColor,earliestDepth)>1500) {
|
||||
// The server snapshots its acquisition thread. Wait for a new pair;
|
||||
// never combine a live color frame with an older depth image.
|
||||
const quint64 generation=m_serial;
|
||||
QTimer::singleShot(80,this,[this,generation] {
|
||||
if(m_serial!=generation||m_phase!=Phase::LockImage||m_imageToken) return;
|
||||
m_imageToken=kImagePrefix|++m_serial; requestLockImage();
|
||||
});
|
||||
return;
|
||||
}
|
||||
TouchPlanner::DepthImage depth;
|
||||
depth.width=metadata.value("depthWidth").toInt(); depth.height=metadata.value("depthHeight").toInt();
|
||||
depth.data=metadata.value("depthData").toByteArray(); depth.float32=metadata.value("depthFloat32").toBool();
|
||||
depth.metresPerUnit=metadata.value("metresPerUnit").toDouble();
|
||||
if(image.isNull()||!TouchPlanner::cameraModel(intrinsics,image.width(),image.height(),m_cameraModel,&error)
|
||||
||(!planeMode && (depth.width!=image.width()||depth.height!=image.height()
|
||||
||!std::isfinite(depth.metresPerUnit)||depth.metresPerUnit<=0||depth.metresPerUnit>1
|
||||
||qint64(depth.width)*depth.height*(depth.float32?4:2)!=depth.data.size()))) {
|
||||
fail(QStringLiteral("RGBD 尺寸、单位或内参无效:%1").arg(error)); return;
|
||||
}
|
||||
if(planeMode && (!handEye() || !TouchPlaneStore::matches(m_planeRecord,m_device,m_cameraCapabilities.value("serial").toString(),*handEye(),intrinsics))) {
|
||||
fail(QStringLiteral("平面参数与当前手眼标定或原始图像内参不匹配")); return;
|
||||
}
|
||||
if(m_capabilitiesReceived && handEye()) {
|
||||
TouchPlanner::CameraModel saved;
|
||||
if(!TouchPlanner::cameraModel(handEye()->intrinsics,image.width(),image.height(),saved,&error)) {
|
||||
fail(QStringLiteral("手眼结果内参与当前原始图像不匹配:%1").arg(error)); return;
|
||||
}
|
||||
auto same=[](double a,double b) { return std::abs(a-b)<=1e-4+1e-6*std::abs(a); };
|
||||
bool matching=same(saved.fx,m_cameraModel.fx)&&same(saved.fy,m_cameraModel.fy)&&same(saved.cx,m_cameraModel.cx)&&same(saved.cy,m_cameraModel.cy)
|
||||
&&saved.distortion.size()==m_cameraModel.distortion.size();
|
||||
for(size_t i=0;matching&&i<saved.distortion.size();++i) matching=same(saved.distortion[i],m_cameraModel.distortion[i]);
|
||||
if(!matching) { fail(QStringLiteral("相机内参已改变,请重新核对或标定手眼关系")); return; }
|
||||
}
|
||||
m_depth=depth; m_pendingImage=image; m_captureAt=qMax(colorAt,depthAt); m_phase=Phase::LockAfter; readPose();
|
||||
}
|
||||
void TouchOperationWidget::acceptCommand(const QString &command,bool success,const QString &detail) { m_sequence->acceptCommand(command,success,detail); }
|
||||
TouchPlanner::Parameters TouchOperationWidget::parameters() const {
|
||||
TouchPlanner::Parameters p; p.approachM=m_approach->value()/1000; p.contactOffsetM=m_press->value()/1000;
|
||||
p.doubleLiftM=m_lift->value()/1000; p.travelVelocityMps=m_speed->value()/1000; p.contactVelocityMps=m_contactSpeed->value()/1000;
|
||||
p.maxTravelM=m_travel->value()/1000; p.contactDwellMs=m_dwell->value(); p.doubleIntervalMs=m_gap->value(); return p;
|
||||
}
|
||||
bool TouchOperationWidget::buildPlane(TouchPlanner::Plane &plane,QString &error) const {
|
||||
if(CameraCapabilities::mode(m_cameraCapabilities)==CameraCapabilities::Mode::Plane) {
|
||||
Pose offset{},tip{};
|
||||
if(!validPlaneBinding()||!selectedTool(offset)||!TcpCalibration::toolPose(m_lockedFlange,offset,tip,&error)) {
|
||||
error=QStringLiteral("请导入匹配的平面参数"); return false;
|
||||
}
|
||||
plane=m_planeRecord.plane; for(int i=0;i<3;++i) plane.orientationRad[size_t(i)]=tip[size_t(i+3)];
|
||||
return true;
|
||||
}
|
||||
QVector<TouchPlanner::Point> points,cameraPoints;
|
||||
TouchPlanner::Matrix baseCamera{}; Pose offset{},tip{};
|
||||
if(!resolveTargets(points,cameraPoints,error)||!selectedTool(offset)
|
||||
||!TcpCalibration::toolPose(m_lockedFlange,offset,tip,&error)
|
||||
||!TouchPlanner::cameraTransform(*handEye(),m_lockedFlange,baseCamera,&error)) return false;
|
||||
plane.origin=points.first();
|
||||
// Same free-pixel approach direction as phone: negative camera Z.
|
||||
// Preserve the selected stylus orientation taught at the observation pose.
|
||||
for(int i=0;i<3;++i) { plane.normal[i]=-baseCamera[i*4+2]; plane.orientationRad[i]=tip[i+3]; }
|
||||
return true;
|
||||
}
|
||||
void TouchOperationWidget::calculate() {
|
||||
invalidatePlan(); QString error; Pose tool{}; TouchPlanner::Plane plane; QVector<TouchPlanner::Point> points,cameraPoints;
|
||||
TouchPlanner::Matrix baseCamera{};
|
||||
if(!ready()||!handEye()||!observationValid()||!selectedTool(tool)||!m_video->locked()||!m_lockedAt||QDateTime::currentMSecsSinceEpoch()-m_lockedAt>60000) { fail(QStringLiteral("请在观察位重新锁定画面后取点。")); return; }
|
||||
if(!buildPlane(plane,error)||!resolveTargets(points,cameraPoints,error)
|
||||
||!TouchPlanner::cameraTransform(*handEye(),m_lockedFlange,baseCamera,&error)
|
||||
||(CameraCapabilities::mode(m_cameraCapabilities)!=CameraCapabilities::Mode::Plane && m_action->currentIndex()==2&&!TouchPlanner::validateDepthSwipe(m_video->selectedPoints(),m_cameraModel,m_depth,baseCamera,parameters(),&error))
|
||||
||!TouchPlanner::buildPlan(static_cast<TouchPlanner::Action>(m_action->currentIndex()),points,plane,m_observation,m_activeOffset,tool,parameters(),m_plan,&error,CameraCapabilities::mode(m_cameraCapabilities)!=CameraCapabilities::Mode::Plane)) { fail(error); return; }
|
||||
m_planValid=true; m_steps->setRowCount(m_plan.steps.size());
|
||||
for(int i=0;i<m_plan.steps.size();++i) { const auto &step=m_plan.steps[i]; m_steps->setItem(i,0,new QTableWidgetItem(QString::number(i+1)+" · "+step.label));
|
||||
m_steps->setItem(i,1,new QTableWidgetItem(poseText(step.target))); m_steps->setItem(i,2,new QTableWidgetItem(QString::number(step.velocityMps*1000,'f',1))); }
|
||||
refresh(); emit logMessage("INFO",QStringLiteral("末端操作:已转换 %1 个目标,规划 %2 个动作步骤").arg(points.size()).arg(m_plan.steps.size()));
|
||||
}
|
||||
void TouchOperationWidget::execute() {
|
||||
if(!m_planValid||!m_pathConfirmed->isChecked()||running()||!ready()||!handEye()||!observationValid()||QDateTime::currentMSecsSinceEpoch()-m_lockedAt>60000) { fail(QStringLiteral("请重新预览路径并确认后执行。")); return; }
|
||||
QVector<TouchSequenceController::Step> steps;
|
||||
for(const auto &s:m_plan.steps) steps.append({s.target,s.velocityMps,s.accelerationMps2,s.pauseMs,s.label});
|
||||
m_sequence->setContext(m_endpoint,m_device,ready(),m_activeOffset);
|
||||
m_sequence->start(steps,m_observation); refresh();
|
||||
}
|
||||
void TouchOperationWidget::returnObservation(const Pose ¤t) {
|
||||
// Explicit straight return; automatic touch sequences retract before return.
|
||||
auto p=parameters(); double distance=0; for(int i=0;i<3;++i) distance+=std::pow(current[i]-m_observation[i],2);
|
||||
if(std::sqrt(distance)>p.maxTravelM) { fail(QStringLiteral("当前位置超出所设回程范围,请手动接近观察位。")); return; }
|
||||
QVector<TouchSequenceController::Step> steps; Pose tool{};
|
||||
steps.append({m_observation,p.travelVelocityMps,p.accelerationMps2,0,QStringLiteral("返回观察位")});
|
||||
if(!selectedTool(tool)) { fail(QStringLiteral("请选择有效 TCP。")); return; }
|
||||
Pose previous=current,previousFlange{},previousTip{},obsFlange{},obsTip{};
|
||||
if(!TcpCalibration::flangePose(current,m_activeOffset,previousFlange)||!TcpCalibration::toolPose(previousFlange,tool,previousTip)
|
||||
||!TcpCalibration::flangePose(m_observation,m_activeOffset,obsFlange)||!TcpCalibration::toolPose(obsFlange,tool,obsTip)) { fail(QStringLiteral("回程位姿转换失败。")); return; }
|
||||
for(const auto &step:steps) {
|
||||
Pose nextFlange{},nextTip{};
|
||||
if(!TcpCalibration::flangePose(step.target,m_activeOffset,nextFlange)||!TcpCalibration::toolPose(nextFlange,tool,nextTip)) { fail(QStringLiteral("回程位姿转换失败。")); return; }
|
||||
auto norm=[](const Pose &a,const Pose &b) { double sum=0; for(int i=0;i<3;++i) sum+=std::pow(a[i]-b[i],2); return std::sqrt(sum); };
|
||||
const Pose origin{};
|
||||
if(norm(step.target,previous)>p.maxTravelM||norm(nextTip,previousTip)>p.maxTravelM||norm(nextFlange,previousFlange)>p.maxTravelM
|
||||
||norm(step.target,m_observation)>p.maxTravelM||norm(nextTip,obsTip)>p.maxTravelM||norm(nextFlange,obsFlange)>p.maxTravelM
|
||||
||norm(step.target,origin)>p.maxReachM||norm(nextTip,origin)>p.maxReachM||norm(nextFlange,origin)>p.maxReachM) { fail(QStringLiteral("回程路径超出所设运动范围。")); return; }
|
||||
previous=step.target; previousTip=nextTip; previousFlange=nextFlange;
|
||||
}
|
||||
m_sequence->setContext(m_endpoint,m_device,ready(),m_activeOffset); m_sequence->start(steps,current); refresh();
|
||||
}
|
||||
QString TouchOperationWidget::settingsKey() const {
|
||||
QByteArray identity=m_endpoint.toUtf8(); identity.append('\0'); identity.append(m_device.toUtf8());
|
||||
return QStringLiteral("touchOperation/v1/")+QString::fromLatin1(QCryptographicHash::hash(identity,QCryptographicHash::Sha256).toHex());
|
||||
}
|
||||
void TouchOperationWidget::saveTeaching() {
|
||||
if(m_loading||m_endpoint.isEmpty()||m_device.isEmpty()) return;
|
||||
Pose tool{}; QVariantMap data{{"endpoint",m_endpoint},{"device",m_device},{"handEye",m_handEyeChoice->currentText()},{"tool",m_toolChoice->currentText()},
|
||||
{"pose_frame","tcp1"},{"joint_positions",m_observationJoints},{"tcp1_pose",values(m_observationTip)},
|
||||
{"observed",m_observed},{"observation",values(m_observation)},{"activeOffset",values(m_teachingOffset)}};
|
||||
if(m_observed) data.insert("toolOffset",values(m_observationTool));
|
||||
QSettings settings; settings.setValue(settingsKey(),QJsonDocument::fromVariant(data).toJson(QJsonDocument::Compact)); settings.sync();
|
||||
if(settings.status()!=QSettings::NoError) { m_status->setText(QStringLiteral("示教配置写入失败")); emit logMessage("ERROR",m_status->text()); }
|
||||
}
|
||||
void TouchOperationWidget::loadTeaching() {
|
||||
QSettings settings; auto bytes=settings.value(settingsKey()).toByteArray(); if(bytes.isEmpty()) return;
|
||||
const auto data=QJsonDocument::fromJson(bytes).toVariant().toMap();
|
||||
if(data.value("endpoint").toString()!=m_endpoint||data.value("device").toString()!=m_device) return;
|
||||
m_loading=true; const int h=m_handEyeChoice->findText(data.value("handEye").toString()),t=m_toolChoice->findText(data.value("tool").toString());
|
||||
if(h>=0) m_handEyeChoice->setCurrentIndex(h);
|
||||
if(t>=0) m_toolChoice->setCurrentIndex(t);
|
||||
m_loading=false;
|
||||
m_observed=data.value("observed").toBool()&&poseFrom(data.value("observation"),m_observation)&&poseFrom(data.value("activeOffset"),m_teachingOffset);
|
||||
Pose selected{}; m_observationJoints=data.value("joint_positions").toList();
|
||||
m_observed=m_observed && data.value("pose_frame").toString()=="tcp1" && !m_observationJoints.isEmpty()
|
||||
&& poseFrom(data.value("tcp1_pose"),m_observationTip) && poseFrom(data.value("toolOffset"),m_observationTool)
|
||||
&& selectedTool(selected) && selected==m_observationTool;
|
||||
for(const auto &v:m_observationJoints) { bool ok=false; const double n=v.toDouble(&ok); if(!ok||!std::isfinite(n)) m_observed=false; }
|
||||
|
||||
|
||||
}
|
||||
void TouchOperationWidget::refresh() {
|
||||
const bool planeMode=CameraCapabilities::mode(m_cameraCapabilities)==CameraCapabilities::Mode::Plane;
|
||||
m_cameraMode->setText(CameraCapabilities::title(m_cameraCapabilities));
|
||||
if(handEye() && CameraCapabilities::known(m_cameraCapabilities) && handEye()->cameraSerial.isEmpty()) {
|
||||
m_cameraMode->setText(m_cameraMode->text()+QStringLiteral("\n旧标定未绑定相机序列号,请确认归属"));
|
||||
m_cameraConfirmed->setToolTip(QStringLiteral("勾选表示确认当前手眼结果“%1”属于相机 %2(会话 %3),并已核对内参与采集时钟;更换相机后需重新确认。")
|
||||
.arg(handEye()->name,m_cameraCapabilities.value("serial").toString(),m_cameraCapabilities.value("sessionGeneration").toString()));
|
||||
}
|
||||
m_planeImport->setVisible(planeMode); m_planeTemplate->setVisible(planeMode); m_planeStatus->setVisible(planeMode);
|
||||
m_planeImport->setEnabled(!running() && m_phase==Phase::Idle && handEye());
|
||||
m_planeTemplate->setEnabled(m_planeImport->isEnabled());
|
||||
m_planeStatus->setText(validPlaneBinding()?QStringLiteral("平面:%1").arg(m_planeRecord.name):QStringLiteral("平面参数未就绪或与当前标定不匹配"));
|
||||
bool busy=running()||m_phase!=Phase::Idle; Pose offset{}; bool selected=selectedTool(offset);
|
||||
m_handEyeChoice->setVisible(m_handSource->currentIndex()==0); m_handFileLabel->setVisible(m_handSource->currentIndex()==1);
|
||||
m_toolChoice->setVisible(m_toolSource->currentIndex()==0); m_toolFileLabel->setVisible(m_toolSource->currentIndex()==1);
|
||||
for(auto *w:QList<QWidget*>{m_handSource,m_toolSource,m_handFileButton,m_toolFileButton,m_cameraChoice}) w->setEnabled(!busy);
|
||||
m_cameraChoice->setEnabled(!busy&&!handEye());
|
||||
if(handEye() && !m_capabilitiesReceived) { const QSignalBlocker block(m_cameraChoice); m_cameraChoice->setCurrentText(handEye()->cameraId); }
|
||||
if(m_capabilitiesReceived) m_cameraChoice->setEnabled(false);
|
||||
m_cameraName->setText(cameraId().isEmpty()?QStringLiteral("请先选择手眼标定"):cameraId());
|
||||
for(auto *w:QList<QWidget*>{m_handEyeChoice,m_toolChoice,m_action,m_reloadButton,m_cameraConfirmed,m_approach,m_press,m_lift,m_speed,m_contactSpeed,m_travel,m_dwell,m_gap}) w->setEnabled(!busy);
|
||||
m_teachObservation->setEnabled(ready()&&selected&&!busy); m_returnButton->setEnabled(ready()&&selected&&observationValid()&&!busy);
|
||||
|
||||
m_previewButton->setEnabled(m_connected&&!m_demo&&!cameraId().isEmpty()&&!m_preview&&!busy); m_stopPreviewButton->setEnabled(m_preview);
|
||||
const QString blocker=pickingBlocker();
|
||||
m_lockButton->setEnabled(blocker.isEmpty());
|
||||
m_lockButton->setToolTip(blocker.isEmpty()?QStringLiteral("获取同步 RGBD 与静止机械臂位姿后取点"):blocker);
|
||||
m_pickingStatus->setText(!blocker.isEmpty()?blocker:m_video->locked()
|
||||
?QStringLiteral("可取点:点击画面选择 A / B;滑动按 A → B 执行。")
|
||||
:QStringLiteral("请点击“锁定观察画面”,获取同步 RGBD 后取点。"));
|
||||
m_liveButton->setEnabled(m_video->locked()&&!busy); m_video->setEnabled(!busy);
|
||||
m_calculateButton->setEnabled(ready()&&handEye()&&observationValid()&&m_video->locked()&&!m_video->selectedPoints().isEmpty()&&(m_action->currentIndex()!=2||m_video->selectedPoints().size()==2)&&!busy);
|
||||
m_executeButton->setEnabled(ready()&&handEye()&&observationValid()&&m_planValid&&m_pathConfirmed->isChecked()&&!busy);
|
||||
m_pathConfirmed->setEnabled(m_planValid&&!busy);
|
||||
QStringList angles; for(const auto &j:m_observationJoints) angles<<QString::number(j.toDouble()*180/3.141592653589793,'f',2);
|
||||
m_observationText->setText(m_observed?QStringLiteral("触控笔 TCP 观察位 · 已录入\n关节 (°):%1\nXYZ (mm) / Rx Ry Rz (°):%2").arg(angles.join(" / "),poseText(m_observationTip)):QStringLiteral("尚未录入观察位"));
|
||||
refreshTargetResults();
|
||||
if(!running()) m_status->setText(!m_connected||m_demo?QStringLiteral("请连接真实机器人服务"):
|
||||
!m_reference?QStringLiteral("请在 TCP 标定页核对控制器当前工具偏移"):
|
||||
!selected?QStringLiteral("请选择或导入触控笔 TCP 标定"):
|
||||
!handEye()?QStringLiteral("请选择或导入手眼标定;视频可独立预览"):
|
||||
!observationValid()?QStringLiteral("请录入当前 TCP 的观察位"):
|
||||
!m_preview?QStringLiteral("请启动相机视频"):
|
||||
!m_cameraConfirmed->isChecked()?QStringLiteral("请核对相机内参与时钟"):
|
||||
busy?QStringLiteral("正在读取真实位姿 / RGBD 图像…"):
|
||||
m_planValid?QStringLiteral("路径已就绪,核对后执行"):
|
||||
m_video->locked()?(m_action->currentIndex()==2?QStringLiteral("滑动:请选择 A、B 两点后转换"):QStringLiteral("请选择 1–2 个目标点后转换")):
|
||||
QStringLiteral("请将机械臂停在观察位,再锁定观察画面"));
|
||||
}
|
||||
|
||||
bool TouchOperationWidget::resolveTargets(QVector<TouchPlanner::Point> &basePoints,
|
||||
QVector<TouchPlanner::Point> &cameraPoints,QString &error) const {
|
||||
if(!m_video->locked()||!m_lockedAt) { error=QStringLiteral("请锁定观察画面后选择目标点"); return false; }
|
||||
if(m_video->selectedPoints().isEmpty()) { error=QStringLiteral("请选择 A / B 目标点"); return false; }
|
||||
if(QDateTime::currentMSecsSinceEpoch()-m_lockedAt>60000) { error=QStringLiteral("观察画面已过期,请重新锁定"); return false; }
|
||||
if(!ready()||!handEye()) { error=QStringLiteral("请核对连接、手眼标定与 TCP 偏移"); return false; }
|
||||
TouchPlanner::Matrix baseCamera{};
|
||||
if(!TouchPlanner::cameraTransform(*handEye(),m_lockedFlange,baseCamera,&error)) return false;
|
||||
if(CameraCapabilities::mode(m_cameraCapabilities)==CameraCapabilities::Mode::Plane) {
|
||||
if(!validPlaneBinding()) { error=QStringLiteral("平面参数不匹配"); return false; }
|
||||
auto p=parameters(); p.maxTravelM=qMin(p.maxTravelM,m_planeRecord.operatingRadiusM);
|
||||
if(!TouchPlanner::resolvePixels(m_video->selectedPoints(),m_cameraModel,baseCamera,m_planeRecord.plane,p,basePoints,&error)) return false;
|
||||
QVector<TouchPlanner::Point> camera;
|
||||
for(const auto& point:basePoints) {
|
||||
TouchPlanner::Point converted{};
|
||||
for(int i=0;i<3;++i) for(int j=0;j<3;++j) converted[size_t(i)]+=baseCamera[size_t(j*4+i)]*(point[size_t(j)]-baseCamera[size_t(j*4+3)]);
|
||||
camera<<converted;
|
||||
}
|
||||
cameraPoints=camera; return true;
|
||||
}
|
||||
return TouchPlanner::resolveDepthPixels(m_video->selectedPoints(),m_cameraModel,m_depth,baseCamera,
|
||||
parameters(),basePoints,cameraPoints,&error);
|
||||
|
||||
}
|
||||
|
||||
void TouchOperationWidget::refreshTargetResults() {
|
||||
const auto pixels=m_video->selectedPoints(); QVector<TouchPlanner::Point> base,camera; QString error;
|
||||
const bool valid=resolveTargets(base,camera,error);
|
||||
m_conversionStatus->setText(valid?QStringLiteral("%1 个目标点 · 换算完成").arg(base.size()):error);
|
||||
m_targets->setRowCount(pixels.size());
|
||||
auto xyz=[](const TouchPlanner::Point &point) {
|
||||
return QStringLiteral("X %1\nY %2\nZ %3").arg(point[0]*1000,0,'f',3).arg(point[1]*1000,0,'f',3).arg(point[2]*1000,0,'f',3);
|
||||
};
|
||||
for(int i=0;i<pixels.size();++i) {
|
||||
const QStringList row={i==0?"A":"B",QStringLiteral("u %1\nv %2").arg(pixels[i].x(),0,'f',1).arg(pixels[i].y(),0,'f',1),
|
||||
valid?xyz(camera[i]):QStringLiteral("待换算"),valid?xyz(base[i]):QStringLiteral("待换算")};
|
||||
for(int col=0;col<row.size();++col) { auto *item=new QTableWidgetItem(row[col]); item->setTextAlignment(Qt::AlignLeft|Qt::AlignVCenter); m_targets->setItem(i,col,item); }
|
||||
m_targets->setRowHeight(i,74);
|
||||
}
|
||||
}
|
||||
|
||||
void TouchOperationWidget::requestLockImage() { emit imageRequested(cameraId(),m_imageToken); }
|
||||
bool TouchOperationWidget::validPlaneBinding() const {
|
||||
const auto *h=handEye();
|
||||
return m_hasPlane && h && TouchPlaneStore::matches(m_planeRecord,m_device,
|
||||
m_cameraCapabilities.value("serial").toString(),*h,h->intrinsics)
|
||||
&& m_planeRecord.operatingRadiusM<=parameters().maxTravelM;
|
||||
}
|
||||
void TouchOperationWidget::setCameraCapabilities(const QString& camera,const QVariantMap& c) {
|
||||
const bool identity=!m_capabilitiesReceived || camera!=m_cameraChoice->currentText()
|
||||
|| c.value("serial")!=m_cameraCapabilities.value("serial")
|
||||
|| c.value("sessionGeneration").toULongLong()!=m_cameraCapabilities.value("sessionGeneration").toULongLong();
|
||||
const bool geometry=c.value("width")!=m_cameraCapabilities.value("width") || c.value("height")!=m_cameraCapabilities.value("height")
|
||||
||c.value("intrinsicsSignature")!=m_cameraCapabilities.value("intrinsicsSignature");
|
||||
const bool changed=identity || geometry || CameraCapabilities::mode(c)!=CameraCapabilities::mode(m_cameraCapabilities);
|
||||
m_capabilitiesReceived=true;
|
||||
if(changed) { stopPreview(); invalidateFrame(); m_previewGeometry.clear(); m_cameraConfirmed->setChecked(false); }
|
||||
m_cameraCapabilities=c;
|
||||
if(identity) {
|
||||
const QSignalBlocker block(m_cameraChoice); m_cameraChoice->clear(); if(!camera.isEmpty()) m_cameraChoice->addItem(camera);
|
||||
QSettings settings; QString error; m_hasPlane=TouchPlaneStore::load(settings,m_endpoint,m_device,c.value("serial").toString(),m_planeRecord,error);
|
||||
reloadCalibrations();
|
||||
}
|
||||
refresh(); autoPreview();
|
||||
}
|
||||
void TouchOperationWidget::importPlane() {
|
||||
if(running()||m_phase!=Phase::Idle||!handEye()) return;
|
||||
const auto path=QFileDialog::getOpenFileName(this,QStringLiteral("导入平面参数"),{},QStringLiteral("JSON (*.json)")); if(path.isEmpty()) return;
|
||||
QFile file(path); if(!file.open(QIODevice::ReadOnly)||file.size()>1024*1024) { fail(QStringLiteral("平面文件无法读取或过大")); return; }
|
||||
QJsonParseError parseError; const auto json=QJsonDocument::fromJson(file.readAll(),&parseError);
|
||||
TouchPlaneStore::Record record; QString error;
|
||||
if(parseError.error!=QJsonParseError::NoError || !TouchPlaneStore::parse(json.toVariant().toMap(),record,error)) { fail(error.isEmpty()?QStringLiteral("平面 JSON 无效"):error); return; }
|
||||
if(!TouchPlaneStore::matches(record,m_device,m_cameraCapabilities.value("serial").toString(),*handEye(),handEye()->intrinsics)
|
||||
||record.operatingRadiusM>parameters().maxTravelM) { fail(QStringLiteral("平面绑定或操作半径与当前任务不匹配,请使用当前任务导出的模板")); return; }
|
||||
QSettings settings;
|
||||
if(!TouchPlaneStore::save(settings,m_endpoint,m_device,m_cameraCapabilities.value("serial").toString(),json.toVariant().toMap(),error)) { fail(error); return; }
|
||||
invalidateFrame(); m_planeRecord=record; m_hasPlane=true; refresh();
|
||||
emit logMessage("OK",QStringLiteral("已导入平面参数:%1").arg(record.name));
|
||||
}
|
||||
void TouchOperationWidget::exportPlaneTemplate() {
|
||||
const auto *h=handEye(); if(!h||!CameraCapabilities::known(m_cameraCapabilities)) return;
|
||||
const auto path=QFileDialog::getSaveFileName(this,QStringLiteral("导出平面模板"),QStringLiteral("touch_plane.json"),QStringLiteral("JSON (*.json)")); if(path.isEmpty()) return;
|
||||
const QVariantMap data{{"schema_version",1},{"units","m"},{"frame","robot_base"},{"name","TouchPlane"},
|
||||
{"robot_id",m_device},{"camera_serial",m_cameraCapabilities.value("serial")},{"handeye_name",h->name},
|
||||
{"handeye_fingerprint",TouchPlaneStore::fingerprint(*h)},{"intrinsics_fingerprint",TouchPlaneStore::fingerprint(h->intrinsics)},
|
||||
{"origin",QVariantList{0.,0.,0.}},{"normal",QVariantList{0.,0.,1.}},
|
||||
{"operating_radius_m",parameters().maxTravelM},{"instructions",QStringLiteral("请填写实际基座平面原点及向外单位法向,导入后使用;模板不是测量结果。")}};
|
||||
const auto bytes=QJsonDocument::fromVariant(data).toJson(); QSaveFile file(path);
|
||||
if(!file.open(QIODevice::WriteOnly)||file.write(bytes)!=bytes.size()||!file.commit()) { fail(QStringLiteral("平面模板写入失败")); return; }
|
||||
emit logMessage("OK",QStringLiteral("已导出平面模板:%1").arg(path));
|
||||
}
|
||||
129
src/touchoperationwidget.h
Normal file
129
src/touchoperationwidget.h
Normal file
@ -0,0 +1,129 @@
|
||||
#pragma once
|
||||
#include "touchplanner.h"
|
||||
#include "touchsequencecontroller.h"
|
||||
#include "tcptoolstore.h"
|
||||
#include "touchplanestore.h"
|
||||
#include "cameracapabilities.h"
|
||||
#include "videoframe.h"
|
||||
#include <QWidget>
|
||||
#include <QImage>
|
||||
|
||||
class QComboBox;
|
||||
class QDoubleSpinBox;
|
||||
class QSpinBox;
|
||||
class QCheckBox;
|
||||
class QLabel;
|
||||
class QPushButton;
|
||||
class QTableWidget;
|
||||
class TouchVideoWidget;
|
||||
|
||||
// Page-level workflow. Geometry and motion sequencing live in separate helpers;
|
||||
// all camera/arm I/O is routed through the existing MainWindow / RobotClient.
|
||||
class TouchOperationWidget : public QWidget {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit TouchOperationWidget(QWidget *parent=nullptr);
|
||||
void setContext(const QString &endpoint,const QString &device,bool connected,bool demo,
|
||||
bool reference,const TcpCalibration::Pose &activeOffset);
|
||||
bool running() const;
|
||||
void setCameraIds(const QStringList &ids);
|
||||
public slots:
|
||||
void setCameraCapabilities(const QString &camera,const QVariantMap &capabilities);
|
||||
void reloadCalibrations();
|
||||
void stop();
|
||||
void acceptPose(quint64 token,const QString &device,const QVariantMap &pose,
|
||||
const QVariantMap &state,bool success,const QString &detail);
|
||||
void acceptImage(quint64 token,const QString &camera,const QImage &image,
|
||||
const QVariantMap &intrinsics,const QVariantMap &metadata,bool success,const QString &detail);
|
||||
void acceptFrame(const QString &camera,const VideoFrame &frame,const QString &detail);
|
||||
void acceptStreamState(const QString &camera,bool running,const QString &detail);
|
||||
void acceptCommand(const QString &command,bool success,const QString &detail);
|
||||
signals:
|
||||
void captureRequested(const QString &device,quint64 token);
|
||||
void imageRequested(const QString &camera,quint64 token);
|
||||
void previewRequested(const QString &camera,bool start);
|
||||
void moveRequested(const QString &device,const QVariantMap &target,double speed,double acceleration,quint64 token);
|
||||
void stopRequested(const QString &device);
|
||||
void logMessage(const QString &level,const QString &message);
|
||||
protected:
|
||||
void showEvent(QShowEvent *event) override;
|
||||
void hideEvent(QHideEvent *event) override;
|
||||
private:
|
||||
enum class Phase { Idle, Observation, LockBefore, LockImage, LockAfter, Return };
|
||||
using Pose=TcpCalibration::Pose;
|
||||
void refresh();
|
||||
void invalidateFrame();
|
||||
void invalidatePlan();
|
||||
void teach(Phase phase);
|
||||
void readPose();
|
||||
void lockFrame();
|
||||
void startPreview();
|
||||
void autoPreview();
|
||||
void importCalibration(bool handEyeFile);
|
||||
QComboBox *m_cameraChoice,*m_handSource,*m_toolSource;
|
||||
QPushButton *m_handFileButton,*m_toolFileButton;
|
||||
QLabel *m_handFileLabel,*m_toolFileLabel;
|
||||
HandEyeStore::Record m_fileHand;
|
||||
TcpToolStore::Tool m_fileTool;
|
||||
bool m_hasFileHand=false,m_hasFileTool=false;
|
||||
QVariantList m_observationJoints;
|
||||
Pose m_observationTool{},m_observationTip{};
|
||||
void stopPreview();
|
||||
void calculate();
|
||||
void execute();
|
||||
void returnObservation(const Pose ¤t);
|
||||
void fail(const QString &message);
|
||||
bool ready() const;
|
||||
bool observationValid() const;
|
||||
QString pickingBlocker() const;
|
||||
bool selectedTool(Pose &offset) const;
|
||||
const HandEyeStore::Record *handEye() const;
|
||||
QString cameraId() const;
|
||||
QString settingsKey() const;
|
||||
void loadTeaching();
|
||||
void saveTeaching();
|
||||
TouchPlanner::Parameters parameters() const;
|
||||
bool buildPlane(TouchPlanner::Plane &plane,QString &error) const;
|
||||
bool resolveTargets(QVector<TouchPlanner::Point> &basePoints,
|
||||
QVector<TouchPlanner::Point> &cameraPoints,QString &error) const;
|
||||
void refreshTargetResults();
|
||||
void importPlane();
|
||||
void exportPlaneTemplate();
|
||||
bool validPlaneBinding() const;
|
||||
void requestLockImage();
|
||||
QVariantMap m_cameraCapabilities;
|
||||
QString m_previewGeometry;
|
||||
bool m_capabilitiesReceived=false;
|
||||
TouchPlaneStore::Record m_planeRecord;
|
||||
bool m_hasPlane=false;
|
||||
QLabel *m_cameraMode,*m_planeStatus;
|
||||
QPushButton *m_planeImport,*m_planeTemplate;
|
||||
|
||||
QString m_endpoint,m_device,m_previewCamera;
|
||||
bool m_connected=false,m_demo=false,m_reference=false,m_loading=false,m_preview=false;
|
||||
bool m_observed=false,m_planValid=false;
|
||||
int m_previewReconnects=0;
|
||||
Pose m_activeOffset{},m_observation{},m_before{},m_lockedFlange{},m_teachingOffset{};
|
||||
HandEyeStore::Snapshot m_handEyes;
|
||||
TcpToolStore::Snapshot m_tools;
|
||||
TouchPlanner::Plan m_plan;
|
||||
TouchPlanner::CameraModel m_cameraModel;
|
||||
TouchPlanner::DepthImage m_depth;
|
||||
QImage m_pendingImage;
|
||||
qint64 m_beforeAt=0,m_captureAt=0,m_lockedAt=0,m_requestAt=0;
|
||||
quint64 m_serial=0,m_poseToken=0,m_imageToken=0;
|
||||
Phase m_phase=Phase::Idle;
|
||||
QTimer m_timeout;
|
||||
TouchSequenceController *m_sequence;
|
||||
TouchVideoWidget *m_video;
|
||||
QComboBox *m_handEyeChoice,*m_toolChoice,*m_action;
|
||||
QLabel *m_cameraName,*m_status,*m_observationText;
|
||||
QLabel *m_conversionStatus;
|
||||
QLabel *m_pickingStatus;
|
||||
QCheckBox *m_cameraConfirmed,*m_pathConfirmed;
|
||||
QPushButton *m_previewButton,*m_stopPreviewButton,*m_lockButton,*m_liveButton,*m_teachObservation;
|
||||
QPushButton *m_returnButton,*m_calculateButton,*m_executeButton,*m_reloadButton;
|
||||
QDoubleSpinBox *m_approach,*m_press,*m_lift,*m_speed,*m_contactSpeed,*m_travel;
|
||||
QSpinBox *m_dwell,*m_gap;
|
||||
QTableWidget *m_targets,*m_steps;
|
||||
};
|
||||
69
src/touchplanestore.cpp
Normal file
69
src/touchplanestore.cpp
Normal file
@ -0,0 +1,69 @@
|
||||
#include "touchplanestore.h"
|
||||
#include <QCryptographicHash>
|
||||
#include <QJsonDocument>
|
||||
#include <QSettings>
|
||||
#include <cmath>
|
||||
|
||||
namespace TouchPlaneStore {
|
||||
namespace {
|
||||
QString hash(const QVariantMap& value) { return QString::fromLatin1(QCryptographicHash::hash(
|
||||
QJsonDocument::fromVariant(value).toJson(QJsonDocument::Compact),QCryptographicHash::Sha256).toHex()); }
|
||||
QString key(const QString& endpoint,const QString& device,const QString& serial) {
|
||||
return QStringLiteral("touch/planes/")+hash({{"endpoint",endpoint},{"device",device},{"serial",serial}});
|
||||
}
|
||||
bool point(const QVariant& value,TouchPlanner::Point& out) {
|
||||
const auto list=value.toList(); if(list.size()!=3) return false;
|
||||
for(int i=0;i<3;++i) { bool ok=false; out[size_t(i)]=list[i].toDouble(&ok); if(!ok || !std::isfinite(out[size_t(i)])) return false; }
|
||||
return true;
|
||||
}
|
||||
}
|
||||
QString fingerprint(const QVariantMap& k) {
|
||||
QVariantMap normalized;
|
||||
for(const auto& field:{"fx","fy","cx","cy","coeffs","width","height"}) normalized.insert(field,k.value(field));
|
||||
return hash(normalized);
|
||||
}
|
||||
QString fingerprint(const HandEyeStore::Record& h) {
|
||||
QVariantList matrix; for(double v:h.transform) matrix<<v;
|
||||
return hash({{"mode",h.mode},{"matrix",matrix},{"camera",h.cameraSerial},{"intrinsics",fingerprint(h.intrinsics)}});
|
||||
}
|
||||
bool parse(const QVariantMap& map,Record& record,QString& error) {
|
||||
auto fail=[&](const char* text) { error=QString::fromUtf8(text); return false; };
|
||||
if(map.value("schema_version").toInt()!=1 || map.value("units").toString()!="m" || map.value("frame").toString()!="robot_base")
|
||||
return fail("平面参数必须为 schema_version=1、units=m、frame=robot_base");
|
||||
Record r; r.name=map.value("name").toString().trimmed(); r.robotId=map.value("robot_id").toString();
|
||||
r.cameraSerial=map.value("camera_serial").toString(); r.handEyeName=map.value("handeye_name").toString();
|
||||
r.handEyeFingerprint=map.value("handeye_fingerprint").toString(); r.intrinsicsFingerprint=map.value("intrinsics_fingerprint").toString();
|
||||
if(r.name.isEmpty()||r.robotId.isEmpty()||r.cameraSerial.isEmpty()||r.handEyeName.isEmpty()
|
||||
||r.handEyeFingerprint.size()!=64||r.intrinsicsFingerprint.size()!=64) return fail("平面文件缺少设备绑定或标定指纹,请先导出模板");
|
||||
if(!point(map.value("origin"),r.plane.origin)||!point(map.value("normal"),r.plane.normal)) return fail("平面原点与法向必须各有三个有限数值");
|
||||
double norm=0; for(double v:r.plane.normal) norm+=v*v;
|
||||
if(std::abs(norm-1)>1e-6) return fail("平面法向必须为单位向量");
|
||||
bool ok=false; r.operatingRadiusM=map.value("operating_radius_m").toDouble(&ok);
|
||||
if(!ok||!std::isfinite(r.operatingRadiusM)||r.operatingRadiusM<=0||r.operatingRadiusM>2) return fail("平面操作半径无效(0–2 m)");
|
||||
record=r; error.clear(); return true;
|
||||
}
|
||||
bool matches(const Record& r,const QString& device,const QString& serial,const HandEyeStore::Record& h,const QVariantMap& k) {
|
||||
return r.robotId==device && r.cameraSerial==serial && r.handEyeName==h.name
|
||||
&& r.handEyeFingerprint==fingerprint(h) && r.intrinsicsFingerprint==fingerprint(k);
|
||||
}
|
||||
bool load(QSettings& settings,const QString& endpoint,const QString& device,const QString& serial,Record& r,QString& error) {
|
||||
const auto data=settings.value(key(endpoint,device,serial)).toByteArray();
|
||||
if(data.isEmpty()) { error=QStringLiteral("请导入当前相机的平面参数"); return false; }
|
||||
QJsonParseError e; const auto json=QJsonDocument::fromJson(data,&e);
|
||||
if(e.error!=QJsonParseError::NoError || !json.isObject()) { error=QStringLiteral("已保存的平面参数损坏"); return false; }
|
||||
Record next; if(!parse(json.toVariant().toMap(),next,error)) return false;
|
||||
if(next.robotId!=device || next.cameraSerial!=serial) { error=QStringLiteral("平面参数与当前机械臂或相机不匹配"); return false; }
|
||||
r=next; return true;
|
||||
}
|
||||
bool save(QSettings& settings,const QString& endpoint,const QString& device,const QString& serial,const QVariantMap& map,QString& error) {
|
||||
Record r; if(!parse(map,r,error)) return false;
|
||||
if(r.robotId!=device || r.cameraSerial!=serial) { error=QStringLiteral("平面文件属于其他机械臂或相机"); return false; }
|
||||
const QString storage=key(endpoint,device,serial); const bool existed=settings.contains(storage); const auto previous=settings.value(storage);
|
||||
settings.setValue(storage,QJsonDocument::fromVariant(map).toJson(QJsonDocument::Compact)); settings.sync();
|
||||
if(settings.status()!=QSettings::NoError) {
|
||||
if(existed) settings.setValue(storage,previous); else settings.remove(storage);
|
||||
error=QStringLiteral("平面参数写入失败:%1").arg(settings.fileName()); return false;
|
||||
}
|
||||
error.clear(); return true;
|
||||
}
|
||||
}
|
||||
16
src/touchplanestore.h
Normal file
16
src/touchplanestore.h
Normal file
@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
#include "touchplanner.h"
|
||||
class QSettings;
|
||||
namespace TouchPlaneStore {
|
||||
struct Record {
|
||||
QString name, robotId, cameraSerial, handEyeName, handEyeFingerprint, intrinsicsFingerprint;
|
||||
TouchPlanner::Plane plane;
|
||||
double operatingRadiusM=0;
|
||||
};
|
||||
QString fingerprint(const QVariantMap& intrinsics);
|
||||
QString fingerprint(const HandEyeStore::Record& handEye);
|
||||
bool parse(const QVariantMap&,Record&,QString& error);
|
||||
bool load(QSettings&,const QString& endpoint,const QString& device,const QString& serial,Record&,QString& error);
|
||||
bool save(QSettings&,const QString& endpoint,const QString& device,const QString& serial,const QVariantMap&,QString& error);
|
||||
bool matches(const Record&,const QString& device,const QString& serial,const HandEyeStore::Record&,const QVariantMap& intrinsics);
|
||||
}
|
||||
369
src/touchplanner.cpp
Normal file
369
src/touchplanner.cpp
Normal file
@ -0,0 +1,369 @@
|
||||
#include "touchplanner.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <QtEndian>
|
||||
|
||||
namespace TouchPlanner {
|
||||
namespace {
|
||||
bool fail(QString *error, const char *message) {
|
||||
if (error) *error=QString::fromUtf8(message);
|
||||
return false;
|
||||
}
|
||||
void clear(QString *error) { if (error) error->clear(); }
|
||||
bool finite(const Point &p) { return std::all_of(p.begin(),p.end(),[](double v){return std::isfinite(v);}); }
|
||||
double norm(const Point &p) { return std::hypot(std::hypot(p[0],p[1]),p[2]); }
|
||||
Point subtract(const Point &a,const Point &b) { return {{a[0]-b[0],a[1]-b[1],a[2]-b[2]}}; }
|
||||
double dot(const Point &a,const Point &b) { return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]; }
|
||||
Point position(const Pose &p) { return {{p[0],p[1],p[2]}}; }
|
||||
Point shifted(const Point &p,const Point &n,double distance) {
|
||||
return {{p[0]+n[0]*distance,p[1]+n[1]*distance,p[2]+n[2]*distance}};
|
||||
}
|
||||
bool within(double value,double minimum,double maximum) {
|
||||
return std::isfinite(value) && value>=minimum && value<=maximum;
|
||||
}
|
||||
bool validParameters(const Parameters &p,QString *error) {
|
||||
if (!within(p.approachM,.001,.05) || !within(p.contactOffsetM,0,.002)
|
||||
|| !within(p.doubleLiftM,.0005,.05)
|
||||
|| !within(p.contactVelocityMps,.005,.03) || !within(p.travelVelocityMps,.005,.1)
|
||||
|| !within(p.accelerationMps2,.01,.5) || p.contactDwellMs<0 || p.contactDwellMs>5000
|
||||
|| p.doubleIntervalMs<0 || p.doubleIntervalMs>500
|
||||
|| !within(p.maxTravelM,.01,1) || !within(p.maxReachM,.05,3)
|
||||
|| !within(p.maxCameraRangeM,.05,5))
|
||||
return fail(error,"触控参数超出允许范围,检查距离、速度、加速度和停留时间。");
|
||||
return true;
|
||||
}
|
||||
bool validPlane(const Plane &p,QString *error) {
|
||||
if (!finite(p.origin) || !finite(p.normal) || !finite(p.orientationRad)
|
||||
|| norm(p.origin)>3 || std::abs(norm(p.normal)-1)>1e-6)
|
||||
return fail(error,"目标位置、触控姿态或接近方向无效,请重新取点。");
|
||||
return true;
|
||||
}
|
||||
bool validCamera(const CameraModel &c,QString *error) {
|
||||
if (c.width<2 || c.width>16384 || c.height<2 || c.height>16384
|
||||
|| !within(c.fx,1,1e6) || !within(c.fy,1,1e6)
|
||||
|| !within(c.cx,-c.width,2.0*c.width) || !within(c.cy,-c.height,2.0*c.height))
|
||||
return fail(error,"RGB 图像尺寸、焦距或主点无效。");
|
||||
const auto size=c.distortion.size();
|
||||
if (size!=0 && size!=4 && size!=5 && size!=8)
|
||||
return fail(error,"仅支持无畸变或 4、5、8 项标准 Brown 畸变系数。");
|
||||
for (double v:c.distortion) if (!within(v,-100,100))
|
||||
return fail(error,"RGB 畸变系数不是有效的有限数值。");
|
||||
return true;
|
||||
}
|
||||
bool number(const QVariant &v,double &out) {
|
||||
if (v.type()!=QVariant::Double && v.type()!=QVariant::Int && v.type()!=QVariant::UInt
|
||||
&& v.type()!=QVariant::LongLong && v.type()!=QVariant::ULongLong) return false;
|
||||
out=v.toDouble(); return std::isfinite(out);
|
||||
}
|
||||
// Brown forward projection and analytic Jacobian. A positive, non-singular
|
||||
// Jacobian is required so an inverse on a folded distortion branch is rejected.
|
||||
bool distort(double x,double y,const std::array<double,8> &k,
|
||||
double &dx,double &dy,std::array<double,4> &j) {
|
||||
if (!within(x,-5,5) || !within(y,-5,5)) return false;
|
||||
const double r2=x*x+y*y,r4=r2*r2,r6=r4*r2;
|
||||
const double a=1+k[0]*r2+k[1]*r4+k[4]*r6;
|
||||
const double b=1+k[5]*r2+k[6]*r4+k[7]*r6;
|
||||
if (!std::isfinite(a) || !std::isfinite(b) || a<=1e-9 || b<=1e-9) return false;
|
||||
const double radial=a/b;
|
||||
const double derivative=((k[0]+2*k[1]*r2+3*k[4]*r4)*b
|
||||
-a*(k[5]+2*k[6]*r2+3*k[7]*r4))/(b*b);
|
||||
dx=x*radial+2*k[2]*x*y+k[3]*(r2+2*x*x);
|
||||
dy=y*radial+k[2]*(r2+2*y*y)+2*k[3]*x*y;
|
||||
j={{radial+2*x*x*derivative+2*k[2]*y+6*k[3]*x,
|
||||
2*x*y*derivative+2*k[2]*x+2*k[3]*y,
|
||||
2*x*y*derivative+2*k[2]*x+2*k[3]*y,
|
||||
radial+2*y*y*derivative+6*k[2]*y+2*k[3]*x}};
|
||||
const double det=j[0]*j[3]-j[1]*j[2];
|
||||
return std::isfinite(dx) && std::isfinite(dy) && std::isfinite(det) && det>1e-10;
|
||||
}
|
||||
bool ray(const QPointF &pixel,const CameraModel &c,Point &direction,QString *error) {
|
||||
if (!within(pixel.x(),0,c.width-1.0) || !within(pixel.y(),0,c.height-1.0))
|
||||
return fail(error,"触控像素必须位于所锁定的 RGB 图像内。");
|
||||
const double wantedX=(pixel.x()-c.cx)/c.fx,wantedY=(pixel.y()-c.cy)/c.fy;
|
||||
double x=wantedX,y=wantedY;
|
||||
std::array<double,8> k{};
|
||||
std::copy(c.distortion.begin(),c.distortion.end(),k.begin());
|
||||
bool converged=false;
|
||||
for (int iteration=0;iteration<30;++iteration) {
|
||||
double actualX=0,actualY=0; std::array<double,4> j{};
|
||||
if (!distort(x,y,k,actualX,actualY,j))
|
||||
return fail(error,"畸变反解不稳定,不能生成触控射线。");
|
||||
const double ex=actualX-wantedX,ey=actualY-wantedY;
|
||||
if (std::hypot(ex,ey)<1e-12) { converged=true; break; }
|
||||
const double det=j[0]*j[3]-j[1]*j[2];
|
||||
const double sx=(j[3]*ex-j[1]*ey)/det,sy=(-j[2]*ex+j[0]*ey)/det;
|
||||
bool improved=false;
|
||||
for (int search=0;search<12;++search) {
|
||||
const double scale=std::ldexp(1.0,-search);
|
||||
const double tx=x-scale*sx,ty=y-scale*sy;
|
||||
double px=0,py=0; std::array<double,4> unused{};
|
||||
if (distort(tx,ty,k,px,py,unused) && std::hypot(px-wantedX,py-wantedY)<std::hypot(ex,ey)) {
|
||||
x=tx; y=ty; improved=true; break;
|
||||
}
|
||||
}
|
||||
if (!improved) break;
|
||||
}
|
||||
if (!converged) return fail(error,"RGB 像素畸变反解未收敛,请核对相机内参与模型。");
|
||||
const double length=std::hypot(std::hypot(x,y),1.0);
|
||||
direction={{x/length,y/length,1.0/length}};
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool teachPlane(const std::array<Pose,3> &contacts,const Pose &observation,Plane &plane,QString *error) {
|
||||
if (!TcpCalibration::validPose(observation) || norm(position(observation))>3)
|
||||
return fail(error,"观察位必须是有限的米制 TCP 位姿。");
|
||||
for (const Pose &p:contacts) if (!TcpCalibration::validPose(p) || norm(position(p))>3)
|
||||
return fail(error,"平面示教点必须是有限的米制 TCP 位姿。");
|
||||
const Point a=subtract(position(contacts[1]),position(contacts[0]));
|
||||
const Point b=subtract(position(contacts[2]),position(contacts[0]));
|
||||
const double la=norm(a),lb=norm(b);
|
||||
if (!within(la,.01,1) || !within(lb,.01,1)
|
||||
|| !within(norm(subtract(position(contacts[2]),position(contacts[1]))),.01,1))
|
||||
return fail(error,"三个平面示教点之间至少间隔 10 mm,最大基线不超过 1 m。");
|
||||
Point n{{a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]}};
|
||||
const double length=norm(n);
|
||||
if (length/(la*lb)<.08715574274765817)
|
||||
return fail(error,"平面示教点共线或接近共线,请扩大点位三角形(夹角至少 5 度)。");
|
||||
for (double &v:n) v/=length;
|
||||
const double side=dot(subtract(position(observation),position(contacts[0])),n);
|
||||
if (std::abs(side)<.001)
|
||||
return fail(error,"观察位必须离开触控平面至少 1 mm,以确定安全回撤方向。");
|
||||
if (side<0) for (double &v:n) v=-v;
|
||||
Plane result; result.origin=position(contacts[0]); result.normal=n;
|
||||
result.orientationRad={{contacts[0][3],contacts[0][4],contacts[0][5]}};
|
||||
plane=result; clear(error); return true;
|
||||
}
|
||||
|
||||
bool cameraTransform(const HandEyeStore::Record &record,const Pose &flange,Matrix &baseCamera,QString *error) {
|
||||
QString detail;
|
||||
if (!HandEyeStore::validateRecord(record,detail)) { if (error) *error=detail; return false; }
|
||||
Matrix result=record.transform;
|
||||
if (record.mode==QStringLiteral("eye_in_hand")) {
|
||||
Matrix baseFlange{};
|
||||
if (!TcpCalibration::poseMatrix(flange,baseFlange,error)) return false;
|
||||
result.fill(0);
|
||||
for (int r=0;r<4;++r) for (int c=0;c<4;++c) for (int k=0;k<4;++k)
|
||||
result[size_t(4*r+c)]+=baseFlange[size_t(4*r+k)]*record.transform[size_t(4*k+c)];
|
||||
}
|
||||
Pose checked{};
|
||||
if (!TcpCalibration::matrixPose(result,checked,error)) return false;
|
||||
baseCamera=result; clear(error); return true;
|
||||
}
|
||||
|
||||
bool cameraModel(const QVariantMap &data,int width,int height,CameraModel &camera,QString *error) {
|
||||
CameraModel result; result.width=width; result.height=height;
|
||||
for (const QString &key:{QStringLiteral("width"),QStringLiteral("height")}) if (data.contains(key)) {
|
||||
double value=0;
|
||||
if (!number(data.value(key),value) || value!=(key=="width"?width:height))
|
||||
return fail(error,"RGB 内参尺寸与图像不一致,禁止自动缩放或使用裁剪图。");
|
||||
}
|
||||
for (const QString &key:{QStringLiteral("model"),QStringLiteral("distortion_model")}) if (data.contains(key)) {
|
||||
const QString model=data.value(key).toString().trimmed().toLower();
|
||||
if (model!="none" && model!="0" && model!="4" && model!="brown_conrady"
|
||||
&& model!="brown-conrady" && model!="opencv" && model!="plumb_bob"
|
||||
&& model!="rational_polynomial")
|
||||
return fail(error,"当前 RGB 畸变模型不是受支持的标准 Brown 模型。");
|
||||
}
|
||||
if (data.contains("camera_matrix")) {
|
||||
const auto values=data.value("camera_matrix").toList();
|
||||
std::array<double,9> k{};
|
||||
if (values.size()!=9) return fail(error,"相机内参矩阵需要 9 个有限数值。");
|
||||
for (int i=0;i<9;++i) if (!number(values[i],k[size_t(i)]))
|
||||
return fail(error,"相机内参矩阵需要 9 个有限数值。");
|
||||
if (std::abs(k[1])+std::abs(k[3])+std::abs(k[6])+std::abs(k[7])+std::abs(k[8]-1)>1e-9)
|
||||
return fail(error,"相机内参必须为无斜切的标准针孔矩阵。");
|
||||
result.fx=k[0]; result.fy=k[4]; result.cx=k[2]; result.cy=k[5];
|
||||
} else if (!number(data.value("fx"),result.fx) || !number(data.value("fy"),result.fy)
|
||||
|| !number(data.value("cx"),result.cx) || !number(data.value("cy"),result.cy)) {
|
||||
return fail(error,"缺少有效的 RGB 焦距与主点参数。");
|
||||
}
|
||||
const QVariant coefficients=data.value(data.contains("coeffs")?"coeffs":"distortion");
|
||||
if (coefficients.type()!=QVariant::List)
|
||||
return fail(error,"RGB 内参必须明确提供畸变系数列表(无畸变时为空列表)。");
|
||||
for (const QVariant &v:coefficients.toList()) {
|
||||
double value=0;
|
||||
if (!number(v,value)) return fail(error,"畸变系数必须为有限数值。");
|
||||
result.distortion.push_back(value);
|
||||
}
|
||||
if (!validCamera(result,error)) return false;
|
||||
camera=result; clear(error); return true;
|
||||
}
|
||||
|
||||
bool resolvePixels(const QVector<QPointF> &pixels,const CameraModel &camera,const Matrix &baseCamera,
|
||||
const Plane &plane,const Parameters ¶meters,QVector<Point> &points,QString *error) {
|
||||
if (pixels.isEmpty() || pixels.size()>2) return fail(error,"请选择 1 至 2 个 RGB 图像点。");
|
||||
if (!validCamera(camera,error) || !validPlane(plane,error) || !validParameters(parameters,error)) return false;
|
||||
Pose cameraPose{};
|
||||
if (!TcpCalibration::matrixPose(baseCamera,cameraPose,error)) return false;
|
||||
const Point origin=position(cameraPose);
|
||||
if (norm(origin)>parameters.maxReachM) return fail(error,"相机基座坐标超出配置的工作空间范围。");
|
||||
QVector<Point> result;
|
||||
for (const QPointF &pixel:pixels) {
|
||||
Point cameraRay{},baseRay{};
|
||||
if (!ray(pixel,camera,cameraRay,error)) return false;
|
||||
for (int r=0;r<3;++r) for (int c=0;c<3;++c)
|
||||
baseRay[size_t(r)]+=baseCamera[size_t(r*4+c)]*cameraRay[size_t(c)];
|
||||
const double cosine=dot(plane.normal,baseRay);
|
||||
if (std::abs(cosine)<.02) return fail(error,"像素射线与示教平面接近平行,无法可靠求交。");
|
||||
const double distance=dot(plane.normal,subtract(plane.origin,origin))/cosine;
|
||||
if (!within(distance,.005,parameters.maxCameraRangeM))
|
||||
return fail(error,"触控交点位于相机后方、过近或超出相机距离限制。");
|
||||
const Point point=shifted(origin,baseRay,distance);
|
||||
if (!finite(point) || norm(point)>parameters.maxReachM)
|
||||
return fail(error,"触控交点超出配置的基座工作空间范围。");
|
||||
if (norm(subtract(point,plane.origin))>parameters.maxTravelM)
|
||||
return fail(error,"触控交点离平面示教原点过远,超过最大行程。");
|
||||
result.append(point);
|
||||
}
|
||||
points=result; clear(error); return true;
|
||||
}
|
||||
|
||||
bool resolveDepthPixels(const QVector<QPointF> &pixels,const CameraModel &camera,
|
||||
const DepthImage &depth,const Matrix &baseCamera,const Parameters &p,
|
||||
QVector<Point> &basePoints,QVector<Point> &cameraPoints,QString *error) {
|
||||
if (pixels.isEmpty() || pixels.size()>2 || !validCamera(camera,error) || !validParameters(p,error))
|
||||
return fail(error,"请选择 1 至 2 个有效 RGB 点并核对相机参数。");
|
||||
Pose pose{};
|
||||
if (!TcpCalibration::matrixPose(baseCamera,pose,error)) return false;
|
||||
const int bytes=depth.float32?4:2;
|
||||
if (depth.width!=camera.width || depth.height!=camera.height
|
||||
|| !within(depth.metresPerUnit,1e-9,1)
|
||||
|| qint64(depth.width)*depth.height*bytes!=depth.data.size())
|
||||
return fail(error,"缺少与锁定 RGB 对齐的原始深度或有效深度单位。");
|
||||
if (norm(position(pose))>p.maxReachM) return fail(error,"相机位置超出工作空间。");
|
||||
QVector<Point> base,cameraResult;
|
||||
for (const auto &pixel:pixels) {
|
||||
Point direction{}; if (!ray(pixel,camera,direction,error)) return false;
|
||||
const int x=qRound(pixel.x()),y=qRound(pixel.y());
|
||||
std::vector<double> samples;
|
||||
// Phone _depth_mm: local valid-depth median. Keep a small 5x5 patch;
|
||||
// reject depth edges instead of expanding onto an unrelated surface.
|
||||
for (int v=qMax(0,y-2);v<=qMin(depth.height-1,y+2);++v)
|
||||
for (int u=qMax(0,x-2);u<=qMin(depth.width-1,x+2);++u) {
|
||||
const auto *raw=reinterpret_cast<const uchar*>(depth.data.constData())+(v*depth.width+u)*bytes;
|
||||
double value=0;
|
||||
if (depth.float32) {
|
||||
const quint32 bits=qFromLittleEndian<quint32>(raw); float f=0;
|
||||
std::memcpy(&f,&bits,sizeof(f)); value=f;
|
||||
} else value=qFromLittleEndian<quint16>(raw);
|
||||
value*=depth.metresPerUnit;
|
||||
if (within(value,.05,p.maxCameraRangeM)) samples.push_back(value);
|
||||
}
|
||||
if (samples.size()<5) return fail(error,"目标点附近有效深度不足,请重新取图或选择可测量位置。");
|
||||
std::sort(samples.begin(),samples.end());
|
||||
const double z=samples[samples.size()/2];
|
||||
if (samples.back()-samples.front()>.005)
|
||||
return fail(error,"目标点处深度跳变超过 5 mm,请避开遮挡边缘或重新取图。");
|
||||
Point cp{},bp{};
|
||||
for (int i=0;i<3;++i) cp[i]=direction[i]*z/direction[2]; // Z, not Euclidean range.
|
||||
if (norm(cp)>p.maxCameraRangeM) return fail(error,"目标超出相机测量范围。");
|
||||
for (int r=0;r<3;++r) {
|
||||
bp[r]=baseCamera[r*4+3];
|
||||
for (int c=0;c<3;++c) bp[r]+=baseCamera[r*4+c]*cp[c];
|
||||
}
|
||||
if (!finite(bp) || norm(bp)>p.maxReachM) return fail(error,"深度目标超出基座工作空间。");
|
||||
base.append(bp); cameraResult.append(cp);
|
||||
}
|
||||
basePoints=base; cameraPoints=cameraResult; clear(error); return true;
|
||||
}
|
||||
|
||||
bool validateDepthSwipe(const QVector<QPointF> &pixels,const CameraModel &camera,
|
||||
const DepthImage &depth,const Matrix &baseCamera,const Parameters &p,QString *error) {
|
||||
if (pixels.size()!=2) return fail(error,"滑动需要 A/B 两点。");
|
||||
QVector<Point> ends,unused;
|
||||
if (!resolveDepthPixels(pixels,camera,depth,baseCamera,p,ends,unused,error)) return false;
|
||||
const Point segment=subtract(ends[1],ends[0]); const double length=norm(segment);
|
||||
if (length<.0001) return fail(error,"滑动端点间距不足 0.1 mm。");
|
||||
const int count=qMax(2,int(std::ceil(std::hypot(pixels[1].x()-pixels[0].x(),pixels[1].y()-pixels[0].y())/2)));
|
||||
for (int i=1;i<count;++i) {
|
||||
const double t=double(i)/count;
|
||||
QVector<Point> current;
|
||||
if (!resolveDepthPixels({pixels[0]*(1-t)+pixels[1]*t},camera,depth,baseCamera,p,current,unused,error)) return false;
|
||||
const Point delta=subtract(current[0],ends[0]);
|
||||
const double along=dot(delta,segment)/(length*length);
|
||||
if (along<-.01 || along>1.01 || norm(subtract(delta,shifted(Point{},segment,along)))>.003)
|
||||
return fail(error,"滑动路径深度偏离直线超过 3 mm,不能执行直线触控。");
|
||||
}
|
||||
clear(error); return true;
|
||||
}
|
||||
|
||||
bool buildPlan(Action action,const QVector<Point> &points,const Plane &plane,const Pose &observationActive,
|
||||
const Pose &flangeActive,const Pose &flangeSelected,const Parameters &p,Plan &plan,QString *error,bool depthTargets) {
|
||||
if (action!=Action::SingleTap && action!=Action::DoubleTap && action!=Action::Swipe)
|
||||
return fail(error,"未知触控动作。");
|
||||
if (points.isEmpty() || points.size()>2 || (action==Action::Swipe && points.size()!=2))
|
||||
return fail(error,"单击或双击需要 1 至 2 点,滑动必须恰好选择 2 点。");
|
||||
if (!validPlane(plane,error) || !validParameters(p,error)) return false;
|
||||
if (action==Action::DoubleTap && (p.doubleLiftM<p.contactOffsetM+.0005 || p.doubleLiftM>p.approachM+p.contactOffsetM))
|
||||
return fail(error,"双击短抬必须越过接触偏移至少 0.5 mm,且不超过接近点。");
|
||||
Pose observationFlange{},observationSelected{};
|
||||
if (!TcpCalibration::flangePose(observationActive,flangeActive,observationFlange,error)
|
||||
|| !TcpCalibration::toolPose(observationFlange,flangeSelected,observationSelected,error)) return false;
|
||||
if (dot(subtract(position(observationSelected),plane.origin),plane.normal)<p.approachM-1e-9)
|
||||
return fail(error,"观察 TCP 必须位于平面外侧,且离面距离不少于接近距离。");
|
||||
for (const Point &point:points) {
|
||||
if (!finite(point) || (!depthTargets && std::abs(dot(subtract(point,plane.origin),plane.normal))>1e-5))
|
||||
return fail(error,"触控目标不在已示教平面上。");
|
||||
if (depthTargets && dot(subtract(position(observationSelected),point),plane.normal)<p.approachM)
|
||||
return fail(error,"观察位必须位于每个深度目标的接近方向外侧。");
|
||||
if (norm(subtract(point,plane.origin))>p.maxTravelM)
|
||||
return fail(error,"触控目标之间的距离超过最大行程。");
|
||||
}
|
||||
if (action==Action::Swipe && norm(subtract(points[0],points[1]))<.0001)
|
||||
return fail(error,"滑动起点和终点至少间隔 0.1 mm。");
|
||||
Plan result; result.contacts=points;
|
||||
Pose previousActive=observationActive,previousSelected=observationSelected;
|
||||
double totalTravel=0;
|
||||
const auto append=[&](const QString &label,const Pose &active,const Pose &selected,
|
||||
double speed,int pause)->bool {
|
||||
Pose flange{};
|
||||
if (!TcpCalibration::flangePose(active,flangeActive,flange,error)) return false;
|
||||
if (!TcpCalibration::validPose(active) || !TcpCalibration::validPose(selected)
|
||||
|| norm(position(active))>p.maxReachM || norm(position(selected))>p.maxReachM
|
||||
|| norm(position(flange))>p.maxReachM)
|
||||
return fail(error,"规划路径超出配置的 TCP / 法兰工作空间半径。");
|
||||
const double activeTravel=norm(subtract(position(active),position(previousActive)));
|
||||
const double tipTravel=norm(subtract(position(selected),position(previousSelected)));
|
||||
if (activeTravel>p.maxTravelM || tipTravel>p.maxTravelM
|
||||
|| norm(subtract(position(active),position(observationActive)))>p.maxTravelM
|
||||
|| norm(subtract(position(selected),position(observationSelected)))>p.maxTravelM)
|
||||
return fail(error,"规划路径超出单段行程或观察位距离限制。");
|
||||
totalTravel+=std::max(activeTravel,tipTravel);
|
||||
if (totalTravel>12*p.maxTravelM || result.steps.size()>=12)
|
||||
return fail(error,"触控路径总行程或步骤数量超出限制。");
|
||||
result.steps.append(Step{label,active,speed,p.accelerationMps2,pause});
|
||||
previousActive=active; previousSelected=selected; return true;
|
||||
};
|
||||
// Check the starting poses too, including a potentially long saved tool offset.
|
||||
if (norm(position(observationActive))>p.maxReachM || norm(position(observationSelected))>p.maxReachM
|
||||
|| norm(position(observationFlange))>p.maxReachM)
|
||||
return fail(error,"观察位超出配置的 TCP / 法兰工作空间半径。");
|
||||
const auto target=[&](const QString &label,const Point &surface,double normalOffset,double speed,int pause)->bool {
|
||||
const Point xyz=shifted(surface,plane.normal,normalOffset);
|
||||
const Pose selected{{xyz[0],xyz[1],xyz[2],plane.orientationRad[0],plane.orientationRad[1],plane.orientationRad[2]}};
|
||||
Pose flange{},active{};
|
||||
if (!TcpCalibration::flangePose(selected,flangeSelected,flange,error)
|
||||
|| !TcpCalibration::toolPose(flange,flangeActive,active,error)) return false;
|
||||
return append(label,active,selected,speed,pause);
|
||||
};
|
||||
const int visits=action==Action::Swipe?1:points.size();
|
||||
for (int visit=0;visit<visits;++visit) {
|
||||
const Point &start=points[visit];
|
||||
const QString index=QString::number(visit+1);
|
||||
if (!target(QStringLiteral("接近点 ")+index,start,p.approachM,p.travelVelocityMps,0)
|
||||
|| !target(QStringLiteral("接触点 ")+index,start,-p.contactOffsetM,p.contactVelocityMps,
|
||||
action==Action::Swipe?0:p.contactDwellMs)) return false;
|
||||
if (action==Action::DoubleTap) {
|
||||
if (!target(QStringLiteral("双击短抬 ")+index,start,p.doubleLiftM-p.contactOffsetM,p.contactVelocityMps,p.doubleIntervalMs)
|
||||
|| !target(QStringLiteral("第二次接触 ")+index,start,-p.contactOffsetM,p.contactVelocityMps,p.contactDwellMs)) return false;
|
||||
}
|
||||
if (action==Action::Swipe && !target(QStringLiteral("滑动到终点"),points[1],-p.contactOffsetM,p.contactVelocityMps,p.contactDwellMs)) return false;
|
||||
const Point &end=action==Action::Swipe?points[1]:start;
|
||||
if (!target(QStringLiteral("回撤"),end,p.approachM,p.contactVelocityMps,0)
|
||||
|| !append(QStringLiteral("返回观察位"),observationActive,observationSelected,p.travelVelocityMps,0)) return false;
|
||||
}
|
||||
plan=result; clear(error); return true;
|
||||
}
|
||||
}
|
||||
83
src/touchplanner.h
Normal file
83
src/touchplanner.h
Normal file
@ -0,0 +1,83 @@
|
||||
#pragma once
|
||||
|
||||
#include "handeyestore.h"
|
||||
#include <QPointF>
|
||||
#include <QVector>
|
||||
#include <QByteArray>
|
||||
|
||||
// Offline geometry only. All distances are metres and all angles are ZYX radians.
|
||||
// The caller owns frame provenance, observation matching, controller reach/IK
|
||||
// checks, collision clearance, and execution; no hardware is accessed here.
|
||||
namespace TouchPlanner {
|
||||
using Pose = TcpCalibration::Pose;
|
||||
using Matrix = TcpCalibration::Matrix;
|
||||
using Point = std::array<double, 3>;
|
||||
|
||||
struct CameraModel {
|
||||
int width = 0, height = 0;
|
||||
double fx = 0, fy = 0, cx = 0, cy = 0;
|
||||
std::vector<double> distortion; // OpenCV Brown order: k1,k2,p1,p2[,k3[,k4,k5,k6]].
|
||||
};
|
||||
struct Plane {
|
||||
Point origin{};
|
||||
Point normal{}; // Unit outward normal, toward the taught observation tip.
|
||||
Point orientationRad{}; // Selected-tip orientation from the first contact teach.
|
||||
};
|
||||
struct DepthImage {
|
||||
int width = 0, height = 0;
|
||||
QByteArray data; // Owning raw little-endian samples, aligned to native RGB.
|
||||
bool float32 = false;
|
||||
double metresPerUnit = 0; // Explicit transport contract, never inferred from type.
|
||||
};
|
||||
struct Parameters {
|
||||
double approachM = .01;
|
||||
double contactOffsetM = 0; // Positive presses inward, opposite the outward normal.
|
||||
double doubleLiftM = .003;
|
||||
double contactVelocityMps = .01;
|
||||
double travelVelocityMps = .03;
|
||||
double accelerationMps2 = .1;
|
||||
int contactDwellMs = 80;
|
||||
int doubleIntervalMs = 100;
|
||||
double maxTravelM = .3; // Radius from observation AND maximum movement per segment.
|
||||
double maxReachM = 2; // Conservative base-origin sphere, not a substitute for IK.
|
||||
double maxCameraRangeM = 3;
|
||||
};
|
||||
enum class Action { SingleTap, DoubleTap, Swipe };
|
||||
struct Step {
|
||||
QString label;
|
||||
Pose target{}; // Target of the controller's existing active TCP.
|
||||
double velocityMps = 0;
|
||||
double accelerationMps2 = 0;
|
||||
int pauseMs = 0; // Applied after the target has been reached.
|
||||
};
|
||||
struct Plan {
|
||||
QVector<Step> steps;
|
||||
QVector<Point> contacts; // Unpressed surface points in base coordinates.
|
||||
};
|
||||
|
||||
// All functions leave output unchanged on failure and clear error on success.
|
||||
bool teachPlane(const std::array<Pose, 3> &selectedContacts,
|
||||
const Pose &observationSelected, Plane &plane, QString *error = nullptr);
|
||||
bool cameraTransform(const HandEyeStore::Record &record, const Pose &lockedBaseFlange,
|
||||
Matrix &baseCamera, QString *error = nullptr);
|
||||
// Exact-size intrinsics only; callers must establish the RGB distortion model.
|
||||
// Supports fx/fy/cx/cy + coeffs, or camera_matrix + distortion. Does not rescale.
|
||||
bool cameraModel(const QVariantMap &intrinsics, int imageWidth, int imageHeight,
|
||||
CameraModel &camera, QString *error = nullptr);
|
||||
bool resolvePixels(const QVector<QPointF> &pixels, const CameraModel &camera,
|
||||
const Matrix &baseCamera, const Plane &plane, const Parameters ¶meters,
|
||||
QVector<Point> &points, QString *error = nullptr);
|
||||
bool resolveDepthPixels(const QVector<QPointF> &pixels, const CameraModel &camera,
|
||||
const DepthImage &depth, const Matrix &baseCamera,
|
||||
const Parameters ¶meters, QVector<Point> &basePoints,
|
||||
QVector<Point> &cameraPoints, QString *error = nullptr);
|
||||
bool validateDepthSwipe(const QVector<QPointF> &pixels, const CameraModel &camera,
|
||||
const DepthImage &depth, const Matrix &baseCamera,
|
||||
const Parameters ¶meters, QString *error = nullptr);
|
||||
// Single/double tap visit 1-2 contacts sequentially, returning to observation after
|
||||
// each. Swipe requires two distinct contacts. All use approach/contact/retract.
|
||||
bool buildPlan(Action action, const QVector<Point> &points, const Plane &plane,
|
||||
const Pose &observationActive, const Pose &flangeActive,
|
||||
const Pose &flangeSelected, const Parameters ¶meters,
|
||||
Plan &plan, QString *error = nullptr, bool depthTargets = false);
|
||||
}
|
||||
228
src/touchsequencecontroller.cpp
Normal file
228
src/touchsequencecontroller.cpp
Normal file
@ -0,0 +1,228 @@
|
||||
#include "touchsequencecontroller.h"
|
||||
#include <QDateTime>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace {
|
||||
constexpr int kReadTimeoutMs = 6000;
|
||||
constexpr int kMoveTimeoutMs = 30000;
|
||||
constexpr int kSequenceTimeoutMs = 180000;
|
||||
constexpr double kPositionToleranceM = .0005;
|
||||
constexpr double kRotationToleranceRad = .2 * 3.14159265358979323846 / 180;
|
||||
|
||||
bool poseMatches(const TcpCalibration::Pose &actual, const TcpCalibration::Pose &expected)
|
||||
{
|
||||
double squaredDistance = 0;
|
||||
for (int i = 0; i < 3; ++i)
|
||||
squaredDistance += std::pow(actual[size_t(i)] - expected[size_t(i)], 2);
|
||||
if (squaredDistance > kPositionToleranceM * kPositionToleranceM)
|
||||
return false;
|
||||
TcpCalibration::Matrix a{}, b{};
|
||||
if (!TcpCalibration::poseMatrix(actual, a) || !TcpCalibration::poseMatrix(expected, b))
|
||||
return false;
|
||||
// Relative rotation, including equivalent Euler representations at +/-pi.
|
||||
double trace = 0;
|
||||
for (int row = 0; row < 3; ++row)
|
||||
for (int col = 0; col < 3; ++col)
|
||||
trace += a[size_t(row * 4 + col)] * b[size_t(row * 4 + col)];
|
||||
const double angle = std::acos(std::max(-1.0, std::min(1.0, (trace - 1) / 2)));
|
||||
return angle <= kRotationToleranceRad;
|
||||
}
|
||||
|
||||
bool stoppedHealthy(const QVariantMap &state)
|
||||
{
|
||||
return state.value("connected").toBool()
|
||||
&& !state.value("moving", true).toBool()
|
||||
&& !state.value("fault", true).toBool()
|
||||
&& !state.value("protectiveStopped", true).toBool()
|
||||
&& !state.value("emergencyStopped", true).toBool();
|
||||
}
|
||||
}
|
||||
|
||||
TouchSequenceController::TouchSequenceController(QObject *parent) : QObject(parent)
|
||||
{
|
||||
m_timeout.setSingleShot(true);
|
||||
m_deadline.setSingleShot(true);
|
||||
m_dwell.setSingleShot(true);
|
||||
m_dwell.setTimerType(Qt::PreciseTimer);
|
||||
connect(&m_timeout, &QTimer::timeout, this, [this] {
|
||||
fail(QStringLiteral("触控动作反馈超时,已请求停止;不会自动回程"));
|
||||
});
|
||||
connect(&m_deadline, &QTimer::timeout, this, [this] {
|
||||
fail(QStringLiteral("触控任务超出总时限,已请求停止;不会自动回程"));
|
||||
});
|
||||
connect(&m_dwell, &QTimer::timeout, this, [this] {
|
||||
if (m_phase == Phase::Dwelling) readPose(Phase::AfterDwellRead);
|
||||
});
|
||||
}
|
||||
|
||||
QString TouchSequenceController::commandName(quint64 token)
|
||||
{
|
||||
// RobotClient::requestTcpJogMove uses this existing command namespace.
|
||||
return QStringLiteral("TCPJog/%1").arg(token);
|
||||
}
|
||||
|
||||
void TouchSequenceController::setContext(const QString &endpoint, const QString &device,
|
||||
bool ready, const TcpCalibration::Pose &activeOffset,
|
||||
const QString &contextRevision)
|
||||
{
|
||||
if (m_endpoint != endpoint || m_device != device || m_ready != ready
|
||||
|| m_activeOffset != activeOffset || m_contextRevision != contextRevision)
|
||||
stop(); // Stop the old device before replacing its identity.
|
||||
m_endpoint = endpoint;
|
||||
m_device = device;
|
||||
m_ready = ready;
|
||||
m_activeOffset = activeOffset;
|
||||
m_contextRevision = contextRevision;
|
||||
}
|
||||
|
||||
bool TouchSequenceController::start(const QVector<Step> &steps,
|
||||
const TcpCalibration::Pose &expectedInitialPose)
|
||||
{
|
||||
if (running()) return false;
|
||||
bool valid = m_ready && !m_endpoint.trimmed().isEmpty() && !m_device.trimmed().isEmpty()
|
||||
&& TcpCalibration::validPose(m_activeOffset)
|
||||
&& TcpCalibration::validPose(expectedInitialPose)
|
||||
&& !steps.isEmpty() && steps.size() <= 128;
|
||||
for (const auto &step : steps) {
|
||||
valid = valid && TcpCalibration::validPose(step.target)
|
||||
&& std::isfinite(step.speed) && step.speed > 0 && step.speed <= .05
|
||||
&& std::isfinite(step.acceleration) && step.acceleration > 0 && step.acceleration <= .5
|
||||
&& step.dwellMs >= 0 && step.dwellMs <= 5000;
|
||||
}
|
||||
if (!valid) {
|
||||
emit errorOccurred(QStringLiteral("触控路径或机械臂上下文无效,请核对连接、活动 TCP 和运动参数"));
|
||||
return false;
|
||||
}
|
||||
m_steps = steps;
|
||||
m_expected = expectedInitialPose;
|
||||
m_index = 0;
|
||||
m_deadline.start(kSequenceTimeoutMs);
|
||||
readPose(Phase::InitialRead);
|
||||
return true;
|
||||
}
|
||||
|
||||
void TouchSequenceController::readPose(Phase phase)
|
||||
{
|
||||
m_phase = phase;
|
||||
++m_token;
|
||||
m_captureIssuedAtMs = QDateTime::currentMSecsSinceEpoch();
|
||||
m_timeout.start(kReadTimeoutMs);
|
||||
emit captureRequested(m_device, m_token);
|
||||
}
|
||||
|
||||
void TouchSequenceController::moveNext()
|
||||
{
|
||||
if (!running()) return;
|
||||
const Step step = m_steps.at(m_index);
|
||||
m_phase = Phase::Moving;
|
||||
const quint64 token = ++m_token;
|
||||
m_timeout.start(kMoveTimeoutMs);
|
||||
emit progressChanged(m_index + 1, m_steps.size(), step.label);
|
||||
// A direct progress listener may cancel or change context synchronously.
|
||||
if (m_phase != Phase::Moving || m_token != token) return;
|
||||
QVariantMap target;
|
||||
const char *keys[] = {"x", "y", "z", "rx", "ry", "rz"};
|
||||
for (int i = 0; i < 6; ++i) target[keys[i]] = step.target[size_t(i)];
|
||||
emit moveRequested(m_device, target, step.speed, step.acceleration, token);
|
||||
}
|
||||
|
||||
void TouchSequenceController::acceptPose(quint64 token, const QString &device,
|
||||
const QVariantMap &pose, const QVariantMap &state,
|
||||
bool success, const QString &detail)
|
||||
{
|
||||
if ((m_phase != Phase::InitialRead && m_phase != Phase::VerifyRead
|
||||
&& m_phase != Phase::AfterDwellRead) || token != m_token || device != m_device)
|
||||
return;
|
||||
if (!success) {
|
||||
fail(detail.isEmpty() ? QStringLiteral("触控任务读取实时位姿失败") : detail);
|
||||
return;
|
||||
}
|
||||
if (!stoppedHealthy(state)) {
|
||||
fail(QStringLiteral("机械臂未停稳、未连接或处于故障/停止状态,已取消触控任务"));
|
||||
return;
|
||||
}
|
||||
bool requestedOk = false, receivedOk = false;
|
||||
const qint64 requested = state.value("requestedAtMs").toLongLong(&requestedOk);
|
||||
const qint64 received = state.value("receivedAtMs").toLongLong(&receivedOk);
|
||||
const qint64 now = QDateTime::currentMSecsSinceEpoch();
|
||||
if (!requestedOk || !receivedOk || requested < m_captureIssuedAtMs
|
||||
|| received < requested || received > now + 50 || now - received > 1500
|
||||
|| state.value("source").toString() != QStringLiteral("getRobotState.actual_tcp_pose")) {
|
||||
fail(QStringLiteral("触控任务收到过期或来源不明的位姿,已请求停止"));
|
||||
return;
|
||||
}
|
||||
TcpCalibration::Pose actual{};
|
||||
const char *keys[] = {"x", "y", "z", "rx", "ry", "rz"};
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
bool ok = false;
|
||||
actual[size_t(i)] = pose.value(keys[i]).toDouble(&ok);
|
||||
if (!ok || !std::isfinite(actual[size_t(i)])) {
|
||||
fail(QStringLiteral("触控任务收到无效的 TCP 位姿"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!poseMatches(actual, m_expected)) {
|
||||
fail(m_phase == Phase::InitialRead
|
||||
? QStringLiteral("当前位姿已偏离观察位(允许 0.5 mm / 0.2°),请重新定位并确认画面")
|
||||
: QStringLiteral("实际 TCP 未到达触控路径目标(允许 0.5 mm / 0.2°),已停止且不会自动回程"));
|
||||
return;
|
||||
}
|
||||
m_timeout.stop();
|
||||
if (m_phase == Phase::InitialRead) {
|
||||
moveNext();
|
||||
} else if (m_phase == Phase::VerifyRead && m_steps.at(m_index).dwellMs > 0) {
|
||||
m_phase = Phase::Dwelling;
|
||||
++m_token;
|
||||
m_dwell.start(m_steps.at(m_index).dwellMs);
|
||||
} else {
|
||||
completeStep();
|
||||
}
|
||||
}
|
||||
|
||||
void TouchSequenceController::acceptCommand(const QString &command, bool success,
|
||||
const QString &detail)
|
||||
{
|
||||
if (m_phase != Phase::Moving || command != commandName(m_token)) return;
|
||||
if (!success) {
|
||||
fail(detail.isEmpty() ? QStringLiteral("触控运动命令失败") : detail);
|
||||
return;
|
||||
}
|
||||
m_expected = m_steps.at(m_index).target;
|
||||
readPose(Phase::VerifyRead);
|
||||
}
|
||||
|
||||
void TouchSequenceController::completeStep()
|
||||
{
|
||||
++m_index;
|
||||
if (m_index == m_steps.size())
|
||||
finish(true, QStringLiteral("触控路径已完成,实际 TCP 已到达最终目标"), false);
|
||||
else
|
||||
moveNext();
|
||||
}
|
||||
|
||||
void TouchSequenceController::finish(bool success, const QString &detail, bool requestStop)
|
||||
{
|
||||
if (!running()) return;
|
||||
const QString device = m_device;
|
||||
m_phase = Phase::Idle;
|
||||
++m_token;
|
||||
m_timeout.stop();
|
||||
m_deadline.stop();
|
||||
m_dwell.stop();
|
||||
m_steps.clear();
|
||||
if (requestStop) emit stopRequested(device);
|
||||
emit finished(success, detail);
|
||||
}
|
||||
|
||||
void TouchSequenceController::stop()
|
||||
{
|
||||
finish(false, QStringLiteral("触控任务已取消并请求停止;不会自动回程"), true);
|
||||
}
|
||||
|
||||
void TouchSequenceController::fail(const QString &message)
|
||||
{
|
||||
if (!running()) return;
|
||||
finish(false, message, true);
|
||||
emit errorOccurred(message);
|
||||
}
|
||||
65
src/touchsequencecontroller.h
Normal file
65
src/touchsequencecontroller.h
Normal file
@ -0,0 +1,65 @@
|
||||
#pragma once
|
||||
|
||||
#include "tcpcalibration.h"
|
||||
#include <QObject>
|
||||
#include <QTimer>
|
||||
#include <QVariantMap>
|
||||
#include <QVector>
|
||||
|
||||
// Runs an already reviewed path of targets for the driver's ACTIVE TCP.
|
||||
// Connect its requests to the existing RobotClient; it owns no transport.
|
||||
class TouchSequenceController : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
struct Step {
|
||||
TcpCalibration::Pose target{};
|
||||
double speed = .01;
|
||||
double acceleration = .1;
|
||||
int dwellMs = 0;
|
||||
QString label;
|
||||
};
|
||||
|
||||
explicit TouchSequenceController(QObject *parent = nullptr);
|
||||
void setContext(const QString &endpoint, const QString &device, bool ready,
|
||||
const TcpCalibration::Pose &activeOffset,
|
||||
const QString &contextRevision = QString());
|
||||
// expectedInitialPose is the taught observation pose, or a separately
|
||||
// verified current pose for an explicitly requested return movement.
|
||||
bool start(const QVector<Step> &steps, const TcpCalibration::Pose &expectedInitialPose);
|
||||
bool running() const { return m_phase != Phase::Idle; }
|
||||
static QString commandName(quint64 token);
|
||||
|
||||
public slots:
|
||||
void stop();
|
||||
void acceptPose(quint64 token, const QString &device, const QVariantMap &pose,
|
||||
const QVariantMap &state, bool success, const QString &detail);
|
||||
void acceptCommand(const QString &command, bool success, const QString &detail);
|
||||
|
||||
signals:
|
||||
void captureRequested(const QString &device, quint64 token);
|
||||
void moveRequested(const QString &device, const QVariantMap &target,
|
||||
double speed, double acceleration, quint64 token);
|
||||
void stopRequested(const QString &device);
|
||||
void progressChanged(int step, int total, const QString &label);
|
||||
void errorOccurred(const QString &message);
|
||||
void finished(bool success, const QString &detail);
|
||||
|
||||
private:
|
||||
enum class Phase { Idle, InitialRead, Moving, VerifyRead, Dwelling, AfterDwellRead };
|
||||
void readPose(Phase phase);
|
||||
void moveNext();
|
||||
void completeStep();
|
||||
void fail(const QString &message);
|
||||
void finish(bool success, const QString &detail, bool requestStop);
|
||||
|
||||
QString m_endpoint, m_device, m_contextRevision;
|
||||
TcpCalibration::Pose m_activeOffset{}, m_expected{};
|
||||
bool m_ready = false;
|
||||
Phase m_phase = Phase::Idle;
|
||||
QVector<Step> m_steps;
|
||||
int m_index = 0;
|
||||
quint64 m_token = quint64(1) << 59;
|
||||
qint64 m_captureIssuedAtMs = 0;
|
||||
QTimer m_timeout, m_deadline, m_dwell;
|
||||
};
|
||||
192
src/touchvideowidget.cpp
Normal file
192
src/touchvideowidget.cpp
Normal file
@ -0,0 +1,192 @@
|
||||
#include "touchvideowidget.h"
|
||||
|
||||
#include <QMouseEvent>
|
||||
#include <QPainter>
|
||||
|
||||
#include <cmath>
|
||||
|
||||
namespace {
|
||||
QRect imageRectangle(const QSize &widgetSize, const QSize &imageSize)
|
||||
{
|
||||
if (widgetSize.isEmpty() || imageSize.isEmpty()) return {};
|
||||
QSize target = imageSize;
|
||||
target.scale(widgetSize, Qt::KeepAspectRatio);
|
||||
return QRect((widgetSize.width() - target.width()) / 2,
|
||||
(widgetSize.height() - target.height()) / 2,
|
||||
target.width(), target.height());
|
||||
}
|
||||
|
||||
QRectF frameRectangle(const QSize &widgetSize, const QSize &imageSize, VideoPixelFormat format)
|
||||
{
|
||||
if (format == VideoPixelFormat::RGBA) return imageRectangle(widgetSize, imageSize);
|
||||
if (widgetSize.isEmpty() || imageSize.isEmpty()) return {};
|
||||
// The GL video renderer preserves fractional dimensions and centres the
|
||||
// quad exactly; its geometry differs from the integer RGBA image path.
|
||||
const double scale = qMin(double(widgetSize.width()) / imageSize.width(),
|
||||
double(widgetSize.height()) / imageSize.height());
|
||||
const QSizeF target(imageSize.width() * scale, imageSize.height() * scale);
|
||||
return QRectF((widgetSize.width() - target.width()) / 2,
|
||||
(widgetSize.height() - target.height()) / 2,
|
||||
target.width(), target.height());
|
||||
}
|
||||
|
||||
bool mapPoint(const QPointF &position, const QRectF &area, const QSize &imageSize, QPointF *pixel)
|
||||
{
|
||||
if (!pixel || !std::isfinite(position.x()) || !std::isfinite(position.y())
|
||||
|| imageSize.isEmpty() || area.isEmpty()
|
||||
|| position.x() < area.x() || position.y() < area.y()
|
||||
|| position.x() >= area.x() + area.width()
|
||||
|| position.y() >= area.y() + area.height()) return false;
|
||||
const double x = (position.x() - area.x()) * imageSize.width() / area.width() - .5;
|
||||
const double y = (position.y() - area.y()) * imageSize.height() / area.height() - .5;
|
||||
*pixel = QPointF(qBound(0.0, x, double(imageSize.width() - 1)),
|
||||
qBound(0.0, y, double(imageSize.height() - 1)));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
TouchVideoWidget::TouchVideoWidget(QWidget *parent) : VideoRenderWidget(parent)
|
||||
{
|
||||
setMinimumSize(320, 240);
|
||||
}
|
||||
|
||||
void TouchVideoWidget::present(const VideoFrame &frame)
|
||||
{
|
||||
if (!frame.isValid()) return;
|
||||
m_latestFrame = frame;
|
||||
if (m_locked) return;
|
||||
m_imageSize = QSize(frame.width, frame.height);
|
||||
setFrame(frame);
|
||||
}
|
||||
|
||||
bool TouchVideoWidget::lockImage(const QImage &image)
|
||||
{
|
||||
if (image.isNull()) return false;
|
||||
m_locked = true;
|
||||
m_imageSize = image.size();
|
||||
m_lockedFormat = VideoPixelFormat::RGBA;
|
||||
setImage(image);
|
||||
clearSelection();
|
||||
setCursor(Qt::CrossCursor);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TouchVideoWidget::lockFrame(const VideoFrame &frame)
|
||||
{
|
||||
if (!frame.isValid()) return false;
|
||||
m_locked = true;
|
||||
m_imageSize = QSize(frame.width, frame.height);
|
||||
m_lockedFormat = frame.format;
|
||||
// VideoFrame keeps its backing AVFrame alive through its shared owner.
|
||||
// Keep the exact frame, including timestamps and matching intrinsics.
|
||||
setFrame(frame);
|
||||
clearSelection();
|
||||
setCursor(Qt::CrossCursor);
|
||||
return true;
|
||||
}
|
||||
|
||||
void TouchVideoWidget::unlock()
|
||||
{
|
||||
m_locked = false;
|
||||
m_lockedFormat = VideoPixelFormat::Invalid;
|
||||
clearSelection();
|
||||
unsetCursor();
|
||||
if (m_latestFrame.isValid()) {
|
||||
m_imageSize = QSize(m_latestFrame.width, m_latestFrame.height);
|
||||
setFrame(m_latestFrame);
|
||||
} else {
|
||||
m_imageSize = {};
|
||||
VideoRenderWidget::clearFrame();
|
||||
}
|
||||
}
|
||||
|
||||
void TouchVideoWidget::clearFrame(const QString &message)
|
||||
{
|
||||
m_latestFrame = {};
|
||||
m_imageSize = {};
|
||||
m_locked = false;
|
||||
m_lockedFormat = VideoPixelFormat::Invalid;
|
||||
clearSelection();
|
||||
unsetCursor();
|
||||
VideoRenderWidget::clearFrame(message);
|
||||
}
|
||||
|
||||
void TouchVideoWidget::clearSelection()
|
||||
{
|
||||
if (m_points.isEmpty()) return;
|
||||
m_points.clear();
|
||||
update();
|
||||
emit pointsChanged();
|
||||
}
|
||||
|
||||
void TouchVideoWidget::setMaxPoints(int count)
|
||||
{
|
||||
count = qBound(1, count, 2);
|
||||
if (count == m_maxPoints) return;
|
||||
m_maxPoints = count;
|
||||
clearSelection();
|
||||
}
|
||||
|
||||
bool TouchVideoWidget::mapToImage(const QPointF &position, const QSizeF &widgetSize,
|
||||
const QSize &imageSize, QPointF *pixel)
|
||||
{
|
||||
if (!std::isfinite(widgetSize.width()) || !std::isfinite(widgetSize.height())
|
||||
|| widgetSize.isEmpty() || imageSize.isEmpty()) return false;
|
||||
return mapPoint(position, imageRectangle(widgetSize.toSize(), imageSize), imageSize, pixel);
|
||||
}
|
||||
|
||||
void TouchVideoWidget::mousePressEvent(QMouseEvent *event)
|
||||
{
|
||||
QPointF pixel;
|
||||
if (event->button() == Qt::LeftButton && !m_locked && !m_imageSize.isEmpty()
|
||||
&& mapPoint(event->localPos(), frameRectangle(size(), m_imageSize, m_latestFrame.format), m_imageSize, &pixel)) {
|
||||
emit selectionBlocked();
|
||||
event->accept();
|
||||
return;
|
||||
}
|
||||
if (event->button() != Qt::LeftButton || !m_locked
|
||||
|| !mapPoint(event->localPos(), frameRectangle(size(), m_imageSize, m_lockedFormat), m_imageSize, &pixel)) {
|
||||
VideoRenderWidget::mousePressEvent(event);
|
||||
return;
|
||||
}
|
||||
if (m_points.size() >= m_maxPoints) m_points.clear();
|
||||
m_points.append(pixel);
|
||||
update();
|
||||
emit pointsChanged();
|
||||
event->accept();
|
||||
}
|
||||
|
||||
void TouchVideoWidget::paintGL()
|
||||
{
|
||||
VideoRenderWidget::paintGL();
|
||||
if (!m_locked || m_points.isEmpty() || m_imageSize.isEmpty()) return;
|
||||
const QRectF area = frameRectangle(size(), m_imageSize, m_lockedFormat);
|
||||
if (area.isEmpty()) return;
|
||||
QVector<QPointF> screenPoints;
|
||||
for (const QPointF &point : m_points) {
|
||||
screenPoints.append(QPointF(area.x() + (point.x() + .5) * area.width() / m_imageSize.width(),
|
||||
area.y() + (point.y() + .5) * area.height() / m_imageSize.height()));
|
||||
}
|
||||
QPainter painter(this);
|
||||
painter.setRenderHint(QPainter::Antialiasing);
|
||||
painter.setClipRect(area);
|
||||
painter.setPen(QPen(QColor(QStringLiteral("#f4d26c")), 2));
|
||||
if (screenPoints.size() == 2) painter.drawLine(screenPoints[0], screenPoints[1]);
|
||||
for (int i = 0; i < screenPoints.size(); ++i) {
|
||||
const QPointF center = screenPoints[i];
|
||||
painter.setPen(QPen(i == 0 ? QColor(QStringLiteral("#4cdd9b"))
|
||||
: QColor(QStringLiteral("#ffac60")), 2));
|
||||
painter.setBrush(QColor(14, 17, 21, 180));
|
||||
painter.drawEllipse(center, 7, 7);
|
||||
const QString label = i == 0 ? QStringLiteral("A") : QStringLiteral("B");
|
||||
const qreal labelWidth = painter.fontMetrics().horizontalAdvance(label) + 8;
|
||||
const qreal labelHeight = painter.fontMetrics().height() + 4;
|
||||
const qreal left = qBound(qreal(area.left()), center.x() + 11,
|
||||
qMax(qreal(area.left()), area.x() + area.width() - labelWidth));
|
||||
const qreal top = qBound(qreal(area.top()), center.y() - labelHeight - 3,
|
||||
qMax(qreal(area.top()), area.y() + area.height() - labelHeight));
|
||||
const QRectF labelRect(left, top, labelWidth, labelHeight);
|
||||
painter.fillRect(labelRect, QColor(14, 17, 21, 210));
|
||||
painter.drawText(labelRect, Qt::AlignCenter, label);
|
||||
}
|
||||
}
|
||||
50
src/touchvideowidget.h
Normal file
50
src/touchvideowidget.h
Normal file
@ -0,0 +1,50 @@
|
||||
#pragma once
|
||||
|
||||
#include "videorenderwidget.h"
|
||||
|
||||
#include <QPointF>
|
||||
#include <QSizeF>
|
||||
#include <QVector>
|
||||
|
||||
class QMouseEvent;
|
||||
|
||||
// Presents an existing camera session. Selection belongs to a frozen native
|
||||
// image, whose matching intrinsics and robot pose are owned by the caller.
|
||||
class TouchVideoWidget : public VideoRenderWidget
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit TouchVideoWidget(QWidget *parent = nullptr);
|
||||
|
||||
void present(const VideoFrame &frame);
|
||||
bool lockImage(const QImage &image);
|
||||
bool lockFrame(const VideoFrame &frame);
|
||||
void unlock();
|
||||
void clearFrame(const QString &message = QStringLiteral("暂无画面"));
|
||||
void clearSelection();
|
||||
void setMaxPoints(int count);
|
||||
QVector<QPointF> selectedPoints() const { return m_points; }
|
||||
bool locked() const { return m_locked; }
|
||||
QSize imageSize() const { return m_imageSize; }
|
||||
|
||||
// OpenCV coordinates: the centre of the first pixel is (0, 0).
|
||||
// Uses the same integer letterbox rectangle as the base RGBA renderer.
|
||||
static bool mapToImage(const QPointF &position, const QSizeF &widgetSize,
|
||||
const QSize &imageSize, QPointF *pixel);
|
||||
|
||||
signals:
|
||||
void pointsChanged();
|
||||
void selectionBlocked();
|
||||
|
||||
protected:
|
||||
void mousePressEvent(QMouseEvent *event) override;
|
||||
void paintGL() override;
|
||||
|
||||
private:
|
||||
VideoFrame m_latestFrame;
|
||||
QSize m_imageSize;
|
||||
VideoPixelFormat m_lockedFormat = VideoPixelFormat::Invalid;
|
||||
QVector<QPointF> m_points;
|
||||
int m_maxPoints = 1;
|
||||
bool m_locked = false;
|
||||
};
|
||||
@ -66,6 +66,7 @@
|
||||
#include <QMatrix3x3>
|
||||
#include <QMouseEvent>
|
||||
#include <QProgressBar>
|
||||
#include <QPointer>
|
||||
#include <QPushButton>
|
||||
#include <QQuaternion>
|
||||
#include <QSignalBlocker>
|
||||
@ -692,7 +693,29 @@ void UrdfViewerWidget::setLoading(bool loading, const QString &message)
|
||||
|
||||
UrdfViewerWidget::~UrdfViewerWidget()
|
||||
{
|
||||
// Qt3DWindow's aspect engine owns and synchronously tears down the scene.
|
||||
if (m_demoTimer)
|
||||
m_demoTimer->stop();
|
||||
|
||||
// Qt 5.12/MinGW has a reproducible access violation in Qt53DRender.dll
|
||||
// when an embedded Qt3DWindow is destroyed while its render aspect is
|
||||
// winding down. Detach this process-lifetime viewer so normal QWidget
|
||||
// destruction cannot enter the faulty Qt3D teardown path; the OS reclaims
|
||||
// it immediately when the process exits.
|
||||
if (m_viewContainer)
|
||||
m_viewContainer->removeEventFilter(this);
|
||||
if (m_view)
|
||||
m_view->removeEventFilter(this);
|
||||
if (m_viewContainer) {
|
||||
m_layout->removeWidget(m_viewContainer);
|
||||
m_viewContainer->hide();
|
||||
m_viewContainer->setParent(nullptr);
|
||||
}
|
||||
m_viewContainer = nullptr;
|
||||
m_view = nullptr;
|
||||
m_camera = nullptr;
|
||||
m_teachingRayCaster = nullptr;
|
||||
m_modelRoot = nullptr;
|
||||
m_rootEntity = nullptr;
|
||||
}
|
||||
|
||||
void UrdfViewerWidget::showEvent(QShowEvent *event)
|
||||
@ -916,8 +939,7 @@ bool UrdfViewerWidget::loadUrdf(const QString &filePath)
|
||||
return false;
|
||||
}
|
||||
|
||||
setLoading(true, QStringLiteral("正在初始化 Qt3D 场景…"));
|
||||
ensureSceneInitialized();
|
||||
setLoading(true, QStringLiteral("正在解析 URDF 关节数据…"));
|
||||
m_statusLabel->setText(QStringLiteral("正在解析 %1…").arg(fileInfo.fileName()));
|
||||
|
||||
QFile file(fileInfo.absoluteFilePath());
|
||||
@ -939,6 +961,8 @@ bool UrdfViewerWidget::loadUrdf(const QString &filePath)
|
||||
return false;
|
||||
}
|
||||
|
||||
ensureSceneInitialized();
|
||||
|
||||
clearModel();
|
||||
m_currentFile = fileInfo.absoluteFilePath();
|
||||
m_urdfDirectory = fileInfo.absolutePath();
|
||||
@ -946,7 +970,9 @@ bool UrdfViewerWidget::loadUrdf(const QString &filePath)
|
||||
m_pathEdit->setText(fileInfo.fileName());
|
||||
m_pathEdit->setToolTip(QDir::toNativeSeparators(m_currentFile));
|
||||
m_reloadButton->setEnabled(true);
|
||||
m_modelRoot = new Qt3DCore::QEntity(m_rootEntity);
|
||||
// Publish the complete component tree only after construction. Qt 5.12
|
||||
// must not synchronize a partially built model in the render aspect.
|
||||
m_modelRoot = new Qt3DCore::QEntity;
|
||||
m_modelRoot->setObjectName(QStringLiteral("urdfModelRoot"));
|
||||
|
||||
std::function<void(const urdf::LinkConstSharedPtr &, Qt3DCore::QEntity *,
|
||||
@ -1041,9 +1067,13 @@ bool UrdfViewerWidget::loadUrdf(const QString &filePath)
|
||||
QQuaternion::fromAxisAndAngle(1.0f, 0.0f, 0.0f, 90.0f));
|
||||
}
|
||||
Qt3DRender::QSceneLoader *loader = new Qt3DRender::QSceneLoader(geometryEntity);
|
||||
const QPointer<Qt3DRender::QSceneLoader> guardedLoader(loader);
|
||||
const QPointer<Qt3DCore::QEntity> guardedGeometry(geometryEntity);
|
||||
connect(loader, &Qt3DRender::QSceneLoader::statusChanged, this,
|
||||
[this, loader, source, geometryEntity, teachingJointName]
|
||||
[this, guardedLoader, source, guardedGeometry, teachingJointName]
|
||||
(Qt3DRender::QSceneLoader::Status status) {
|
||||
if (!guardedLoader || !guardedGeometry)
|
||||
return;
|
||||
if (status == Qt3DRender::QSceneLoader::Error) {
|
||||
m_statusLabel->setText(
|
||||
QStringLiteral("网格加载失败 · 请检查 Qt3D Assimp 插件"));
|
||||
@ -1051,12 +1081,12 @@ bool UrdfViewerWidget::loadUrdf(const QString &filePath)
|
||||
QStringLiteral("Qt3D 无法加载网格:%1").arg(source));
|
||||
} else if (status == Qt3DRender::QSceneLoader::Ready
|
||||
&& !teachingJointName.isEmpty()) {
|
||||
const QStringList entityNames = loader->entityNames();
|
||||
const QStringList entityNames = guardedLoader->entityNames();
|
||||
for (const QString &entityName : entityNames) {
|
||||
Qt3DCore::QEntity *loadedEntity = loader->entity(entityName);
|
||||
Qt3DCore::QEntity *loadedEntity = guardedLoader->entity(entityName);
|
||||
if (!loadedEntity)
|
||||
continue;
|
||||
if (loader->component(
|
||||
if (guardedLoader->component(
|
||||
entityName,
|
||||
Qt3DRender::QSceneLoader::GeometryRendererComponent)) {
|
||||
attachTeachingPicker(loadedEntity, teachingJointName);
|
||||
@ -1064,7 +1094,7 @@ bool UrdfViewerWidget::loadUrdf(const QString &filePath)
|
||||
attachTeachingPickersRecursively(loadedEntity,
|
||||
teachingJointName);
|
||||
}
|
||||
attachTeachingPickersRecursively(geometryEntity,
|
||||
attachTeachingPickersRecursively(guardedGeometry.data(),
|
||||
teachingJointName);
|
||||
}
|
||||
if (m_view)
|
||||
@ -1135,6 +1165,7 @@ bool UrdfViewerWidget::loadUrdf(const QString &filePath)
|
||||
for (const QString &jointName : m_jointOrder)
|
||||
m_jointPositions.insert(jointName, m_latestTelemetryPositions.value(jointName, 0.0));
|
||||
applyJointPositions(m_jointPositions);
|
||||
m_modelRoot->setParent(m_rootEntity);
|
||||
const int linkCount = static_cast<int>(model->links_.size());
|
||||
const int jointCount = static_cast<int>(model->joints_.size());
|
||||
m_modelSummary = QStringLiteral("%1 个 Link · %2 个 Joint")
|
||||
@ -1638,18 +1669,16 @@ QString UrdfViewerWidget::resolveMeshPath(const QString &uri) const
|
||||
|
||||
void UrdfViewerWidget::scheduleViewAll()
|
||||
{
|
||||
// QCamera::viewEntity() starts a backend bounding-volume query. In Qt
|
||||
// 5.12 on Windows that query can race the first scene synchronization and
|
||||
// crash inside Qt53DRender.dll. The viewer already has a deterministic
|
||||
// camera in resetView(), so only request frames after the scene settles.
|
||||
QTimer::singleShot(120, this, [this]() {
|
||||
if (m_camera && m_modelRoot) {
|
||||
m_camera->viewEntity(m_modelRoot);
|
||||
if (m_view)
|
||||
if (m_view && m_modelRoot)
|
||||
m_view->requestUpdate();
|
||||
}
|
||||
});
|
||||
QTimer::singleShot(700, this, [this]() {
|
||||
if (m_camera && m_modelRoot) {
|
||||
m_camera->viewEntity(m_modelRoot);
|
||||
if (m_view)
|
||||
if (m_view && m_modelRoot)
|
||||
m_view->requestUpdate();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@ -201,6 +201,8 @@ struct VideoDecoder::Impl
|
||||
}
|
||||
|
||||
VideoFrame output;
|
||||
output.presentationTimestamp = frame->pts != AV_NOPTS_VALUE
|
||||
? frame->pts : frame->best_effort_timestamp;
|
||||
output.width = sourceFrame->width;
|
||||
output.height = sourceFrame->height;
|
||||
const AVPixelFormat sourceFormat =
|
||||
|
||||
@ -2,7 +2,9 @@
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QMetaType>
|
||||
#include <QVariantMap>
|
||||
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
|
||||
enum class VideoPixelFormat
|
||||
@ -25,6 +27,10 @@ struct VideoFrame
|
||||
int stride1 = 0;
|
||||
int stride2 = 0;
|
||||
std::shared_ptr<void> owner;
|
||||
// Original decoded AVFrame timestamp, before any hardware-to-CPU transfer.
|
||||
qint64 presentationTimestamp = std::numeric_limits<qint64>::min();
|
||||
QVariantMap intrinsics;
|
||||
QVariantMap metadata;
|
||||
|
||||
bool isValid() const
|
||||
{
|
||||
|
||||
@ -77,11 +77,51 @@ VideoRenderWidget::~VideoRenderWidget()
|
||||
}
|
||||
}
|
||||
|
||||
void VideoRenderWidget::setFrameAspectLayoutEnabled(bool enabled)
|
||||
{
|
||||
m_frameAspectLayout = enabled;
|
||||
QSizePolicy policy(QSizePolicy::Expanding, enabled ? QSizePolicy::Fixed : QSizePolicy::Expanding);
|
||||
policy.setHeightForWidth(enabled);
|
||||
setSizePolicy(policy);
|
||||
if (enabled) updateAspectHeight();
|
||||
else { setMinimumHeight(0); setMaximumHeight(QWIDGETSIZE_MAX); }
|
||||
updateGeometry();
|
||||
}
|
||||
|
||||
int VideoRenderWidget::heightForWidth(int width) const
|
||||
{
|
||||
return m_frameAspectLayout ? qMax(1, qRound(double(width) * m_layoutFrameSize.height()
|
||||
/ m_layoutFrameSize.width())) : -1;
|
||||
}
|
||||
|
||||
QSize VideoRenderWidget::sizeHint() const
|
||||
{
|
||||
return m_frameAspectLayout ? QSize(640,heightForWidth(640)) : QOpenGLWidget::sizeHint();
|
||||
}
|
||||
|
||||
void VideoRenderWidget::updateAspectHeight()
|
||||
{
|
||||
if (!m_frameAspectLayout) return;
|
||||
const int wanted = heightForWidth(width());
|
||||
if (minimumHeight() != wanted || maximumHeight() != wanted) setFixedHeight(wanted);
|
||||
}
|
||||
|
||||
void VideoRenderWidget::resizeEvent(QResizeEvent *event)
|
||||
{
|
||||
QOpenGLWidget::resizeEvent(event);
|
||||
updateAspectHeight();
|
||||
}
|
||||
|
||||
void VideoRenderWidget::setFrame(const VideoFrame &frame)
|
||||
{
|
||||
if (!frame.isValid())
|
||||
return;
|
||||
m_frame = frame;
|
||||
if (m_layoutFrameSize != QSize(frame.width, frame.height)) {
|
||||
m_layoutFrameSize = QSize(frame.width, frame.height);
|
||||
updateAspectHeight();
|
||||
if (m_frameAspectLayout) updateGeometry();
|
||||
}
|
||||
m_message.clear();
|
||||
m_frameDirty = true;
|
||||
update();
|
||||
|
||||
@ -23,10 +23,15 @@ public:
|
||||
void setImage(const QImage &image);
|
||||
void clearFrame(const QString &message = QStringLiteral("暂无画面"));
|
||||
bool hasFrame() const { return m_frame.isValid(); }
|
||||
// Opt-in for calibration panels; other video pages keep their layout.
|
||||
void setFrameAspectLayoutEnabled(bool enabled);
|
||||
int heightForWidth(int width) const override;
|
||||
QSize sizeHint() const override;
|
||||
|
||||
protected:
|
||||
void initializeGL() override;
|
||||
void paintGL() override;
|
||||
void resizeEvent(QResizeEvent *event) override;
|
||||
|
||||
private:
|
||||
void releaseTextures();
|
||||
@ -34,6 +39,9 @@ private:
|
||||
unsigned int format, const QByteArray &data,
|
||||
int textureIndex);
|
||||
void drawMessage(const QString &message);
|
||||
void updateAspectHeight();
|
||||
bool m_frameAspectLayout = false;
|
||||
QSize m_layoutFrameSize{640, 480}; // Placeholder until the first camera frame.
|
||||
|
||||
std::unique_ptr<QOpenGLShaderProgram> m_program;
|
||||
VideoFrame m_frame;
|
||||
|
||||
205
styles.qss
205
styles.qss
@ -747,9 +747,51 @@ QTabWidget#armMotionCommandTabs QTabBar::tab:selected {
|
||||
font-weight: 600;
|
||||
}
|
||||
QSplitter#armTargetTables::handle {
|
||||
background: #dfe5ec;
|
||||
width: 1px;
|
||||
margin: 26px 5px 4px 5px;
|
||||
background: transparent;
|
||||
width: 12px;
|
||||
}
|
||||
QWidget#armTargetGroup {
|
||||
background: transparent;
|
||||
}
|
||||
QTableWidget#leftMotionTable,
|
||||
QTableWidget#motionTable {
|
||||
background: #ffffff;
|
||||
alternate-background-color: #f8fafc;
|
||||
border: 1px solid #dce3ea;
|
||||
border-radius: 6px;
|
||||
color: #26323d;
|
||||
}
|
||||
QTableWidget#leftMotionTable QHeaderView::section,
|
||||
QTableWidget#motionTable QHeaderView::section {
|
||||
background: #eef3f7;
|
||||
color: #526171;
|
||||
border: none;
|
||||
border-bottom: 1px solid #d7e0e8;
|
||||
padding: 6px 8px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
QTableWidget#leftMotionTable::item,
|
||||
QTableWidget#motionTable::item {
|
||||
padding: 3px 8px;
|
||||
border-bottom: 1px solid #edf1f4;
|
||||
}
|
||||
QTableWidget#leftMotionTable QDoubleSpinBox,
|
||||
QTableWidget#motionTable QDoubleSpinBox {
|
||||
min-height: 24px;
|
||||
padding: 1px 7px;
|
||||
background: #f5f8fb;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 4px;
|
||||
color: #1d5fa7;
|
||||
font-weight: 600;
|
||||
}
|
||||
QTableWidget#leftMotionTable QDoubleSpinBox:hover,
|
||||
QTableWidget#motionTable QDoubleSpinBox:hover,
|
||||
QTableWidget#leftMotionTable QDoubleSpinBox:focus,
|
||||
QTableWidget#motionTable QDoubleSpinBox:focus {
|
||||
background: #ffffff;
|
||||
border-color: #6aa7ea;
|
||||
}
|
||||
|
||||
QFrame#urdfToolbar, QFrame#urdfStatusBar {
|
||||
@ -1357,9 +1399,9 @@ QTabWidget#armJogModeTabs::pane {
|
||||
background: #ffffff;
|
||||
}
|
||||
QTabWidget#armJogModeTabs QTabBar::tab {
|
||||
min-width: 150px;
|
||||
min-width: 80px;
|
||||
min-height: 32px;
|
||||
padding: 0 18px;
|
||||
padding: 0 8px;
|
||||
color: #64717d;
|
||||
background: #f2f5f8;
|
||||
border: 1px solid #dbe2e8;
|
||||
@ -1370,6 +1412,9 @@ QTabWidget#armJogModeTabs QTabBar::tab:selected {
|
||||
border-color: #8db9f3;
|
||||
font-weight: 600;
|
||||
}
|
||||
QWidget#handEyeMotionPanel QDoubleSpinBox {
|
||||
padding: 6px 8px;
|
||||
}
|
||||
QFrame#jogAxisRow {
|
||||
background: transparent;
|
||||
border: none;
|
||||
@ -1463,6 +1508,12 @@ QPushButton#cartesianPadButton[padRole="north"] {
|
||||
border-bottom-left-radius: 9px;
|
||||
border-bottom-right-radius: 9px;
|
||||
}
|
||||
QPushButton#cartesianPadButton[padRole="compact"] {
|
||||
min-height: 36px;
|
||||
max-height: 36px;
|
||||
border-radius: 6px;
|
||||
font-size: 12px;
|
||||
}
|
||||
QPushButton#cartesianPadButton[padRole="south"] {
|
||||
border-top-left-radius: 9px;
|
||||
border-top-right-radius: 9px;
|
||||
@ -1570,6 +1621,150 @@ QToolTip {
|
||||
border: none;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
/* Arm point and flow planner */
|
||||
QDialog#jointFlowDialog {
|
||||
background: transparent;
|
||||
border: none;
|
||||
}
|
||||
QDialog#jointFlowChildDialog {
|
||||
background: transparent;
|
||||
border: none;
|
||||
}
|
||||
QFrame#jointFlowChildSurface {
|
||||
background: #f5f7fa;
|
||||
border: 1px solid #cbd2da;
|
||||
border-radius: 9px;
|
||||
}
|
||||
QWidget#jointFlowChildTitleBar {
|
||||
background: #f8fafc;
|
||||
border: none;
|
||||
border-bottom: 1px solid #dce1e6;
|
||||
border-top-left-radius: 8px;
|
||||
border-top-right-radius: 8px;
|
||||
}
|
||||
QWidget#jointFlowChildContent {
|
||||
background: #ffffff;
|
||||
border: none;
|
||||
border-bottom-left-radius: 8px;
|
||||
border-bottom-right-radius: 8px;
|
||||
}
|
||||
QWidget#jointFlowChildContent QLabel {
|
||||
color: #4f5d69;
|
||||
font-weight: 600;
|
||||
}
|
||||
QWidget#jointFlowChildContent QLineEdit {
|
||||
min-height: 34px;
|
||||
padding: 0 10px;
|
||||
background: #ffffff;
|
||||
border: 1px solid #bfc9d4;
|
||||
border-radius: 5px;
|
||||
selection-background-color: #dbeafe;
|
||||
selection-color: #155dcc;
|
||||
}
|
||||
QWidget#jointFlowChildContent QLineEdit:focus {
|
||||
border: 1px solid #1b6ef3;
|
||||
}
|
||||
QFrame#jointFlowDialogSurface {
|
||||
background: #f3f6f9;
|
||||
border: 1px solid #cbd2da;
|
||||
border-radius: 9px;
|
||||
}
|
||||
QWidget#jointFlowDialogTitleBar {
|
||||
background: #f8fafc;
|
||||
border: none;
|
||||
border-bottom: 1px solid #dce1e6;
|
||||
border-top-left-radius: 8px;
|
||||
border-top-right-radius: 8px;
|
||||
}
|
||||
QLabel#jointFlowDialogMark {
|
||||
color: #ffffff;
|
||||
background: #1b6ef3;
|
||||
border-radius: 5px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
QLabel#jointFlowDialogTitle {
|
||||
color: #202832;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
QLabel#jointFlowDialogSubtitle {
|
||||
color: #78838f;
|
||||
font-size: 11px;
|
||||
}
|
||||
QPushButton#jointFlowDialogWindowButton,
|
||||
QPushButton#jointFlowDialogCloseButton {
|
||||
min-height: 45px;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: 0;
|
||||
}
|
||||
QPushButton#jointFlowDialogWindowButton:hover {
|
||||
background: #e9edf2;
|
||||
}
|
||||
QPushButton#jointFlowDialogCloseButton {
|
||||
border-top-right-radius: 8px;
|
||||
}
|
||||
QPushButton#jointFlowDialogCloseButton:hover {
|
||||
background: #fde8e8;
|
||||
}
|
||||
QWidget#jointFlowWorkspace {
|
||||
background: #f3f6f9;
|
||||
}
|
||||
QFrame#jointPointPanel,
|
||||
QFrame#jointFlowPanel,
|
||||
QFrame#jointProgramGroupPanel {
|
||||
background: #ffffff;
|
||||
border: 1px solid #dce3ea;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QLabel#jointFlowSectionTitle {
|
||||
color: #202a34;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
QLabel#jointFlowSectionSubtitle {
|
||||
color: #77838f;
|
||||
font-size: 11px;
|
||||
}
|
||||
QLabel#jointFlowContextChip {
|
||||
color: #155dcc;
|
||||
background: #eaf3ff;
|
||||
border: 1px solid #c9def8;
|
||||
border-radius: 12px;
|
||||
padding: 4px 10px;
|
||||
font-weight: 600;
|
||||
}
|
||||
QFrame#jointFlowToolbar {
|
||||
background: #f7f9fb;
|
||||
border: 1px solid #e1e7ed;
|
||||
border-radius: 6px;
|
||||
}
|
||||
QPushButton#secondaryButton {
|
||||
color: #2866a8;
|
||||
background: #ffffff;
|
||||
border-color: #b9cde2;
|
||||
}
|
||||
QPushButton#secondaryButton:hover {
|
||||
color: #155dcc;
|
||||
background: #edf5ff;
|
||||
border-color: #6fa7e5;
|
||||
}
|
||||
QTableWidget#jointPointTable {
|
||||
border: 1px solid #e0e6ec;
|
||||
border-radius: 6px;
|
||||
}
|
||||
QGraphicsView#jointFlowCanvas {
|
||||
background: #f4f7fa;
|
||||
border: 1px solid #dce3ea;
|
||||
border-radius: 6px;
|
||||
}
|
||||
QSplitter#jointFlowSplitter::handle {
|
||||
height: 10px;
|
||||
background: transparent;
|
||||
}
|
||||
QFrame#bottomStatusBar {
|
||||
background: #ffffff;
|
||||
border: none;
|
||||
|
||||
333
tests/handeyeintegration_test.cpp
Normal file
333
tests/handeyeintegration_test.cpp
Normal file
@ -0,0 +1,333 @@
|
||||
// Real UI/backend objects, loopback-only gRPC, isolated settings, no hardware.
|
||||
#include <QtTest>
|
||||
#include <QApplication>
|
||||
#include <QCheckBox>
|
||||
#include <QComboBox>
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QLineEdit>
|
||||
#include <QMainWindow>
|
||||
#include <QPushButton>
|
||||
#include <QSettings>
|
||||
#include <QSpinBox>
|
||||
#include <QTemporaryDir>
|
||||
#include <QTabWidget>
|
||||
#include <grpcpp/grpcpp.h>
|
||||
#include "cmvr/api/arm_service.grpc.pb.h"
|
||||
#include "cmvr/api/camera_service.grpc.pb.h"
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#define private public
|
||||
#include "../src/mainwindow.h"
|
||||
#undef private
|
||||
#include "../src/robotclient.h"
|
||||
#include "../src/handeyemotionwidget.h"
|
||||
#include "../src/tcpcalibrationwidget.h"
|
||||
#include "../src/urdfviewerwidget.h"
|
||||
#include "../ui/handeyecalibrationwidget.h"
|
||||
|
||||
static void require(bool ok, const char *detail)
|
||||
{
|
||||
if (!ok) throw std::runtime_error(detail);
|
||||
}
|
||||
static bool until(const std::function<bool()> &predicate, int timeout=5000)
|
||||
{
|
||||
QElapsedTimer timer; timer.start();
|
||||
while (!predicate() && timer.elapsed()<timeout) QTest::qWait(10);
|
||||
return predicate();
|
||||
}
|
||||
class FakeCamera : public cmvr::api::CameraService::Service {
|
||||
public:
|
||||
std::atomic<int> mode{0}, reads{0};
|
||||
grpc::Status GetRGBImage(grpc::ServerContext *, const cmvr::api::GetRGBImageCommand::Request *r,
|
||||
cmvr::api::GetRGBImageCommand::Feedback *s) override
|
||||
{
|
||||
++reads;
|
||||
if (r->header().device_id()!="camera-a") {
|
||||
s->mutable_header()->set_success(false);
|
||||
s->mutable_header()->set_error_message("unexpected camera identity");
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
s->mutable_header()->set_success(true);
|
||||
auto *frame=s->mutable_color_frame();
|
||||
frame->set_width(2); frame->set_height(1);
|
||||
frame->set_type(cmvr::api::FrameData::U8C3); frame->set_codec("none");
|
||||
const char pixels[]={10,20,30,40,50,60};
|
||||
frame->set_data(pixels,mode.load()==2 ? 5 : sizeof(pixels));
|
||||
auto *k=s->mutable_intrinsics();
|
||||
k->set_fx(mode.load()==1 ? 0.f : 800.f); k->set_fy(810.f);
|
||||
k->set_cx(.5f); k->set_cy(.25f);
|
||||
for (int i=0;i<5;++i) k->add_coeffs(0.f);
|
||||
if (mode.load()==3) k->set_fy(std::numeric_limits<float>::quiet_NaN());
|
||||
// The audited unary server omits capture/source metadata.
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
};
|
||||
class FakeArm : public cmvr::api::ArmService::Service {
|
||||
public:
|
||||
std::atomic<int> poses{0}, moves{0};
|
||||
std::mutex mutex;
|
||||
std::string lastPoseDevice;
|
||||
grpc::Status GetArmInfo(grpc::ServerContext *,const cmvr::api::GetArmInfo::Request *r,
|
||||
cmvr::api::GetArmInfo::Response *s) override
|
||||
{
|
||||
s->mutable_header()->set_success(true); s->set_device_id(r->header().device_id());
|
||||
s->set_driver_type("AuboARM"); s->set_manufacturer("Aubo"); s->set_dof(6);
|
||||
s->set_default_base_frame("base"); s->set_default_tcp_frame("tcp");
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
grpc::Status getRobotState(grpc::ServerContext *,const cmvr::api::GetRobotState::Request *r,
|
||||
cmvr::api::GetRobotState::Response *s) override
|
||||
{
|
||||
++poses;
|
||||
{ std::lock_guard<std::mutex> lock(mutex); lastPoseDevice=r->header().device_id(); }
|
||||
s->mutable_header()->set_success(true);
|
||||
auto *state=s->mutable_state(); state->set_connected(true); state->set_powered_on(true);
|
||||
state->set_robot_mode(cmvr::api::ARM_ROBOT_MODE_IDLE);
|
||||
state->set_safety_mode(cmvr::api::ARM_SAFETY_MODE_NORMAL);
|
||||
state->set_timestamp(123.);
|
||||
auto *pose=state->mutable_actual_tcp_pose();
|
||||
pose->set_x(.4); pose->set_y(.2); pose->set_z(.5);
|
||||
auto *j=state->mutable_actual_joint_state();
|
||||
for (int i=0;i<6;++i) { j->add_position(.1); j->add_velocity(0.); }
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
grpc::Status moveL(grpc::ServerContext *,const cmvr::api::MoveL::Request *,
|
||||
cmvr::api::MoveL::Response *s) override
|
||||
{
|
||||
++moves; s->mutable_header()->set_success(true); return grpc::Status::OK;
|
||||
}
|
||||
};
|
||||
static HandEyeStore::Record record(const QString &name,const QString &mode)
|
||||
{
|
||||
HandEyeStore::Record r;
|
||||
r.name=name; r.mode=mode; r.cameraId="camera-a"; r.method="PARK";
|
||||
r.createdAt="2026-09-30T10:00:00Z"; r.sampleCount=12;
|
||||
r.transform={{0,-1,0,.1, 1,0,0,.2, 0,0,1,.3, 0,0,0,1}};
|
||||
r.metrics={{"accepted",true},{"translation_rms_mm",.2},{"rotation_rms_deg",.1}};
|
||||
r.board={{"type","chessboard"},{"rows",6},{"square_size_m",.025}};
|
||||
r.intrinsics={{"camera_matrix",QVariantList{800.,0.,320.,0.,800.,240.,0.,0.,1.}},
|
||||
{"distortion",QVariantList{0.,0.,0.,0.,0.}}};
|
||||
return r;
|
||||
}
|
||||
static QList<QVariant> imageReply(RobotClient &client,QSignalSpy &spy,quint64 token)
|
||||
{
|
||||
spy.clear(); client.requestHandEyeImage("camera-a",token);
|
||||
require(until([&] { return !spy.isEmpty(); }),"image callback missing");
|
||||
const auto reply=spy.takeFirst();
|
||||
require(reply.at(0).toULongLong()==token && reply.at(1).toString()=="camera-a",
|
||||
"image callback lost token/camera identity");
|
||||
return reply;
|
||||
}
|
||||
static void assertPoint(QSignalSpy &spy,double x,double y,double z,const QString &profile)
|
||||
{
|
||||
require(!spy.isEmpty(),"coordinate result signal missing");
|
||||
const auto response=spy.takeFirst();
|
||||
require(response.at(0).toString()=="camera-a" && response.at(1).toString()==profile,
|
||||
"coordinate result used wrong camera/profile");
|
||||
const auto point=response.at(2).toList();
|
||||
require(point.size()==3,"coordinate result is not XYZ");
|
||||
const double expected[]={x,y,z};
|
||||
for (int i=0;i<3;++i)
|
||||
require(std::abs(point.at(i).toDouble()-expected[i])<1e-9,
|
||||
"coordinate result transform, rotation, offset or units incorrect");
|
||||
}
|
||||
int main(int argc,char **argv)
|
||||
{
|
||||
QApplication app(argc,argv);
|
||||
app.setStyle("Fusion");
|
||||
QFile styleFile(":/styles.qss");
|
||||
if (styleFile.open(QIODevice::ReadOnly))
|
||||
app.setStyleSheet(QString::fromUtf8(styleFile.readAll()));
|
||||
QTemporaryDir settingsDirectory;
|
||||
app.setOrganizationName("CMVR-HandEye-Isolated-Test"); app.setApplicationName("Integration");
|
||||
QSettings::setDefaultFormat(QSettings::IniFormat);
|
||||
QSettings::setPath(QSettings::IniFormat,QSettings::UserScope,settingsDirectory.path());
|
||||
FakeCamera camera; FakeArm arm;
|
||||
grpc::ServerBuilder builder; int port=0;
|
||||
builder.AddListeningPort("127.0.0.1:0",grpc::InsecureServerCredentials(),&port);
|
||||
builder.RegisterService(&camera); builder.RegisterService(&arm);
|
||||
auto server=builder.BuildAndStart();
|
||||
try {
|
||||
require(settingsDirectory.isValid() && server && port>0,"isolated test startup failed");
|
||||
{
|
||||
RobotClient isolated;
|
||||
QSignalSpy replies(&isolated,&RobotClient::handEyeImageReceived);
|
||||
require(!imageReply(isolated,replies,1).at(5).toBool(),"disconnected image accepted");
|
||||
QSignalSpy connected(&isolated,&RobotClient::connectionChanged);
|
||||
isolated.connectToServer("127.0.0.1",port,true);
|
||||
require(until([&] { return !connected.isEmpty(); }),"demo connection callback missing");
|
||||
require(!imageReply(isolated,replies,2).at(5).toBool(),"demo image accepted");
|
||||
require(camera.reads.load()==0,"demo/disconnected request reached camera RPC");
|
||||
}
|
||||
MainWindow window;
|
||||
window.m_demoCheck->setChecked(false);
|
||||
window.m_hostEdit->setText("127.0.0.1"); window.m_portSpin->setValue(port);
|
||||
window.m_armIdEdit->setText("arm-a"); window.m_cameraIdEdit->setText("camera-a");
|
||||
window.toggleConnection();
|
||||
require(until([&] { return window.m_connected; }),"real loopback connection failed");
|
||||
QSignalSpy images(window.m_client,&RobotClient::handEyeImageReceived);
|
||||
const auto imageResult=imageReply(*window.m_client,images,10);
|
||||
require(imageResult.at(5).toBool(),"valid unary image rejected");
|
||||
const QImage image=qvariant_cast<QImage>(imageResult.at(2));
|
||||
require(image.size()==QSize(2,1) && image.pixelColor(0,0)==QColor(30,20,10)
|
||||
&& image.pixelColor(1,0)==QColor(60,50,40),"BGR image conversion or lifetime incorrect");
|
||||
const auto intrinsics=imageResult.at(3).toMap(), metadata=imageResult.at(4).toMap();
|
||||
require(intrinsics.value("fx").toDouble()==800. && intrinsics.value("fy").toDouble()==810.
|
||||
&& intrinsics.value("width").toInt()==2 && intrinsics.value("coeffs").toList().size()==5,
|
||||
"snapshot lost native intrinsics");
|
||||
require(!metadata.value("captureTimestampAvailable").toBool()
|
||||
&& metadata.value("captureUtcNs").toLongLong()==0,"missing capture timestamp fabricated");
|
||||
camera.mode=1;
|
||||
require(!imageReply(*window.m_client,images,11).at(5).toBool(),"zero focal length accepted");
|
||||
camera.mode=2;
|
||||
require(!imageReply(*window.m_client,images,12).at(5).toBool(),"malformed RGB byte count accepted");
|
||||
camera.mode=3;
|
||||
require(!imageReply(*window.m_client,images,13).at(5).toBool(),"NaN focal length accepted");
|
||||
require(image.pixelColor(0,0)==QColor(30,20,10),"snapshot pixels changed after later RPCs");
|
||||
camera.mode=0;
|
||||
|
||||
const QString endpoint=window.endpoint(); QSettings settings; QString error;
|
||||
auto eth=record("fixed-camera","eye_to_hand"), eih=record("wrist-camera","eye_in_hand");
|
||||
require(HandEyeStore::save(settings,endpoint,"arm-a",eth,false,error),"save ETH profile failed");
|
||||
require(HandEyeStore::save(settings,endpoint,"arm-a",eih,false,error),"save EIH profile failed");
|
||||
auto other=record("other-robot","eye_to_hand");
|
||||
require(HandEyeStore::save(settings,endpoint,"arm-b",other,false,error),"save other robot failed");
|
||||
other.name="other-server";
|
||||
require(HandEyeStore::save(settings,"other:1234","arm-a",other,false,error),"save other server failed");
|
||||
auto *panel=window.m_handEyeMotion;
|
||||
auto *profiles=panel->findChild<QComboBox *>("handEyeMotionProfiles");
|
||||
auto *convert=panel->findChild<QPushButton *>("handEyeConvert");
|
||||
require(profiles && convert,"handeye motion UI missing");
|
||||
window.m_handEye->calibrationsChanged(endpoint,"arm-a",eth.name);
|
||||
require(profiles->count()==2 && profiles->currentData().toString()==eth.name,
|
||||
"save notification did not immediately populate/select motion profile");
|
||||
require(profiles->findData("other-robot")<0 && profiles->findData("other-server")<0,
|
||||
"calibration leaked across robot/server identity");
|
||||
window.m_armIdEdit->setText("arm-b");
|
||||
require(profiles->count()==1 && profiles->findData("other-robot")>=0,"robot switch not isolated");
|
||||
window.m_armIdEdit->setText("arm-a");
|
||||
require(profiles->count()==2 && profiles->findData("other-robot")<0,"return robot retained wrong profiles");
|
||||
profiles->setCurrentIndex(profiles->findData(eth.name));
|
||||
const double inputs[]={100.,20.,300.};
|
||||
for (int i=0;i<3;++i)
|
||||
panel->findChild<QDoubleSpinBox *>(QString("handEyeCameraPoint%1").arg(i))->setValue(inputs[i]);
|
||||
QSignalSpy points(panel,&HandEyeMotionWidget::basePointPrepared);
|
||||
QSignalSpy captures(panel,&HandEyeMotionWidget::captureRequested);
|
||||
QSignalSpy moveJ(window.m_client,&RobotClient::moveJRequested);
|
||||
QSignalSpy moveL(window.m_client,&RobotClient::moveJPoseRequested);
|
||||
QSignalSpy jog(window.m_client,&RobotClient::tcpJogMoveRequested);
|
||||
QSignalSpy speedJ(window.m_client,&RobotClient::speedJRequested);
|
||||
QSignalSpy speedL(window.m_client,&RobotClient::speedLRequested);
|
||||
require(convert->isEnabled(),"fixed camera conversion disabled"); convert->click();
|
||||
assertPoint(points,.08,.3,.6,eth.name);
|
||||
require(captures.isEmpty(),"fixed camera unnecessarily requested robot pose");
|
||||
profiles->setCurrentIndex(profiles->findData(eih.name));
|
||||
require(!convert->isEnabled(),"wrist conversion enabled without verified active TCP offset");
|
||||
window.m_tcpCalibration->findChild<QDoubleSpinBox *>("tcpSource2")->setValue(200.);
|
||||
window.m_tcpCalibration->findChild<QDoubleSpinBox *>("tcpSource5")->setValue(90.);
|
||||
window.m_tcpCalibration->findChild<QCheckBox *>("tcpSourceConfirmed")->setChecked(true);
|
||||
require(convert->isEnabled(),"wrist conversion not enabled after real reference confirmation");
|
||||
const int poseCount=arm.poses.load(); convert->click();
|
||||
require(until([&] { return !points.isEmpty(); }),"wrist conversion failed to receive real pose");
|
||||
require(captures.size()==1 && arm.poses.load()>poseCount,"wrist conversion bypassed real pose RPC");
|
||||
{ std::lock_guard<std::mutex> lock(arm.mutex);
|
||||
require(arm.lastPoseDevice=="arm-a","wrist pose RPC used wrong robot"); }
|
||||
assertPoint(points,.7,.12,.9,eih.name);
|
||||
require(moveJ.isEmpty() && moveL.isEmpty() && jog.isEmpty() && speedJ.isEmpty()
|
||||
&& speedL.isEmpty() && arm.moves.load()==0,"coordinate conversion sent robot motion");
|
||||
// Exercise export notification through the real MainWindow model loader.
|
||||
const QString urdfSource=settingsDirectory.filePath("robot.urdf");
|
||||
QFile urdf(urdfSource);
|
||||
require(urdf.open(QIODevice::WriteOnly),"URDF fixture creation failed");
|
||||
urdf.write("<robot name=\"fixture\"><link name=\"flange\"/></robot>"); urdf.close();
|
||||
panel->setUrdfFile(urdfSource);
|
||||
auto *reference=panel->findChild<QComboBox *>("handEyeUrdfReference");
|
||||
reference->setCurrentIndex(reference->findData("flange"));
|
||||
panel->findChild<QComboBox *>("handEyeUrdfCamera")->setEditText("camera_optical");
|
||||
panel->findChild<QCheckBox *>("handEyeUrdfConfirmed")->setChecked(true);
|
||||
const QString urdfOutput=settingsDirectory.filePath("robot_calibrated.urdf");
|
||||
require(panel->exportUrdf(urdfOutput,error),qPrintable(error));
|
||||
require(QFileInfo(window.m_urdfViewer->currentFile())==QFileInfo(urdfOutput),
|
||||
"exported URDF was not loaded by MainWindow");
|
||||
require(arm.moves.load()==0,"URDF update sent robot motion");
|
||||
// Inspect UI request routing without starting even a loopback video
|
||||
// worker. Other tests above exercise the real unary backend unchanged.
|
||||
QObject::disconnect(window.m_client,&RobotClient::cameraStreamStartRequested,nullptr,nullptr);
|
||||
QObject::disconnect(window.m_client,&RobotClient::cameraStreamStopRequested,nullptr,nullptr);
|
||||
QSignalSpy starts(window.m_client,&RobotClient::cameraStreamStartRequested);
|
||||
QSignalSpy stops(window.m_client,&RobotClient::cameraStreamStopRequested);
|
||||
for (int codecIndex=0;codecIndex<2;++codecIndex) {
|
||||
window.m_cameraCodecCombo->setCurrentIndex(codecIndex);
|
||||
window.m_handEye->previewRequested("camera-a",true);
|
||||
require(starts.size()==1,"handeye preview did not request one stream");
|
||||
const auto start=starts.takeFirst();
|
||||
require(start.at(0).toString()=="camera-a"
|
||||
&& start.at(1).toString()==(codecIndex==0 ? "h264" : "h265")
|
||||
&& start.at(2).toString()=="rgb","handeye preview sent display codec instead of canonical RGB codec");
|
||||
window.m_handEye->previewRequested("camera-a",false);
|
||||
require(stops.size()==1 && stops.takeFirst().at(0).toString()=="camera-a",
|
||||
"handeye stop did not preserve per-camera ownership");
|
||||
}
|
||||
require(HandEyeStore::remove(settings,endpoint,"arm-a",eth.name,error),"remove fixed profile failed");
|
||||
require(HandEyeStore::remove(settings,endpoint,"arm-a",eih.name,error),"remove wrist profile failed");
|
||||
window.m_handEye->calibrationsChanged(endpoint,"arm-a",QString());
|
||||
require(profiles->count()==0 && !convert->isEnabled(),"delete notification left selectable profile");
|
||||
for (int i=0;i<3;++i)
|
||||
require(panel->findChild<QLineEdit *>(QString("handEyeBasePoint%1").arg(i))->text().isEmpty(),
|
||||
"deleted profile left stale converted coordinates");
|
||||
window.toggleConnection();
|
||||
require(until([&] { return !window.m_connected; }),"disconnect did not complete");
|
||||
const int screenshotOption=app.arguments().indexOf("--screenshot");
|
||||
if (screenshotOption>=0 && screenshotOption+1<app.arguments().size()) {
|
||||
window.selectPage(14); window.resize(1440,1000); window.show();
|
||||
QTest::qWait(250);
|
||||
const QString screenshot=app.arguments().at(screenshotOption+1);
|
||||
require(window.grab().save(screenshot),"screenshot save failed");
|
||||
window.selectPage(1);
|
||||
for (auto *tabs : window.findChildren<QTabWidget *>()) {
|
||||
for (int i=0;i<tabs->count();++i) {
|
||||
if (tabs->widget(i)==panel || tabs->widget(i)->isAncestorOf(panel))
|
||||
tabs->setCurrentIndex(i);
|
||||
}
|
||||
}
|
||||
QTest::qWait(250);
|
||||
const QFileInfo screenshotInfo(screenshot);
|
||||
require(window.grab().save(screenshotInfo.path()+"/"+screenshotInfo.completeBaseName()+"-arm.png"),
|
||||
"arm screenshot save failed");
|
||||
window.m_jogModeTabs->setCurrentIndex(1);
|
||||
QTest::qWait(100);
|
||||
require(window.m_jogModeTabs->parentWidget()->grab().save(
|
||||
screenshotInfo.path()+"/"+screenshotInfo.completeBaseName()+"-jog.png"),
|
||||
"Cartesian jog screenshot save failed");
|
||||
window.selectPage(13);
|
||||
window.m_tcpCalibration->findChild<QComboBox *>("tcpCalibrationMethod")->setCurrentIndex(1);
|
||||
QTest::qWait(250);
|
||||
require(window.grab().save(screenshotInfo.path()+"/"+screenshotInfo.completeBaseName()+"-tcp.png"),
|
||||
"TCP screenshot save failed");
|
||||
window.selectPage(15);
|
||||
QTest::qWait(250);
|
||||
require(window.grab().save(screenshotInfo.path()+"/"+screenshotInfo.completeBaseName()+"-touch.png"),
|
||||
"Touch operation screenshot save failed");
|
||||
// Layout verification at a smaller desktop size, without hardware.
|
||||
window.resize(1280,800);
|
||||
for(int page:{13,14,15}) {
|
||||
window.selectPage(page); QTest::qWait(250);
|
||||
require(window.grab().save(screenshotInfo.path()+"/"+screenshotInfo.completeBaseName()
|
||||
+QStringLiteral("-compact-%1.png").arg(page)),"compact calibration screenshot failed");
|
||||
}
|
||||
}
|
||||
std::puts("PASS: real unary BGR/K/lifetime validation, missing timestamps, rejection paths, isolated live dropdowns, ETH/EIH actual coordinate conversion and no motion, deletion invalidation");
|
||||
} catch (const std::exception &error) {
|
||||
std::fprintf(stderr,"FAIL: %s\n",error.what());
|
||||
if (server) server->Shutdown();
|
||||
return 1;
|
||||
}
|
||||
server->Shutdown(); return 0;
|
||||
}
|
||||
199
tests/handeyemotion_test.cpp
Normal file
199
tests/handeyemotion_test.cpp
Normal file
@ -0,0 +1,199 @@
|
||||
#include "../src/handeyemotionwidget.h"
|
||||
#include <QtTest>
|
||||
#include <QComboBox>
|
||||
#include <QCheckBox>
|
||||
#include <QFile>
|
||||
#include <QXmlStreamReader>
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QLineEdit>
|
||||
#include <QPushButton>
|
||||
#include <QSettings>
|
||||
#include <QScrollArea>
|
||||
#include <QScrollBar>
|
||||
#include <QDir>
|
||||
#include <QTemporaryDir>
|
||||
#include <cmath>
|
||||
|
||||
class HandEyeMotionTest : public QObject {
|
||||
Q_OBJECT
|
||||
QTemporaryDir m_dir;
|
||||
void seed(const QString &name, const QString &mode, const QString &robot="r") {
|
||||
HandEyeStore::Record record;
|
||||
record.name=name; record.mode=mode; record.cameraId="camera-"+name;
|
||||
record.method="PARK"; record.createdAt="2026-09-30T12:00:00Z";
|
||||
record.sampleCount=8; record.metrics={{"accepted",true}};
|
||||
record.transform={{0,-1,0,.1, 1,0,0,.2, 0,0,1,.3, 0,0,0,1}};
|
||||
QSettings settings; QString error;
|
||||
QVERIFY2(HandEyeStore::save(settings,"s",robot,record,false,error),qPrintable(error));
|
||||
}
|
||||
static void point(HandEyeMotionWidget &widget) {
|
||||
const double values[]={400,500,600};
|
||||
for(int i=0;i<3;++i) widget.findChild<QDoubleSpinBox *>(QString("handEyeCameraPoint%1").arg(i))->setValue(values[i]);
|
||||
}
|
||||
static QPushButton *button(HandEyeMotionWidget &widget) {
|
||||
return widget.findChild<QPushButton *>("handEyeConvert");
|
||||
}
|
||||
static QVariantMap pose() {
|
||||
return {{"x",1.0},{"y",2.0},{"z",3.5},{"rx",0.0},{"ry",0.0},{"rz",1.5707963267948966}};
|
||||
}
|
||||
static QVariantMap state() { return {{"connected",true},{"moving",false},{"fault",false}}; }
|
||||
private slots:
|
||||
void initTestCase() {
|
||||
QVERIFY(m_dir.isValid());
|
||||
QCoreApplication::setOrganizationName("CMVR-HandEye-Motion-Test");
|
||||
QCoreApplication::setApplicationName("Motion");
|
||||
QSettings::setDefaultFormat(QSettings::IniFormat);
|
||||
QSettings::setPath(QSettings::IniFormat,QSettings::UserScope,m_dir.path());
|
||||
}
|
||||
void init() { QSettings s; s.clear(); s.sync(); }
|
||||
void compactPanelDoesNotOverlap() {
|
||||
QFile style(QFileInfo(QString::fromUtf8(__FILE__)).dir().filePath("../styles.qss"));
|
||||
QVERIFY(style.open(QIODevice::ReadOnly));
|
||||
seed("Camera_01","eye_to_hand");
|
||||
HandEyeMotionWidget widget;
|
||||
widget.setStyleSheet(QString::fromUtf8(style.readAll()));
|
||||
widget.setContext("s","r",false,false,false,{});
|
||||
widget.resize(430,400); widget.show(); QTest::qWait(50);
|
||||
auto *scroll=widget.findChild<QScrollArea *>(); QVERIFY(scroll);
|
||||
QVERIFY(scroll->verticalScrollBar()->maximum()>0);
|
||||
QCOMPARE(scroll->horizontalScrollBar()->maximum(),0);
|
||||
auto *input=widget.findChild<QDoubleSpinBox *>("handEyeCameraPoint0");
|
||||
auto *output=widget.findChild<QLineEdit *>("handEyeBasePoint0");
|
||||
QVERIFY(input->geometry().bottom()<output->geometry().top());
|
||||
QVERIFY(input->height()>=input->minimumSizeHint().height());
|
||||
QVERIFY(widget.grab().save("motion-urdf-top.png"));
|
||||
auto *update=widget.findChild<QPushButton *>("handEyeUpdateUrdf");
|
||||
scroll->ensureWidgetVisible(update); QTest::qWait(20);
|
||||
QVERIFY(scroll->viewport()->rect().intersects(QRect(update->mapTo(scroll->viewport(),QPoint()),update->size())));
|
||||
QVERIFY(widget.grab().save("motion-urdf-bottom.png"));
|
||||
}
|
||||
void eyeToHandAndSelectionPersistence() {
|
||||
seed("fixed","eye_to_hand"); seed("moving","eye_in_hand"); seed("other","eye_to_hand","other");
|
||||
HandEyeMotionWidget widget; widget.setContext("s","r",false,true,false,{});
|
||||
auto *combo=widget.findChild<QComboBox *>("handEyeMotionProfiles"); QVERIFY(combo); QCOMPARE(combo->count(),2);
|
||||
combo->setCurrentIndex(0); QVERIFY(combo->currentText().contains("camera-fixed"));
|
||||
QSignalSpy capture(&widget,&HandEyeMotionWidget::captureRequested);
|
||||
QSignalSpy prepared(&widget,&HandEyeMotionWidget::basePointPrepared);
|
||||
point(widget); QVERIFY(button(widget)->isEnabled()); button(widget)->click();
|
||||
QCOMPARE(capture.size(),0); QCOMPARE(prepared.size(),1);
|
||||
QCOMPARE(prepared.first().at(0).toString(),QString("camera-fixed"));
|
||||
const auto values=prepared.first().at(2).toList();
|
||||
QVERIFY(std::abs(values[0].toDouble()+.4)<1e-12); QVERIFY(std::abs(values[1].toDouble()-.6)<1e-12);
|
||||
QVERIFY(std::abs(values[2].toDouble()-.9)<1e-12);
|
||||
auto *result=widget.findChild<QLineEdit *>("handEyeBasePoint0"); QVERIFY(!result->text().isEmpty()); QVERIFY(result->isReadOnly());
|
||||
widget.findChild<QDoubleSpinBox *>("handEyeCameraPoint0")->setValue(401); QVERIFY(result->text().isEmpty());
|
||||
QSettings settings; HandEyeStore::Snapshot snapshot; QString error;
|
||||
QVERIFY(HandEyeStore::load(settings,"s","r",snapshot,error)); QCOMPARE(snapshot.current,QString("fixed"));
|
||||
widget.setContext("s","other",true,false,true,{}); QCOMPARE(combo->count(),1); QVERIFY(combo->currentText().contains("other"));
|
||||
}
|
||||
void eyeInHandUsesFreshPoseAndActiveOffset() {
|
||||
seed("moving","eye_in_hand"); HandEyeMotionWidget widget;
|
||||
widget.setContext("s","r",true,false,true,{{0,0,.5,0,0,0}}); point(widget);
|
||||
QSignalSpy capture(&widget,&HandEyeMotionWidget::captureRequested);
|
||||
QSignalSpy prepared(&widget,&HandEyeMotionWidget::basePointPrepared);
|
||||
button(widget)->click(); QCOMPARE(capture.size(),1); QCOMPARE(prepared.size(),0);
|
||||
const quint64 token=capture.first().at(1).toULongLong(); QVERIFY(token & (quint64(1)<<61));
|
||||
widget.acceptPose(token,"wrong",pose(),state(),true,{}); QCOMPARE(prepared.size(),0);
|
||||
widget.acceptPose(token,"r",pose(),state(),true,{}); QCOMPARE(prepared.size(),1);
|
||||
const auto values=prepared.first().at(2).toList();
|
||||
QVERIFY(std::abs(values[0].toDouble()-.4)<1e-12); QVERIFY(std::abs(values[1].toDouble()-1.6)<1e-12);
|
||||
QVERIFY(std::abs(values[2].toDouble()-3.9)<1e-12);
|
||||
widget.acceptPose(token,"r",pose(),state(),true,{}); QCOMPARE(prepared.size(),1);
|
||||
widget.setContext("s","r",false,false,true,{{0,0,.5,0,0,0}});
|
||||
QVERIFY(widget.findChild<QLineEdit *>("handEyeBasePoint0")->text().isEmpty()); QVERIFY(!button(widget)->isEnabled());
|
||||
}
|
||||
void lateResponsesInvalidated_data() {
|
||||
QTest::addColumn<int>("change");
|
||||
QTest::newRow("input")<<0; QTest::newRow("selection")<<1; QTest::newRow("robot")<<2;
|
||||
QTest::newRow("reference")<<3; QTest::newRow("offset")<<4; QTest::newRow("reload")<<5;
|
||||
QTest::newRow("disconnect")<<6; QTest::newRow("demo")<<7;
|
||||
}
|
||||
void lateResponsesInvalidated() {
|
||||
QFETCH(int,change); seed("fixed","eye_to_hand"); seed("moving","eye_in_hand");
|
||||
HandEyeMotionWidget widget; widget.setContext("s","r",true,false,true,{}); point(widget);
|
||||
QSignalSpy capture(&widget,&HandEyeMotionWidget::captureRequested);
|
||||
QSignalSpy prepared(&widget,&HandEyeMotionWidget::basePointPrepared);
|
||||
button(widget)->click(); QCOMPARE(capture.size(),1); const auto token=capture.first().at(1).toULongLong();
|
||||
switch(change) {
|
||||
case 0:widget.findChild<QDoubleSpinBox *>("handEyeCameraPoint0")->setValue(12);break;
|
||||
case 1:widget.findChild<QComboBox *>("handEyeMotionProfiles")->setCurrentIndex(0);break;
|
||||
case 2:widget.setContext("s","other",true,false,true,{});break;
|
||||
case 3:widget.setContext("s","r",true,false,false,{});break;
|
||||
case 4:widget.setContext("s","r",true,false,true,{{0,0,.1,0,0,0}});break;
|
||||
case 5:widget.reload();break;
|
||||
case 6:widget.setContext("s","r",false,false,true,{});break;
|
||||
case 7:widget.setContext("s","r",true,true,true,{});break;
|
||||
}
|
||||
widget.acceptPose(token,"r",pose(),state(),true,{}); QCOMPARE(prepared.size(),0);
|
||||
QVERIFY(widget.findChild<QLineEdit *>("handEyeBasePoint0")->text().isEmpty());
|
||||
}
|
||||
void savedProfileUrdfExport_data() {
|
||||
QTest::addColumn<QString>("mode"); QTest::addColumn<bool>("newCamera");
|
||||
QTest::newRow("EIH-existing")<<QString("eye_in_hand")<<false;
|
||||
QTest::newRow("ETH-existing")<<QString("eye_to_hand")<<false;
|
||||
QTest::newRow("EIH-new")<<QString("eye_in_hand")<<true;
|
||||
QTest::newRow("ETH-new")<<QString("eye_to_hand")<<true;
|
||||
}
|
||||
void savedProfileUrdfExport() {
|
||||
QFETCH(QString,mode); QFETCH(bool,newCamera); seed("saved",mode);
|
||||
QTemporaryDir files; const QString source=files.filePath("source.urdf"),target=files.filePath("export.urdf");
|
||||
QFile input(source); QVERIFY(input.open(QIODevice::WriteOnly));
|
||||
const QByteArray xml=newCamera ? QByteArray("<robot name='r'><link name='reference'/></robot>")
|
||||
: QByteArray("<robot name='r'><link name='reference'/><link name='optical'/><joint name='camera' type='fixed'><parent link='reference'/><child link='optical'/></joint></robot>");
|
||||
QCOMPARE(input.write(xml),qint64(xml.size())); input.close();
|
||||
HandEyeMotionWidget widget; widget.setContext("s","r",false,false,false,{}); widget.setUrdfFile(source);
|
||||
auto *profiles=widget.findChild<QComboBox *>("handEyeMotionProfiles"); QVERIFY(profiles); QCOMPARE(profiles->currentData().toString(),QString("saved"));
|
||||
auto *reference=widget.findChild<QComboBox *>("handEyeUrdfReference"); QVERIFY(reference);
|
||||
auto *camera=widget.findChild<QComboBox *>("handEyeUrdfCamera"); QVERIFY(camera);
|
||||
auto *confirmed=widget.findChild<QCheckBox *>("handEyeUrdfConfirmed"); QVERIFY(confirmed);
|
||||
auto *exportButton=widget.findChild<QPushButton *>("handEyeUpdateUrdf"); QVERIFY(exportButton);
|
||||
reference->setCurrentIndex(reference->findData("reference")); camera->setEditText("optical");
|
||||
QString error; QSignalSpy updated(&widget,&HandEyeMotionWidget::urdfUpdated);
|
||||
QSignalSpy capture(&widget,&HandEyeMotionWidget::captureRequested);
|
||||
QVERIFY(!exportButton->isEnabled()); QVERIFY(!widget.exportUrdf(target,error)); QVERIFY(!QFile::exists(target));
|
||||
confirmed->setChecked(true); QVERIFY(exportButton->isEnabled());
|
||||
QVERIFY2(widget.exportUrdf(target,error),qPrintable(error)); QCOMPARE(updated.size(),1); QCOMPARE(capture.size(),0);
|
||||
QCOMPARE(updated[0][0].toString(),QString("s")); QCOMPARE(updated[0][1].toString(),QString("r")); QCOMPARE(updated[0][2].toString(),target);
|
||||
QFile output(target); QVERIFY(output.open(QIODevice::ReadOnly)); QXmlStreamReader reader(output.readAll());
|
||||
TcpCalibration::Pose p{}; bool found=false;
|
||||
while(!reader.atEnd()) { reader.readNext(); if(reader.isStartElement() && reader.name()=="origin") {
|
||||
int offset=0; for(const auto &field:{"xyz","rpy"}) { const auto values=reader.attributes().value(field).toString().split(' ');
|
||||
QCOMPARE(values.size(),3); for(int i=0;i<3;++i) p[offset+i]=values[i].toDouble(); offset=3; } found=true; } }
|
||||
QVERIFY(!reader.hasError()); QVERIFY(found); TcpCalibration::Matrix actual{}; QVERIFY(TcpCalibration::poseMatrix(p,actual));
|
||||
QSettings settings; HandEyeStore::Snapshot saved; QVERIFY(HandEyeStore::load(settings,"s","r",saved,error));
|
||||
for(int i=0;i<16;++i) QVERIFY(std::abs(actual[i]-saved.records[0].transform[i])<1e-10);
|
||||
QVERIFY(input.open(QIODevice::ReadOnly)); QCOMPARE(input.readAll(),xml);
|
||||
}
|
||||
void urdfConfirmationInvalidated_data() {
|
||||
QTest::addColumn<int>("change"); QTest::newRow("profile")<<0; QTest::newRow("robot")<<1;
|
||||
QTest::newRow("endpoint")<<2; QTest::newRow("reference")<<3; QTest::newRow("camera")<<4; QTest::newRow("source")<<5;
|
||||
}
|
||||
void urdfConfirmationInvalidated() {
|
||||
QFETCH(int,change); seed("first","eye_to_hand"); seed("second","eye_in_hand"); seed("other","eye_to_hand","other");
|
||||
QTemporaryDir files; const QString source=files.filePath("source.urdf"),target=files.filePath("export.urdf");
|
||||
QFile input(source); QVERIFY(input.open(QIODevice::WriteOnly)); input.write("<robot name='r'><link name='base'/></robot>"); input.close();
|
||||
HandEyeMotionWidget widget; widget.setContext("s","r",false,false,false,{}); widget.setUrdfFile(source);
|
||||
auto *profiles=widget.findChild<QComboBox *>("handEyeMotionProfiles"); profiles->setCurrentIndex(0);
|
||||
auto *reference=widget.findChild<QComboBox *>("handEyeUrdfReference"); reference->setCurrentIndex(reference->findData("base"));
|
||||
auto *camera=widget.findChild<QComboBox *>("handEyeUrdfCamera"); camera->setEditText("optical");
|
||||
auto *confirmed=widget.findChild<QCheckBox *>("handEyeUrdfConfirmed"); confirmed->setChecked(true);
|
||||
auto *exportButton=widget.findChild<QPushButton *>("handEyeUpdateUrdf"); QVERIFY(exportButton->isEnabled());
|
||||
switch(change) {
|
||||
case 0: profiles->setCurrentIndex(1); break;
|
||||
case 1: widget.setContext("s","other",false,false,false,{}); break;
|
||||
case 2: widget.setContext("different","r",false,false,false,{}); break;
|
||||
case 3: reference->setCurrentIndex(0); break;
|
||||
case 4: camera->setEditText("new_optical"); break;
|
||||
case 5: widget.setUrdfFile(source); break;
|
||||
}
|
||||
QVERIFY(!confirmed->isChecked()); QVERIFY(!exportButton->isEnabled());
|
||||
QString error; QSignalSpy updated(&widget,&HandEyeMotionWidget::urdfUpdated);
|
||||
QVERIFY(!widget.exportUrdf(target,error)); QVERIFY(!QFile::exists(target)); QCOMPARE(updated.size(),0);
|
||||
if(change==1 || change==2) {
|
||||
QVERIFY(widget.findChild<QLineEdit *>("handEyeUrdfPath")->text().isEmpty());
|
||||
confirmed->setChecked(true); QVERIFY(!exportButton->isEnabled()); QVERIFY(!widget.exportUrdf(target,error));
|
||||
}
|
||||
}
|
||||
};
|
||||
QTEST_MAIN(HandEyeMotionTest)
|
||||
#include "handeyemotion_test.moc"
|
||||
9
tests/handeyemotion_test.pro
Normal file
9
tests/handeyemotion_test.pro
Normal file
@ -0,0 +1,9 @@
|
||||
QT += core gui widgets testlib
|
||||
CONFIG += console testcase c++14
|
||||
CONFIG -= app_bundle
|
||||
TEMPLATE = app
|
||||
TARGET = handeyemotion_test
|
||||
SOURCES += handeyemotion_test.cpp ../src/handeyemotionwidget.cpp ../src/handeyestore.cpp ../src/tcpcalibration.cpp
|
||||
SOURCES += ../src/handeyeurdf.cpp
|
||||
HEADERS += ../src/handeyeurdf.h
|
||||
HEADERS += ../src/handeyemotionwidget.h ../src/handeyestore.h ../src/tcpcalibration.h
|
||||
342
tests/handeyestore_test.cpp
Normal file
342
tests/handeyestore_test.cpp
Normal file
@ -0,0 +1,342 @@
|
||||
#include "../src/handeyestore.h"
|
||||
#include <QtTest>
|
||||
#include <QFile>
|
||||
#include <QSettings>
|
||||
#include <QTemporaryDir>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
class HandEyeStoreTest : public QObject {
|
||||
Q_OBJECT
|
||||
static HandEyeStore::Record record() {
|
||||
HandEyeStore::Record r;
|
||||
r.name = QStringLiteral("标定一"); r.cameraId = QStringLiteral("camera-1");
|
||||
r.mode = QStringLiteral("eye_in_hand"); r.method = QStringLiteral("PARK");
|
||||
r.createdAt = QStringLiteral("2026-09-30T10:00:00Z"); r.sampleCount = 12;
|
||||
r.transform = {{0,-1,0,.1, 1,0,0,.2, 0,0,1,.3, 0,0,0,1}};
|
||||
r.metrics = {{"accepted",true},{"translation_rms_mm",.2},{"rotation_rms_deg",.1}};
|
||||
r.board = {{"type","chessboard"},{"rows",6},{"square_size_m",.025}};
|
||||
r.intrinsics = {{"camera_matrix",QVariantList{800.,0.,320.,0.,800.,240.,0.,0.,1.}},
|
||||
{"distortion",QVariantList{0.,0.,0.,0.,0.}}};
|
||||
return r;
|
||||
}
|
||||
static QVariantList matrix(const TcpCalibration::Matrix &m) {
|
||||
QVariantList result; for (double value : m) result.append(value); return result;
|
||||
}
|
||||
static QVariantList observations() {
|
||||
QVariantList points, objects, ids;
|
||||
for (int i=0; i<6; ++i) {
|
||||
points.append(QVariant(QVariantList{100.+i*10.,200.+i*5.}));
|
||||
objects.append(QVariant(QVariantList{(i%3)*.025,(i/3)*.025,0.})); ids.append(i);
|
||||
}
|
||||
const QVariantMap observation{{"T_base_flange",matrix(record().transform)},
|
||||
{"T_camera_target",matrix(record().transform)},{"reprojection_px",.2},
|
||||
{"image_points",points},{"object_points",objects},{"corner_ids",ids},
|
||||
{"K",QVariantList{800.,0.,320.,0.,800.,240.,0.,0.,1.}},
|
||||
{"D",QVariantList{0.,0.,0.,0.,0.}},{"width",640},{"height",480},
|
||||
{"capture_id","phone-frame"},{"timestamp_ms",qint64(1720000000000LL)}};
|
||||
QVariantList result; for (int i=0; i<12; ++i) result.append(observation); return result;
|
||||
}
|
||||
static QVariantMap refinement() {
|
||||
const auto m=matrix(record().transform);
|
||||
return {{"method","joint_reprojection_lm"},{"matrix",m},{"fixed_matrix",m},
|
||||
{"initial_matrix",m},{"initial_fixed_matrix",m},{"matrix_name","T_flange_camera"},
|
||||
{"fixed_matrix_name","T_base_target"},{"converged",true},{"accepted",true},
|
||||
{"metrics",QVariantMap{{"initial_rms_px",1.2},{"final_rms_px",.4},
|
||||
{"validation_rms_px",.6},{"validation_sample_count",12},
|
||||
{"iterations",8},{"jacobian_condition",125.}}},{"quality_flags",QVariantList{}},
|
||||
{"extra_metadata",QVariantMap{{"version",1},{"description","preserve me"}}}};
|
||||
}
|
||||
private slots:
|
||||
void fiveSampleRawLegacyIsValidAndRefinementFlagsReject() {
|
||||
auto r=record(); r.sampleCount=5; r.observations=observations();
|
||||
while(r.observations.size()>5) r.observations.removeLast();
|
||||
QString error;
|
||||
QVERIFY2(HandEyeStore::validateRecord(r,error),qPrintable(error));
|
||||
r.sampleCount=12; r.observations=observations(); r.refinement=refinement();
|
||||
r.refinement["quality_flags"]=QVariantList{"validation failed"};
|
||||
QVERIFY(!HandEyeStore::validateRecord(r,error));
|
||||
}
|
||||
void refinedRecordRoundTripAndPointConversion_data() {
|
||||
QTest::addColumn<QString>("mode");
|
||||
QTest::newRow("eye in hand")<<QString("eye_in_hand");
|
||||
QTest::newRow("eye to hand")<<QString("eye_to_hand");
|
||||
}
|
||||
void refinedRecordRoundTripAndPointConversion() {
|
||||
QFETCH(QString,mode); auto r=record(); r.mode=mode;
|
||||
r.refinement=refinement(); r.observations=observations();
|
||||
// Retain rejected originals while reporting only the six active samples.
|
||||
r.sampleCount=6; auto metrics=r.refinement.value("metrics").toMap();
|
||||
metrics["validation_sample_count"]=6; metrics["final_rms_px"]=1.5;
|
||||
metrics["validation_rms_px"]=3.; r.refinement["metrics"]=metrics;
|
||||
if (mode=="eye_to_hand") {
|
||||
r.refinement["matrix_name"]="T_base_camera";
|
||||
r.refinement["fixed_matrix_name"]="T_flange_target";
|
||||
}
|
||||
auto first=r.observations.first().toMap(); first["D"]=QVariantList{};
|
||||
r.observations[0]=first;
|
||||
QTemporaryDir dir; const auto path=dir.filePath("store.ini"); QString error;
|
||||
{
|
||||
QSettings settings(path,QSettings::IniFormat);
|
||||
QVERIFY2(HandEyeStore::save(settings,"s","r",r,false,error),qPrintable(error));
|
||||
}
|
||||
QSettings reopened(path,QSettings::IniFormat); HandEyeStore::Snapshot snapshot;
|
||||
QVERIFY2(HandEyeStore::load(reopened,"s","r",snapshot,error),qPrintable(error));
|
||||
const auto restored=snapshot.records.first();
|
||||
QVERIFY(restored.transform==r.transform); QCOMPARE(restored.refinement,r.refinement);
|
||||
QCOMPARE(restored.observations,r.observations); QCOMPARE(restored.sampleCount,6);
|
||||
const TcpCalibration::Pose flange{{1.,2.,3.,0.,0.,1.5707963267948966}};
|
||||
std::array<double,3> point{};
|
||||
QVERIFY(HandEyeStore::cameraPointToBase(restored,flange,{{.4,.5,.6}},point,error));
|
||||
if (mode=="eye_in_hand") {
|
||||
QVERIFY(std::abs(point[0]-.4)<1e-12); QVERIFY(std::abs(point[1]-1.6)<1e-12);
|
||||
QVERIFY(std::abs(point[2]-3.9)<1e-12);
|
||||
} else {
|
||||
QVERIFY(std::abs(point[0]+.4)<1e-12); QVERIFY(std::abs(point[1]-.6)<1e-12);
|
||||
QVERIFY(std::abs(point[2]-.9)<1e-12);
|
||||
}
|
||||
// Raw phone observations are also useful with a legacy pose-only result.
|
||||
r.refinement.clear(); r.name="raw only";
|
||||
QVERIFY2(HandEyeStore::save(reopened,"s","r",r,false,error),qPrintable(error));
|
||||
QVERIFY(HandEyeStore::load(reopened,"s","r",snapshot,error));
|
||||
QCOMPARE(snapshot.records.last().observations,r.observations);
|
||||
QVERIFY(snapshot.records.last().refinement.isEmpty());
|
||||
r.refinement=restored.refinement; r.observations.clear();
|
||||
QVERIFY(!HandEyeStore::save(reopened,"s","r",r,true,error));
|
||||
QVERIFY(HandEyeStore::load(reopened,"s","r",snapshot,error));
|
||||
QVERIFY(!snapshot.records.last().observations.isEmpty());
|
||||
}
|
||||
void refinementStoragePreservesDataAndLegacy() {
|
||||
QTemporaryDir dir; const auto path=dir.filePath("store.ini"); QString error;
|
||||
QVariantMap original;
|
||||
{
|
||||
QSettings settings(path,QSettings::IniFormat);
|
||||
QVERIFY(HandEyeStore::save(settings,"s","r",record(),false,error));
|
||||
const auto key=settings.allKeys().first(); auto stored=settings.value(key).toMap();
|
||||
QCOMPARE(stored.value("schemaVersion").toInt(),1);
|
||||
auto entries=stored.value("records").toList();
|
||||
original=entries.first().toMap();
|
||||
auto refined=original; refined["name"]="refined";
|
||||
refined["refinement"]=refinement(); refined["observations"]=observations();
|
||||
entries.append(refined); stored["records"]=entries; settings.setValue(key,stored); settings.sync();
|
||||
}
|
||||
QSettings reopened(path,QSettings::IniFormat); HandEyeStore::Snapshot snapshot;
|
||||
QVERIFY2(HandEyeStore::load(reopened,"s","r",snapshot,error),qPrintable(error));
|
||||
QCOMPARE(snapshot.records.size(),2);
|
||||
QVERIFY2(HandEyeStore::select(reopened,"s","r","refined",error),qPrintable(error));
|
||||
const auto saved=reopened.value(reopened.allKeys().first()).toMap().value("records").toList();
|
||||
QCOMPARE(saved.first().toMap(),original);
|
||||
QCOMPARE(saved.last().toMap().value("refinement").toMap(),refinement());
|
||||
QCOMPARE(saved.last().toMap().value("observations").toList(),observations());
|
||||
}
|
||||
void invalidRefinementStorage_data() {
|
||||
QTest::addColumn<int>("bad");
|
||||
const char *cases[]={"wrong refinement type","wrong observations type","missing observations",
|
||||
"wrong method","wrong transform direction","wrong fixed direction","different outer matrix",
|
||||
"invalid fixed pose","missing initial matrix","string accepted","not converged",
|
||||
"missing metrics","negative initial error","excess final error","excess heldout error",
|
||||
"validation count mismatch","infinite condition","wrong flags type","too few observations",
|
||||
"too many observations","active count exceeds observations","non map observation",
|
||||
"invalid flange pose","invalid target pose","negative pose error","unpaired corners",
|
||||
"too few corners","too many corners","string image point","infinite object point",
|
||||
"invalid intrinsic length","negative focal length","invalid intrinsic row","invalid distortion length",
|
||||
"nonfinite distortion","small width","large height","duplicate corner id","negative corner id",
|
||||
"fractional corner id","missing initial fixed matrix","missing accepted","wrong numeric metric",
|
||||
"wrong image point dimension","wrong object point dimension","wrong id count","nonfinite metadata",
|
||||
"fractional width","negative iteration count","nonfinite initial matrix"};
|
||||
for (int i=0;i<int(sizeof(cases)/sizeof(*cases));++i) QTest::newRow(cases[i])<<i;
|
||||
}
|
||||
void invalidRefinementStorage() {
|
||||
QFETCH(int,bad); QTemporaryDir dir; QSettings settings(dir.filePath("store.ini"),QSettings::IniFormat);
|
||||
QString error; QVERIFY(HandEyeStore::save(settings,"s","r",record(),false,error));
|
||||
const auto key=settings.allKeys().first(); auto stored=settings.value(key).toMap();
|
||||
auto entries=stored.value("records").toList(); auto entry=entries.first().toMap();
|
||||
auto ref=refinement(); auto obs=observations(); auto first=obs.first().toMap();
|
||||
auto metrics=ref.value("metrics").toMap();
|
||||
switch(bad) {
|
||||
case 3:ref["method"]="unknown";break;
|
||||
case 4:ref["matrix_name"]="T_base_camera";break;
|
||||
case 5:ref["fixed_matrix_name"]="T_flange_target";break;
|
||||
case 6:{auto m=ref.value("matrix").toList();m[3]=.7;ref["matrix"]=m;break;}
|
||||
case 7:{auto m=ref.value("fixed_matrix").toList();m[0]=2.;ref["fixed_matrix"]=m;break;}
|
||||
case 8:ref.remove("initial_matrix");break;
|
||||
case 9:ref["accepted"]="true";break;
|
||||
case 10:ref["converged"]=false;break;
|
||||
case 12:metrics["initial_rms_px"]=-1.;break;
|
||||
case 13:metrics["final_rms_px"]=1.5001;break;
|
||||
case 14:metrics["validation_rms_px"]=3.0001;break;
|
||||
case 15:metrics["validation_sample_count"]=11;break;
|
||||
case 16:metrics["jacobian_condition"]=INFINITY;break;
|
||||
case 17:ref["quality_flags"]="none";break;
|
||||
case 18:obs=QVariantList{first,first,first,first,first};break;
|
||||
case 19:while(obs.size()<101) obs.append(first);break;
|
||||
case 20:entry["sampleCount"]=13;metrics["validation_sample_count"]=13;break;
|
||||
case 22:{auto m=first.value("T_base_flange").toList();m[15]=0.;first["T_base_flange"]=m;break;}
|
||||
case 23:{auto m=first.value("T_camera_target").toList();m[3]=NAN;first["T_camera_target"]=m;break;}
|
||||
case 24:first["reprojection_px"]=-.1;break;
|
||||
case 25:{auto p=first.value("image_points").toList();p.removeLast();first["image_points"]=p;break;}
|
||||
case 26:case 27:{QVariantList p,o,ids;const int n=bad==26?5:10001;
|
||||
for(int i=0;i<n;++i){p.append(QVariant(QVariantList{1.,2.}));o.append(QVariant(QVariantList{0.,0.,0.}));ids.append(i);}
|
||||
first["image_points"]=p;first["object_points"]=o;first["corner_ids"]=ids;break;}
|
||||
case 28:case 43:{auto p=first.value("image_points").toList();p[0]=bad==28?QVariantList{"1",2.}:QVariantList{1.,2.,3.};first["image_points"]=p;break;}
|
||||
case 29:case 44:{auto p=first.value("object_points").toList();p[0]=bad==29?QVariantList{0.,INFINITY,0.}:QVariantList{0.,0.};first["object_points"]=p;break;}
|
||||
case 30:first["K"]=QVariantList{800.,0.,320.};break;
|
||||
case 31:case 32:{auto k=first.value("K").toList();k[bad==31?0:8]=bad==31?-800.:2.;first["K"]=k;break;}
|
||||
case 33:first["D"]=QVariantList{0.};break;
|
||||
case 34:first["D"]=QVariantList{NAN,0.,0.,0.};break;
|
||||
case 35:first["width"]=1;break;case 36:first["height"]=8193;break;
|
||||
case 37:case 38:case 39:{auto ids=first.value("corner_ids").toList();ids[0]=bad==37?QVariant(1):bad==38?QVariant(-1):QVariant(.5);first["corner_ids"]=ids;break;}
|
||||
case 40:ref.remove("initial_fixed_matrix");break;
|
||||
case 41:ref.remove("accepted");break;
|
||||
case 42:metrics["final_rms_px"]="0.4";break;
|
||||
case 45:first["corner_ids"]=QVariantList{0};break;
|
||||
case 46:first["timing"]=QVariantMap{{"duration_ms",INFINITY}};break;
|
||||
case 47:first["width"]=640.5;break;
|
||||
case 48:metrics["iterations"]=-1;break;
|
||||
case 49:{auto m=ref.value("initial_matrix").toList();m[3]=INFINITY;ref["initial_matrix"]=m;break;}
|
||||
}
|
||||
ref["metrics"]=metrics; if(bad==11) ref.remove("metrics");
|
||||
obs[0]=bad==21?QVariant("bad"):QVariant(first);
|
||||
entry["refinement"]=bad==0?QVariant("bad"):QVariant(ref);
|
||||
entry["observations"]=bad==1?QVariant("bad"):QVariant(obs);
|
||||
if(bad==2) entry.remove("observations");
|
||||
entries[0]=entry;stored["records"]=entries;settings.setValue(key,stored);settings.sync();
|
||||
HandEyeStore::Snapshot snapshot;
|
||||
QVERIFY(!HandEyeStore::load(settings,"s","r",snapshot,error)); QVERIFY(!error.isEmpty());
|
||||
QVERIFY(snapshot.records.isEmpty());
|
||||
QVERIFY(!HandEyeStore::save(settings,"s","r",record(),true,error));
|
||||
QCOMPARE(settings.value(key).toMap(),stored);
|
||||
}
|
||||
void roundTripIsolationAndMultipleCameras() {
|
||||
QTemporaryDir dir; QVERIFY(dir.isValid()); QString error;
|
||||
const QString path=dir.filePath("settings.ini");
|
||||
const auto original=record();
|
||||
{
|
||||
QSettings settings(path,QSettings::IniFormat);
|
||||
QVERIFY2(HandEyeStore::save(settings,"server-1","robot-1",original,false,error),qPrintable(error));
|
||||
auto second=original; second.name="second"; second.cameraId="camera-2";
|
||||
QVERIFY(HandEyeStore::save(settings,"server-1","robot-1",second,false,error));
|
||||
second.name=original.name; second.transform[3]=.7;
|
||||
QVERIFY(HandEyeStore::save(settings,"server-1","robot-2",second,false,error));
|
||||
second.transform[3]=.8;
|
||||
QVERIFY(HandEyeStore::save(settings,"server-2","robot-1",second,false,error));
|
||||
}
|
||||
QSettings reopened(path,QSettings::IniFormat); HandEyeStore::Snapshot s;
|
||||
QVERIFY2(HandEyeStore::load(reopened,"server-1","robot-1",s,error),qPrintable(error));
|
||||
QCOMPARE(s.records.size(),2); QCOMPARE(s.current,QString("second"));
|
||||
const auto restored=s.records.first();
|
||||
QCOMPARE(restored.name,original.name); QCOMPARE(restored.cameraId,original.cameraId);
|
||||
QCOMPARE(restored.mode,original.mode); QCOMPARE(restored.method,original.method);
|
||||
QCOMPARE(restored.createdAt,original.createdAt); QCOMPARE(restored.sampleCount,12);
|
||||
QVERIFY(restored.transform==original.transform); QCOMPARE(restored.metrics,original.metrics);
|
||||
QCOMPARE(restored.board,original.board); QCOMPARE(restored.intrinsics,original.intrinsics);
|
||||
QVERIFY(HandEyeStore::load(reopened,"server-1","robot-2",s,error));
|
||||
QCOMPARE(s.records.size(),1); QCOMPARE(s.records.first().transform[3],.7);
|
||||
QVERIFY(HandEyeStore::load(reopened,"server-2","robot-1",s,error));
|
||||
QCOMPARE(s.records.first().transform[3],.8);
|
||||
QVERIFY(HandEyeStore::load(reopened,"unknown","robot-1",s,error)); QVERIFY(s.records.isEmpty());
|
||||
}
|
||||
void overwriteDeleteAndCurrentSelection() {
|
||||
QTemporaryDir dir; QSettings settings(dir.filePath("store.ini"),QSettings::IniFormat);
|
||||
QString error; auto r=record(); HandEyeStore::Snapshot s;
|
||||
QVERIFY(HandEyeStore::save(settings,"s","r",r,false,error));
|
||||
r.transform[3]=.9; QVERIFY(!HandEyeStore::save(settings,"s","r",r,false,error));
|
||||
QVERIFY(!error.isEmpty()); QVERIFY(HandEyeStore::load(settings,"s","r",s,error));
|
||||
QCOMPARE(s.records.first().transform[3],.1);
|
||||
QVERIFY(HandEyeStore::save(settings,"s","r",r,true,error));
|
||||
r.name="second"; QVERIFY(HandEyeStore::save(settings,"s","r",r,false,error));
|
||||
QVERIFY(HandEyeStore::select(settings,"s","r",record().name,error));
|
||||
QVERIFY(!HandEyeStore::select(settings,"s","r","missing",error));
|
||||
QVERIFY(!HandEyeStore::remove(settings,"s","r","missing",error));
|
||||
QVERIFY(HandEyeStore::load(settings,"s","r",s,error)); QCOMPARE(s.current,record().name);
|
||||
QCOMPARE(s.records.first().transform[3],.9);
|
||||
QVERIFY(HandEyeStore::remove(settings,"s","r",record().name,error));
|
||||
QVERIFY(HandEyeStore::load(settings,"s","r",s,error)); QVERIFY(s.current.isEmpty()); QCOMPARE(s.records.size(),1);
|
||||
QVERIFY(HandEyeStore::select(settings,"s","r","second",error));
|
||||
QVERIFY(HandEyeStore::select(settings,"s","r",QString(),error));
|
||||
QVERIFY(HandEyeStore::load(settings,"s","r",s,error)); QVERIFY(s.current.isEmpty());
|
||||
}
|
||||
void invalidRecords_data() {
|
||||
QTest::addColumn<int>("bad");
|
||||
const char *cases[]={"empty name","whitespace name","empty camera","invalid mode","empty method",
|
||||
"empty timestamp","too few samples","missing accepted","rejected quality","string accepted",
|
||||
"reflection","scale","homogeneous row","matrix NaN","matrix infinity","metadata NaN"};
|
||||
for(int i=0;i<16;++i) QTest::newRow(cases[i])<<i;
|
||||
}
|
||||
void invalidRecords() {
|
||||
QFETCH(int,bad); auto r=record();
|
||||
switch(bad) {
|
||||
case 0:r.name.clear();break; case 1:r.name=" bad ";break; case 2:r.cameraId.clear();break;
|
||||
case 3:r.mode="unknown";break; case 4:r.method.clear();break; case 5:r.createdAt.clear();break;
|
||||
case 6:r.sampleCount=4;break; case 7:r.metrics.remove("accepted");break;
|
||||
case 8:r.metrics["accepted"]=false;break; case 9:r.metrics["accepted"]="true";break;
|
||||
case 10:r.transform[1]=1.;break; case 11:r.transform[1]=-2.;break;
|
||||
case 12:r.transform[15]=0.;break; case 13:r.transform[3]=std::numeric_limits<double>::quiet_NaN();break;
|
||||
case 14:r.transform[3]=std::numeric_limits<double>::infinity();break;
|
||||
case 15:r.intrinsics["nested"]=QVariantMap{{"bad",std::numeric_limits<double>::quiet_NaN()}};break;
|
||||
}
|
||||
QString error; QVERIFY(!HandEyeStore::validateRecord(r,error)); QVERIFY(!error.isEmpty());
|
||||
QTemporaryDir dir; QSettings settings(dir.filePath("store.ini"),QSettings::IniFormat);
|
||||
QVERIFY(!HandEyeStore::save(settings,"s","r",r,false,error)); QVERIFY(settings.allKeys().isEmpty());
|
||||
}
|
||||
void malformedStorageFailsClosed_data() {
|
||||
QTest::addColumn<int>("bad");
|
||||
const char *cases[]={"schema","units","direction","missing metrics","string sample count",
|
||||
"duplicate names","missing current","unknown current","wrong identity","string matrix",
|
||||
"non map record","non list records","missing board","missing intrinsics"};
|
||||
for(int i=0;i<14;++i) QTest::newRow(cases[i])<<i;
|
||||
}
|
||||
void malformedStorageFailsClosed() {
|
||||
QFETCH(int,bad); QTemporaryDir dir; QSettings settings(dir.filePath("store.ini"),QSettings::IniFormat);
|
||||
QString error; QVERIFY(HandEyeStore::save(settings,"s","r",record(),false,error));
|
||||
const QString key=settings.allKeys().first(); auto stored=settings.value(key).toMap();
|
||||
auto records=stored.value("records").toList(); auto first=records.first().toMap();
|
||||
switch(bad) {
|
||||
case 0:stored.remove("schemaVersion");break; case 1:stored["units"]="mm_deg";break;
|
||||
case 2:first["matrixDirection"]="Camera_T_Flange";break; case 3:first.remove("metrics");break;
|
||||
case 4:first["sampleCount"]="12";break; case 5:records.append(first);break;
|
||||
case 6:stored.remove("current");break; case 7:stored["current"]="missing";break;
|
||||
case 8:stored["device"]="other";break;
|
||||
case 9:{auto matrix=first.value("transformSI").toList();matrix[0]="0";first["transformSI"]=matrix;break;}
|
||||
case 10:records[0]="bad";break; case 11:stored["records"]="bad";break;
|
||||
case 12:first.remove("board");break;case 13:first.remove("intrinsics");break;
|
||||
}
|
||||
if(bad!=10) records[0]=first;
|
||||
if(bad!=11) stored["records"]=records;
|
||||
settings.setValue(key,stored); settings.sync(); HandEyeStore::Snapshot snapshot;
|
||||
snapshot.records.append(record()); snapshot.current="stale";
|
||||
QVERIFY(!HandEyeStore::load(settings,"s","r",snapshot,error)); QVERIFY(!error.isEmpty());
|
||||
QVERIFY(snapshot.records.isEmpty()); QVERIFY(snapshot.current.isEmpty());
|
||||
QVERIFY(!HandEyeStore::save(settings,"s","r",record(),true,error));
|
||||
QVERIFY(!HandEyeStore::remove(settings,"s","r",record().name,error));
|
||||
QVERIFY(!HandEyeStore::select(settings,"s","r",QString(),error));
|
||||
QCOMPARE(settings.value(key).toMap(),stored);
|
||||
}
|
||||
void pointConversionKnownTruth() {
|
||||
auto r=record(); QString error;
|
||||
const TcpCalibration::Pose flange{{1.,2.,3.,0.,0.,1.5707963267948966}};
|
||||
std::array<double,3> out{{99,99,99}};
|
||||
QVERIFY2(HandEyeStore::cameraPointToBase(r,flange,{{.4,.5,.6}},out,error),qPrintable(error));
|
||||
QVERIFY(std::abs(out[0]-.4)<1e-12); QVERIFY(std::abs(out[1]-1.6)<1e-12); QVERIFY(std::abs(out[2]-3.9)<1e-12);
|
||||
r.mode="eye_to_hand";
|
||||
QVERIFY(HandEyeStore::cameraPointToBase(r,flange,{{.4,.5,.6}},out,error));
|
||||
QVERIFY(std::abs(out[0]+.4)<1e-12); QVERIFY(std::abs(out[1]-.6)<1e-12); QVERIFY(std::abs(out[2]-.9)<1e-12);
|
||||
const auto unchanged=out;
|
||||
QVERIFY(!HandEyeStore::cameraPointToBase(r,flange,{{NAN,0,0}},out,error)); QVERIFY(out==unchanged);
|
||||
r.mode="eye_in_hand"; auto invalid=flange; invalid[0]=INFINITY;
|
||||
QVERIFY(!HandEyeStore::cameraPointToBase(r,invalid,{{0,0,0}},out,error)); QVERIFY(out==unchanged);
|
||||
r.metrics["accepted"]=false;
|
||||
QVERIFY(!HandEyeStore::cameraPointToBase(r,flange,{{0,0,0}},out,error)); QVERIFY(out==unchanged);
|
||||
}
|
||||
void emptyIdentityAndWriteFailure() {
|
||||
QTemporaryDir dir; QSettings settings(dir.filePath("store.ini"),QSettings::IniFormat);
|
||||
QString error; HandEyeStore::Snapshot s;
|
||||
QVERIFY(!HandEyeStore::save(settings,"","r",record(),false,error));
|
||||
QVERIFY(!HandEyeStore::load(settings,"s"," ",s,error));
|
||||
QFile blocker(dir.filePath("blocker")); QVERIFY(blocker.open(QIODevice::WriteOnly)); blocker.close();
|
||||
QSettings unwritable(dir.filePath("blocker/store.ini"),QSettings::IniFormat);
|
||||
QVERIFY(!HandEyeStore::save(unwritable,"s","r",record(),false,error)); QVERIFY(!error.isEmpty());
|
||||
}
|
||||
};
|
||||
QTEST_GUILESS_MAIN(HandEyeStoreTest)
|
||||
#include "handeyestore_test.moc"
|
||||
8
tests/handeyestore_test.pro
Normal file
8
tests/handeyestore_test.pro
Normal file
@ -0,0 +1,8 @@
|
||||
QT += core testlib
|
||||
QT -= gui
|
||||
CONFIG += console testcase c++14
|
||||
CONFIG -= app_bundle
|
||||
TEMPLATE = app
|
||||
TARGET = handeyestore_test
|
||||
SOURCES += handeyestore_test.cpp ../src/handeyestore.cpp ../src/tcpcalibration.cpp
|
||||
HEADERS += ../src/handeyestore.h ../src/tcpcalibration.h
|
||||
553
tests/handeyeui_test.cpp
Normal file
553
tests/handeyeui_test.cpp
Normal file
@ -0,0 +1,553 @@
|
||||
#include <QtWidgets>
|
||||
#include <QtTest>
|
||||
#include <QTemporaryDir>
|
||||
#include <cmath>
|
||||
#include "../src/handeyestore.h"
|
||||
#include "../src/videoframe.h"
|
||||
#include "../src/handeyebridge.h"
|
||||
#include "../src/videorenderwidget.h"
|
||||
// Exercise the real UI state machine without a robot, stream or application.
|
||||
#define private public
|
||||
#include "../ui/handeyecalibrationwidget.h"
|
||||
#undef private
|
||||
|
||||
class OffscreenDialogFilter : public QObject
|
||||
{
|
||||
public:
|
||||
using QObject::QObject;
|
||||
bool eventFilter(QObject *object,QEvent *event) override {
|
||||
return QGuiApplication::platformName()==QStringLiteral("offscreen")
|
||||
&& event->type()==QEvent::Show && qobject_cast<QMessageBox *>(object);
|
||||
}
|
||||
};
|
||||
|
||||
class HandEyeUiTest : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
QTemporaryDir settingsDir;
|
||||
QTimer dialogCloser;
|
||||
QString python,script;
|
||||
const QString camera=QStringLiteral("test-camera");
|
||||
const QString device=QStringLiteral("aubo-test");
|
||||
|
||||
static QImage boardImage() {
|
||||
QImage image(800,600,QImage::Format_RGBA8888); image.fill(Qt::white);
|
||||
QPainter painter(&image);
|
||||
for (int y=0;y<7;++y) for (int x=0;x<10;++x)
|
||||
if ((x+y)%2==0) painter.fillRect(100+x*50,100+y*50,50,50,Qt::black);
|
||||
return image;
|
||||
}
|
||||
static QVariantMap intrinsics() {
|
||||
return {{"fx",700.0},{"fy",700.0},{"cx",400.0},{"cy",300.0},
|
||||
{"width",800},{"height",600},{"coeffs",QVariantList{0.,0.,0.,0.,0.}}};
|
||||
}
|
||||
static VideoFrame frame() {
|
||||
const QImage image=boardImage();
|
||||
VideoFrame frame;
|
||||
frame.width=image.width(); frame.height=image.height();
|
||||
frame.format=VideoPixelFormat::RGBA; frame.stride0=image.bytesPerLine();
|
||||
// Own the bytes; no borrowed QImage pointer crosses the worker thread.
|
||||
frame.plane0=QByteArray(reinterpret_cast<const char *>(image.constBits()),int(image.sizeInBytes()));
|
||||
frame.intrinsics=intrinsics();
|
||||
frame.metadata={{"kind","rgb"},{"ptsMatched",true},{"captureTimestampAvailable",true},
|
||||
{"captureUtcNs",QDateTime::currentMSecsSinceEpoch()*1000000}, {"sourceSequence",qulonglong(1)}};
|
||||
return frame;
|
||||
}
|
||||
static QVariantMap pose() {
|
||||
return {{"x",.35},{"y",-.1},{"z",.6},{"rx",.2},{"ry",-.1},{"rz",.3}};
|
||||
}
|
||||
static QVariantMap state(qint64 requested,qint64 received) {
|
||||
return {{"connected",true},{"moving",false},{"fault",false},
|
||||
{"requestedAtMs",requested},{"receivedAtMs",received}};
|
||||
}
|
||||
QVariantMap detectionRequest(const QString &id) const {
|
||||
return {{"op","detect"},{"id",id},{"width",800},{"height",600},
|
||||
{"K",QVariantList{700.,0.,400.,0.,700.,300.,0.,0.,1.}},
|
||||
{"D",QVariantList{0.,0.,0.,0.,0.}},
|
||||
{"board",QVariantMap{{"type","chessboard"},{"columns",9},{"rows",6},{"square_size_m",.025}}}};
|
||||
}
|
||||
void ready(HandEyeCalibrationWidget &widget) {
|
||||
widget.setContext(QStringLiteral("test-server:50052"),device,true,false,true,{});
|
||||
widget.setCameraIds({camera});
|
||||
widget.findChild<QCheckBox *>(QStringLiteral("cameraConfirmed"))->setChecked(true);
|
||||
QSignalSpy images(&widget,&HandEyeCalibrationWidget::imageRequested);
|
||||
widget.startPreview();
|
||||
QCOMPARE(images.count(),1);
|
||||
widget.acceptImage(images.first().at(1).toULongLong(),camera,boardImage(),intrinsics(),{},true,QString());
|
||||
QTRY_VERIFY_WITH_TIMEOUT(widget.m_ready,10000);
|
||||
QVERIFY(widget.m_preview);
|
||||
QVERIFY(!widget.m_nativeIntrinsics.isEmpty());
|
||||
}
|
||||
void beforePose(HandEyeCalibrationWidget &widget) {
|
||||
QSignalSpy requests(&widget,&HandEyeCalibrationWidget::captureRequested);
|
||||
widget.capture();
|
||||
QCOMPARE(requests.count(),1);
|
||||
const qint64 now=QDateTime::currentMSecsSinceEpoch();
|
||||
widget.acceptPose(requests.first().at(1).toULongLong(),device,pose(),state(now-2,now-1),true,QString());
|
||||
QCOMPARE(int(widget.m_phase),int(HandEyeCalibrationWidget::WaitingFrame));
|
||||
}
|
||||
void finishPair(HandEyeCalibrationWidget &widget) {
|
||||
widget.acceptFrame(camera,frame(),QString());
|
||||
QTRY_COMPARE_WITH_TIMEOUT(int(widget.m_phase),int(HandEyeCalibrationWidget::AfterPose),10000);
|
||||
const qint64 now=QDateTime::currentMSecsSinceEpoch();
|
||||
widget.acceptPose(widget.m_poseToken,device,pose(),state(now,now),true,QString());
|
||||
QCOMPARE(int(widget.m_phase),int(HandEyeCalibrationWidget::Idle));
|
||||
}
|
||||
private slots:
|
||||
void initTestCase() {
|
||||
QVERIFY(settingsDir.isValid());
|
||||
qApp->installEventFilter(new OffscreenDialogFilter(qApp));
|
||||
QSettings::setDefaultFormat(QSettings::IniFormat);
|
||||
QSettings::setPath(QSettings::IniFormat,QSettings::UserScope,settingsDir.path());
|
||||
QCoreApplication::setOrganizationName(QStringLiteral("CMVR-HandEye-Isolated-Test"));
|
||||
QCoreApplication::setApplicationName(QStringLiteral("HandEyeUi"));
|
||||
python=QDir(QCoreApplication::applicationDirPath()).filePath("runtime/handeye/python.exe");
|
||||
QVERIFY2(QFileInfo::exists(python),"Deploy the bundled runtime beside this test executable");
|
||||
script=QFINDTESTDATA("../scripts/handeye_worker.py");
|
||||
QVERIFY(QFileInfo::exists(script));
|
||||
connect(&dialogCloser,&QTimer::timeout,[] {
|
||||
for (QWidget *widget:QApplication::topLevelWidgets())
|
||||
if (auto *box=qobject_cast<QMessageBox *>(widget)) {
|
||||
auto *button=box->button(QMessageBox::Ok);
|
||||
if (button) button->click();
|
||||
}
|
||||
});
|
||||
dialogCloser.start(25);
|
||||
}
|
||||
void init() {
|
||||
QSettings settings;
|
||||
settings.clear(); settings.sync();
|
||||
}
|
||||
void bundledRuntimeStartsOnShowAndIgnoresOldConfiguration() {
|
||||
QSettings settings;
|
||||
settings.setValue("handEyeCalibration/python",QStringLiteral("Z:/missing-old-python.exe"));
|
||||
settings.sync();
|
||||
HandEyeCalibrationWidget widget;
|
||||
QVERIFY(!widget.findChild<QLineEdit *>(QStringLiteral("handEyePythonPath")));
|
||||
widget.show();
|
||||
QTRY_VERIFY_WITH_TIMEOUT(widget.m_ready,10000);
|
||||
QVERIFY(widget.m_errorMessage.isEmpty());
|
||||
widget.hide();
|
||||
QVERIFY(!widget.m_ready);
|
||||
widget.show();
|
||||
QTRY_VERIFY_WITH_TIMEOUT(widget.m_ready,10000);
|
||||
widget.hide();
|
||||
}
|
||||
void livePreviewDoesNotWaitForDetectionOrIntrinsics() {
|
||||
HandEyeCalibrationWidget widget;
|
||||
widget.m_preview=true; widget.m_previewCamera=camera;
|
||||
widget.m_ready=true; widget.m_nativeIntrinsics=intrinsics();
|
||||
auto *video=widget.findChild<VideoRenderWidget *>();
|
||||
QVERIFY(video);
|
||||
auto input=frame(); input.intrinsics.clear();
|
||||
widget.acceptFrame(camera,input,QString());
|
||||
QVERIFY2(video->hasFrame(),"Valid RGB must display even when calibration metadata is missing");
|
||||
widget.m_phase=HandEyeCalibrationWidget::DetectPair;
|
||||
input.height=300;
|
||||
widget.acceptFrame(camera,input,QString());
|
||||
QCOMPARE(video->heightForWidth(800),300);
|
||||
widget.m_detectFrame=frame(); widget.m_requestId="old"; widget.m_requestOp="detect";
|
||||
widget.handleReply({{"id","old"},{"ok",true},{"valid",false}});
|
||||
QCOMPARE(video->heightForWidth(800),300);
|
||||
widget.stopPreview();
|
||||
QVERIFY(!video->hasFrame());
|
||||
}
|
||||
void previewFillsHostWithoutChangingFrameAspect() {
|
||||
HandEyeCalibrationWidget widget;
|
||||
widget.resize(1800,1100); widget.show();
|
||||
auto *video=widget.findChild<VideoRenderWidget *>();
|
||||
QVERIFY(video);
|
||||
QTest::qWait(100);
|
||||
QVERIFY2(video->width()>=video->parentWidget()->width()-32,"Preview must fill its host, not stay at the 640px size hint");
|
||||
auto input=frame(); input.height=450;
|
||||
video->setFrame(input);
|
||||
QTest::qWait(30);
|
||||
QCOMPARE(video->height(),qRound(video->width()*450.0/800));
|
||||
widget.hide();
|
||||
}
|
||||
void ordinaryPreviewDoesNotLaunchBoardDetection() {
|
||||
HandEyeCalibrationWidget widget; ready(widget);
|
||||
for (int i=0;i<10;++i) widget.acceptFrame(camera,frame(),QString());
|
||||
QVERIFY(!widget.m_bridge->busy());
|
||||
QVERIFY(widget.m_requestId.isEmpty());
|
||||
QVERIFY(widget.findChild<VideoRenderWidget *>()->hasFrame());
|
||||
beforePose(widget); finishPair(widget);
|
||||
QCOMPARE(widget.m_samples.size(),1);
|
||||
}
|
||||
void autoPreviewAndJointJogLifecycle() {
|
||||
HandEyeCalibrationWidget widget; QSignalSpy preview(&widget,&HandEyeCalibrationWidget::previewRequested);
|
||||
QSignalSpy jog(&widget,&HandEyeCalibrationWidget::jointJogRequested),stop(&widget,&HandEyeCalibrationWidget::jointJogStopped);
|
||||
widget.setContext("server",device,true,false,true,{}); widget.setCameraIds({camera});
|
||||
widget.setJointStates({"joint1","joint2"},{}); QCOMPARE(stop.count(),0);
|
||||
widget.show(); QTRY_VERIFY(widget.m_preview); QCOMPARE(preview.count(),1);
|
||||
widget.m_jointButtons[1]->pressed(); QCOMPARE(jog.count(),1); QCOMPARE(jog.first()[0].toInt(),0); QCOMPARE(jog.first()[1].toInt(),1);
|
||||
widget.hide(); QCOMPARE(stop.count(),1); QVERIFY(!widget.m_preview);
|
||||
}
|
||||
void processCheckAndRealDetection() {
|
||||
HandEyeBridge bridge;
|
||||
QSignalSpy replies(&bridge,&HandEyeBridge::completed),errors(&bridge,&HandEyeBridge::failed);
|
||||
bridge.start(python,script);
|
||||
QVERIFY(bridge.submit({{"op","check"},{"id","9007199254740993"}}));
|
||||
QTRY_COMPARE_WITH_TIMEOUT(replies.count(),1,10000);
|
||||
QCOMPARE(errors.count(),0);
|
||||
const auto check=replies.first().first().toMap();
|
||||
QVERIFY(check.value("ok").toBool()); QCOMPARE(check.value("protocol").toInt(),1);
|
||||
QCOMPARE(check.value("id").toString(),QStringLiteral("9007199254740993"));
|
||||
QCOMPARE(check.value("methods").toList().size(),6);
|
||||
QVERIFY(bridge.submit(detectionRequest("detect-1"),frame()));
|
||||
QTRY_COMPARE_WITH_TIMEOUT(replies.count(),2,10000);
|
||||
const auto detection=replies.last().first().toMap();
|
||||
QVERIFY2(detection.value("valid").toBool(),qPrintable(detection.value("error").toString()));
|
||||
QCOMPARE(detection.value("T_camera_target").toList().size(),16);
|
||||
QCOMPARE(detection.value("corners").toList().size(),54);
|
||||
QCOMPARE(detection.value("axes").toList().size(),4);
|
||||
QVERIFY(detection.value("reprojection_px").toDouble()<.5);
|
||||
QVERIFY(!bridge.busy());
|
||||
}
|
||||
void failedProcessCanRestartAndReturnLatestEpoch() {
|
||||
HandEyeBridge bridge;
|
||||
QSignalSpy replies(&bridge,&HandEyeBridge::completed),errors(&bridge,&HandEyeBridge::failed);
|
||||
bridge.start(settingsDir.filePath("missing-python.exe"),script);
|
||||
QVERIFY(bridge.submit({{"op","check"},{"id","bad"}}));
|
||||
QTRY_VERIFY_WITH_TIMEOUT(!errors.isEmpty(),5000);
|
||||
QVERIFY(!bridge.busy());
|
||||
bridge.start(python,script);
|
||||
QVERIFY(bridge.submit({{"op","check"},{"id","restarted"}}));
|
||||
QTRY_COMPARE_WITH_TIMEOUT(replies.count(),1,10000);
|
||||
QCOMPARE(replies.first().first().toMap().value("id").toString(),QStringLiteral("restarted"));
|
||||
bridge.start(python,script);
|
||||
QVERIFY(bridge.submit({{"op","check"},{"id","superseded"}}));
|
||||
bridge.start(python,script);
|
||||
QVERIFY(bridge.submit({{"op","check"},{"id","latest"}}));
|
||||
QTRY_COMPARE_WITH_TIMEOUT(replies.count(),2,10000);
|
||||
QCOMPARE(replies.last().first().toMap().value("id").toString(),QStringLiteral("latest"));
|
||||
}
|
||||
void pairedSampleAndDuplicateRejection() {
|
||||
HandEyeCalibrationWidget widget; ready(widget);
|
||||
QSignalSpy detections(widget.m_bridge,&HandEyeBridge::completed);
|
||||
beforePose(widget); finishPair(widget);
|
||||
QCOMPARE(widget.m_samples.size(),1);
|
||||
const auto sample=widget.m_samples.first();
|
||||
QCOMPARE(sample.value("T_base_flange").toList().size(),16);
|
||||
QCOMPARE(sample.value("T_camera_target").toList().size(),16);
|
||||
QVERIFY(sample.value("reprojection_px").toDouble()<.5);
|
||||
QVERIFY(!detections.isEmpty());
|
||||
const auto detected=detections.last().first().toMap();
|
||||
for (const auto &key:{"image_points","object_points","corner_ids","K","D","width","height"}) {
|
||||
QVERIFY2(sample.contains(key),key);
|
||||
QCOMPARE(sample.value(key),detected.value(key));
|
||||
}
|
||||
QCOMPARE(sample.value("image_points").toList().size(),54);
|
||||
QCOMPARE(sample.value("object_points").toList().size(),54);
|
||||
QCOMPARE(sample.value("corner_ids").toList().size(),54);
|
||||
QCOMPARE(sample.value("K").toList(),detectionRequest("unused").value("K").toList());
|
||||
QCOMPARE(sample.value("width").toInt(),800);
|
||||
QCOMPARE(sample.value("height").toInt(),600);
|
||||
beforePose(widget); finishPair(widget);
|
||||
QCOMPARE(widget.m_samples.size(),1);
|
||||
}
|
||||
void algorithmSelectionPreservesRawSamplesAndInvalidatesResult() {
|
||||
HandEyeCalibrationWidget widget; ready(widget);
|
||||
QCOMPARE(widget.m_optimization->currentData().toString(),QStringLiteral("joint_reprojection"));
|
||||
beforePose(widget); finishPair(widget);
|
||||
const auto samples=widget.m_samples;
|
||||
for (auto *choice:{widget.m_optimization,widget.m_method}) {
|
||||
QVERIFY(choice->count()>1);
|
||||
widget.m_resultValid=true;
|
||||
widget.m_result.metrics={{"accepted",true}};
|
||||
widget.m_result.refinement={{"accepted",true}};
|
||||
widget.refresh();
|
||||
QVERIFY(widget.m_save->isEnabled());
|
||||
choice->setCurrentIndex(1);
|
||||
QCOMPARE(widget.m_samples,samples);
|
||||
QVERIFY(!widget.m_resultValid);
|
||||
QVERIFY(widget.m_result.metrics.isEmpty());
|
||||
QVERIFY(widget.m_result.refinement.isEmpty());
|
||||
QVERIFY(!widget.m_save->isEnabled());
|
||||
QVERIFY(widget.m_preview); QVERIFY(widget.m_ready);
|
||||
}
|
||||
}
|
||||
void algorithmChangeIgnoresRealPendingSolveReply() {
|
||||
HandEyeCalibrationWidget widget; ready(widget);
|
||||
beforePose(widget); finishPair(widget);
|
||||
const auto sample=widget.m_samples.first();
|
||||
while (widget.m_samples.size()<6) widget.m_samples.append(sample);
|
||||
const auto samples=widget.m_samples;
|
||||
QSignalSpy replies(widget.m_bridge,&HandEyeBridge::completed);
|
||||
widget.calculate();
|
||||
QCOMPARE(widget.m_requestOp,QStringLiteral("solve"));
|
||||
const auto obsolete=widget.m_requestId;
|
||||
QVERIFY(!obsolete.isEmpty());
|
||||
widget.m_optimization->setCurrentIndex(1);
|
||||
QVERIFY(widget.m_requestId.isEmpty());
|
||||
QVERIFY(widget.m_requestOp.isEmpty());
|
||||
QTRY_COMPARE_WITH_TIMEOUT(replies.count(),1,10000);
|
||||
QCOMPARE(replies.first().first().toMap().value("id").toString(),obsolete);
|
||||
// Repeated robot poses make the actual worker reply a failure. It belongs
|
||||
// to the old selection and must not populate the current error/result.
|
||||
QVERIFY(!replies.first().first().toMap().value("ok").toBool());
|
||||
QVERIFY(widget.m_errorMessage.isEmpty());
|
||||
QVERIFY(widget.m_result.metrics.isEmpty());
|
||||
QVERIFY(!widget.m_resultValid);
|
||||
QCOMPARE(widget.m_samples,samples);
|
||||
QVERIFY(widget.m_preview); QVERIFY(widget.m_ready);
|
||||
}
|
||||
void jointCalculationSaveReloadAndPointConversion_data() {
|
||||
QTest::addColumn<QString>("mode");
|
||||
QTest::newRow("eye-in-hand")<<QStringLiteral("eye_in_hand");
|
||||
QTest::newRow("eye-to-hand")<<QStringLiteral("eye_to_hand");
|
||||
}
|
||||
void jointCalculationSaveReloadAndPointConversion() {
|
||||
QFETCH(QString,mode);
|
||||
const QString fixtures=QFINDTESTDATA("test_handeye_joint_worker.py");
|
||||
QVERIFY(QFileInfo::exists(fixtures));
|
||||
// Generate observations and expected point independently of production
|
||||
// transforms. The fixture uses physical chains and explicit Brown optics.
|
||||
const QString code=QStringLiteral(
|
||||
"import sys,json,numpy as np; sys.path.insert(0,sys.argv[1]); "
|
||||
"from test_handeye_joint_worker import request_for; "
|
||||
"x,y,request=request_for(sys.argv[2]); "
|
||||
"g=np.array(request['samples'][0]['T_base_flange']).reshape(4,4); "
|
||||
"p=np.array([.1,-.05,.7,1.]); "
|
||||
"expected=(g@x@p if sys.argv[2]=='eye_in_hand' else x@p); "
|
||||
"print(json.dumps(dict(request=request,x=x.ravel().tolist(),y=y.ravel().tolist(),"
|
||||
"g=g.ravel().tolist(),point=p[:3].tolist(),expected=expected[:3].tolist())))");
|
||||
QProcess generator;
|
||||
generator.start(python,{"-B","-c",code,QFileInfo(fixtures).absolutePath(),mode});
|
||||
QVERIFY(generator.waitForStarted(10000));
|
||||
QVERIFY(generator.waitForFinished(20000));
|
||||
QCOMPARE(generator.exitStatus(),QProcess::NormalExit);
|
||||
QVERIFY2(generator.exitCode()==0,generator.readAllStandardError().constData());
|
||||
QJsonParseError parseError;
|
||||
const auto payload=QJsonDocument::fromJson(generator.readAllStandardOutput(),&parseError).toVariant().toMap();
|
||||
QCOMPARE(parseError.error,QJsonParseError::NoError);
|
||||
const auto request=payload.value("request").toMap();
|
||||
const auto observations=request.value("samples").toList();
|
||||
QCOMPARE(observations.size(),12);
|
||||
HandEyeCalibrationWidget widget; ready(widget);
|
||||
widget.m_mode->setCurrentIndex(widget.m_mode->findData(mode));
|
||||
widget.m_columns->setValue(7); widget.m_rows->setValue(5);
|
||||
widget.m_square->setValue(25.0); // UI millimetres; fixture object points are metres.
|
||||
for (const auto &observation:observations) widget.m_samples.append(observation.toMap());
|
||||
const auto first=observations.first().toMap();
|
||||
const auto k=first.value("K").toList();
|
||||
widget.m_usedIntrinsics={{"fx",k[0]},{"fy",k[4]},{"cx",k[2]},{"cy",k[5]},
|
||||
{"width",first.value("width")},{"height",first.value("height")},{"coeffs",first.value("D")}};
|
||||
QSignalSpy replies(widget.m_bridge,&HandEyeBridge::completed);
|
||||
widget.calculate();
|
||||
QTRY_COMPARE_WITH_TIMEOUT(replies.count(),1,30000);
|
||||
QVERIFY2(widget.m_resultValid,qPrintable(widget.m_errorMessage));
|
||||
QVERIFY(widget.m_save->isEnabled());
|
||||
QCOMPARE(widget.m_result.mode,mode);
|
||||
QVERIFY(widget.m_result.refinement.value("accepted").toBool());
|
||||
const auto computed=widget.m_result;
|
||||
const auto expectedX=payload.value("x").toList(),expectedY=payload.value("y").toList();
|
||||
const auto fixed=computed.refinement.value("fixed_matrix").toList();
|
||||
QCOMPARE(fixed.size(),16);
|
||||
for (int i=0;i<16;++i) {
|
||||
QVERIFY(std::abs(computed.transform[size_t(i)]-expectedX[i].toDouble())<2e-6);
|
||||
QVERIFY(std::abs(fixed[i].toDouble()-expectedY[i].toDouble())<2e-6);
|
||||
}
|
||||
const QString name=QStringLiteral("joint-%1").arg(mode);
|
||||
widget.m_name->setText(name);
|
||||
QSignalSpy changed(&widget,&HandEyeCalibrationWidget::calibrationsChanged);
|
||||
widget.saveResult();
|
||||
QCOMPARE(changed.count(),1);
|
||||
QCOMPARE(changed.first().at(0).toString(),widget.m_endpoint);
|
||||
QCOMPARE(changed.first().at(1).toString(),device);
|
||||
QCOMPARE(changed.first().at(2).toString(),name);
|
||||
QSettings reopened;
|
||||
HandEyeStore::Snapshot saved; QString error;
|
||||
QVERIFY2(HandEyeStore::load(reopened,widget.m_endpoint,device,saved,error),qPrintable(error));
|
||||
QCOMPARE(saved.records.size(),1);
|
||||
QCOMPARE(saved.current,name);
|
||||
const auto restored=saved.records.first();
|
||||
QCOMPARE(restored.mode,mode);
|
||||
QCOMPARE(restored.observations,observations);
|
||||
QCOMPARE(restored.refinement,computed.refinement);
|
||||
for (size_t i=0;i<restored.transform.size();++i)
|
||||
QCOMPARE(restored.transform[i],computed.transform[i]);
|
||||
TcpCalibration::Matrix g{};
|
||||
const auto robot=payload.value("g").toList();
|
||||
for (int i=0;i<16;++i) g[size_t(i)]=robot[i].toDouble();
|
||||
TcpCalibration::Pose flange{};
|
||||
QVERIFY2(TcpCalibration::matrixPose(g,flange,&error),qPrintable(error));
|
||||
const auto point=payload.value("point").toList();
|
||||
const std::array<double,3> cameraPoint{{point[0].toDouble(),point[1].toDouble(),point[2].toDouble()}};
|
||||
std::array<double,3> actual{},inParent{},expectedRefined{};
|
||||
QVERIFY2(HandEyeStore::cameraPointToBase(restored,flange,cameraPoint,actual,error),qPrintable(error));
|
||||
for (int row=0;row<3;++row) {
|
||||
inParent[size_t(row)]=restored.transform[size_t(row*4+3)];
|
||||
for (int col=0;col<3;++col)
|
||||
inParent[size_t(row)]+=restored.transform[size_t(row*4+col)]*cameraPoint[size_t(col)];
|
||||
}
|
||||
expectedRefined=inParent;
|
||||
if (mode=="eye_in_hand") for (int row=0;row<3;++row) {
|
||||
expectedRefined[size_t(row)]=g[size_t(row*4+3)];
|
||||
for (int col=0;col<3;++col) expectedRefined[size_t(row)]+=g[size_t(row*4+col)]*inParent[size_t(col)];
|
||||
}
|
||||
const auto expectedPoint=payload.value("expected").toList();
|
||||
for (int axis=0;axis<3;++axis) {
|
||||
QVERIFY(std::abs(actual[size_t(axis)]-expectedRefined[size_t(axis)])<1e-10);
|
||||
QVERIFY(std::abs(actual[size_t(axis)]-expectedPoint[axis].toDouble())<2e-6);
|
||||
}
|
||||
}
|
||||
void absentTimestampCannotCompletePair() {
|
||||
HandEyeCalibrationWidget widget; ready(widget); beforePose(widget);
|
||||
VideoFrame missing=frame(); missing.metadata.remove("captureUtcNs");
|
||||
missing.metadata.insert("captureTimestampAvailable",false);
|
||||
widget.acceptFrame(camera,missing,QString());
|
||||
QCOMPARE(int(widget.m_phase),int(HandEyeCalibrationWidget::WaitingFrame));
|
||||
QVERIFY(widget.m_samples.isEmpty()); QVERIFY(!widget.m_bridge->busy());
|
||||
VideoFrame unmatched=frame(); unmatched.metadata.insert("ptsMatched",false);
|
||||
widget.acceptFrame(camera,unmatched,QString());
|
||||
QCOMPARE(int(widget.m_phase),int(HandEyeCalibrationWidget::WaitingFrame));
|
||||
QVERIFY(widget.m_samples.isEmpty());
|
||||
widget.reset();
|
||||
}
|
||||
void samplePhotoPairingRemovalAndReset() {
|
||||
HandEyeCalibrationWidget widget; ready(widget); beforePose(widget); finishPair(widget);
|
||||
QCOMPARE(widget.m_samples.size(),1);
|
||||
QCOMPARE(widget.m_samplePhotos.size(),1);
|
||||
const QByteArray jpeg=widget.m_samplePhotos.first().jpeg;
|
||||
const QImage photo=QImage::fromData(jpeg,"JPEG");
|
||||
QCOMPARE(photo.size(),QSize(800,600));
|
||||
QVERIFY(photo.pixelColor(125,125).lightness()<10);
|
||||
QVERIFY(photo.pixelColor(175,125).lightness()>245);
|
||||
QVERIFY(!widget.m_samplePhotos.first().corners.isEmpty());
|
||||
QVERIFY(!widget.m_samples.first().contains("photo_jpeg"));
|
||||
auto *table=widget.findChild<QTableWidget *>("sampleTable");
|
||||
QCOMPARE(table->columnCount(),6);
|
||||
auto *view=qobject_cast<QPushButton *>(table->cellWidget(0,5));
|
||||
QVERIFY(view && view->isEnabled()); view->click();
|
||||
QVERIFY(widget.findChild<QDialog *>("handEyeSamplePhoto"));
|
||||
// A subsequent preview must not replace a paired photograph.
|
||||
widget.m_lastPreviewMs=0; widget.acceptFrame(camera,frame(),QString());
|
||||
QTRY_VERIFY_WITH_TIMEOUT(!widget.m_bridge->busy(),10000);
|
||||
QCOMPARE(widget.m_samplePhotos.first().jpeg,jpeg);
|
||||
// Remove an earlier row and ensure its successor retains its own image.
|
||||
QImage red(800,600,QImage::Format_RGB32); red.fill(Qt::red);
|
||||
QByteArray redJpeg; QBuffer redBuffer(&redJpeg); redBuffer.open(QIODevice::WriteOnly); QVERIFY(red.save(&redBuffer,"JPEG"));
|
||||
widget.m_samples.append(widget.m_samples.first());
|
||||
widget.m_samplePhotos.append({redJpeg,{}, {}}); widget.refresh();
|
||||
table->setCurrentCell(0,0); widget.m_remove->click();
|
||||
QCOMPARE(widget.m_samples.size(),1); QCOMPARE(widget.m_samplePhotos.first().jpeg,redJpeg);
|
||||
QVERIFY(!widget.findChild<QDialog *>("handEyeSamplePhoto"));
|
||||
view=qobject_cast<QPushButton *>(table->cellWidget(0,5)); QVERIFY(view); view->click();
|
||||
QVERIFY(widget.findChild<QDialog *>("handEyeSamplePhoto"));
|
||||
table->setCurrentCell(0,0); widget.m_remove->click();
|
||||
QVERIFY(widget.m_samples.isEmpty()); QVERIFY(widget.m_samplePhotos.isEmpty());
|
||||
beforePose(widget); finishPair(widget);
|
||||
QCOMPARE(widget.m_samplePhotos.size(),1);
|
||||
widget.reset();
|
||||
QVERIFY(widget.m_samplePhotos.isEmpty());
|
||||
QVERIFY(!widget.findChild<QDialog *>("handEyeSamplePhoto"));
|
||||
}
|
||||
void sampleLimitAndMissingHistoricalPhoto() {
|
||||
HandEyeCalibrationWidget widget; ready(widget);
|
||||
for (int i=0;i<100;++i) widget.m_samples.append(QVariantMap());
|
||||
widget.refresh();
|
||||
QVERIFY(!widget.m_capture->isEnabled());
|
||||
auto *table=widget.findChild<QTableWidget *>("sampleTable");
|
||||
auto *view=qobject_cast<QPushButton *>(table->cellWidget(0,5));
|
||||
QVERIFY(view && !view->isEnabled());
|
||||
QSignalSpy requests(&widget,&HandEyeCalibrationWidget::captureRequested);
|
||||
widget.capture(); QCOMPARE(requests.count(),0); QCOMPARE(widget.m_samples.size(),100);
|
||||
widget.showSamplePhoto(0); QVERIFY(!widget.findChild<QDialog *>("handEyeSamplePhoto"));
|
||||
widget.reset(); QVERIFY(widget.m_capture->isEnabled());
|
||||
}
|
||||
void missingOrMismatchedPhotoCannotCommitSample() {
|
||||
for (bool mismatched:{false,true}) {
|
||||
HandEyeCalibrationWidget widget; ready(widget); beforePose(widget);
|
||||
widget.acceptFrame(camera,frame(),QString());
|
||||
QTRY_COMPARE_WITH_TIMEOUT(int(widget.m_phase),int(HandEyeCalibrationWidget::AfterPose),10000);
|
||||
if (mismatched) {
|
||||
QImage small(2,2,QImage::Format_RGB32); small.fill(Qt::red);
|
||||
QByteArray bytes; QBuffer buffer(&bytes); buffer.open(QIODevice::WriteOnly); QVERIFY(small.save(&buffer,"JPEG"));
|
||||
widget.m_detection["photo_jpeg"]=bytes.toBase64();
|
||||
} else widget.m_detection.remove("photo_jpeg");
|
||||
const qint64 now=QDateTime::currentMSecsSinceEpoch();
|
||||
widget.acceptPose(widget.m_poseToken,device,pose(),state(now,now),true,QString());
|
||||
QVERIFY(widget.m_samples.isEmpty()); QVERIFY(widget.m_samplePhotos.isEmpty());
|
||||
QVERIFY(!widget.m_errorMessage.isEmpty());
|
||||
}
|
||||
}
|
||||
void changedContextRejectsStalePoseAndFrame() {
|
||||
HandEyeCalibrationWidget widget; ready(widget);
|
||||
widget.capture(); const quint64 token=widget.m_poseToken;
|
||||
widget.setContext(QStringLiteral("another-server:50052"),QStringLiteral("another-arm"),true,false,true,{});
|
||||
const qint64 now=QDateTime::currentMSecsSinceEpoch();
|
||||
widget.acceptPose(token,device,pose(),state(now,now),true,QString());
|
||||
widget.acceptFrame(camera,frame(),QString());
|
||||
QVERIFY(widget.m_samples.isEmpty()); QVERIFY(!widget.m_preview);
|
||||
QCOMPARE(int(widget.m_phase),int(HandEyeCalibrationWidget::Idle));
|
||||
}
|
||||
void resetDiscardsPendingDetectionAndPreservesPreview() {
|
||||
HandEyeCalibrationWidget widget; ready(widget); beforePose(widget);
|
||||
widget.acceptFrame(camera,frame(),QString());
|
||||
QCOMPARE(int(widget.m_phase),int(HandEyeCalibrationWidget::DetectPair));
|
||||
const QString obsolete=widget.m_requestId;
|
||||
widget.m_resultValid=true;
|
||||
widget.reset();
|
||||
QVERIFY(widget.m_preview); QVERIFY(widget.m_ready);
|
||||
QVERIFY(widget.m_samples.isEmpty()); QVERIFY(!widget.m_resultValid);
|
||||
QVERIFY(widget.m_samplePhotos.isEmpty());
|
||||
QVERIFY(widget.m_requestId.isEmpty());
|
||||
QTRY_VERIFY_WITH_TIMEOUT(!widget.m_bridge->busy(),10000);
|
||||
QVERIFY(widget.m_samples.isEmpty());
|
||||
QCOMPARE(int(widget.m_phase),int(HandEyeCalibrationWidget::Idle));
|
||||
QVERIFY(widget.m_samplePhotos.isEmpty());
|
||||
QVERIFY(widget.m_poseToken==0);
|
||||
QVERIFY(!obsolete.isEmpty());
|
||||
}
|
||||
void cameraInventoryChangePreservesOrInvalidatesCaptureContext() {
|
||||
HandEyeCalibrationWidget widget; ready(widget);
|
||||
beforePose(widget); finishPair(widget);
|
||||
QCOMPARE(widget.m_samples.size(),1);
|
||||
auto *confirmed=widget.findChild<QCheckBox *>(QStringLiteral("cameraConfirmed"));
|
||||
QVERIFY(confirmed->isChecked());
|
||||
widget.setCameraIds({camera,QStringLiteral("camera-B")});
|
||||
QCOMPARE(widget.m_camera->currentText(),camera);
|
||||
QCOMPARE(widget.m_samples.size(),1);
|
||||
QVERIFY(widget.m_preview); QVERIFY(widget.m_ready);
|
||||
QVERIFY(confirmed->isChecked());
|
||||
widget.m_resultValid=true;
|
||||
widget.setCameraIds({QStringLiteral("camera-B")});
|
||||
QCOMPARE(widget.m_camera->currentText(),QStringLiteral("camera-B"));
|
||||
QVERIFY(widget.m_samples.isEmpty());
|
||||
QVERIFY(!widget.m_preview); QVERIFY(!widget.m_resultValid);
|
||||
QVERIFY(!confirmed->isChecked());
|
||||
}
|
||||
void intrinsicsResizeAndSourceMismatch() {
|
||||
HandEyeCalibrationWidget widget;
|
||||
widget.m_nativeIntrinsics={{"width",640},{"height",480},
|
||||
{"fx",600.0},{"fy",620.0},{"cx",320.0},{"cy",240.0},
|
||||
{"coeffs",QVariantList{.01,-.02,.001,.002,0.0}}};
|
||||
VideoFrame small;
|
||||
small.width=320; small.height=240;
|
||||
small.intrinsics=widget.m_nativeIntrinsics;
|
||||
QVariantMap scaled; QString error;
|
||||
QVERIFY2(widget.frameIntrinsics(small,scaled,error),qPrintable(error));
|
||||
QCOMPARE(scaled.value("fx").toDouble(),300.0);
|
||||
QCOMPARE(scaled.value("fy").toDouble(),310.0);
|
||||
QCOMPARE(scaled.value("cx").toDouble(),160.0);
|
||||
QCOMPARE(scaled.value("cy").toDouble(),120.0);
|
||||
QCOMPARE(scaled.value("width").toInt(),320);
|
||||
QCOMPARE(scaled.value("height").toInt(),240);
|
||||
// Servers may report either unscaled native K or correctly scaled K.
|
||||
small.intrinsics=scaled;
|
||||
QVERIFY2(widget.frameIntrinsics(small,scaled,error),qPrintable(error));
|
||||
small.width=400;
|
||||
QVERIFY(!widget.frameIntrinsics(small,scaled,error));
|
||||
QVERIFY(!error.isEmpty());
|
||||
small.width=320;
|
||||
small.intrinsics=widget.m_nativeIntrinsics;
|
||||
small.intrinsics.insert("fx",450.0);
|
||||
QVERIFY(!widget.frameIntrinsics(small,scaled,error));
|
||||
small.intrinsics=widget.m_nativeIntrinsics;
|
||||
small.intrinsics.insert("coeffs",QVariantList{0.,0.,0.,0.,0.});
|
||||
QVERIFY(!widget.frameIntrinsics(small,scaled,error));
|
||||
}
|
||||
};
|
||||
QTEST_MAIN(HandEyeUiTest)
|
||||
#include "handeyeui_test.moc"
|
||||
13
tests/handeyeui_test.pro
Normal file
13
tests/handeyeui_test.pro
Normal file
@ -0,0 +1,13 @@
|
||||
QT += core gui widgets testlib opengl
|
||||
CONFIG += console testcase c++14
|
||||
CONFIG -= app_bundle
|
||||
TEMPLATE = app
|
||||
TARGET = handeyeui_test
|
||||
INCLUDEPATH += ../src ../ui
|
||||
SOURCES += handeyeui_test.cpp ../ui/handeyecalibrationwidget.cpp \
|
||||
../src/handeyebridge.cpp ../src/handeyestore.cpp \
|
||||
../src/tcpcalibration.cpp ../src/videorenderwidget.cpp
|
||||
HEADERS += ../ui/handeyecalibrationwidget.h ../src/handeyebridge.h \
|
||||
../src/handeyestore.h ../src/tcpcalibration.h ../src/videorenderwidget.h ../src/videoframe.h
|
||||
FORMS += ../ui/handeyecalibrationwidget.ui
|
||||
win32:LIBS += -lopengl32
|
||||
84
tests/handeyeurdf_test.cpp
Normal file
84
tests/handeyeurdf_test.cpp
Normal file
@ -0,0 +1,84 @@
|
||||
#include "../src/handeyeurdf.h"
|
||||
#include <QtTest>
|
||||
#include <QTemporaryDir>
|
||||
#include <QFile>
|
||||
#include <QXmlStreamReader>
|
||||
#include <cmath>
|
||||
|
||||
class HandEyeUrdfTest : public QObject {
|
||||
Q_OBJECT
|
||||
static QByteArray robot() { return "<robot name='test'><!--keep--><link name='base'><inertial><mass value='2'/></inertial><visual><geometry><mesh filename='meshes/a.stl'/></geometry><material name='m'><texture filename='package://pkg/a.png'/></material></visual></link><link name='mount'/><link name='optical'/><joint name='offset' type='fixed'><parent link='base'/><child link='mount'/><origin xyz='1 0 0' rpy='0 0 1.5707963267948966'/></joint><joint name='camera' type='fixed'><parent link='mount'/><child link='optical'/><origin xyz='0 0 0' rpy='0 0 0'/></joint></robot>"; }
|
||||
static bool write(const QString &path,const QByteArray &data) { QFile f(path); return f.open(QIODevice::WriteOnly) && f.write(data)==data.size(); }
|
||||
static QByteArray read(const QString &path) { QFile f(path); f.open(QIODevice::ReadOnly); return f.readAll(); }
|
||||
static HandEyeStore::Record record(const QString &mode) {
|
||||
HandEyeStore::Record r; r.name="test"; r.cameraId="c"; r.mode=mode; r.method="PARK";
|
||||
r.createdAt="2026-09-30T10:00:00Z"; r.sampleCount=12;
|
||||
TcpCalibration::poseMatrix({{2,3,4,.2,.3,.4}},r.transform);
|
||||
r.metrics={{"accepted",true},{"translation_rms_mm",.2},{"rotation_rms_deg",.1}};
|
||||
r.board={{"type","chessboard"},{"rows",6},{"square_size_m",.025}};
|
||||
r.intrinsics={{"camera_matrix",QVariantList{800.,0.,320.,0.,800.,240.,0.,0.,1.}}, {"distortion",QVariantList{0.,0.,0.,0.,0.}}};
|
||||
return r;
|
||||
}
|
||||
static TcpCalibration::Matrix jointMatrix(const QByteArray &xml,const QString &joint) {
|
||||
QXmlStreamReader r(xml); bool found=false; TcpCalibration::Pose p{};
|
||||
while (!r.atEnd()) { r.readNext(); if (r.isStartElement() && r.name()=="joint") found=r.attributes().value("name")==joint;
|
||||
if (found && r.isStartElement() && r.name()=="origin") { int offset=0; for (const auto &field:{"xyz","rpy"}) {
|
||||
const auto v=r.attributes().value(field).toString().split(' '); for(int i=0;i<3;++i) p[offset+i]=v[i].toDouble(); offset=3; } break; } }
|
||||
TcpCalibration::Matrix m{}; TcpCalibration::poseMatrix(p,m); return m;
|
||||
}
|
||||
private slots:
|
||||
void fixedChain_data() { QTest::addColumn<QString>("mode"); QTest::newRow("EIH")<<QString("eye_in_hand"); QTest::newRow("ETH")<<QString("eye_to_hand"); }
|
||||
void fixedChain() {
|
||||
QFETCH(QString,mode); QTemporaryDir dir; QString error; const auto src=dir.filePath("source.urdf"), dst=dir.filePath("result.urdf");
|
||||
QVERIFY(write(src,robot())); const auto r=record(mode);
|
||||
QVERIFY2(HandEyeUrdf::update(src,dst,"base","optical",r,error),qPrintable(error));
|
||||
const auto local=jointMatrix(read(dst),"camera"), preceding=jointMatrix(robot(),"offset");
|
||||
for(int i=0;i<4;++i) for(int j=0;j<4;++j) { double v=0; for(int k=0;k<4;++k) v+=preceding[4*i+k]*local[4*k+j]; QVERIFY(std::abs(v-r.transform[4*i+j])<1e-10); }
|
||||
QCOMPARE(read(src),robot()); const auto xml=read(dst); QVERIFY(xml.contains("<!--keep-->")); QVERIFY(xml.contains("<mass value=\"2\""));
|
||||
QVERIFY(xml.contains("package://pkg/a.png")); QVERIFY(xml.contains(dir.filePath("meshes/a.stl").toUtf8()));
|
||||
}
|
||||
void newFrame() {
|
||||
QTemporaryDir dir; QString error; const auto src=dir.filePath("s"),dst=dir.filePath("d");
|
||||
QVERIFY(write(src,"<robot name='r'><link name='base'/></robot>")); auto r=record("eye_to_hand");
|
||||
QVERIFY2(HandEyeUrdf::update(src,dst,"base","camera_optical",r,error),qPrintable(error));
|
||||
QStringList links; QList<HandEyeUrdf::FixedJoint> joints;
|
||||
QVERIFY2(HandEyeUrdf::readUrdf(dst,links,joints,error),qPrintable(error)); QCOMPARE(links.size(),2); QCOMPARE(joints.size(),1);
|
||||
auto m=jointMatrix(read(dst),joints[0].name); for(int i=0;i<16;++i) QVERIFY(std::abs(m[i]-r.transform[i])<1e-10);
|
||||
}
|
||||
void missingOriginAndGimbalLock() {
|
||||
QTemporaryDir dir; QString error; auto xml=robot();
|
||||
xml.replace("<origin xyz='0 0 0' rpy='0 0 0'/>","");
|
||||
const auto src=dir.filePath("s"),dst=dir.filePath("out"); QVERIFY(write(src,xml));
|
||||
auto r=record("eye_in_hand"); TcpCalibration::poseMatrix({{.1,.2,.3,.4,1.5707963267948966,.6}},r.transform);
|
||||
QVERIFY2(HandEyeUrdf::update(src,dst,"mount","optical",r,error),qPrintable(error));
|
||||
auto m=jointMatrix(read(dst),"camera"); for(int i=0;i<16;++i) QVERIFY(std::abs(m[i]-r.transform[i])<1e-10);
|
||||
QVERIFY(!HandEyeUrdf::update(src,dst,"mount","optical",r,error));
|
||||
QVERIFY(!HandEyeUrdf::update(src,dir.filePath("bad"),"missing","new",r,error));
|
||||
QVERIFY(!HandEyeUrdf::update(src,dir.filePath("bad"),"base","invalid name",r,error));
|
||||
QVERIFY(!QFile::exists(dir.filePath("bad")));
|
||||
}
|
||||
void rejects_data() {
|
||||
QTest::addColumn<QByteArray>("xml");
|
||||
auto x=robot(); x.replace("name='optical'","name='base'"); QTest::newRow("duplicate")<<x;
|
||||
x=robot(); x.replace("link='optical'","link='missing'"); QTest::newRow("missing")<<x;
|
||||
QTest::newRow("invalid XML")<<QByteArray("<robot>");
|
||||
x=robot(); x.replace("name='camera' type='fixed'","name='camera' type='revolute'"); QTest::newRow("moving camera")<<x;
|
||||
x=robot(); x.replace("name='offset' type='fixed'","name='offset' type='revolute'"); QTest::newRow("moving chain")<<x;
|
||||
x=robot(); x.replace("<parent link='base'/>","<parent link='optical'/>"); QTest::newRow("cycle")<<x;
|
||||
x=robot(); x.replace("</robot>","<link name='loose'/></robot>"); QTest::newRow("disconnected")<<x;
|
||||
x=robot(); x.replace("</joint>","<mimic joint='offset'/></joint>"); QTest::newRow("mimic")<<x;
|
||||
x=robot(); x.replace("xyz='1 0 0'","xyz='${length} 0 0'"); QTest::newRow("xacro")<<x;
|
||||
x=robot(); x.replace("xyz='1 0 0'","xyz='nan 0 0'"); QTest::newRow("nonfinite origin")<<x;
|
||||
}
|
||||
void rejects() { QFETCH(QByteArray,xml); QTemporaryDir d; QString error; QVERIFY(write(d.filePath("s"),xml));
|
||||
QVERIFY(!HandEyeUrdf::update(d.filePath("s"),d.filePath("out"),"base","optical",record("eye_in_hand"),error)); QVERIFY(!QFile::exists(d.filePath("out"))); QVERIFY(!error.isEmpty()); }
|
||||
void failedWriteAndInvalidRecord() {
|
||||
QTemporaryDir d; QString error; const auto src=d.filePath("s"); QVERIFY(write(src,robot())); auto r=record("eye_in_hand");
|
||||
QVERIFY(!HandEyeUrdf::update(src,d.filePath("absent/out"),"base","optical",r,error));
|
||||
QVERIFY(!HandEyeUrdf::update(src,src,"base","optical",r,error)); QCOMPARE(read(src),robot());
|
||||
r.transform[0]=2.; QVERIFY(!HandEyeUrdf::update(src,d.filePath("out"),"base","optical",r,error));
|
||||
QVERIFY(!QFile::exists(d.filePath("out")));
|
||||
}
|
||||
};
|
||||
QTEST_APPLESS_MAIN(HandEyeUrdfTest)
|
||||
#include "handeyeurdf_test.moc"
|
||||
8
tests/handeyeurdf_test.pro
Normal file
8
tests/handeyeurdf_test.pro
Normal file
@ -0,0 +1,8 @@
|
||||
QT += core testlib
|
||||
QT -= gui
|
||||
CONFIG += console testcase c++14
|
||||
CONFIG -= app_bundle
|
||||
TEMPLATE = app
|
||||
TARGET = handeyeurdf_test
|
||||
SOURCES += handeyeurdf_test.cpp ../src/handeyeurdf.cpp ../src/handeyestore.cpp ../src/tcpcalibration.cpp
|
||||
HEADERS += ../src/handeyeurdf.h ../src/handeyestore.h ../src/tcpcalibration.h
|
||||
83
tests/jointflow_update_test.cpp
Normal file
83
tests/jointflow_update_test.cpp
Normal file
@ -0,0 +1,83 @@
|
||||
// Real scene selection and execution order; no robot or server is used.
|
||||
#include <QApplication>
|
||||
#include <QGraphicsScene>
|
||||
#include <QGraphicsItem>
|
||||
#include <QGraphicsSceneMouseEvent>
|
||||
#include <QJsonObject>
|
||||
#include <cstdio>
|
||||
#include <stdexcept>
|
||||
#include "jointfloweditor.h"
|
||||
static void check(bool ok,const char *message) { if(!ok) throw std::runtime_error(message); }
|
||||
static void select(JointFlowEditor &editor,const QString &name) {
|
||||
QString id;
|
||||
for(const auto &v:editor.toJson()) if(v.toObject()["nodeName"].toString()==name) id=v.toObject()["id"].toString();
|
||||
check(!id.isEmpty(),"node not found");
|
||||
auto *scene=editor.findChild<QGraphicsScene *>();scene->clearSelection();
|
||||
for(auto *item:scene->items()) if(item->data(0).toString()==id) item->setSelected(true);
|
||||
}
|
||||
static QStringList order(JointFlowEditor &editor) {
|
||||
QString error;QStringList points;
|
||||
for(const auto &step:editor.expandedSteps(&error))points<<step.pointName;
|
||||
check(error.isEmpty(),"flow expansion failed");return points;
|
||||
}
|
||||
int main(int argc,char **argv) {
|
||||
QApplication app(argc,argv);int failures=0;
|
||||
for(int mode=0;mode<(argc>1?4:7);++mode) {
|
||||
JointFlowEditor editor;editor.setAvailablePointNames({"A","B","C","D"});
|
||||
QString context;
|
||||
try {
|
||||
QObject::connect(&editor,&JointFlowEditor::insertionContextChanged,[&](const QString &value){context=value;});
|
||||
if(mode<3) {
|
||||
editor.addSingleNode("A","A",0);editor.addSingleNode("B","B",0);select(editor,"A");
|
||||
if(mode==0)editor.setInsertionAtRoot();
|
||||
if(mode==2)editor.findChild<QGraphicsScene *>()->clearSelection();
|
||||
editor.addSingleNode("C","C",0);
|
||||
check(order(editor)==(mode==1?QStringList{"A","C","B"}:QStringList{"A","B","C"}),
|
||||
mode==0?"root-end inserted after old selection":mode==1?"selected insertion did not insert after A":"empty selection did not append");
|
||||
check(context.contains("C"),"insertion context did not follow newly selected node");
|
||||
} else if(mode==3) {
|
||||
editor.addLoopNode("Loop",2,0);select(editor,"Loop");
|
||||
check(editor.useSelectedLoopAsInsertionParent(),"cannot enter loop");
|
||||
editor.addSingleNode("A","A",0);editor.addSingleNode("B","B",0);select(editor,"A");editor.addSingleNode("C","C",0);
|
||||
check(order(editor)==QStringList{"A","C","B","A","C","B"},"nested insertion changed order or hierarchy");
|
||||
editor.setInsertionAtRoot();editor.addSingleNode("D","D",0);
|
||||
check(order(editor)==QStringList{"A","C","B","A","C","B","D"},"leaving loop did not append root node");
|
||||
JointFlowEditor restored;restored.setAvailablePointNames({"A","B","C","D"});
|
||||
check(restored.fromJson(editor.toJson()) && order(restored)==order(editor),"saved flow changed execution order");
|
||||
restored.clear();
|
||||
} else if(mode==4) {
|
||||
editor.addLoopNode("L1",2,0);select(editor,"L1");
|
||||
check(editor.useSelectedLoopAsInsertionParent(),"cannot enter first loop");
|
||||
editor.addSingleNode("A","A",0);editor.addSingleNode("B","B",0);
|
||||
editor.setInsertionAtRoot();editor.addLoopNode("L2",2,0);select(editor,"L2");
|
||||
check(editor.useSelectedLoopAsInsertionParent(),"cannot enter second loop");
|
||||
editor.addSingleNode("C","C",0);
|
||||
QList<QRectF> boxes;
|
||||
for(auto *item:editor.findChild<QGraphicsScene *>()->items()) {
|
||||
if(item->data(0).toString().isEmpty())continue;
|
||||
const QRectF box=item->sceneBoundingRect();
|
||||
for(const auto &previous:boxes)check(!box.intersects(previous),"expanded sibling loops overlap their child cards");
|
||||
boxes.append(box);
|
||||
}
|
||||
check(order(editor)==QStringList{"A","B","A","B","C","C"},"layout changed loop execution order");
|
||||
} else if(mode==5) {
|
||||
editor.addSingleNode("A","A",0);editor.addSingleNode("B","B",0);editor.addSingleNode("C","C",0);
|
||||
select(editor,"C");auto *scene=editor.findChild<QGraphicsScene *>();
|
||||
QGraphicsItem *card=scene->selectedItems().first();card->setPos(-100,40);
|
||||
QGraphicsSceneMouseEvent release(QEvent::GraphicsSceneMouseRelease);
|
||||
release.setButton(Qt::LeftButton);release.setButtons(Qt::NoButton);
|
||||
release.setPos(QPointF(20,20));release.setScenePos(card->mapToScene(release.pos()));
|
||||
scene->sendEvent(card,&release);
|
||||
check(order(editor)==QStringList{"C","A","B"},"drop handler did not reorder siblings");
|
||||
const auto saved=editor.toJson();
|
||||
for(const auto &v:saved)check(v.toObject()["parentId"].toString().isEmpty(),"drag changed node hierarchy");
|
||||
} else {
|
||||
// Destruction with a selected card must not invoke callbacks after members die.
|
||||
for(int i=0;i<20;++i) { JointFlowEditor temporary;temporary.addSingleNode("A","A",0); }
|
||||
}
|
||||
std::printf("PASS flow scenario %d\n",mode);std::fflush(stdout);
|
||||
} catch(const std::exception &e) {++failures;std::fprintf(stderr,"FAIL flow scenario %d: %s\n",mode,e.what());std::fflush(stderr);}
|
||||
editor.clear();
|
||||
}
|
||||
return failures?1:0;
|
||||
}
|
||||
8
tests/jointflow_update_test.pro
Normal file
8
tests/jointflow_update_test.pro
Normal file
@ -0,0 +1,8 @@
|
||||
QT += core gui widgets
|
||||
CONFIG += console c++14
|
||||
CONFIG -= app_bundle
|
||||
TEMPLATE = app
|
||||
TARGET = jointflow_update_test
|
||||
INCLUDEPATH += ../src
|
||||
SOURCES += jointflow_update_test.cpp ../src/jointfloweditor.cpp
|
||||
HEADERS += ../src/jointfloweditor.h
|
||||
119
tests/jointjog_restore_test.cpp
Normal file
119
tests/jointjog_restore_test.cpp
Normal file
@ -0,0 +1,119 @@
|
||||
// Only an ephemeral localhost arm is used; no physical motion is possible.
|
||||
#include <QtTest>
|
||||
#include <QApplication>
|
||||
#include <QCheckBox>
|
||||
#include <QLabel>
|
||||
#include <QLineEdit>
|
||||
#include <QPushButton>
|
||||
#include <QSettings>
|
||||
#include <QSlider>
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QTemporaryDir>
|
||||
#include <QTableWidget>
|
||||
#include <atomic>
|
||||
#include <limits>
|
||||
#include <cstring>
|
||||
#include <google/protobuf/unknown_field_set.h>
|
||||
#include <grpcpp/grpcpp.h>
|
||||
#include "cmvr/api/arm_service.grpc.pb.h"
|
||||
#define private public
|
||||
#include "../src/mainwindow.h"
|
||||
#undef private
|
||||
#include "../src/robotclient.h"
|
||||
|
||||
class LegacyArm final : public cmvr::api::ArmService::Service {
|
||||
public:
|
||||
std::atomic<int> currentMode{0};
|
||||
// Older services expose the ordered position array but no GetArmInfo/names.
|
||||
grpc::Status getRobotState(grpc::ServerContext *,const cmvr::api::GetRobotState::Request *,
|
||||
cmvr::api::GetRobotState::Response *reply) override {
|
||||
reply->mutable_header()->set_success(true);
|
||||
auto *state=reply->mutable_state(); state->set_connected(true); state->set_powered_on(true);
|
||||
for(int i=0;i<6;++i) { state->mutable_actual_joint_state()->add_position(.1*(i+1)); state->mutable_actual_joint_state()->add_velocity(0); }
|
||||
const int mode=currentMode.load();
|
||||
if(mode) {
|
||||
auto *joints=state->mutable_actual_joint_state();
|
||||
const double values[]={0.0,-125.0,320.0,std::numeric_limits<double>::quiet_NaN(),std::numeric_limits<double>::infinity()};
|
||||
for(double value:values) {
|
||||
const auto *field=joints->GetDescriptor()->FindFieldByNumber(6);
|
||||
if(field) joints->GetReflection()->AddDouble(joints,field,value);
|
||||
else {
|
||||
quint64 bits;std::memcpy(&bits,&value,sizeof(bits));
|
||||
joints->GetReflection()->MutableUnknownFields(joints)->AddFixed64(6,bits);
|
||||
}
|
||||
}
|
||||
}
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
};
|
||||
static bool waitFor(const std::function<bool()> &condition,int timeout=2500) {
|
||||
QElapsedTimer timer; timer.start();
|
||||
while(!condition() && timer.elapsed()<timeout) QTest::qWait(10);
|
||||
return condition();
|
||||
}
|
||||
static void require(bool ok,const char *message) { if(!ok) throw std::runtime_error(message); }
|
||||
int main(int argc,char **argv) {
|
||||
QApplication app(argc,argv); QTemporaryDir settings;
|
||||
QCoreApplication::setOrganizationName("CMVR-JointJog-Restore-Test"); QCoreApplication::setApplicationName("Test");
|
||||
QSettings::setDefaultFormat(QSettings::IniFormat);
|
||||
QSettings::setPath(QSettings::IniFormat,QSettings::UserScope,settings.path());
|
||||
QSettings().setValue("connection/demo",false);
|
||||
LegacyArm service; grpc::ServerBuilder builder; int port=0;
|
||||
builder.AddListeningPort("127.0.0.1:0",grpc::InsecureServerCredentials(),&port); builder.RegisterService(&service);
|
||||
auto server=builder.BuildAndStart(); if(!server || !port) return 2;
|
||||
int result=0;
|
||||
{
|
||||
MainWindow window;
|
||||
try {
|
||||
window.m_armIdEdit->setText("legacy_arm");
|
||||
window.m_client->connectToServer("127.0.0.1",port,false);
|
||||
require(waitFor([&] { return window.m_connected; }),"loopback connection failed");
|
||||
window.m_client->setArmTelemetry("legacy_arm",true);
|
||||
require(waitFor([&] { return window.m_jointJogPlusButtons.size()==6; }),"joint rows remain empty without GetArmInfo");
|
||||
require(window.m_jointJogPositionLabels[2]->text().contains("0.3000"),"live joint position was not displayed");
|
||||
require(window.m_jointTable->columnCount()==5,"joint current column is missing");
|
||||
require(window.m_jointTable->item(0,4)->text()==QStringLiteral("未提供"),"legacy missing current looks like a real zero");
|
||||
service.currentMode=1;
|
||||
require(waitFor([&] { return window.m_jointTable->item(2,4)->text()==QStringLiteral("320"); }),"real current not displayed in mA");
|
||||
require(window.m_jointTable->item(0,4)->text()==QStringLiteral("0"),"real zero current lost");
|
||||
require(window.m_jointTable->item(1,4)->text()==QStringLiteral("-125"),"signed current lost");
|
||||
require(window.m_jointTable->item(3,4)->text()==QStringLiteral("无效") && window.m_jointTable->item(4,4)->text()==QStringLiteral("无效"),"nonfinite current displayed as valid");
|
||||
require(window.m_jointTable->item(5,4)->text()==QStringLiteral("未提供"),"partial current array filled with zero");
|
||||
service.currentMode=0;
|
||||
require(waitFor([&] { return window.m_jointTable->item(2,4)->text()==QStringLiteral("未提供"); }),"stale current survived omitted data");
|
||||
QPointer<QPushButton> original=window.m_jointJogPlusButtons[2];
|
||||
window.updateArmInfo("legacy_arm",{{"jointNames",QStringList{}}});
|
||||
require(window.m_jointJogPlusButtons.size()==6 && original,"empty info erased telemetry-derived rows");
|
||||
QSignalSpy speeds(window.m_client,&RobotClient::speedJRequested);
|
||||
QSignalSpy stops(window.m_client,&RobotClient::armStopRequested);
|
||||
window.m_jogSpeedSlider->setValue(28);
|
||||
QMetaObject::invokeMethod(original,"pressed",Qt::DirectConnection);
|
||||
require(speeds.size()==1,"press did not request SpeedJ");
|
||||
const auto velocity=speeds.last()[1].toList();
|
||||
require(velocity.size()==6 && qAbs(velocity[2].toDouble()-window.m_velocitySpin->value()*.28)<1e-9,"wrong joint speed or multiplier");
|
||||
for(int i=0;i<6;++i) if(i!=2) require(velocity[i].toDouble()==0,"another joint received speed");
|
||||
QMetaObject::invokeMethod(original,"released",Qt::DirectConnection);
|
||||
require(!stops.isEmpty(),"release did not request stop");
|
||||
window.m_client->setArmTelemetry("legacy_arm",false);
|
||||
QTest::qWait(100);
|
||||
const QStringList names={"axis1","axis2","axis3","axis4","axis5","axis6"};
|
||||
window.updateArmInfo("legacy_arm",{{"jointNames",names}});
|
||||
QPointer<QPushButton> refreshed=window.m_jointJogPlusButtons[0];
|
||||
window.updateArmInfo("legacy_arm",{{"jointNames",names}});
|
||||
QCoreApplication::sendPostedEvents(nullptr,QEvent::DeferredDelete);
|
||||
require(refreshed && window.m_jointJogPlusButtons[0]==refreshed,"unchanged info destroys held jog controls");
|
||||
window.updateArmInfo("another_arm",{{"jointNames",QStringList{"wrong"}}});
|
||||
require(window.m_activeArmJointNames==names,"another robot changed this robot's controls");
|
||||
window.updateArmInfo("legacy_arm",{{"jointNames",QStringList{"axis1","axis2","axis3","axis4"}}});
|
||||
require(window.m_jointJogPlusButtons.size()==4,"joint count was fixed to six");
|
||||
QMetaObject::invokeMethod(window.m_jointJogMinusButtons[1],"pressed",Qt::DirectConnection);
|
||||
const auto negative=speeds.last()[1].toList();
|
||||
require(negative.size()==4 && negative[1].toDouble()<0,"negative jog does not use the current robot's joint count");
|
||||
QMetaObject::invokeMethod(window.m_jointJogMinusButtons[1],"released",Qt::DirectConnection);
|
||||
std::printf("PASS: legacy telemetry restores rows, live angles, SpeedJ ratio, release stop, stable refresh and robot isolation\n");
|
||||
} catch(const std::exception &error) { std::fprintf(stderr,"FAIL: %s\n",error.what()); result=1; }
|
||||
window.m_client->disconnectFromServer(); waitFor([&] { return !window.m_connected; });
|
||||
for(auto *button:window.m_jointJogPlusButtons) if(button->isEnabled()) result=1;
|
||||
}
|
||||
server->Shutdown(); server->Wait(); return result;
|
||||
}
|
||||
71
tests/mainwindow_merge_test.cpp
Normal file
71
tests/mainwindow_merge_test.cpp
Normal file
@ -0,0 +1,71 @@
|
||||
// Exercise merged flow cancellation against the actual MainWindow objects.
|
||||
// No server is connected; only outgoing Qt signals are observed.
|
||||
#include <QtTest>
|
||||
#include <QApplication>
|
||||
#include <QCheckBox>
|
||||
#include <QLineEdit>
|
||||
#include <QSettings>
|
||||
#include <QTemporaryDir>
|
||||
#include <QStackedWidget>
|
||||
#include <stdexcept>
|
||||
#define private public
|
||||
#include "../src/mainwindow.h"
|
||||
#undef private
|
||||
#include "../src/jointfloweditor.h"
|
||||
#include "../src/robotclient.h"
|
||||
|
||||
static void check(bool value,const char *reason) { if(!value) throw std::runtime_error(reason); }
|
||||
static void setup(MainWindow &window,double interval)
|
||||
{
|
||||
check(window.m_pages->count()==16 && window.m_handEye && window.m_tcpCalibration
|
||||
&& window.m_touchOperation,"merged navigation lost an existing calibration page");
|
||||
QObject::disconnect(window.m_client,&RobotClient::commandFinished,&window,&MainWindow::handleCommand);
|
||||
window.m_demoCheck->setChecked(false); window.m_connected=true;
|
||||
window.m_recordedJointPoints.clear();
|
||||
for(int i=0;i<2;++i) {
|
||||
MainWindow::RecordedJointPoint point;
|
||||
point.name=QStringLiteral("point%1").arg(i); point.deviceId=window.m_armIdEdit->text();
|
||||
point.positions={0,0,0,0,0,0}; window.m_recordedJointPoints.append(point);
|
||||
}
|
||||
window.m_jointFlowEditor->clear();
|
||||
window.m_jointFlowEditor->addSingleNode("first","point0",interval);
|
||||
window.m_jointFlowEditor->addSingleNode("second","point1",interval);
|
||||
}
|
||||
int main(int argc,char **argv)
|
||||
{
|
||||
QApplication application(argc,argv);
|
||||
QTemporaryDir settings;
|
||||
QCoreApplication::setOrganizationName("CMVR-Merge-Test");
|
||||
QCoreApplication::setApplicationName("Merge");
|
||||
QSettings::setDefaultFormat(QSettings::IniFormat);
|
||||
QSettings::setPath(QSettings::IniFormat,QSettings::UserScope,settings.path());
|
||||
QSettings initial; initial.setValue("connection/demo",false); initial.sync();
|
||||
int failures=0;
|
||||
for(int mode=0;mode<4;++mode) {
|
||||
try {
|
||||
MainWindow window; setup(window,.08);
|
||||
QSignalSpy moves(window.m_client,&RobotClient::moveJRequested);
|
||||
window.startJointPointLoop(); check(moves.size()==1,"first flow step did not dispatch");
|
||||
window.handleCommand("MoveJ",true,{});
|
||||
if(mode==0) window.m_client->requestSystemStopAll("*");
|
||||
if(mode==1) window.m_client->requestArmStop(window.m_armIdEdit->text());
|
||||
if(mode==2) window.m_client->disconnectFromServer();
|
||||
if(mode==3) window.m_client->requestMoveJ(window.m_armIdEdit->text(),{0,0,0,0,0,0},.1,.1);
|
||||
const int afterStop=moves.size(); QTest::qWait(160);
|
||||
check(!window.m_jointPointLoopActive && moves.size()==afterStop,"stopped flow dispatched another movement");
|
||||
std::printf("PASS: stop/interlock %d\n",mode);
|
||||
} catch(const std::exception &error) { ++failures; std::fprintf(stderr,"FAIL: stop/interlock %d: %s\n",mode,error.what()); }
|
||||
}
|
||||
try {
|
||||
MainWindow window; setup(window,.10);
|
||||
QSignalSpy moves(window.m_client,&RobotClient::moveJRequested);
|
||||
window.startJointPointLoop(); window.handleCommand("MoveJ",true,{});
|
||||
window.stopJointPointLoop("replace flow"); setup(window,.45);
|
||||
window.startJointPointLoop(); window.handleCommand("MoveJ",true,{});
|
||||
QTest::qWait(230); check(moves.size()==2,"old flow timer advanced a new flow");
|
||||
QTest::qWait(280); check(moves.size()==3,"current flow timer did not advance its own flow");
|
||||
window.stopJointPointLoop("test finished");
|
||||
std::printf("PASS: old timer cannot advance replacement flow\n");
|
||||
} catch(const std::exception &error) { ++failures; std::fprintf(stderr,"FAIL: timer generation: %s\n",error.what()); }
|
||||
return failures?1:0;
|
||||
}
|
||||
75
tests/merge_retention_test.cpp
Normal file
75
tests/merge_retention_test.cpp
Normal file
@ -0,0 +1,75 @@
|
||||
// Local loopback only: verify automatic device discovery survives integration.
|
||||
#include <QtTest>
|
||||
#include <QApplication>
|
||||
#include <atomic>
|
||||
#include <grpcpp/grpcpp.h>
|
||||
#include "cmvr/api/system_service.grpc.pb.h"
|
||||
#include "../src/robotclient.h"
|
||||
|
||||
class ChangingSystem final : public cmvr::api::SystemService::Service
|
||||
{
|
||||
public:
|
||||
std::atomic<int> revision{0}, reads{0};
|
||||
grpc::Status GetSystemStatus(grpc::ServerContext *,
|
||||
const cmvr::api::GetSystemStatusCommand::Request *,
|
||||
cmvr::api::GetSystemStatusCommand::Feedback *reply) override
|
||||
{
|
||||
++reads;
|
||||
reply->mutable_header()->set_success(true);
|
||||
auto *camera=reply->add_device_list();
|
||||
camera->set_device_id(revision.load()==0 ? "camera_before" : "camera_after");
|
||||
camera->set_device_type(cmvr::api::Camera);
|
||||
camera->set_driver_type("AutoCamera");
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
};
|
||||
|
||||
static bool waitFor(const std::function<bool()> &condition, int milliseconds=3000)
|
||||
{
|
||||
QElapsedTimer timer; timer.start();
|
||||
while (!condition() && timer.elapsed()<milliseconds) QTest::qWait(10);
|
||||
return condition();
|
||||
}
|
||||
|
||||
int main(int argc,char **argv)
|
||||
{
|
||||
QApplication app(argc,argv);
|
||||
ChangingSystem service;
|
||||
grpc::ServerBuilder builder;
|
||||
int port=0;
|
||||
builder.AddListeningPort("127.0.0.1:0",grpc::InsecureServerCredentials(),&port);
|
||||
builder.RegisterService(&service);
|
||||
auto server=builder.BuildAndStart();
|
||||
if (!server || !port) return 2;
|
||||
int result=0;
|
||||
{
|
||||
RobotClient client;
|
||||
QSignalSpy connected(&client,&RobotClient::connectionChanged);
|
||||
QString discovered;
|
||||
QObject::connect(&client,&RobotClient::systemStatusReceived,&app,
|
||||
[&](double,double,double,const QVariantList &devices) {
|
||||
discovered=devices.value(0).toMap().value("deviceId").toString();
|
||||
});
|
||||
client.connectToServer("127.0.0.1",port,false);
|
||||
if (!waitFor([&] { return !connected.isEmpty() && connected.last()[0].toBool(); })) {
|
||||
std::fprintf(stderr,"FAIL: loopback connection\n"); result=1;
|
||||
} else {
|
||||
// No manual refresh and no arm telemetry: discovery must run by itself.
|
||||
if (!waitFor([&] { return discovered=="camera_before"; })) {
|
||||
std::fprintf(stderr,"FAIL: periodic device discovery is missing\n"); result=1;
|
||||
} else {
|
||||
service.revision.store(1);
|
||||
if (!waitFor([&] { return discovered=="camera_after"; })) {
|
||||
std::fprintf(stderr,"FAIL: camera replacement was not discovered\n"); result=1;
|
||||
} else std::printf("PASS: automatic device discovery and replacement\n");
|
||||
}
|
||||
}
|
||||
client.disconnectFromServer();
|
||||
waitFor([&] { return !connected.isEmpty() && !connected.last()[0].toBool(); });
|
||||
const int before=service.reads.load(); QTest::qWait(1200);
|
||||
if (service.reads.load()!=before) { std::fprintf(stderr,"FAIL: polling after disconnect\n"); result=1; }
|
||||
else std::printf("PASS: device polling stops on disconnect\n");
|
||||
}
|
||||
server->Shutdown(); server->Wait();
|
||||
return result;
|
||||
}
|
||||
24
tests/run_app_object_test.py
Normal file
24
tests/run_app_object_test.py
Normal file
@ -0,0 +1,24 @@
|
||||
"""Link a UI regression test against an existing qmake Debug app, no hardware."""
|
||||
import argparse,os,re,shlex,subprocess
|
||||
from pathlib import Path
|
||||
p=argparse.ArgumentParser()
|
||||
p.add_argument('--build-dir',required=True,type=Path)
|
||||
p.add_argument('--qt-bin',required=True,type=Path)
|
||||
p.add_argument('--source',required=True,type=Path)
|
||||
p.add_argument('--makefile',default='Makefile.Merge.Debug')
|
||||
p.add_argument('--platform',default='offscreen')
|
||||
a=p.parse_args(); root=Path(__file__).resolve().parents[1]; build=a.build_dir.resolve()
|
||||
text=(build/a.makefile).read_text(encoding='utf-8')
|
||||
def value(name): return re.search(r'^'+name+r'\s*=\s*(.*)$',text,re.M).group(1).strip()
|
||||
def args(text): return [word.strip('"') for word in shlex.split(text,posix=False)]
|
||||
env=dict(os.environ); env['PATH']=str(a.qt_bin.resolve())+os.pathsep+str(root/'bin/debug')+os.pathsep+env['PATH']
|
||||
env['QT_QPA_PLATFORM']=a.platform; env['QT_QPA_FONTDIR']='C:/Windows/Fonts'
|
||||
output=root/'build/incoming-main-merge/runtime'; output.mkdir(parents=True,exist_ok=True)
|
||||
binary=output/(a.source.stem+'.exe'); obj=build/(a.source.stem+'.o')
|
||||
compiler=value('CXX'); flags=value('CXXFLAGS').replace('$(DEFINES)',value('DEFINES'))
|
||||
subprocess.run([compiler,'-c',*args(flags),*args(value('INCPATH')),'-I'+str(a.qt_bin.parent/'include/QtTest'),str(a.source.resolve()),'-o',str(obj)],cwd=build,env=env,check=True)
|
||||
objects=(build/'object_script.CmvrControlStation_d.Debug').read_text().splitlines()
|
||||
objects=[x for x in objects if not x.replace('\\','/').endswith('/main.o')]
|
||||
response=build/(a.source.stem+'.rsp'); response.write_text('\n'.join(objects),encoding='utf-8')
|
||||
subprocess.run([compiler,'-mthreads','-o',str(binary),str(obj),'@'+str(response),*args(value('LIBS')),str(a.qt_bin.parent/'lib/libQt5Testd.a')],cwd=build,env=env,check=True)
|
||||
subprocess.run([str(binary)],cwd=output,env=env,check=True,timeout=40)
|
||||
53
tests/run_handeye_integration.py
Normal file
53
tests/run_handeye_integration.py
Normal file
@ -0,0 +1,53 @@
|
||||
"""Compile/link the hand-eye loopback integration harness against built app objects.
|
||||
|
||||
Usage: python tests/run_handeye_integration.py --build-dir <qmake shadow dir> --qt-bin <Qt bin>
|
||||
Only an ephemeral 127.0.0.1 fake service and temporary settings are used.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--build-dir', required=True, type=Path)
|
||||
parser.add_argument('--qt-bin', required=True, type=Path)
|
||||
parser.add_argument('--screenshot', type=Path)
|
||||
options = parser.parse_args()
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
build = options.build_dir.resolve()
|
||||
makefile = (build / 'Makefile.Debug').read_text(encoding='utf-8')
|
||||
|
||||
|
||||
def value(name):
|
||||
return re.search(r'^' + name + r'\s*=\s*(.*)$', makefile, re.M).group(1).strip()
|
||||
|
||||
|
||||
def args(text):
|
||||
return [word.strip('"') for word in shlex.split(text, posix=False)]
|
||||
|
||||
|
||||
output = root / 'bin/debug/handeye_integration_test.exe'
|
||||
obj = build / 'handeyeintegration_test.o'
|
||||
env = dict(os.environ)
|
||||
env['PATH'] = str(options.qt_bin.resolve()) + os.pathsep + env['PATH']
|
||||
env['QT_QPA_PLATFORM'] = 'offscreen'
|
||||
env['QT_QPA_FONTDIR'] = 'C:/Windows/Fonts'
|
||||
compiler = value('CXX')
|
||||
flags = value('CXXFLAGS').replace('$(DEFINES)', value('DEFINES'))
|
||||
subprocess.run([compiler, '-c', *args(flags), *args(value('INCPATH')),
|
||||
'-I' + str(options.qt_bin.resolve().parent / 'include/QtTest'),
|
||||
str(root / 'tests/handeyeintegration_test.cpp'), '-o', str(obj)],
|
||||
cwd=build, env=env, check=True)
|
||||
objects = (build / 'object_script.CmvrControlStation_d.Debug').read_text().splitlines()
|
||||
objects = [line for line in objects if not line.replace('\\', '/').endswith('/main.o')]
|
||||
response = build / 'handeyeintegration_objects.rsp'
|
||||
response.write_text('\n'.join(objects), encoding='utf-8')
|
||||
subprocess.run([compiler, '-mthreads', '-o', str(output), str(obj), '@' + str(response),
|
||||
*args(value('LIBS')), str(options.qt_bin.resolve().parent / 'lib/libQt5Testd.a')],
|
||||
cwd=build, env=env, check=True)
|
||||
run_args = [str(output)]
|
||||
if options.screenshot:
|
||||
run_args.extend(['--screenshot', str(options.screenshot.resolve())])
|
||||
subprocess.run(run_args, cwd=output.parent, env=env, check=True, timeout=50)
|
||||
42
tests/run_tcp_integration.py
Normal file
42
tests/run_tcp_integration.py
Normal file
@ -0,0 +1,42 @@
|
||||
"""Link a loopback integration harness against an already-built qmake Debug app.
|
||||
Usage: python tests/run_tcp_integration.py --build-dir <qmake shadow dir> --qt-bin <Qt bin>
|
||||
Uses the app's actual objects/libraries; never executes the normal app or connects to hardware.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument('--build-dir', required=True, type=Path)
|
||||
p.add_argument('--qt-bin', required=True, type=Path)
|
||||
a = p.parse_args()
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
build = a.build_dir.resolve()
|
||||
makefile = (build / 'Makefile.Debug').read_text(encoding='utf-8')
|
||||
def value(name):
|
||||
return re.search(r'^' + name + r'\s*=\s*(.*)$', makefile, re.M).group(1).strip()
|
||||
def args(text):
|
||||
return [word.strip('"') for word in shlex.split(text, posix=False)]
|
||||
output = root / 'bin/debug/tcp_integration_test.exe'
|
||||
obj = build / 'tcpintegration_test.o'
|
||||
env = dict(os.environ)
|
||||
env['PATH'] = str(a.qt_bin.resolve()) + os.pathsep + env['PATH']
|
||||
env['QT_QPA_PLATFORM'] = 'offscreen'
|
||||
env['QT_QPA_FONTDIR'] = 'C:/Windows/Fonts'
|
||||
compiler = value('CXX')
|
||||
flags = value('CXXFLAGS').replace('$(DEFINES)', value('DEFINES'))
|
||||
subprocess.run([compiler, '-c', *args(flags), *args(value('INCPATH')),
|
||||
'-I' + str(a.qt_bin.resolve().parent / 'include/QtTest'),
|
||||
str(root / 'tests/tcpintegration_test.cpp'), '-o', str(obj)],
|
||||
cwd=build, env=env, check=True)
|
||||
objects = (build / 'object_script.CmvrControlStation_d.Debug').read_text().splitlines()
|
||||
objects = [line for line in objects if not line.replace('\\', '/').endswith('/main.o')]
|
||||
response = build / 'tcpintegration_objects.rsp'
|
||||
response.write_text('\n'.join(objects), encoding='utf-8')
|
||||
subprocess.run([compiler, '-mthreads', '-o', str(output), str(obj), '@' + str(response),
|
||||
*args(value('LIBS')), str(a.qt_bin.resolve().parent / 'lib/libQt5Testd.a')],
|
||||
cwd=build, env=env, check=True)
|
||||
subprocess.run([str(output)], cwd=output.parent, env=env, check=True, timeout=40)
|
||||
58
tests/run_touch_integration.py
Normal file
58
tests/run_touch_integration.py
Normal file
@ -0,0 +1,58 @@
|
||||
"""Link the touch loopback harness against the actual qmake Debug app objects.
|
||||
|
||||
Usage: python tests/run_touch_integration.py --build-dir <shadow dir> --qt-bin <Qt bin>
|
||||
The executable creates its own ephemeral loopback service and never opens hardware.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--build-dir", required=True, type=Path)
|
||||
parser.add_argument("--qt-bin", required=True, type=Path)
|
||||
options = parser.parse_args()
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
build = options.build_dir.resolve()
|
||||
qt_bin = options.qt_bin.resolve()
|
||||
makefile = (build / "Makefile.Debug").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def value(name):
|
||||
match = re.search(r"^" + name + r"\s*=\s*(.*)$", makefile, re.M)
|
||||
if not match:
|
||||
raise RuntimeError(f"Missing {name} in {build / 'Makefile.Debug'}")
|
||||
return match.group(1).strip()
|
||||
|
||||
|
||||
def arguments(text):
|
||||
return [word.strip('"') for word in shlex.split(text, posix=False)]
|
||||
|
||||
|
||||
output = root / "bin/debug/touch_integration_test.exe"
|
||||
obj = build / "touchintegration_test.o"
|
||||
env = dict(os.environ)
|
||||
env["PATH"] = str(qt_bin) + os.pathsep + env["PATH"]
|
||||
compiler = value("CXX")
|
||||
flags = value("CXXFLAGS").replace("$(DEFINES)", value("DEFINES"))
|
||||
subprocess.run(
|
||||
[compiler, "-c", *arguments(flags), *arguments(value("INCPATH")),
|
||||
"-I" + str(qt_bin.parent / "include/QtTest"),
|
||||
str(root / "tests/touchintegration_test.cpp"), "-o", str(obj)],
|
||||
cwd=build, env=env, check=True,
|
||||
)
|
||||
objects = (build / "object_script.CmvrControlStation_d.Debug").read_text().splitlines()
|
||||
objects = [line for line in objects if not line.replace("\\", "/").endswith("/main.o")]
|
||||
if not any("touchsequencecontroller.o" in line for line in objects):
|
||||
raise RuntimeError("Build the Debug application with TouchSequenceController before running this harness")
|
||||
response = build / "touchintegration_objects.rsp"
|
||||
response.write_text("\n".join(objects), encoding="utf-8")
|
||||
subprocess.run(
|
||||
[compiler, "-mthreads", "-o", str(output), str(obj), "@" + str(response),
|
||||
*arguments(value("LIBS")), str(qt_bin.parent / "lib/libQt5Testd.a")],
|
||||
cwd=build, env=env, check=True,
|
||||
)
|
||||
subprocess.run([str(output)], cwd=output.parent, env=env, check=True, timeout=40)
|
||||
241
tests/tcpcalibration_test.cpp
Normal file
241
tests/tcpcalibration_test.cpp
Normal file
@ -0,0 +1,241 @@
|
||||
#include <QtTest>
|
||||
#include "../src/tcpcalibration.h"
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <random>
|
||||
|
||||
using namespace TcpCalibration;
|
||||
namespace {
|
||||
constexpr double pi = 3.14159265358979323846;
|
||||
std::vector<Pose> exactSamples()
|
||||
{
|
||||
// Independent rotations about distinct axes, with t = fixed - R * offset.
|
||||
// Truth: offset=(.02,-.03,.12), fixed=(.4,-.2,.6), all in metres.
|
||||
return {{.38,-.17,.48,0,0,0}, {.38,-.08,.63,pi/2,0,0},
|
||||
{.28,-.17,.62,0,pi/2,0}, {.37,-.22,.48,0,0,pi/2}};
|
||||
}
|
||||
using Vector = std::array<double,3>;
|
||||
// Independent sequential active rotations, used only to construct truth data.
|
||||
Vector rotate(Vector v, const Pose &p)
|
||||
{
|
||||
for (int axis=0;axis<3;++axis) {
|
||||
const int a=(axis+1)%3,b=(axis+2)%3;
|
||||
const double x=v[a],y=v[b],c=std::cos(p[3+axis]),s=std::sin(p[3+axis]);
|
||||
v[a]=c*x-s*y; v[b]=s*x+c*y;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
const std::array<Vector,3> toolAxes{{{{2./3,-2./3,1./3}},
|
||||
{{1./3,2./3,2./3}},{{-2./3,-1./3,2./3}}}};
|
||||
std::vector<Pose> sixSamples(const Vector &offset, bool xz)
|
||||
{
|
||||
std::vector<Pose> poses{{{0,0,0,.2,-.3,.4}},{{0,0,0,1.1,.5,-.4}},
|
||||
{{0,0,0,-.8,.7,1.2}},{{0,0,0,.4,-.6,.8}}};
|
||||
const Vector fixed{{.4,-.2,.6}};
|
||||
for (auto &p:poses) {
|
||||
const auto shifted=rotate(offset,p);
|
||||
for(int i=0;i<3;++i) p[i]=fixed[i]-shifted[i];
|
||||
}
|
||||
poses.push_back(poses[3]); poses.push_back(poses[3]);
|
||||
for(int i=0;i<3;++i) {
|
||||
poses[4][i]+=.3*toolAxes[0][i];
|
||||
// Non-perpendicular teaching vector: projection must recover the axis.
|
||||
poses[5][i]+=.04*toolAxes[0][i]+.35*toolAxes[xz?2:1][i];
|
||||
}
|
||||
return poses;
|
||||
}
|
||||
}
|
||||
|
||||
class TcpCalibrationTest : public QObject {
|
||||
Q_OBJECT
|
||||
private slots:
|
||||
void sixPointRecoversFlangeToolAndJogAxes()
|
||||
{
|
||||
std::mt19937 rng(7281); std::uniform_real_distribution<double> random(-.15,.15);
|
||||
for(bool xz:{true,false}) for(int trial=0;trial<20;++trial) {
|
||||
const Vector truth{{random(rng),random(rng),random(rng)}};
|
||||
const auto poses=sixSamples(truth,xz); Result result; QString error;
|
||||
QVERIFY2(solveSixPoint(poses,xz?DirectionMethod::XZ:DirectionMethod::XY,result,&error),qPrintable(error));
|
||||
for(int i=0;i<3;++i) QVERIFY(std::abs(result.offset[i]-truth[i])<1e-12);
|
||||
QCOMPARE(result.residualsMm.size(),size_t(3));
|
||||
QVERIFY(result.rmsMm<1e-9);
|
||||
QVERIFY(std::abs(result.directionBaselineMm[0]-300)<1e-9);
|
||||
Pose selected{}; Matrix matrix{};
|
||||
QVERIFY(toolPose(poses[3],result.offset,selected)); QVERIFY(poseMatrix(selected,matrix));
|
||||
for(int axis=0;axis<3;++axis) for(int row=0;row<3;++row)
|
||||
QVERIFY(std::abs(matrix[row*4+axis]-toolAxes[axis][row])<1e-10);
|
||||
// Existing jogTarget must move the controller TCP along the taught
|
||||
// base axes even with a different active TCP translation/rotation.
|
||||
const Pose activeOffset{{.013,-.022,.09,.1,.2,-.3}}; Pose active{};
|
||||
QVERIFY(toolPose(poses[3],activeOffset,active));
|
||||
for(int axis=0;axis<3;++axis) {
|
||||
Pose target{}; QVERIFY(jogTarget(active,activeOffset,result.offset,axis,.001,target));
|
||||
for(int row=0;row<3;++row)
|
||||
QVERIFY(std::abs(target[row]-active[row]-.001*toolAxes[axis][row])<1e-10);
|
||||
}
|
||||
}
|
||||
}
|
||||
void sixPointRejectsInvalidTeaching()
|
||||
{
|
||||
const auto good=sixSamples({{.04,-.03,.12}},true); Result r; QString error;
|
||||
auto p=good; p.pop_back(); QVERIFY(!solveSixPoint(p,DirectionMethod::XZ,r));
|
||||
p=good; p.push_back(p.back()); QVERIFY(!solveSixPoint(p,DirectionMethod::XZ,r));
|
||||
p=good; p[1]=p[0]; QVERIFY(!solveSixPoint(p,DirectionMethod::XZ,r));
|
||||
p=good; p[4][3]+=.21*pi/180; QVERIFY(!solveSixPoint(p,DirectionMethod::XZ,r,&error));
|
||||
QVERIFY(error.contains("orientation",Qt::CaseInsensitive));
|
||||
p=good; p[5]=p[4]; QVERIFY(!solveSixPoint(p,DirectionMethod::XZ,r));
|
||||
p=good; for(int i=0;i<3;++i) p[5][i]=p[3][i]-(p[4][i]-p[3][i]);
|
||||
QVERIFY(!solveSixPoint(p,DirectionMethod::XZ,r));
|
||||
p=good; for(int i=0;i<3;++i) p[4][i]=p[3][i]+.009*toolAxes[0][i];
|
||||
QVERIFY(!solveSixPoint(p,DirectionMethod::XZ,r));
|
||||
for(int sample=0;sample<6;++sample) for(int component=0;component<6;++component) {
|
||||
p=good; p[sample][component]=std::numeric_limits<double>::quiet_NaN();
|
||||
QVERIFY(!solveSixPoint(p,DirectionMethod::XZ,r));
|
||||
}
|
||||
p=good; for(int i=0;i<3;++i) p[5][i]=p[3][i]+.3*toolAxes[0][i]+.001*toolAxes[2][i];
|
||||
QVERIFY(!solveSixPoint(p,DirectionMethod::XZ,r));
|
||||
}
|
||||
void sixPointUsesCorrectedTcpDirectionsWithinDriftTolerance()
|
||||
{
|
||||
const Vector truth{{.04,-.03,.42}};
|
||||
for(bool xz:{true,false}) {
|
||||
auto poses=sixSamples(truth,xz);
|
||||
for(int i=4;i<6;++i) {
|
||||
const auto oldShift=rotate(truth,poses[i]);
|
||||
poses[i][3]+=(i==4?.19:-.19)*pi/180;
|
||||
const auto newShift=rotate(truth,poses[i]);
|
||||
for(int row=0;row<3;++row) poses[i][row]+=oldShift[row]-newShift[row];
|
||||
}
|
||||
Result result; QString error;
|
||||
QVERIFY2(solveSixPoint(poses,xz?DirectionMethod::XZ:DirectionMethod::XY,result,&error),qPrintable(error));
|
||||
QVERIFY(std::abs(result.directionOrientationDriftDeg-.19)<1e-8);
|
||||
Pose selected{}; Matrix matrix{};
|
||||
QVERIFY(toolPose(poses[3],result.offset,selected)); QVERIFY(poseMatrix(selected,matrix));
|
||||
for(int axis=0;axis<3;++axis) for(int row=0;row<3;++row)
|
||||
QVERIFY(std::abs(matrix[row*4+axis]-toolAxes[axis][row])<1e-10);
|
||||
}
|
||||
}
|
||||
void sixPointDirectionOriginDoesNotEnterPositionFit()
|
||||
{
|
||||
const Vector truth{{.04,-.03,.12}};
|
||||
auto poses=sixSamples(truth,true);
|
||||
// Translate the complete direction construction: position fitting must
|
||||
// still use only the first three fixed-tip observations.
|
||||
for(int sample=3;sample<6;++sample) { poses[sample][0]+=.08; poses[sample][2]-=.03; }
|
||||
Result result; QVERIFY(solveSixPoint(poses,DirectionMethod::XZ,result));
|
||||
for(int i=0;i<3;++i) QVERIFY(std::abs(result.offset[i]-truth[i])<1e-12);
|
||||
QCOMPARE(result.residualsMm.size(),size_t(3)); QVERIFY(result.rmsMm<1e-9);
|
||||
poses[0][0]+=.03;
|
||||
QVERIFY(solveSixPoint(poses,DirectionMethod::XZ,result)); QVERIFY(result.rmsMm>2);
|
||||
double sum=0; for(double residual:result.residualsMm) sum+=residual*residual;
|
||||
QVERIFY(std::abs(result.rmsMm-std::sqrt(sum/3))<1e-10);
|
||||
const Pose before=result.offset;
|
||||
poses[5][2]=std::numeric_limits<double>::infinity(); QString error;
|
||||
QVERIFY(!solveSixPoint(poses,DirectionMethod::XZ,result,&error));
|
||||
QVERIFY(!error.isEmpty()); QVERIFY(result.offset==before);
|
||||
}
|
||||
void knownFixedPoint()
|
||||
{
|
||||
Result result; QString error;
|
||||
QVERIFY2(solve(exactSamples(), result, &error), qPrintable(error));
|
||||
const Pose expected{{.02,-.03,.12,0,0,0}};
|
||||
for (int i=0;i<6;++i) QVERIFY(std::abs(result.offset[i]-expected[i])<1e-12);
|
||||
const std::array<double,3> fixed{{.4,-.2,.6}};
|
||||
for (int i=0;i<3;++i) QVERIFY(std::abs(result.fixedPoint[i]-fixed[i])<1e-12);
|
||||
QVERIFY(result.rmsMm<1e-9);
|
||||
QCOMPARE(result.residualsMm.size(),size_t(4));
|
||||
}
|
||||
void pythonOracleNoise()
|
||||
{
|
||||
// Executed the original phone solve_tcp_offset via AST extraction;
|
||||
// NumPy lstsq(rcond=None), six deterministic noisy metre/radian poses.
|
||||
const std::vector<Pose> poses{
|
||||
{{.42574,-.08238999999999999,.51287,0,0,0}},
|
||||
{{.457164553799518,-.03650321813529867,.5370382366275331,.4,-.5,.2}},
|
||||
{{.3543210819647397,-.12975095802404008,.5494905537789616,-.7,.6,-.4}},
|
||||
{{.3341487250340007,-.13742880292849746,.5861703193608298,.3,.9,.8}},
|
||||
{{.510361219387966,-.09047704603668112,.5244015797563556,-.6,-.7,1}},
|
||||
{{.5100957425540683,-.016694165976644595,.5926624987782261,.9,.2,-.8}}};
|
||||
Result r; QString error;
|
||||
QVERIFY2(solve(poses,r,&error),qPrintable(error));
|
||||
const double offset[]={.023969660655988535,-.03778732181075439,.11685375222330173};
|
||||
const double fixed[]={.4499099776928225,-.11986895192479124,.6299096478598433};
|
||||
for(int i=0;i<3;++i) {
|
||||
QVERIFY(std::abs(r.offset[i]-offset[i])<1e-12);
|
||||
QVERIFY(std::abs(r.fixedPoint[i]-fixed[i])<1e-12);
|
||||
}
|
||||
QVERIFY(std::abs(r.rmsMm-.2962360366900903)<1e-9);
|
||||
}
|
||||
void rejectsUnobservable()
|
||||
{
|
||||
Result r; QString error;
|
||||
QVERIFY(!solve({},r,&error)); QVERIFY(!error.isEmpty());
|
||||
auto poses=exactSamples(); poses.pop_back();
|
||||
QVERIFY(!solve(poses,r));
|
||||
QVERIFY(!solve(std::vector<Pose>(4,Pose{}),r));
|
||||
poses={{{0,0,0,0,0,0}},{{0,0,0,0,0,.2}},
|
||||
{{0,0,0,0,0,.4}},{{0,0,0,0,0,.6}}};
|
||||
QVERIFY(!solve(poses,r)); // Rotations about just one axis leave it unobservable.
|
||||
}
|
||||
void duplicateDoesNotInvalidateOtherwiseObservableSet()
|
||||
{
|
||||
auto poses=exactSamples(); poses.push_back(poses.front()); Result r;
|
||||
QVERIFY(solve(poses,r)); QVERIFY(r.rmsMm<1e-9);
|
||||
}
|
||||
void highResidualRemainsVisible()
|
||||
{
|
||||
auto poses=exactSamples(); poses[0][0]+=.04; Result r;
|
||||
QVERIFY(solve(poses,r)); QVERIFY(r.rmsMm>2.0);
|
||||
double sum=0; for(double x:r.residualsMm)sum+=x*x;
|
||||
QVERIFY(std::abs(r.rmsMm-std::sqrt(sum/r.residualsMm.size()))<1e-10);
|
||||
}
|
||||
void rejectsIllConditioned()
|
||||
{
|
||||
auto poses=exactSamples(); for(auto &p:poses)for(int j=3;j<6;++j)p[j]*=1e-10;
|
||||
Result r; QVERIFY(!solve(poses,r));
|
||||
}
|
||||
void validatesFiniteAndRigid()
|
||||
{
|
||||
Pose p{}; p[1]=std::numeric_limits<double>::quiet_NaN();
|
||||
QVERIFY(!validPose(p)); Matrix m{}; QVERIFY(!poseMatrix(p,m));
|
||||
auto poses=exactSamples(); poses[0]=p; Result r; QVERIFY(!solve(poses,r));
|
||||
QVERIFY(poseMatrix(Pose{},m)); m[15]=2; QVERIFY(!matrixPose(m,p));
|
||||
QVERIFY(poseMatrix(Pose{},m)); m[0]=-1; QVERIFY(!matrixPose(m,p));
|
||||
QVERIFY(poseMatrix(Pose{},m)); m[1]=.1; QVERIFY(!matrixPose(m,p));
|
||||
QVERIFY(poseMatrix(Pose{},m)); m[0]=std::numeric_limits<double>::infinity();
|
||||
QVERIFY(!matrixPose(m,p));
|
||||
}
|
||||
void eulerRoundTripAndOrder()
|
||||
{
|
||||
for(const Pose p : {Pose{{.12,-.23,.34,.4,-.5,1.2}},
|
||||
Pose{{0,0,0,.6,pi/2,-.7}},Pose{{0,0,0,.6,-pi/2,-.7}}}) {
|
||||
Matrix a{},b{}; Pose q{};
|
||||
QVERIFY(poseMatrix(p,a)); QVERIFY(matrixPose(a,q)); QVERIFY(poseMatrix(q,b));
|
||||
for(int i=0;i<16;++i) QVERIFY(std::abs(a[i]-b[i])<1e-9);
|
||||
}
|
||||
Matrix m{}; QVERIFY(poseMatrix(Pose{{0,0,0,pi/2,pi/2,0}},m));
|
||||
// RY * RX maps local Y onto base X, unlike the reverse order.
|
||||
QVERIFY(std::abs(m[1]-1)<1e-12); QVERIFY(std::abs(m[9])<1e-12);
|
||||
}
|
||||
void similarityRequiresBothSmallDeltas()
|
||||
{
|
||||
const Pose zero{};
|
||||
QVERIFY(tooSimilar(zero,zero));
|
||||
QVERIFY(tooSimilar(zero,Pose{{.0009,0,0,0,0,2.9*pi/180}}));
|
||||
QVERIFY(!tooSimilar(zero,Pose{{.001,0,0,0,0,0}}));
|
||||
QVERIFY(!tooSimilar(zero,Pose{{0,0,0,0,0,3.1*pi/180}}));
|
||||
}
|
||||
void flangeCompositionUsesRigidTransforms()
|
||||
{
|
||||
const Pose flange{{.3,-.4,.5,.4,-.5,1.2}};
|
||||
const Pose offset{{.04,-.06,.12,-.3,.2,.7}};
|
||||
Pose tcp{}, recovered{}; Matrix a{},b{};
|
||||
QVERIFY(toolPose(flange,offset,tcp));
|
||||
QVERIFY(flangePose(tcp,offset,recovered));
|
||||
QVERIFY(poseMatrix(flange,a)); QVERIFY(poseMatrix(recovered,b));
|
||||
for(int i=0;i<16;++i) QVERIFY(std::abs(a[i]-b[i])<1e-10);
|
||||
QVERIFY(std::abs(tcp[0]-(flange[0]+offset[0]))>1e-3);
|
||||
}
|
||||
};
|
||||
QTEST_APPLESS_MAIN(TcpCalibrationTest)
|
||||
#include "tcpcalibration_test.moc"
|
||||
8
tests/tcpcalibration_test.pro
Normal file
8
tests/tcpcalibration_test.pro
Normal file
@ -0,0 +1,8 @@
|
||||
QT += core testlib
|
||||
QT -= gui
|
||||
CONFIG += console testcase c++14
|
||||
CONFIG -= app_bundle
|
||||
TEMPLATE = app
|
||||
TARGET = tcpcalibration_test
|
||||
SOURCES += tcpcalibration_test.cpp ../src/tcpcalibration.cpp
|
||||
HEADERS += ../src/tcpcalibration.h
|
||||
185
tests/tcpintegration_test.cpp
Normal file
185
tests/tcpintegration_test.cpp
Normal file
@ -0,0 +1,185 @@
|
||||
// Integration harness: the actual MainWindow and RobotClient talk only to a
|
||||
// loopback fake service. No physical robot or user settings are accessed.
|
||||
#include <QtTest>
|
||||
#include <QApplication>
|
||||
#include <QCheckBox>
|
||||
#include <QComboBox>
|
||||
#include <QLineEdit>
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QSettings>
|
||||
#include <QSlider>
|
||||
#include <QSpinBox>
|
||||
#include <QTemporaryDir>
|
||||
#include <QMainWindow>
|
||||
#include <QPushButton>
|
||||
#include <grpcpp/grpcpp.h>
|
||||
#include "cmvr/api/arm_service.grpc.pb.h"
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <cstdio>
|
||||
#define private public
|
||||
#include "../src/mainwindow.h"
|
||||
#undef private
|
||||
#include "../src/robotclient.h"
|
||||
#include "../src/tcpcalibrationwidget.h"
|
||||
#include "../src/tcpjogcontroller.h"
|
||||
|
||||
using namespace TcpCalibration;
|
||||
class FakeArm : public cmvr::api::ArmService::Service {
|
||||
public:
|
||||
std::atomic<int> moves{0}, stops{0};
|
||||
std::atomic<int> offsetMode{0};
|
||||
grpc::Status ExecuteJsonCommand(grpc::ServerContext *,
|
||||
const cmvr::api::JsonDeviceCommand::Request *r,
|
||||
cmvr::api::JsonDeviceCommand::Feedback *s) override {
|
||||
if (r->header().device_id() != "arm-a"
|
||||
|| r->request_json() != "{\"command\":\"get_active_tcp_offset\"}")
|
||||
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "wrong offset request");
|
||||
s->mutable_header()->set_success(true);
|
||||
const std::string units = offsetMode == 1 ? "mm_deg" : "m_rad";
|
||||
const std::string device = offsetMode == 2 ? "other-arm" : "arm-a";
|
||||
const std::string values = offsetMode == 3 ? "[0,0,null,0,0,0]" : "[0,0,0,0,0,0]";
|
||||
s->set_response_json("{\"success\":true,\"device_id\":\"" + device +
|
||||
"\",\"transform\":\"T_flange_tcp\",\"units\":\"" + units +
|
||||
"\",\"rotation_convention\":\"RzRyRx\",\"offset\":" + values + "}");
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
std::mutex mutex;
|
||||
cmvr::api::MoveL::Request last;
|
||||
Pose current{{.4,.2,.5,0,0,0}};
|
||||
grpc::Status GetArmInfo(grpc::ServerContext *, const cmvr::api::GetArmInfo::Request *r,
|
||||
cmvr::api::GetArmInfo::Response *s) override {
|
||||
s->mutable_header()->set_success(true); s->set_device_id(r->header().device_id());
|
||||
s->set_driver_type("AuboARM"); s->set_manufacturer("Aubo"); s->set_dof(6);
|
||||
s->set_default_base_frame("base"); s->set_default_tcp_frame("tcp");
|
||||
for(int i=0;i<6;++i) s->add_joint_names("joint"+std::to_string(i));
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
grpc::Status getRobotState(grpc::ServerContext *, const cmvr::api::GetRobotState::Request *,
|
||||
cmvr::api::GetRobotState::Response *s) override {
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
s->mutable_header()->set_success(true); auto *state=s->mutable_state();
|
||||
state->set_connected(true); state->set_powered_on(true);
|
||||
state->set_robot_mode(cmvr::api::ARM_ROBOT_MODE_IDLE);
|
||||
state->set_safety_mode(cmvr::api::ARM_SAFETY_MODE_NORMAL);
|
||||
auto *p=state->mutable_actual_tcp_pose();
|
||||
p->set_x(current[0]); p->set_y(current[1]); p->set_z(current[2]);
|
||||
p->set_rx(current[3]); p->set_ry(current[4]); p->set_rz(current[5]);
|
||||
auto *j=state->mutable_actual_joint_state();
|
||||
for(int i=0;i<6;++i) { j->add_position(.1); j->add_velocity(0); }
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
grpc::Status moveL(grpc::ServerContext *, const cmvr::api::MoveL::Request *r,
|
||||
cmvr::api::MoveL::Response *s) override {
|
||||
std::lock_guard<std::mutex> lock(mutex); last=*r;
|
||||
const auto &p=r->target(); current={{p.x(),p.y(),p.z(),p.rx(),p.ry(),p.rz()}};
|
||||
s->mutable_header()->set_success(true); ++moves;
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
grpc::Status stopMotion(grpc::ServerContext *, const cmvr::api::CommandHeader::Request *,
|
||||
cmvr::api::CommandHeader::Feedback *s) override {
|
||||
s->set_success(true); ++stops; return grpc::Status::OK;
|
||||
}
|
||||
};
|
||||
static void require(bool ok,const char *detail) { if(!ok) throw std::runtime_error(detail); }
|
||||
static bool until(const std::function<bool()> &predicate,int timeout=5000) {
|
||||
QElapsedTimer timer; timer.start();
|
||||
while(!predicate() && timer.elapsed()<timeout) QTest::qWait(10);
|
||||
return predicate();
|
||||
}
|
||||
int main(int argc,char **argv) {
|
||||
QApplication app(argc,argv);
|
||||
QTemporaryDir temporary;
|
||||
app.setOrganizationName("CMVR-TCP-Isolated-Test"); app.setApplicationName("Integration");
|
||||
QSettings::setDefaultFormat(QSettings::IniFormat);
|
||||
QSettings::setPath(QSettings::IniFormat,QSettings::UserScope,temporary.path());
|
||||
FakeArm fake; grpc::ServerBuilder builder; int port=0;
|
||||
builder.AddListeningPort("127.0.0.1:0",grpc::InsecureServerCredentials(),&port);
|
||||
builder.RegisterService(&fake); auto server=builder.BuildAndStart();
|
||||
try {
|
||||
require(server && port>0,"loopback server startup failed");
|
||||
MainWindow window;
|
||||
window.m_demoCheck->setChecked(false);
|
||||
window.m_hostEdit->setText("127.0.0.1"); window.m_portSpin->setValue(port);
|
||||
window.m_armIdEdit->setText("arm-a");
|
||||
const QString endpoint=window.endpoint();
|
||||
QSettings settings; QString error;
|
||||
TcpToolStore::Tool a{QStringLiteral("probe-a"),{{0,0,.2,0,0,1.5707963267948966}},.1,4};
|
||||
TcpToolStore::Tool b{QStringLiteral("probe-b"),{{0,0,.1,0,0,0}},.1,4};
|
||||
require(TcpToolStore::save(settings,endpoint,"arm-a",a,false,error),"save arm-a");
|
||||
require(TcpToolStore::save(settings,endpoint,"arm-b",b,false,error),"save arm-b");
|
||||
require(TcpToolStore::save(settings,"other-host:1","arm-a",b,false,error),"save other host");
|
||||
window.m_tcpCalibration->toolsChanged(endpoint,"arm-a",a.name);
|
||||
require(window.m_tcpFrameCombo->findData("local:probe-a")>=0,"saved TCP not in jog dropdown");
|
||||
require(window.m_tcpFrameCombo->findData("local:probe-b")<0,"other robot TCP leaked");
|
||||
window.m_armIdEdit->setText("arm-b");
|
||||
require(window.m_tcpFrameCombo->findData("local:probe-a")<0,"old robot TCP remained");
|
||||
require(window.m_tcpFrameCombo->findData("local:probe-b")>=0,"selected robot TCP missing");
|
||||
window.m_armIdEdit->setText("arm-a");
|
||||
window.toggleConnection();
|
||||
require(until([&]{return window.m_connected;}),"connection failed");
|
||||
require(window.selectedLocalTcp(),"local selection lost on connect");
|
||||
QSignalSpy offsets(window.m_client, &RobotClient::controllerTcpOffsetReceived);
|
||||
for (int mode = 1; mode <= 3; ++mode) {
|
||||
fake.offsetMode = mode;
|
||||
window.m_client->requestControllerTcpOffset("arm-a", 100 + mode);
|
||||
require(until([&] { return offsets.count() == mode; }), "offset response missing");
|
||||
require(!offsets.last().at(3).toBool(), "invalid controller offset accepted");
|
||||
}
|
||||
fake.offsetMode = 0;
|
||||
window.m_tcpCalibration->findChild<QPushButton *>("tcpReadControllerOffset")->click();
|
||||
require(until([&] { return window.m_tcpCalibration->referenceConfirmed(); }),
|
||||
"controller offset did not reach calibration UI");
|
||||
require(fake.moves == 0, "read-only offset request caused motion");
|
||||
window.m_tcpCalibration->findChild<QCheckBox *>("tcpSourceConfirmed")->setChecked(true);
|
||||
window.m_jogSpeedSlider->setValue(100);
|
||||
window.startCartesianJog(0,1);
|
||||
require(until([&]{return fake.moves.load()>0;}),"local TCP did not dispatch a real MoveL RPC");
|
||||
window.stopArmJog();
|
||||
require(until([&]{return fake.stops.load()>0;}),"release did not dispatch stopMotion");
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(fake.mutex);
|
||||
require(fake.last.header().device_id()=="arm-a","wrong device in movement");
|
||||
require(fake.last.base_frame()=="base" && fake.last.tcp_frame()=="tcp","local name leaked into controller request");
|
||||
require(fake.last.target().y()>.2 && std::abs(fake.last.target().x()-.4)<1e-9,"tool orientation did not affect actual movement target");
|
||||
}
|
||||
const int afterStop=fake.moves.load(); QTest::qWait(180);
|
||||
require(fake.moves.load()==afterStop,"movement continued after release");
|
||||
Pose before; { std::lock_guard<std::mutex> lock(fake.mutex); before=fake.current; }
|
||||
window.startCartesianJog(3,1);
|
||||
require(until([&]{return fake.moves.load()>afterStop;}),"rotation not dispatched");
|
||||
window.stopArmJog();
|
||||
Pose selectedBefore{}, selectedAfter{}, after;
|
||||
{ std::lock_guard<std::mutex> lock(fake.mutex); after=fake.current; }
|
||||
toolPose(before,a.offset,selectedBefore); toolPose(after,a.offset,selectedAfter);
|
||||
for(int i=0;i<3;++i) require(std::abs(selectedBefore[size_t(i)]-selectedAfter[size_t(i)])<1e-9,"rotation moved the selected TCP endpoint");
|
||||
const int beforeSwitch=fake.moves.load();
|
||||
window.startCartesianJog(0,1);
|
||||
window.m_armIdEdit->setText("arm-b");
|
||||
QTest::qWait(180);
|
||||
require(fake.moves.load()==beforeSwitch,"pending request moved after robot switch");
|
||||
auto *confirmed=window.m_tcpCalibration->findChild<QCheckBox *>("tcpSourceConfirmed");
|
||||
window.m_tcpCalibration->findChild<QDoubleSpinBox *>("tcpSource0")->setValue(100);
|
||||
confirmed->setChecked(true);
|
||||
require(window.m_tcpCalibration->referenceConfirmed(),"nonzero reference not confirmed");
|
||||
bool invalidBeforeDispatch=false;
|
||||
QObject::connect(window.m_client,&RobotClient::moveJPoseRequested,&window,[&] {
|
||||
invalidBeforeDispatch=!window.m_tcpCalibration->referenceConfirmed();
|
||||
});
|
||||
const int beforeOrdinaryMove=fake.moves.load();
|
||||
QVariantMap ordinary{{"x",.4},{"y",.2},{"z",.5},{"rx",0.},{"ry",0.},{"rz",0.}};
|
||||
window.m_client->requestMoveJPose("arm-b",ordinary,"base","tool0",.01,.1);
|
||||
require(invalidBeforeDispatch,"ordinary MoveL left a stale active TCP confirmation");
|
||||
require(until([&]{return fake.moves.load()>beforeOrdinaryMove;}),"ordinary MoveL regression");
|
||||
confirmed->setChecked(true);
|
||||
window.m_client->requestRpc("cmvr.api.ArmService","moveL","{}","arm-b");
|
||||
require(!window.m_tcpCalibration->referenceConfirmed(),"raw Arm RPC left a stale reference");
|
||||
window.toggleConnection();
|
||||
require(until([&]{return !window.m_connected;}),"disconnect failed");
|
||||
std::puts("PASS: per-robot dropdown, save propagation, real loopback MoveL targets, TCP pivot, stop, robot switch and active TCP invalidation before ordinary MoveL/RPC");
|
||||
} catch(const std::exception &error) {
|
||||
std::fprintf(stderr,"FAIL: %s\n",error.what()); server->Shutdown(); return 1;
|
||||
}
|
||||
server->Shutdown(); return 0;
|
||||
}
|
||||
80
tests/tcpjog_test.cpp
Normal file
80
tests/tcpjog_test.cpp
Normal file
@ -0,0 +1,80 @@
|
||||
#include <QtTest>
|
||||
#include "../src/tcpjogcontroller.h"
|
||||
#include <cmath>
|
||||
|
||||
using namespace TcpCalibration;
|
||||
class TcpJogTest : public QObject {
|
||||
Q_OBJECT
|
||||
static QVariantMap map(const Pose &p) {
|
||||
QVariantMap out; const char *keys[]={"x","y","z","rx","ry","rz"};
|
||||
for(int i=0;i<6;++i) out[keys[i]]=p[size_t(i)];
|
||||
return out;
|
||||
}
|
||||
static QVariantMap healthy() { return {{"connected",true},{"moving",false},{"fault",false}}; }
|
||||
private slots:
|
||||
void translationUsesSelectedToolAxes() {
|
||||
const double halfPi=std::acos(-1.0)/2;
|
||||
Pose active{{.4,.2,.5,0,0,0}}, source{}, tool{{0,0,.2,0,0,halfPi}}, target{};
|
||||
QVERIFY(jogTarget(active,source,tool,0,.002,target));
|
||||
QVERIFY(std::abs(target[0]-.4)<1e-12);
|
||||
QVERIFY(std::abs(target[1]-.202)<1e-12);
|
||||
QVERIFY(std::abs(target[2]-.5)<1e-12);
|
||||
}
|
||||
void rotationKeepsSelectedTcpPosition() {
|
||||
Pose flange{{.3,-.2,.6,.4,-.5,.2}}, source{{.03,.01,.1,-.2,.3,.1}};
|
||||
Pose tool{{.04,-.02,.22,.2,.1,-.3}}, actual{}, before{}, target{}, afterFlange{}, after{};
|
||||
QVERIFY(toolPose(flange,source,actual));
|
||||
QVERIFY(toolPose(flange,tool,before));
|
||||
for(int axis=3;axis<6;++axis) for(double sign:{-1.,1.}) {
|
||||
QVERIFY(jogTarget(actual,source,tool,axis,sign*.005,target));
|
||||
QVERIFY(flangePose(target,source,afterFlange));
|
||||
QVERIFY(toolPose(afterFlange,tool,after));
|
||||
for(int i=0;i<3;++i) QVERIFY(std::abs(before[size_t(i)]-after[size_t(i)])<1e-12);
|
||||
Matrix a{}, b{}; poseMatrix(before,a); poseMatrix(after,b);
|
||||
double trace=0; for(int r=0;r<3;++r) for(int c=0;c<3;++c) trace+=a[r*4+c]*b[r*4+c];
|
||||
QVERIFY(std::abs(std::acos((trace-1)/2)-.005)<1e-10);
|
||||
}
|
||||
QVERIFY(!jogTarget(actual,source,tool,6,.002,target));
|
||||
}
|
||||
void releaseBeforeFeedbackCannotMove() {
|
||||
TcpJogController jog; QSignalSpy reads(&jog,&TcpJogController::captureRequested);
|
||||
QSignalSpy moves(&jog,&TcpJogController::moveRequested), stops(&jog,&TcpJogController::stopRequested);
|
||||
jog.setContext("host:1","arm-a",true,{});
|
||||
QVERIFY(jog.start({},0,1,.02,.2));
|
||||
const auto token=reads.first().at(1).toULongLong();
|
||||
jog.stop();
|
||||
jog.acceptPose(token,"arm-a",map({{.3,.2,.5,0,0,0}}),healthy(),true,{});
|
||||
QCOMPARE(moves.size(),0); QCOMPARE(stops.size(),1);
|
||||
}
|
||||
void moveCompletionDrivesNextFreshRead() {
|
||||
TcpJogController jog; QSignalSpy reads(&jog,&TcpJogController::captureRequested);
|
||||
QSignalSpy moves(&jog,&TcpJogController::moveRequested);
|
||||
jog.setContext("host:1","arm-a",true,{});
|
||||
QVERIFY(jog.start({{0,0,.2,0,0,0}},3,1,.02,.2));
|
||||
const auto token=reads.first().at(1).toULongLong();
|
||||
jog.acceptPose(token,"arm-a",map({{.3,.2,.5,0,0,0}}),healthy(),true,{});
|
||||
QCOMPARE(moves.size(),1); QCOMPARE(moves.first().at(0).toString(),QString("arm-a"));
|
||||
jog.acceptCommand("MoveL",true,{}); // unrelated completion cannot restart jogging
|
||||
QTest::qWait(70); QCOMPARE(reads.size(),1);
|
||||
jog.acceptCommand(TcpJogController::commandName(token),true,{});
|
||||
QTRY_COMPARE(reads.size(),2);
|
||||
QVERIFY(reads.last().at(1).toULongLong()!=token);
|
||||
jog.stop();
|
||||
}
|
||||
void robotSwitchAndFailureCancelPendingMotion() {
|
||||
TcpJogController jog; QSignalSpy reads(&jog,&TcpJogController::captureRequested);
|
||||
QSignalSpy moves(&jog,&TcpJogController::moveRequested), stops(&jog,&TcpJogController::stopRequested);
|
||||
jog.setContext("host:1","arm-a",true,{}); QVERIFY(jog.start({},0,1,.02,.2));
|
||||
const auto old=reads.first().at(1).toULongLong();
|
||||
jog.setContext("host:1","arm-b",false,{});
|
||||
QCOMPARE(stops.first().at(0).toString(),QString("arm-a"));
|
||||
QVERIFY(!jog.start({},0,1,.02,.2));
|
||||
jog.acceptPose(old,"arm-a",map({{.3,.2,.5,0,0,0}}),healthy(),true,{});
|
||||
QCOMPARE(moves.size(),0);
|
||||
jog.setContext("host:1","arm-b",true,{}); QVERIFY(jog.start({},0,1,.02,.2));
|
||||
jog.acceptPose(reads.last().at(1).toULongLong(),"arm-b",{}, {},false,"offline");
|
||||
QVERIFY(!jog.running()); QCOMPARE(moves.size(),0);
|
||||
}
|
||||
};
|
||||
QTEST_GUILESS_MAIN(TcpJogTest)
|
||||
#include "tcpjog_test.moc"
|
||||
7
tests/tcpjog_test.pro
Normal file
7
tests/tcpjog_test.pro
Normal file
@ -0,0 +1,7 @@
|
||||
QT += core testlib
|
||||
QT -= gui
|
||||
CONFIG += console testcase c++14
|
||||
TEMPLATE = app
|
||||
TARGET = tcpjog_test
|
||||
SOURCES += tcpjog_test.cpp ../src/tcpcalibration.cpp ../src/tcpjogcontroller.cpp
|
||||
HEADERS += ../src/tcpcalibration.h ../src/tcpjogcontroller.h
|
||||
426
tests/tcpworkflow_test.cpp
Normal file
426
tests/tcpworkflow_test.cpp
Normal file
@ -0,0 +1,426 @@
|
||||
#include "../src/tcpcalibrationwidget.h"
|
||||
#include "../src/tcptoolstore.h"
|
||||
#include <QtTest>
|
||||
#include <QCheckBox>
|
||||
#include <QComboBox>
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QEvent>
|
||||
#include <QFile>
|
||||
#include <QLabel>
|
||||
#include <QLineEdit>
|
||||
#include <QMessageBox>
|
||||
#include <QPushButton>
|
||||
#include <QSettings>
|
||||
#include <QTableWidget>
|
||||
#include <QTemporaryDir>
|
||||
#include <QTimer>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
// Qt 5.12.4 QMessageBox::showEvent dereferences the Windows native interface,
|
||||
// which the offscreen plugin does not provide. Skip only that show hook in
|
||||
// isolated tests; exec(), the standard buttons and their return values remain real.
|
||||
class OffscreenDialogFilter : public QObject
|
||||
{
|
||||
public:
|
||||
using QObject::QObject;
|
||||
bool eventFilter(QObject *object, QEvent *event) override {
|
||||
return QGuiApplication::platformName() == QStringLiteral("offscreen")
|
||||
&& event->type() == QEvent::Show && qobject_cast<QMessageBox *>(object);
|
||||
}
|
||||
};
|
||||
|
||||
class TcpWorkflowTest : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
QTemporaryDir settingsDir;
|
||||
const QString server = QStringLiteral("test-server:50052");
|
||||
const QString arm = QStringLiteral("aubo_test");
|
||||
static TcpCalibration::Pose flange(int i) {
|
||||
const double angles[][3] = {{0,0,0},{0.8,0.1,-0.3},{-0.4,0.9,0.5},{0.2,-0.7,1.1}};
|
||||
TcpCalibration::Pose pose{{0,0,0,angles[i][0],angles[i][1],angles[i][2]}};
|
||||
TcpCalibration::Matrix matrix{};
|
||||
TcpCalibration::poseMatrix(pose, matrix);
|
||||
const double tcp[] = {.03,-.02,.15}, fixed[] = {.4,-.2,.6};
|
||||
for (int row=0; row<3; ++row) {
|
||||
pose[size_t(row)] = fixed[row];
|
||||
for (int col=0; col<3; ++col) pose[size_t(row)] -= matrix[size_t(4*row+col)] * tcp[col];
|
||||
}
|
||||
return pose;
|
||||
}
|
||||
static QVariantMap poseMap(const TcpCalibration::Pose &pose) {
|
||||
const char *names[] = {"x","y","z","rx","ry","rz"};
|
||||
QVariantMap result;
|
||||
for (int i=0;i<6;++i) result.insert(QString::fromLatin1(names[i]), pose[size_t(i)]);
|
||||
return result;
|
||||
}
|
||||
static void dismissDialog() {
|
||||
QTimer::singleShot(100, [] {
|
||||
for (QWidget *widget : QApplication::topLevelWidgets())
|
||||
if (auto *box = qobject_cast<QMessageBox *>(widget)) {
|
||||
auto *button = box->button(QMessageBox::Yes);
|
||||
if (!button) button = box->button(QMessageBox::Ok);
|
||||
if (button) button->click();
|
||||
}
|
||||
});
|
||||
}
|
||||
static QPushButton *calculate(TcpCalibrationWidget &widget) {
|
||||
for (auto *button : widget.findChildren<QPushButton *>())
|
||||
if (button->property("tcpAction").toString() == QStringLiteral("calculate")) return button;
|
||||
return nullptr;
|
||||
}
|
||||
void ready(TcpCalibrationWidget &widget) {
|
||||
widget.resize(1250,1100);
|
||||
widget.show();
|
||||
QTest::qWait(20);
|
||||
widget.setContext(server, arm, true, false);
|
||||
widget.findChild<QCheckBox *>(QStringLiteral("tcpSourceConfirmed"))->setChecked(true);
|
||||
}
|
||||
void capture(TcpCalibrationWidget &widget, int row, const TcpCalibration::Pose &pose) {
|
||||
QSignalSpy requests(&widget, &TcpCalibrationWidget::captureRequested);
|
||||
auto *button = widget.findChild<QPushButton *>(QStringLiteral("tcpCapture%1").arg(row));
|
||||
QVERIFY(button && button->isEnabled());
|
||||
button->click();
|
||||
QCOMPARE(requests.size(), 1);
|
||||
widget.acceptPose(requests.at(0).at(1).toULongLong(), arm, poseMap(pose),
|
||||
{{"connected",true},{"moving",false},{"fault",false}}, true, QString());
|
||||
}
|
||||
private slots:
|
||||
void controllerOffsetReadIsScopedAndValidated() {
|
||||
TcpCalibrationWidget widget;
|
||||
widget.setContext(server, arm, true, false);
|
||||
auto *read = widget.findChild<QPushButton *>("tcpReadControllerOffset");
|
||||
QVERIFY(read);
|
||||
QSignalSpy requests(&widget, SIGNAL(controllerOffsetRequested(QString,quint64)));
|
||||
read->click();
|
||||
QCOMPARE(requests.count(), 1);
|
||||
const quint64 request = requests.at(0).at(1).toULongLong();
|
||||
const QVariantMap offset = poseMap({{.012, -.023, .145, .1, -.2, .3}});
|
||||
QVERIFY(QMetaObject::invokeMethod(&widget, "acceptControllerOffset",
|
||||
Q_ARG(quint64, request), Q_ARG(QString, arm), Q_ARG(QVariantMap, offset),
|
||||
Q_ARG(bool, true), Q_ARG(QString, QString())));
|
||||
QVERIFY(widget.referenceConfirmed());
|
||||
QVERIFY(std::abs(widget.activeOffset()[0] - .012) < 1e-8);
|
||||
QVERIFY(std::abs(widget.activeOffset()[5] - .3) < 1e-6);
|
||||
read->click();
|
||||
const quint64 stale = requests.last().at(1).toULongLong();
|
||||
widget.setContext(server, "other_arm", true, false);
|
||||
QVERIFY(QMetaObject::invokeMethod(&widget, "acceptControllerOffset",
|
||||
Q_ARG(quint64, stale), Q_ARG(QString, arm), Q_ARG(QVariantMap, offset),
|
||||
Q_ARG(bool, true), Q_ARG(QString, QString())));
|
||||
QVERIFY(!widget.referenceConfirmed());
|
||||
}
|
||||
void initTestCase() {
|
||||
qApp->installEventFilter(new OffscreenDialogFilter(qApp));
|
||||
QVERIFY(settingsDir.isValid());
|
||||
QCoreApplication::setOrganizationName(QStringLiteral("CMVR-TCP-Isolated-Test"));
|
||||
QCoreApplication::setApplicationName(QStringLiteral("Workflow"));
|
||||
QSettings::setDefaultFormat(QSettings::IniFormat);
|
||||
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, settingsDir.path());
|
||||
QFile style(QFINDTESTDATA("../styles.qss"));
|
||||
QVERIFY(style.open(QIODevice::ReadOnly));
|
||||
qApp->setStyleSheet(QString::fromUtf8(style.readAll()));
|
||||
}
|
||||
void init() { QSettings settings; settings.clear(); settings.sync(); }
|
||||
void persistenceIsolationAndRestart() {
|
||||
TcpToolStore::Tool tool{QStringLiteral("工具一"), {{.03,-.02,.15,.1,-.2,.3}}, .12, 6};
|
||||
QString error;
|
||||
{ QSettings settings; QVERIFY2(TcpToolStore::save(settings,server,arm,tool,false,error), qPrintable(error)); }
|
||||
QSettings reloaded;
|
||||
TcpToolStore::Snapshot snapshot;
|
||||
QVERIFY(TcpToolStore::load(reloaded,server,arm,snapshot,error));
|
||||
QCOMPARE(snapshot.tools.size(),1);
|
||||
QCOMPARE(snapshot.current,tool.name);
|
||||
QCOMPARE(snapshot.tools.first().offset[5],.3);
|
||||
QVERIFY(TcpToolStore::load(reloaded,server,QStringLiteral("other-arm"),snapshot,error));
|
||||
QVERIFY(snapshot.tools.isEmpty());
|
||||
QVERIFY(TcpToolStore::load(reloaded,QStringLiteral("other-server"),arm,snapshot,error));
|
||||
QVERIFY(snapshot.tools.isEmpty());
|
||||
QVERIFY(!TcpToolStore::save(reloaded,server,arm,tool,false,error));
|
||||
tool.offset[0] = .04;
|
||||
QVERIFY(TcpToolStore::save(reloaded,server,arm,tool,true,error));
|
||||
QVERIFY(TcpToolStore::load(reloaded,server,arm,snapshot,error));
|
||||
QCOMPARE(snapshot.tools.first().offset[0],.04);
|
||||
QVERIFY(TcpToolStore::remove(reloaded,server,arm,tool.name,error));
|
||||
QVERIFY(TcpToolStore::load(reloaded,server,arm,snapshot,error));
|
||||
QVERIFY(snapshot.tools.isEmpty());
|
||||
}
|
||||
void invalidStorageAndWriteFailure() {
|
||||
QSettings settings;
|
||||
QString error;
|
||||
TcpToolStore::Tool tool{QStringLiteral("tool"), {{0,0,.1,0,0,0}}, .2, 4};
|
||||
tool.rmsMm = 2.001;
|
||||
QVERIFY(!TcpToolStore::save(settings,server,arm,tool,false,error));
|
||||
tool.rmsMm = .2; tool.name.clear();
|
||||
QVERIFY(!TcpToolStore::save(settings,server,arm,tool,false,error));
|
||||
tool.name = QStringLiteral("tool"); tool.offset[0] = std::numeric_limits<double>::quiet_NaN();
|
||||
QVERIFY(!TcpToolStore::save(settings,server,arm,tool,false,error));
|
||||
tool.offset[0] = 0;
|
||||
QVERIFY(TcpToolStore::save(settings,server,arm,tool,false,error));
|
||||
const QString key = settings.allKeys().first();
|
||||
QVariantMap bad = settings.value(key).toMap();
|
||||
bad[QStringLiteral("tools")] = QStringLiteral("not a list");
|
||||
settings.setValue(key,bad); settings.sync();
|
||||
TcpToolStore::Snapshot snapshot;
|
||||
QVERIFY(!TcpToolStore::load(settings,server,arm,snapshot,error));
|
||||
QVERIFY(!TcpToolStore::save(settings,server,arm,tool,true,error));
|
||||
QSettings unwritable(settingsDir.path(),QSettings::IniFormat); // directory, not writable as file
|
||||
QVERIFY(!TcpToolStore::save(unwritable,server,arm,tool,false,error));
|
||||
}
|
||||
void captureSolveSaveReloadAndClear() {
|
||||
TcpCalibrationWidget widget;
|
||||
ready(widget);
|
||||
QSignalSpy changed(&widget,&TcpCalibrationWidget::toolsChanged);
|
||||
widget.findChild<QLineEdit *>(QStringLiteral("tcpToolName"))->setText(QStringLiteral("探针"));
|
||||
for (int i=0;i<4;++i) capture(widget,i,flange(i));
|
||||
QVERIFY(calculate(widget)->isEnabled());
|
||||
calculate(widget)->click();
|
||||
QCOMPARE(widget.findChild<QLabel *>(QStringLiteral("tcpResult0"))->text(),QStringLiteral("30.000"));
|
||||
auto *save = widget.findChild<QPushButton *>(QStringLiteral("tcpSave"));
|
||||
QVERIFY(save->isEnabled());
|
||||
dismissDialog(); save->click();
|
||||
QCOMPARE(changed.size(),1);
|
||||
QCOMPARE(changed.first().at(0).toString(),server);
|
||||
QCOMPARE(changed.first().at(1).toString(),arm);
|
||||
QCOMPARE(changed.first().at(2).toString(),QStringLiteral("探针"));
|
||||
QVERIFY(widget.referenceConfirmed()); // saving does not change the robot's active offset
|
||||
TcpCalibrationWidget reopened;
|
||||
reopened.setContext(server,arm,false,false);
|
||||
QCOMPARE(reopened.findChild<QComboBox *>(QStringLiteral("tcpLocalTools"))->currentText(),QStringLiteral("探针"));
|
||||
QCOMPARE(reopened.findChild<QLabel *>(QStringLiteral("tcpResult2"))->text(),QStringLiteral("150.000"));
|
||||
reopened.setContext(server,QString(),false,false);
|
||||
QCOMPARE(reopened.findChild<QComboBox *>(QStringLiteral("tcpLocalTools"))->count(),1);
|
||||
QVERIFY(reopened.findChild<QLineEdit *>(QStringLiteral("tcpToolName"))->text().isEmpty());
|
||||
reopened.setContext(server,arm,false,false);
|
||||
QCOMPARE(reopened.findChild<QLabel *>(QStringLiteral("tcpResult2"))->text(),QStringLiteral("150.000"));
|
||||
reopened.findChild<QPushButton *>(QStringLiteral("tcpClear"))->click();
|
||||
QVERIFY(!reopened.findChild<QPushButton *>(QStringLiteral("tcpSave"))->isEnabled());
|
||||
QSettings settings;
|
||||
TcpToolStore::Snapshot snapshot; QString error;
|
||||
QVERIFY(TcpToolStore::load(settings,server,arm,snapshot,error));
|
||||
QCOMPARE(snapshot.tools.size(),1);
|
||||
QSignalSpy deleted(&reopened,&TcpCalibrationWidget::toolsChanged);
|
||||
dismissDialog(); reopened.findChild<QPushButton *>(QStringLiteral("tcpDelete"))->click();
|
||||
QCOMPARE(deleted.size(),1);
|
||||
QCOMPARE(deleted.first().at(1).toString(),arm);
|
||||
QVERIFY(deleted.first().at(2).toString().isEmpty());
|
||||
QVERIFY(TcpToolStore::load(settings,server,arm,snapshot,error));
|
||||
QVERIFY(snapshot.tools.isEmpty());
|
||||
}
|
||||
void activeTcpRotationConversion() {
|
||||
TcpCalibrationWidget widget;
|
||||
ready(widget);
|
||||
const TcpCalibration::Pose serverOffset{{.01,-.02,.12,.2,-.3,.4}};
|
||||
for (int i=0;i<6;++i) widget.findChild<QDoubleSpinBox *>(QStringLiteral("tcpSource%1").arg(i))
|
||||
->setValue(i<3 ? serverOffset[size_t(i)]*1000 : serverOffset[size_t(i)]*180/3.141592653589793);
|
||||
widget.findChild<QCheckBox *>(QStringLiteral("tcpSourceConfirmed"))->setChecked(true);
|
||||
for (int i=0;i<4;++i) {
|
||||
TcpCalibration::Pose feedback{};
|
||||
QVERIFY(TcpCalibration::toolPose(flange(i),serverOffset,feedback));
|
||||
capture(widget,i,feedback);
|
||||
}
|
||||
calculate(widget)->click();
|
||||
QCOMPARE(widget.findChild<QLabel *>(QStringLiteral("tcpResult0"))->text(),QStringLiteral("30.000"));
|
||||
QCOMPARE(widget.findChild<QLabel *>(QStringLiteral("tcpResult2"))->text(),QStringLiteral("150.000"));
|
||||
}
|
||||
void lateResponsesAndDeviceChanges() {
|
||||
TcpCalibrationWidget widget; ready(widget);
|
||||
QSignalSpy requests(&widget,&TcpCalibrationWidget::captureRequested);
|
||||
widget.findChild<QPushButton *>(QStringLiteral("tcpCapture0"))->click();
|
||||
const auto token = requests.at(0).at(1).toULongLong();
|
||||
widget.findChild<QPushButton *>(QStringLiteral("tcpClear"))->click();
|
||||
widget.acceptPose(token,arm,poseMap(flange(0)),{{"connected",true},{"moving",false},{"fault",false}},true,{});
|
||||
auto *table = widget.findChild<QTableWidget *>(QStringLiteral("tcpSamples"));
|
||||
QCOMPARE(table->item(0,1)->text(),QStringLiteral("未采集"));
|
||||
capture(widget,0,flange(0));
|
||||
widget.setContext(server,QStringLiteral("other-arm"),true,false);
|
||||
QCOMPARE(table->item(0,1)->text(),QStringLiteral("未采集"));
|
||||
QVERIFY(!widget.findChild<QCheckBox *>(QStringLiteral("tcpSourceConfirmed"))->isChecked());
|
||||
}
|
||||
void recaptureDuplicateFailureAndSourceReset() {
|
||||
TcpCalibrationWidget widget; ready(widget);
|
||||
capture(widget,0,flange(0));
|
||||
dismissDialog(); capture(widget,1,flange(0));
|
||||
auto *table = widget.findChild<QTableWidget *>(QStringLiteral("tcpSamples"));
|
||||
QCOMPARE(table->item(1,1)->text(),QStringLiteral("未采集"));
|
||||
capture(widget,0,flange(1));
|
||||
QCOMPARE(table->item(0,1)->text(),QStringLiteral("已采集"));
|
||||
QSignalSpy requests(&widget,&TcpCalibrationWidget::captureRequested);
|
||||
widget.findChild<QPushButton *>(QStringLiteral("tcpCapture1"))->click();
|
||||
dismissDialog();
|
||||
widget.acceptPose(requests.at(0).at(1).toULongLong(),arm,{}, {},false,QStringLiteral("test unavailable"));
|
||||
QCOMPARE(table->item(1,1)->text(),QStringLiteral("未采集"));
|
||||
widget.findChild<QDoubleSpinBox *>(QStringLiteral("tcpSource0"))->setValue(1);
|
||||
QCOMPARE(table->item(0,1)->text(),QStringLiteral("未采集"));
|
||||
QVERIFY(!widget.findChild<QPushButton *>(QStringLiteral("tcpCapture0"))->isEnabled());
|
||||
}
|
||||
void highErrorCannotSave() {
|
||||
TcpCalibrationWidget widget; ready(widget);
|
||||
widget.findChild<QLineEdit *>(QStringLiteral("tcpToolName"))->setText(QStringLiteral("bad"));
|
||||
for (int i=0;i<4;++i) {
|
||||
auto pose=flange(i); if (i==3) pose[0]+=.03;
|
||||
capture(widget,i,pose);
|
||||
}
|
||||
calculate(widget)->click();
|
||||
QVERIFY(widget.findChild<QLabel *>(QStringLiteral("tcpRms"))->text().contains(QStringLiteral("超限")));
|
||||
QVERIFY(!widget.findChild<QPushButton *>(QStringLiteral("tcpSave"))->isEnabled());
|
||||
}
|
||||
void invalidAndFailedRecaptureCannotReuseOldPoint() {
|
||||
TcpCalibrationWidget widget; ready(widget);
|
||||
capture(widget,0,flange(0));
|
||||
QSignalSpy requests(&widget,&TcpCalibrationWidget::captureRequested);
|
||||
widget.findChild<QPushButton *>(QStringLiteral("tcpCapture0"))->click();
|
||||
auto invalid = poseMap(flange(0)); invalid.remove(QStringLiteral("rx"));
|
||||
dismissDialog();
|
||||
widget.acceptPose(requests.last().at(1).toULongLong(),arm,invalid,
|
||||
{{"connected",true},{"moving",false},{"fault",false}},true,{});
|
||||
auto *table=widget.findChild<QTableWidget *>(QStringLiteral("tcpSamples"));
|
||||
QCOMPARE(table->item(0,1)->text(),QStringLiteral("未采集"));
|
||||
QVERIFY(!calculate(widget)->isEnabled());
|
||||
widget.findChild<QPushButton *>(QStringLiteral("tcpCapture0"))->click();
|
||||
dismissDialog();
|
||||
widget.acceptPose(requests.last().at(1).toULongLong(),arm,poseMap(flange(0)),
|
||||
{{"connected",true},{"moving",true},{"fault",false}},true,{});
|
||||
QCOMPARE(table->item(0,1)->text(),QStringLiteral("未采集"));
|
||||
}
|
||||
void reconnectAndMethodInvalidation() {
|
||||
TcpCalibrationWidget widget; ready(widget);
|
||||
for(int i=0;i<4;++i) capture(widget,i,flange(i));
|
||||
calculate(widget)->click();
|
||||
auto *method=widget.findChild<QComboBox *>(QStringLiteral("tcpCalibrationMethod"));
|
||||
QVERIFY(method); QCOMPARE(method->count(),3);
|
||||
method->setCurrentIndex(method->findData(QStringLiteral("six_point_xz")));
|
||||
QVERIFY(!calculate(widget)->isEnabled());
|
||||
QCOMPARE(widget.findChild<QLabel *>(QStringLiteral("tcpResult0"))->text(),QStringLiteral("--"));
|
||||
auto *table=widget.findChild<QTableWidget *>(QStringLiteral("tcpSamples"));
|
||||
QCOMPARE(table->rowCount(),6);
|
||||
for(int row=0;row<6;++row) QCOMPARE(table->item(row,1)->text(),QStringLiteral("未采集"));
|
||||
QSignalSpy requests(&widget,&TcpCalibrationWidget::captureRequested);
|
||||
widget.findChild<QPushButton *>(QStringLiteral("tcpCapture0"))->click();
|
||||
const auto staleToken=requests.last().at(1).toULongLong();
|
||||
QVERIFY(!method->isEnabled());
|
||||
// A programmatic context change must invalidate an outstanding reply,
|
||||
// too, even though interactive method changes are disabled while busy.
|
||||
method->setCurrentIndex(method->findData(QStringLiteral("four_point")));
|
||||
widget.acceptPose(staleToken,arm,poseMap(flange(0)),
|
||||
{{"connected",true},{"moving",false},{"fault",false}},true,{});
|
||||
QCOMPARE(table->rowCount(),4);
|
||||
QCOMPARE(table->item(0,1)->text(),QStringLiteral("未采集"));
|
||||
widget.findChild<QPushButton *>(QStringLiteral("tcpCapture0"))->click();
|
||||
widget.setContext(server,arm,false,false);
|
||||
ready(widget);
|
||||
widget.acceptPose(requests.last().at(1).toULongLong(),arm,poseMap(flange(0)),
|
||||
{{"connected",true},{"moving",false},{"fault",false}},true,{});
|
||||
QCOMPARE(widget.findChild<QTableWidget *>(QStringLiteral("tcpSamples"))->item(0,1)->text(),QStringLiteral("未采集"));
|
||||
}
|
||||
void sixPointCaptureSaveReload_data() {
|
||||
QTest::addColumn<bool>("xz");
|
||||
QTest::newRow("XZ") << true;
|
||||
QTest::newRow("XY") << false;
|
||||
}
|
||||
void sixPointCaptureSaveReload() {
|
||||
QFETCH(bool,xz);
|
||||
TcpCalibrationWidget widget; ready(widget);
|
||||
const QString methodId=xz?QStringLiteral("six_point_xz"):QStringLiteral("six_point_xy");
|
||||
auto *method=widget.findChild<QComboBox *>(QStringLiteral("tcpCalibrationMethod"));
|
||||
QVERIFY(method);
|
||||
for(int i=3;i<6;++i) QVERIFY(!widget.findChild<QDoubleSpinBox *>(QStringLiteral("tcpOrientation%1").arg(i))->isReadOnly());
|
||||
method->setCurrentIndex(method->findData(methodId));
|
||||
auto *table=widget.findChild<QTableWidget *>(QStringLiteral("tcpSamples"));
|
||||
QCOMPARE(table->rowCount(),6);
|
||||
for(int i=3;i<6;++i) QVERIFY(widget.findChild<QDoubleSpinBox *>(QStringLiteral("tcpOrientation%1").arg(i))->isReadOnly());
|
||||
widget.findChild<QLineEdit *>(QStringLiteral("tcpToolName"))->setText(QStringLiteral("六点探针"));
|
||||
// Base-frame tool axes: a known proper orthonormal basis, not aligned
|
||||
// with either the base or the nonidentity direction-origin flange.
|
||||
const double axes[3][3]={{2./3,-2./3,1./3},{1./3,2./3,2./3},{-2./3,-1./3,2./3}};
|
||||
std::vector<TcpCalibration::Pose> poses{flange(0),flange(1),flange(2),flange(1),flange(1),flange(1)};
|
||||
for(int row=0;row<3;++row) {
|
||||
poses[4][row]+=.3*axes[0][row];
|
||||
poses[5][row]+=.35*axes[xz?2:1][row];
|
||||
}
|
||||
for(int i=0;i<6;++i) capture(widget,i,poses[size_t(i)]);
|
||||
QVERIFY(calculate(widget)->isEnabled()); calculate(widget)->click();
|
||||
QCOMPARE(widget.findChild<QLabel *>(QStringLiteral("tcpResult0"))->text(),QStringLiteral("30.000"));
|
||||
QCOMPARE(widget.findChild<QLabel *>(QStringLiteral("tcpResult2"))->text(),QStringLiteral("150.000"));
|
||||
for(int row=0;row<3;++row) QCOMPARE(table->item(row,8)->text(),QStringLiteral("0.000"));
|
||||
for(int row=3;row<6;++row) QCOMPARE(table->item(row,8)->text(),QStringLiteral("--"));
|
||||
auto *save=widget.findChild<QPushButton *>(QStringLiteral("tcpSave")); QVERIFY(save->isEnabled());
|
||||
dismissDialog(); save->click();
|
||||
QSettings settings; TcpToolStore::Snapshot snapshot; QString error;
|
||||
QVERIFY2(TcpToolStore::load(settings,server,arm,snapshot,error),qPrintable(error));
|
||||
QCOMPARE(snapshot.tools.size(),1); const auto tool=snapshot.tools.first();
|
||||
QCOMPARE(tool.method,methodId); QCOMPARE(tool.sampleCount,6); QVERIFY(tool.rmsMm<1e-8);
|
||||
TcpCalibration::Pose baseTool{}; TcpCalibration::Matrix rotation{};
|
||||
QVERIFY(TcpCalibration::toolPose(poses[3],tool.offset,baseTool));
|
||||
QVERIFY(TcpCalibration::poseMatrix(baseTool,rotation));
|
||||
for(int axis=0;axis<3;++axis) for(int row=0;row<3;++row)
|
||||
QVERIFY(std::abs(rotation[row*4+axis]-axes[axis][row])<1e-10);
|
||||
TcpCalibrationWidget reopened; reopened.setContext(server,arm,false,false);
|
||||
QCOMPARE(reopened.findChild<QComboBox *>(QStringLiteral("tcpCalibrationMethod"))->currentData().toString(),methodId);
|
||||
for(int i=3;i<6;++i) {
|
||||
auto *angle=reopened.findChild<QDoubleSpinBox *>(QStringLiteral("tcpOrientation%1").arg(i));
|
||||
QVERIFY(angle->isReadOnly());
|
||||
QVERIFY(std::abs(angle->value()-tool.offset[i]*180/3.141592653589793)<.000051);
|
||||
}
|
||||
widget.resize(1250,1100); widget.show(); QTest::qWait(20);
|
||||
QVERIFY(widget.grab().save(QStringLiteral("tcp-six-%1.png").arg(xz?"xz":"xy")));
|
||||
}
|
||||
void storageLegacyMethodAndInvalidMethods() {
|
||||
QSettings settings; QString error; TcpToolStore::Snapshot snapshot;
|
||||
TcpToolStore::Tool tool{QStringLiteral("legacy"),{{.01,.02,.1,.1,.2,.3}},.1,5};
|
||||
QVERIFY(TcpToolStore::save(settings,server,arm,tool,false,error));
|
||||
const QString key=settings.allKeys().first();
|
||||
auto value=settings.value(key).toMap(); auto records=value.value(QStringLiteral("tools")).toList();
|
||||
auto record=records.first().toMap(); record.remove(QStringLiteral("method"));
|
||||
records[0]=record; value[QStringLiteral("tools")]=records; settings.setValue(key,value); settings.sync();
|
||||
QVERIFY(TcpToolStore::load(settings,server,arm,snapshot,error));
|
||||
QCOMPARE(snapshot.tools.first().method,QStringLiteral("fixed_point"));
|
||||
QCOMPARE(snapshot.tools.first().sampleCount,5); QCOMPARE(snapshot.tools.first().offset[5],.3);
|
||||
TcpCalibrationWidget widget; widget.setContext(server,arm,false,false);
|
||||
QVERIFY(!widget.findChild<QDoubleSpinBox *>(QStringLiteral("tcpOrientation5"))->isReadOnly());
|
||||
tool.method=QStringLiteral("unknown"); QVERIFY(!TcpToolStore::save(settings,server,arm,tool,true,error));
|
||||
tool.method=QStringLiteral("six_point_xz"); QVERIFY(!TcpToolStore::save(settings,server,arm,tool,true,error));
|
||||
tool.method=QStringLiteral("four_point"); QVERIFY(!TcpToolStore::save(settings,server,arm,tool,true,error));
|
||||
record[QStringLiteral("method")]=QStringLiteral("unknown"); records[0]=record;
|
||||
value[QStringLiteral("tools")]=records; settings.setValue(key,value); settings.sync();
|
||||
QVERIFY(!TcpToolStore::load(settings,server,arm,snapshot,error)); QVERIFY(!error.isEmpty());
|
||||
}
|
||||
void demoCannotCaptureAndRender() {
|
||||
TcpCalibrationWidget widget;
|
||||
widget.setContext(server,arm,true,true);
|
||||
QVERIFY(!widget.findChild<QPushButton *>(QStringLiteral("tcpCapture0"))->isEnabled());
|
||||
ready(widget);
|
||||
widget.findChild<QLineEdit *>(QStringLiteral("tcpToolName"))->setText(QStringLiteral("探针 TCP"));
|
||||
for(int i=0;i<4;++i) capture(widget,i,flange(i));
|
||||
calculate(widget)->click();
|
||||
widget.resize(1250,1100);
|
||||
widget.show();
|
||||
QTest::qWait(50);
|
||||
QVERIFY(widget.grab().save(QStringLiteral("tcp-page.png")));
|
||||
}
|
||||
void neutralUiAndPerRobotTools() {
|
||||
TcpCalibrationWidget widget; ready(widget);
|
||||
for(auto *label:widget.findChildren<QLabel *>()) {
|
||||
QVERIFY(!label->text().contains(QStringLiteral("AUBO")));
|
||||
QVERIFY(!label->text().contains(server));
|
||||
QVERIFY(!label->text().contains(arm));
|
||||
}
|
||||
QSettings settings; QString error;
|
||||
TcpToolStore::Tool a{QStringLiteral("同名工具"),{{.01,0,.1,0,0,0}},.1,4};
|
||||
auto b=a; b.offset[0]=.02;
|
||||
QVERIFY(TcpToolStore::save(settings,server,arm,a,false,error));
|
||||
QVERIFY(TcpToolStore::save(settings,server,"arm-b",b,false,error));
|
||||
widget.setContext(server,"arm-b",true,false);
|
||||
QCOMPARE(widget.findChild<QLabel *>("tcpResult0")->text(),QStringLiteral("20.000"));
|
||||
widget.setContext(server,arm,true,false);
|
||||
QCOMPARE(widget.findChild<QLabel *>("tcpResult0")->text(),QStringLiteral("10.000"));
|
||||
widget.setContext("another-server",arm,true,false);
|
||||
QCOMPARE(widget.findChild<QComboBox *>("tcpLocalTools")->count(),1);
|
||||
QVERIFY(TcpToolStore::select(settings,server,arm,QString(),error));
|
||||
TcpToolStore::Snapshot snapshot;
|
||||
QVERIFY(TcpToolStore::load(settings,server,arm,snapshot,error));
|
||||
QVERIFY(snapshot.current.isEmpty()); QCOMPARE(snapshot.tools.size(),1);
|
||||
}
|
||||
};
|
||||
QTEST_MAIN(TcpWorkflowTest)
|
||||
#include "tcpworkflow_test.moc"
|
||||
8
tests/tcpworkflow_test.pro
Normal file
8
tests/tcpworkflow_test.pro
Normal file
@ -0,0 +1,8 @@
|
||||
QT += core gui widgets testlib
|
||||
CONFIG += console testcase c++14
|
||||
CONFIG -= app_bundle
|
||||
TEMPLATE = app
|
||||
TARGET = tcpworkflow_test
|
||||
SOURCES += tcpworkflow_test.cpp ../src/tcpcalibration.cpp ../src/tcptoolstore.cpp ../src/tcpcalibrationwidget.cpp
|
||||
HEADERS += ../src/tcpcalibration.h ../src/tcptoolstore.h ../src/tcpcalibrationwidget.h
|
||||
RESOURCES += ../resources.qrc
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user