feat: support multi-robot workflows and sync server protocol

Add independent robot connections, per-node device binding and isolated demo state. Improve canvas multi-selection, undo and parameter layouts. Remove remote configuration management and align protos with cmvr-es c8b71b2b. Include Release startup and loopback regression coverage.
This commit is contained in:
linbo 2026-11-25 17:25:39 +08:00
parent cf6fb72fa4
commit ad1a42c761
90 changed files with 2082 additions and 5192 deletions

View File

@ -165,8 +165,6 @@ set(CMVR_SOURCES
src/agvmapviewwidget.h
src/audiostreammanager.cpp
src/audiostreammanager.h
src/configeditorwidget.cpp
src/configeditorwidget.h
src/jointfloweditor.cpp
src/jointfloweditor.h
src/motordebugwidget.h
@ -188,6 +186,8 @@ set(CMVR_SOURCES
src/workflowcanvas.h
src/workflowgraph.h
src/workflowruntime.h
src/workflowrobotmanager.h
src/workflowhistory.h
src/freescaninteropui.h
src/freescaninterop.cpp
src/freescaninterop.h
@ -308,7 +308,6 @@ set(SERVICE_NAMES
cmvr/api/arm_service
cmvr/api/biohead_service
cmvr/api/camera_service
cmvr/api/configuration_service
cmvr/api/dexhand_service
cmvr/api/hlc_service
cmvr/api/microphone_service

View File

@ -44,8 +44,6 @@ PROTO_FILES = \
$$PROTO_ROOT/cmvr/api/biohead_service.proto \
$$PROTO_ROOT/cmvr/api/camera_command.proto \
$$PROTO_ROOT/cmvr/api/camera_service.proto \
$$PROTO_ROOT/cmvr/api/configuration_command.proto \
$$PROTO_ROOT/cmvr/api/configuration_service.proto \
$$PROTO_ROOT/cmvr/api/dexhand_command.proto \
$$PROTO_ROOT/cmvr/api/dexhand_service.proto \
$$PROTO_ROOT/cmvr/api/hlc_command.proto \
@ -64,7 +62,6 @@ GRPC_PROTO_FILES = \
$$PROTO_ROOT/cmvr/api/arm_service.proto \
$$PROTO_ROOT/cmvr/api/biohead_service.proto \
$$PROTO_ROOT/cmvr/api/camera_service.proto \
$$PROTO_ROOT/cmvr/api/configuration_service.proto \
$$PROTO_ROOT/cmvr/api/dexhand_service.proto \
$$PROTO_ROOT/cmvr/api/hlc_service.proto \
$$PROTO_ROOT/cmvr/api/microphone_service.proto \
@ -91,10 +88,13 @@ CONFIG_PROTO_FILES = \
$$PROTO_ROOT/cmvr/config/quic_edge_config/quic_edge_config.proto \
$$PROTO_ROOT/cmvr/config/self_collision_task_config/self_collision_task_config.proto \
$$PROTO_ROOT/cmvr/config/speaker_config/speaker_config.proto \
$$PROTO_ROOT/cmvr/config/touch_config/touch_config.proto \
$$PROTO_ROOT/cmvr/config/task_manager_config/task_manager_config.proto \
$$PROTO_ROOT/cmvr/config/touch_screen_task_config/touch_screen_task_config.proto
CONFIG_ROOT_PROTO_FILES = \
$$PROTO_ROOT/cmvr/config/collision_config.proto \
$$PROTO_ROOT/cmvr/config/joint_motion_config.proto \
$$PROTO_ROOT/cmvr/config/cartesian_motion_validation_config.proto \
$$PROTO_ROOT/cmvr/config/joint_limits_config.proto \
$$PROTO_ROOT/cmvr/config/lawba_ik_config.proto \
@ -264,7 +264,6 @@ SOURCES += \
src/tcpcalibrationwidget.cpp \
src/agvmapviewwidget.cpp \
src/audiostreammanager.cpp \
src/configeditorwidget.cpp \
src/main.cpp \
src/mainwindow.cpp \
src/mainwindow_ui.cpp \
@ -306,7 +305,6 @@ HEADERS += \
src/tcpcalibrationwidget.h \
src/agvmapviewwidget.h \
src/audiostreammanager.h \
src/configeditorwidget.h \
src/mainwindow.h \
src/quictestserver.h \
src/rpcservicewidget.h \
@ -422,3 +420,4 @@ DISTFILES += scripts/repair_qt3d_release.ps1
HEADERS += src/workflowgraph.h src/freescaninteropui.h
HEADERS += src/workflowruntime.h
HEADERS += src/workflowhistory.h src/workflowrobotmanager.h

View File

@ -12,7 +12,7 @@ CMVR Control Station 是一个基于 Qt 5 的桌面控制站,用于连接 CMVR
- Protobuf 配置查看、校验和编辑
- 可选的 MsQuic/TLS 测试服务器
## 设备管理
## 设备连接与控制
### AGV 手动加减速
@ -24,40 +24,16 @@ AGV 页右侧“手动控制”可分别设置线加速度、线减速度(m/s
AGV 的地图工作区可选择“通过服务”或“车辆直连”。该选项只改变地图读取、保存和切图的上位机通信路径,不修改服务端或 gRPC/proto 定义;Demo 模式继续使用演示数据。导航、状态、建图和其他设备仍使用原有服务。
车辆 IP 留空时,上位机通过当前服务地址的 ConfigurationService(默认 50053,可沿用配置服务端口设置)只读查找当前设备 ID 对应的 SEER 地址和端口。也可手填车辆 IP,此时使用标准端口 19204/19205/19207。配置查询和车辆 TCP 操作在独立线程执行,不占用原有控制请求线程。
车辆直连需要手动填写车辆 IP,使用标准端口 19204/19205/19207。车辆 TCP 操作在独立线程执行,不占用原有控制请求线程。
直连保存发送包含顶层 `header` 的完整原始 SMAP,保留未知字段和数字文本。写入前读取最新地图供编辑器合并,并检查车辆速度和导航状态;静止且任务空闲才申请控制权、再次检查状态并发送一次地图请求。切图须同时读取到加载成功和当前地图名称匹配才显示完成。发送后超时、取消或回包异常会显示结果未知,不自动重发;原编辑内容仍保留。直连操作期间,本窗口的导航、运动和建图入口暂时禁用,急停与停止入口保持可用。
该路径要求本机能访问车辆网络,不会修复服务端持有的断开连接。服务状态与直连切图确认分别显示。实车操作前应确保没有其他控制端同时发起导航或修改地图;本机模拟 TCP 测试通过并不等同于实车保存成功。
左侧进入 `gRPC > 设备管理` 后,默认打开“设备总览”:
- 主 gRPC 通道连接成功时自动调用 `GetSystemInfo` 和 `GetSystemStatus`。
- `GetSystemInfo` 用于显示边缘端系统名与版本;`GetSystemStatus.device_list`
用于展示在线设备 ID、设备大类、厂商和运行时驱动,并随系统状态轮询自动更新。
- 设备按 AGV、电池、相机、灵巧手、夹爪、麦克风、机械臂和扬声器分类,
支持按设备 ID 或类型搜索。
- 点击只读状态下的设备卡片会进入对应控制页面,并自动填写该设备的
`device_id`。
- 点击“修改”会从 ConfigurationService 加载 `manager/device_manager.pb.txt`
及 `devices/*/*.pb.txt`:可以修改设备 ID、类型和品牌/驱动,展开“配置参数”
后按 Protobuf 字段逐项编辑,也可以使用卡片右上角删除按钮或末尾的“+”卡片
增删设备。
- 点击“完成”会先写入各设备配置,再写入 DeviceManager 配置;保存使用远端
revision 做并发版本校验。当前只上传配置文件,不会自动重启或重载 cmvr-es。
- “配置管理”页签保留远端 Protobuf 配置的读取、字段编辑、校验和保存能力;
配置服务默认端口为 `50053`,与主控制 gRPC 通道独立连接。
`GetSystemStatus` 的设备条目包含 `device_type`、稳定的 `device_kind`、
`driver_type` 和 `vendor`。上位机优先使用 `device_kind` 判断设备大类,避免 AUBO、
华沿等具体机械臂驱动被错误归类为 AGV;设备卡片副标题会显示如
`AUBO · AuboARM` 的厂商与驱动信息。“在线”仍表示设备存在于边缘端
本次返回的 `device_list` 中。
## 机械臂自动识别与切换
机械臂页面的顶部选单来自 `GetSystemStatus` 返回的全部在线机械臂,不再使用
固定的“左臂/右臂”选项。选择设备管理中的机械臂卡片,或直接切换该选单后,
固定的“左臂/右臂”选项。切换该选单后,
上位机会以相同的 `device_id` 调用 `ArmService.GetArmInfo` 和
`ArmService.getRobotState`:
@ -345,8 +321,16 @@ Proto 约定和目录说明见 [protos/README.md](protos/README.md)。
两个画布均支持 Ctrl+C / Ctrl+V 复制粘贴选中节点。循环连同其内部节点一起复制,多节点保留内部连线;粘贴生成新的节点 ID 并偏移位置,外部连线不复制。点位流程粘贴时要求当前点位库中存在所引用的点位。执行期间禁用粘贴,文本输入框继续使用原有文本复制粘贴。
连线使用方向流动动画,拖动节点时实时跟随端口,选中后可按 Delete 删除。两个编辑器均提供撤销/重做按钮,支持 Ctrl+Z、Ctrl+Shift+Z 和 Ctrl+Y;删除循环时,其内部节点、参数与连线一起恢复。输入框获得焦点时,快捷键用于文字撤销/重做;切换流程会重置当前编辑历史,执行期间禁用图编辑撤销。
`joint_programs.json` 的组保留点位库和多个流程;每个流程用 `flowData` 字符串存储真实 `{nodes,edges}` 图。任务存储使用 `{flows:[{id,name,flowData}],activeFlowId}`,不再把旧的任务数组作为主存储。节点沿用中心坐标 `x/y`、`properties.parentId`、循环 `children` 和 `sourceNodeId/targetNodeId` 连线。旧文件读取后备份为 `.before-graph.<标识>.bak` 并迁移;转换失败时保留原文件。
两个入口均能导入/导出 am-freescan 图 JSON。导出保留 cmvr-es 的服务全名、方法名、完整请求、接口超时及 protobuf 描述集;循环和等待使用原生 loop/sleep 节点。组合点位保留多臂并行运动和逐臂关节顺序校验。网页侧通过自身 gRPC 连接调用 cmvr-es,上位机无需保持运行。资源使用参考项目的机器人角色和设备用途绑定,网页导出后在上位机导入时选择实际设备。
克隆仓库包含对应的网页 JSON 导入/导出、参数面板和 `CMVR_GRPC_UNARY` / `CMVR_ARM_POINT_BATCH` 后端执行适配。这些改动必须由网页项目单独构建部署后才生效,本地修改不代表线上已支持。组合调用先校验所有机械臂,再并行下发同步 MoveJ;失败或取消时取消剩余调用并请求停止。任务编排使用图执行器,支持并行分支、汇合屏障及嵌套循环;每次循环独立记录前驱完成状态,各 RPC 以独立调用标识收取结果。失败和停止会取消全部在途 RPC;已执行的调用不会自动重试。点位执行器保留单路径与组合点位调用。条件分支、运行时参数引用、扫描仪等其他领域动作不能无损转换时明确报错。等待可位于开始之后、任务之后或循环内部。
2026-11-25:协议同步到 cmvr-es `linbo_dev` 提交 `c8b71b2b380bbc53ce7eda148707362f09a1066d`(已合入 `dev` 的 `7d230fa5`)。API 设备类型新增 Touch=8,BioHead=9、Motor=10、MotorSystem=11。当前服务端不提供 moveJPose、SystemService.ExecuteJsonCommand、命令标识/代际反馈和公制深度元数据;界面禁用末端位姿 MoveJ,动作队列使用 MoveL,缺少身份及深度元数据的触摸定位明确返回不支持。普通关节 MoveJ、相机图像和预览保持可用。
任务编排的“机器人管理”可添加、编辑、连接或断开多台 cmvr-es,连接记录保存到 `data/workflow_robots.json`,重新打开软件后不自动连接额外机器人。“执行设置”分别选择机器人和该机器人上的同类设备;节点记录 `robotId`,旧节点默认绑定主界面机器人。不同机器人的同名设备、参数查询、演示状态和执行通道独立;离线、删除或找不到设备时明确报错,不会改发到其他机器人。导出 am-freescan 使用独立机器人角色和设备用途,未知机器人导入后须重新绑定。
任务与点位画布统一为左键框选、Ctrl+左键追加/取消选择、右键拖动画布,左键仍可拖动节点和连接端口。框选节点支持整体拖动和批量删除,删除可撤销。节点参数面板固定显示执行设置和保存按钮,输入参数单独滚动;关节名与角度并排显示,限位单独显示,行高随字体和名称换行调整。

View File

@ -9,7 +9,7 @@
"format": "cmvr.task-flow",
"groups": [
{
"id": "33a7f0ba-6beb-4774-b5b1-5b764c593680",
"id": "462644ae-a674-40c6-8837-8a94cfdb4caa",
"name": "offline example",
"nodes": [
{
@ -32,7 +32,7 @@
"service": "cmvr.api.AgvService",
"timeoutMs": 180000
},
"id": "4747c001-5cef-45cd-8daf-53b6db95936f",
"id": "2572e392-ee21-4c06-bb68-0f59a3d9d2f5",
"kind": "task",
"name": "导航站点",
"operationId": "cmvr.api.AgvService.navigateToStation",
@ -67,7 +67,7 @@
"service": "cmvr.api.AgvService",
"timeoutMs": 180000
},
"id": "b76301ec-520a-4a90-b007-0840b70d9048",
"id": "1c46a051-f643-4d78-98cc-427325e505b3",
"kind": "task",
"name": "停止",
"operationId": "cmvr.api.AgvService.cancelNavigation",
@ -96,7 +96,7 @@
"service": "cmvr.api.AgvService",
"timeoutMs": 180000
},
"id": "458cf1e9-baed-4478-94ce-b4b83ac82a89",
"id": "a9d3408f-1666-4ec9-aba6-bcf505e8d747",
"kind": "task",
"name": "暂停",
"operationId": "cmvr.api.AgvService.pauseNavigation",
@ -125,7 +125,7 @@
"service": "cmvr.api.AgvService",
"timeoutMs": 180000
},
"id": "a325f7d2-c4a9-475c-b945-f39b342a5511",
"id": "08a22229-37ae-4f31-ae1f-64617dca7a95",
"kind": "task",
"name": "继续",
"operationId": "cmvr.api.AgvService.resumeNavigation",
@ -156,7 +156,7 @@
"service": "cmvr.api.BioHeadService",
"timeoutMs": 180000
},
"id": "c4574cc6-a6d1-4a05-9ee7-04db58335ab7",
"id": "a71cef34-837d-4bef-9549-2d499d96c94d",
"kind": "task",
"name": "高兴",
"operationId": "cmvr.api.BioHeadService.Happy",
@ -189,7 +189,7 @@
"service": "cmvr.api.BioHeadService",
"timeoutMs": 180000
},
"id": "104bfb8b-3695-4dab-a5f2-2215bf8b5282",
"id": "e0816c07-4081-4d4c-8ac2-8225aff9dee3",
"kind": "task",
"name": "惊讶",
"operationId": "cmvr.api.BioHeadService.Surprise",
@ -222,7 +222,7 @@
"service": "cmvr.api.BioHeadService",
"timeoutMs": 180000
},
"id": "47afc797-7041-4f9a-bdec-7ae55acee32d",
"id": "d76f12e0-fd8f-4ed9-8385-bad677882a4b",
"kind": "task",
"name": "疲惫",
"operationId": "cmvr.api.BioHeadService.ExpressionTired",
@ -255,7 +255,7 @@
"service": "cmvr.api.BioHeadService",
"timeoutMs": 180000
},
"id": "38e5c86d-83c7-4fb9-a52a-1a38cf4c882f",
"id": "05c928d9-0e19-4091-987c-4dce2de6e0fa",
"kind": "task",
"name": "愤怒",
"operationId": "cmvr.api.BioHeadService.ExpressionAngry",
@ -288,7 +288,7 @@
"service": "cmvr.api.BioHeadService",
"timeoutMs": 180000
},
"id": "daa58640-a575-4b03-b5a8-0e5f76e40655",
"id": "99dea67b-e32d-4f47-9d7d-ce6a3144ecdb",
"kind": "task",
"name": "悲伤",
"operationId": "cmvr.api.BioHeadService.ExpressionSadness",
@ -321,7 +321,7 @@
"service": "cmvr.api.BioHeadService",
"timeoutMs": 180000
},
"id": "5660f447-fe18-4b7b-b4bf-cbfabcececfb",
"id": "9284aba0-8a5c-40a1-b3e0-ea7e660f2e7f",
"kind": "task",
"name": "打哈欠",
"operationId": "cmvr.api.BioHeadService.ExpressionYawn",
@ -354,7 +354,7 @@
"service": "cmvr.api.BioHeadService",
"timeoutMs": 180000
},
"id": "845cfd68-62a2-4c7b-86d2-0d253b72da40",
"id": "b66b0572-e79d-4e87-a00d-404ee03d74d8",
"kind": "task",
"name": "开始说话",
"operationId": "cmvr.api.BioHeadService.SpeakStart",
@ -387,7 +387,7 @@
"service": "cmvr.api.BioHeadService",
"timeoutMs": 180000
},
"id": "c2c56eef-b25b-40fb-a958-46f255be6de9",
"id": "7e93ae71-93ec-4cfe-af20-0ceccc9519a8",
"kind": "task",
"name": "停止说话",
"operationId": "cmvr.api.BioHeadService.SpeakStop",
@ -420,7 +420,7 @@
"service": "cmvr.api.BioHeadService",
"timeoutMs": 180000
},
"id": "75ebd6dd-d989-4d0e-bab8-1d55d399679f",
"id": "18cf31ec-efac-4bab-afe7-65a7a04850f9",
"kind": "task",
"name": "紧急停止",
"operationId": "cmvr.api.BioHeadService.EmergencyStop",
@ -453,7 +453,7 @@
"service": "cmvr.api.BioHeadService",
"timeoutMs": 180000
},
"id": "dda5a413-72e4-477e-96f3-2179a17ce66d",
"id": "32764624-8279-4c18-aefb-b80800a4dca9",
"kind": "task",
"name": "检查设备",
"operationId": "cmvr.api.BioHeadService.GetSystemStatus",
@ -487,7 +487,7 @@
"service": "cmvr.api.SpeakerService",
"timeoutMs": 180000
},
"id": "080a79c5-dc13-4a1d-904e-5f2d3080666d",
"id": "300fd86d-1b21-4f92-b8a1-60772a89b5fb",
"kind": "task",
"name": "播放服务端文件",
"operationId": "cmvr.api.SpeakerService.PlayAudio",
@ -521,7 +521,7 @@
"service": "cmvr.api.SpeakerService",
"timeoutMs": 180000
},
"id": "0205b7bc-11a3-4006-916f-bda7dfec1718",
"id": "24426aec-c0e2-446e-8829-f6d4c64c4abf",
"kind": "task",
"name": "停止文件播放",
"operationId": "cmvr.api.SpeakerService.StopPlayback",
@ -553,7 +553,7 @@
"sampleRate": 48000
}
},
"id": "7f276588-ea95-4e6d-967f-912970e231eb",
"id": "ca5c6e79-b3dd-431c-8f63-a111abc1089a",
"kind": "task",
"name": "本机麦克风流播放",
"operationId": "client.speaker.capture_stream_start",
@ -605,7 +605,7 @@
"parameters": {
}
},
"id": "da815ca3-3ce5-46a5-b613-ac5abfaf907f",
"id": "5c8a0947-20ac-4f80-b5da-e3375dd52d3e",
"kind": "task",
"name": "停止音频流",
"operationId": "client.speaker.stream_stop",
@ -651,7 +651,7 @@
"parameters": {
}
},
"id": "4799da27-00d2-4729-8dce-3f6f00aa7f71",
"id": "08a2ee16-1b63-4c28-9445-9bea74a35149",
"kind": "task",
"name": "开始音频流",
"operationId": "client.speaker.stream_start",
@ -715,7 +715,7 @@
"service": "cmvr.api.ArmService",
"timeoutMs": 180000
},
"id": "1703bebf-9d76-4525-b03c-0c8e8e9f2a30",
"id": "7a653b1b-e0f9-4256-af05-5b7c091acf8a",
"kind": "task",
"name": "MoveJ",
"operationId": "cmvr.api.ArmService.moveJ",
@ -757,7 +757,7 @@
"service": "cmvr.api.ArmService",
"timeoutMs": 180000
},
"id": "ee11a5a1-5d59-48d0-a330-a98357e502a5",
"id": "f4be6958-0216-43ce-9126-6a19957d2efd",
"kind": "task",
"name": "使能",
"operationId": "cmvr.api.ArmService.torqueOn",
@ -786,7 +786,7 @@
"service": "cmvr.api.ArmService",
"timeoutMs": 180000
},
"id": "34b6f6dc-26ce-4b27-9e00-63d149a9f285",
"id": "6591d283-a3e2-4b84-8b57-f2431b715ee0",
"kind": "task",
"name": "去使能",
"operationId": "cmvr.api.ArmService.torqueOff",
@ -815,7 +815,7 @@
"service": "cmvr.api.ArmService",
"timeoutMs": 180000
},
"id": "d0ecce99-1167-45f6-8b27-0da01d078031",
"id": "58e93ec7-5081-4168-beaf-1d3a3998a1ed",
"kind": "task",
"name": "停止",
"operationId": "cmvr.api.ArmService.stopMotion",
@ -844,7 +844,7 @@
"service": "cmvr.api.ArmService",
"timeoutMs": 180000
},
"id": "e22f3a67-c16a-4ae4-93f9-65c0374e92f5",
"id": "428ae96e-6942-4164-b95a-9c3074091f3f",
"kind": "task",
"name": "清除故障",
"operationId": "cmvr.api.ArmService.clearFault",
@ -885,7 +885,7 @@
"service": "cmvr.api.DexHandService",
"timeoutMs": 180000
},
"id": "e3a6a416-b5cb-43a9-bc01-6a5d2547b375",
"id": "46d59eaf-af47-4da5-81a4-505323227139",
"kind": "task",
"name": "设置角度",
"operationId": "cmvr.api.DexHandService.SetDexHandAngle",
@ -938,7 +938,7 @@
"service": "cmvr.api.DexHandService",
"timeoutMs": 180000
},
"id": "c4cbcbe6-d12e-46af-93f4-0661d5f1481f",
"id": "a2a1c709-e3af-4ec4-8082-caabfb86cc9e",
"kind": "task",
"name": "设置位置",
"operationId": "cmvr.api.DexHandService.SetDexHandPos",
@ -991,7 +991,7 @@
"service": "cmvr.api.DexHandService",
"timeoutMs": 180000
},
"id": "ad3a8a64-5bf5-42a4-b24f-c78bf492fc4e",
"id": "b4088c48-1ed6-4830-bbdb-f658e2d11048",
"kind": "task",
"name": "设置速度",
"operationId": "cmvr.api.DexHandService.SetDexHandSpeed",
@ -1044,7 +1044,7 @@
"service": "cmvr.api.DexHandService",
"timeoutMs": 180000
},
"id": "8893e630-90f8-4069-9919-71187a65a921",
"id": "e2800d45-c6ba-42f6-b8e0-c5c9fb6df976",
"kind": "task",
"name": "设置力",
"operationId": "cmvr.api.DexHandService.SetDexHandForce",
@ -1087,7 +1087,7 @@
"service": "cmvr.api.CameraService",
"timeoutMs": 180000
},
"id": "337ef37c-b0d0-43c4-a921-91cd16f73f33",
"id": "84601aaa-b84f-43dd-9f1e-442c47dd7a3d",
"kind": "task",
"name": "RGB抓图",
"operationId": "cmvr.api.CameraService.GetRGBImage",
@ -1120,7 +1120,7 @@
"service": "cmvr.api.CameraService",
"timeoutMs": 180000
},
"id": "e942b241-0a66-4029-b915-2f61f966af0b",
"id": "8ae46e9c-8ee4-4550-9f22-41290a4ec971",
"kind": "task",
"name": "深度抓图",
"operationId": "cmvr.api.CameraService.GetDepthImage",
@ -1149,7 +1149,7 @@
"parameters": {
}
},
"id": "66236fa9-6b08-46d5-bc90-ed007ff5ebd5",
"id": "a6582031-bb3b-45f8-adf3-48273a3874b2",
"kind": "task",
"name": "开始预览",
"operationId": "client.camera.preview_start",
@ -1234,7 +1234,7 @@
"parameters": {
}
},
"id": "ae7eff1f-e82d-4b84-9d36-621b609e37b2",
"id": "820ff21b-4a0d-4e97-a3ee-96c8d8b7d8d1",
"kind": "task",
"name": "停止预览",
"operationId": "client.camera.preview_stop",
@ -1285,7 +1285,7 @@
"service": "cmvr.api.CameraService",
"timeoutMs": 180000
},
"id": "6543cb6c-21b7-47fc-bb9e-b1913f4a7016",
"id": "b8fe3f1c-5bbe-43f4-97e8-13f8aa6913ab",
"kind": "task",
"name": "开始录像",
"operationId": "cmvr.api.CameraService.StartRecording",
@ -1319,7 +1319,7 @@
"service": "cmvr.api.CameraService",
"timeoutMs": 180000
},
"id": "9690be1b-9c83-4a6a-ba31-de6d4fd60884",
"id": "7f1cdf4f-8aca-4aa5-adaa-dd58acefd18e",
"kind": "task",
"name": "停止录像",
"operationId": "cmvr.api.CameraService.StopRecording",
@ -1353,7 +1353,7 @@
"service": "cmvr.api.MicPhoneService",
"timeoutMs": 180000
},
"id": "0ec28a2c-b6f7-4ad8-96e1-f119134ca62b",
"id": "7fc6ff56-01dd-422b-b90c-39e733cb554e",
"kind": "task",
"name": "开始录音",
"operationId": "cmvr.api.MicPhoneService.StartRecord",
@ -1387,7 +1387,7 @@
"service": "cmvr.api.MicPhoneService",
"timeoutMs": 180000
},
"id": "4e2d35d1-0ae4-4589-b499-8f8a1335b441",
"id": "f08159ae-d66a-4b0a-876d-e473577ac456",
"kind": "task",
"name": "停止录音",
"operationId": "cmvr.api.MicPhoneService.StopRecord",
@ -1416,7 +1416,7 @@
"parameters": {
}
},
"id": "79d905bb-8ac4-44f2-b251-9fff59eba2ac",
"id": "f66802c4-d72a-4abc-ab5f-c720966c687f",
"kind": "task",
"name": "开始音频流",
"operationId": "client.microphone.stream_start",
@ -1462,7 +1462,7 @@
"parameters": {
}
},
"id": "78af5597-f9fd-46ce-85f0-9985592f02ce",
"id": "44149516-efd0-4f36-ba83-b704c8652fc3",
"kind": "task",
"name": "停止音频流",
"operationId": "client.microphone.stream_stop",

View File

@ -49,13 +49,13 @@
{
"children": [
{
"action": "接口 · moveJPose",
"action": "接口 · moveL",
"deviceId": "aubo_arm",
"deviceType": "机械臂",
"execution": {
"completion": "rpc_response",
"kind": "grpc_unary",
"method": "moveJPose",
"method": "moveL",
"request": {
"header": {
"device_id": "aubo_arm"
@ -80,10 +80,10 @@
},
"id": "example-movej-pose",
"kind": "task",
"name": "接口 · moveJPose",
"operationId": "cmvr.api.ArmService.moveJPose",
"name": "接口 · moveL",
"operationId": "cmvr.api.ArmService.moveL",
"parameters": {
"method": "moveJPose",
"method": "moveL",
"request": {
"options": {
"acceleration": 0.5,

File diff suppressed because it is too large Load Diff

View File

@ -998,198 +998,6 @@
"number": 4
}
],
"cmvr.api.CommandExecutionState": [
{
"name": "COMMAND_EXECUTION_STATE_UNSPECIFIED",
"number": 0
},
{
"name": "COMMAND_EXECUTION_STATE_RECEIVED",
"number": 1
},
{
"name": "COMMAND_EXECUTION_STATE_RESERVED",
"number": 2
},
{
"name": "COMMAND_EXECUTION_STATE_REJECTED_BEFORE_DISPATCH",
"number": 3
},
{
"name": "COMMAND_EXECUTION_STATE_ADMITTED",
"number": 4
},
{
"name": "COMMAND_EXECUTION_STATE_DISPATCHING",
"number": 5
},
{
"name": "COMMAND_EXECUTION_STATE_ACCEPTED_BY_HARDWARE",
"number": 6
},
{
"name": "COMMAND_EXECUTION_STATE_COMPLETED",
"number": 7
},
{
"name": "COMMAND_EXECUTION_STATE_FAILED",
"number": 8
},
{
"name": "COMMAND_EXECUTION_STATE_CANCELED_BEFORE_DISPATCH",
"number": 9
},
{
"name": "COMMAND_EXECUTION_STATE_OUTCOME_UNKNOWN",
"number": 10
}
],
"cmvr.api.CommandReasonCode": [
{
"name": "COMMAND_REASON_CODE_UNSPECIFIED",
"number": 0
},
{
"name": "COMMAND_REASON_CODE_NONE",
"number": 1
},
{
"name": "COMMAND_REASON_CODE_INVALID_ARGUMENT",
"number": 2
},
{
"name": "COMMAND_REASON_CODE_UNAUTHENTICATED",
"number": 3
},
{
"name": "COMMAND_REASON_CODE_PERMISSION_DENIED",
"number": 4
},
{
"name": "COMMAND_REASON_CODE_RECOVERY_RPC_DISABLED",
"number": 5
},
{
"name": "COMMAND_REASON_CODE_DEVICE_NOT_FOUND",
"number": 6
},
{
"name": "COMMAND_REASON_CODE_DEVICE_UNAVAILABLE",
"number": 7
},
{
"name": "COMMAND_REASON_CODE_UNSUPPORTED_COMMAND",
"number": 8
},
{
"name": "COMMAND_REASON_CODE_SYSTEM_STARTING",
"number": 9
},
{
"name": "COMMAND_REASON_CODE_SYSTEM_STOPPING",
"number": 10
},
{
"name": "COMMAND_REASON_CODE_SAFETY_LATCHED",
"number": 11
},
{
"name": "COMMAND_REASON_CODE_SAFETY_STATE_MISSING",
"number": 12
},
{
"name": "COMMAND_REASON_CODE_SAFETY_STATE_STALE",
"number": 13
},
{
"name": "COMMAND_REASON_CODE_HARDWARE_UNSAFE",
"number": 14
},
{
"name": "COMMAND_REASON_CODE_EMERGENCY_STOP_ACTIVE",
"number": 15
},
{
"name": "COMMAND_REASON_CODE_PROTECTIVE_STOP_ACTIVE",
"number": 16
},
{
"name": "COMMAND_REASON_CODE_DEVICE_DISCONNECTED",
"number": 17
},
{
"name": "COMMAND_REASON_CODE_DEVICE_FAULT",
"number": 18
},
{
"name": "COMMAND_REASON_CODE_DEVICE_NOT_READY",
"number": 19
},
{
"name": "COMMAND_REASON_CODE_DEVICE_STILL_MOVING",
"number": 20
},
{
"name": "COMMAND_REASON_CODE_CONTROL_BUSY",
"number": 21
},
{
"name": "COMMAND_REASON_CODE_GENERATION_MISMATCH",
"number": 22
},
{
"name": "COMMAND_REASON_CODE_COMMAND_ID_REQUIRED",
"number": 23
},
{
"name": "COMMAND_REASON_CODE_COMMAND_ID_CONFLICT",
"number": 24
},
{
"name": "COMMAND_REASON_CODE_RESULT_EVICTED",
"number": 25
},
{
"name": "COMMAND_REASON_CODE_LEDGER_EXHAUSTED",
"number": 26
},
{
"name": "COMMAND_REASON_CODE_BACKPRESSURE",
"number": 27
},
{
"name": "COMMAND_REASON_CODE_DEADLINE_EXCEEDED_BEFORE_DISPATCH",
"number": 28
},
{
"name": "COMMAND_REASON_CODE_OUTCOME_UNKNOWN",
"number": 29
},
{
"name": "COMMAND_REASON_CODE_PARTICIPANT_TIMEOUT",
"number": 30
},
{
"name": "COMMAND_REASON_CODE_STOP_UNCONFIRMED",
"number": 31
},
{
"name": "COMMAND_REASON_CODE_RECOVERY_EPOCH_MISMATCH",
"number": 32
},
{
"name": "COMMAND_REASON_CODE_RECOVERY_REASON_REQUIRED",
"number": 33
},
{
"name": "COMMAND_REASON_CODE_RECOVERY_AUDIT_FAILED",
"number": 34
},
{
"name": "COMMAND_REASON_CODE_INTERNAL_ERROR",
"number": 35
}
],
"cmvr.api.ControlPtzCommand.Action": [
{
"name": "START",
@ -1332,6 +1140,10 @@
{
"name": "PALM",
"number": 5
},
{
"name": "FINGER_UNSPECIFIED",
"number": 6
}
],
"cmvr.api.SensorData.PartType": [
@ -1354,6 +1166,10 @@
{
"name": "PALM_PAD",
"number": 4
},
{
"name": "PART_UNSPECIFIED",
"number": 5
}
],
"cmvr.msgs.AgvMapDimension": [
@ -2729,62 +2545,6 @@
"presence": true,
"repeated": false,
"type": "message"
},
{
"enumType": "cmvr.api.CommandReasonCode",
"jsonName": "reasonCode",
"map": false,
"name": "reason_code",
"number": 4,
"presence": false,
"repeated": false,
"type": "enum"
},
{
"jsonName": "commandId",
"map": false,
"name": "command_id",
"number": 5,
"presence": false,
"repeated": false,
"type": "string"
},
{
"jsonName": "serviceInstanceId",
"map": false,
"name": "service_instance_id",
"number": 6,
"presence": false,
"repeated": false,
"type": "string"
},
{
"jsonName": "safetyEpoch",
"map": false,
"name": "safety_epoch",
"number": 7,
"presence": false,
"repeated": false,
"type": "uint64"
},
{
"jsonName": "deviceGeneration",
"map": false,
"name": "device_generation",
"number": 8,
"presence": false,
"repeated": false,
"type": "uint64"
},
{
"enumType": "cmvr.api.CommandExecutionState",
"jsonName": "executionState",
"map": false,
"name": "execution_state",
"number": 9,
"presence": false,
"repeated": false,
"type": "enum"
}
]
},
@ -2808,42 +2568,6 @@
"presence": true,
"repeated": false,
"type": "message"
},
{
"jsonName": "commandId",
"map": false,
"name": "command_id",
"number": 3,
"presence": false,
"repeated": false,
"type": "string"
},
{
"jsonName": "expectedServiceInstanceId",
"map": false,
"name": "expected_service_instance_id",
"number": 4,
"presence": false,
"repeated": false,
"type": "string"
},
{
"jsonName": "expectedDeviceGeneration",
"map": false,
"name": "expected_device_generation",
"number": 5,
"presence": true,
"repeated": false,
"type": "uint64"
},
{
"jsonName": "validForMs",
"map": false,
"name": "valid_for_ms",
"number": 6,
"presence": false,
"repeated": false,
"type": "uint32"
}
]
},
@ -2984,55 +2708,6 @@
}
]
},
"cmvr.api.DepthGeometry": {
"fields": [
{
"jsonName": "metresPerUnit",
"map": false,
"name": "metres_per_unit",
"number": 1,
"presence": false,
"repeated": false,
"type": "double"
},
{
"jsonName": "alignedToColor",
"map": false,
"name": "aligned_to_color",
"number": 2,
"presence": false,
"repeated": false,
"type": "bool"
},
{
"jsonName": "colorAxialZ",
"map": false,
"name": "color_axial_z",
"number": 3,
"presence": false,
"repeated": false,
"type": "bool"
},
{
"jsonName": "byteOrder",
"map": false,
"name": "byte_order",
"number": 4,
"presence": false,
"repeated": false,
"type": "string"
},
{
"jsonName": "distortionModel",
"map": false,
"name": "distortion_model",
"number": 5,
"presence": false,
"repeated": false,
"type": "string"
}
]
},
"cmvr.api.DexHandState": {
"fields": [
{
@ -3746,42 +3421,6 @@
"presence": false,
"repeated": false,
"type": "uint64"
},
{
"jsonName": "cameraSerial",
"map": false,
"name": "camera_serial",
"number": 14,
"presence": false,
"repeated": false,
"type": "string"
},
{
"jsonName": "cameraSessionGeneration",
"map": false,
"name": "camera_session_generation",
"number": 15,
"presence": false,
"repeated": false,
"type": "uint64"
},
{
"jsonName": "distortionModel",
"map": false,
"name": "distortion_model",
"number": 16,
"presence": false,
"repeated": false,
"type": "string"
},
{
"jsonName": "captureEarliestUtcNs",
"map": false,
"name": "capture_earliest_utc_ns",
"number": 17,
"presence": false,
"repeated": false,
"type": "int64"
}
]
},
@ -4578,16 +4217,6 @@
"presence": true,
"repeated": false,
"type": "message"
},
{
"jsonName": "depthGeometry",
"map": false,
"messageType": "cmvr.api.DepthGeometry",
"name": "depth_geometry",
"number": 5,
"presence": true,
"repeated": false,
"type": "message"
}
]
},
@ -4602,15 +4231,6 @@
"presence": true,
"repeated": false,
"type": "message"
},
{
"jsonName": "requireMetricDepth",
"map": false,
"name": "require_metric_depth",
"number": 2,
"presence": false,
"repeated": false,
"type": "bool"
}
]
},
@ -6308,72 +5928,6 @@
}
]
},
"cmvr.api.MoveJPose.Request": {
"fields": [
{
"jsonName": "header",
"map": false,
"messageType": "cmvr.api.CommandHeader.Request",
"name": "header",
"number": 1,
"presence": true,
"repeated": false,
"type": "message"
},
{
"jsonName": "target",
"map": false,
"messageType": "cmvr.api.CartesianPose",
"name": "target",
"number": 2,
"presence": true,
"repeated": false,
"type": "message"
},
{
"jsonName": "options",
"map": false,
"messageType": "cmvr.api.MotionOptions",
"name": "options",
"number": 3,
"presence": true,
"repeated": false,
"type": "message"
},
{
"jsonName": "userCoordinateName",
"map": false,
"name": "user_coordinate_name",
"number": 4,
"presence": false,
"repeated": false,
"type": "string"
},
{
"jsonName": "userCoordinateRevision",
"map": false,
"name": "user_coordinate_revision",
"number": 5,
"presence": false,
"repeated": false,
"type": "uint64"
}
]
},
"cmvr.api.MoveJPose.Response": {
"fields": [
{
"jsonName": "header",
"map": false,
"messageType": "cmvr.api.CommandHeader.Feedback",
"name": "header",
"number": 1,
"presence": true,
"repeated": false,
"type": "message"
}
]
},
"cmvr.api.MoveL.Request": {
"fields": [
{
@ -9577,17 +9131,6 @@
"serverStreaming": false,
"service": "cmvr.api.ArmService"
},
{
"clientStreaming": false,
"completion": "rpc_response",
"defaultTimeoutMs": 180000,
"id": "cmvr.api.ArmService.moveJPose",
"method": "moveJPose",
"requestType": "cmvr.api.MoveJPose.Request",
"responseType": "cmvr.api.MoveJPose.Response",
"serverStreaming": false,
"service": "cmvr.api.ArmService"
},
{
"clientStreaming": false,
"completion": "rpc_response",

View File

@ -549,16 +549,3 @@ message ComputeForwardKinematics {
TransformMatrix4x4 matrix = 2;
}
}
// Joint-space motion to an absolute TCP pose in an explicitly applied coordinate.
// AUBO converts with SDK Math, solves IK near current joints, then calls moveJoint.
message MoveJPose {
message Request {
CommandHeader.Request header = 1;
CartesianPose target = 2; // Absolute TCP pose: m / rad, RzRyRx.
MotionOptions options = 3; // Joint limits: rad/s, rad/s^2; AUBO does not use jerk.
string user_coordinate_name = 4; // Required. Apply this saved/builtin coordinate first.
uint64 user_coordinate_revision = 5; // 0 = latest saved revision; active revision must match.
}
message Response { CommandHeader.Feedback header = 1; }
}

View File

@ -14,7 +14,6 @@ service ArmService {
// 清除机械臂可恢复故障;不包含数值参数,无单位。
rpc clearFault(CommandHeader.Request) returns (CommandHeader.Feedback);
// 执行关节空间点到点运动;目标角度单位为 rad。
rpc moveJPose(MoveJPose.Request) returns (MoveJPose.Response);
rpc moveJ(MoveJ.Request) returns (MoveJ.Response);
// 执行所选坐标系下的绝对TCP目标直线运动,位置m、姿态rad;不接受增量目标。
rpc moveL(MoveL.Request) returns (MoveL.Response);

View File

@ -6,11 +6,24 @@ import "cmvr/api/head_joint_command.proto";
// 生物头部机器人服务接口
service BioHeadService {
// USB-head joint state, direct joint control and configured expressions.
rpc ControlHeadJoints(HeadJointCommand.Request) returns (HeadJointCommand.Feedback){};
rpc GetHeadJointState(GetHeadJointStateCommand.Request) returns (GetHeadJointStateCommand.Feedback){};
rpc SetHeadExpression(SetHeadExpressionCommand.Request) returns (SetHeadExpressionCommand.Feedback){};
rpc PlayHeadExpression(PlayHeadExpressionCommand.Request) returns (PlayHeadExpressionCommand.Feedback){};
// USB 头部关节控制。
rpc ControlHeadJoints(HeadJointCommand.Request)
returns (HeadJointCommand.Feedback);
// 查询 USB 头部的配置、连接和命令目标缓存。
rpc GetHeadJointState(GetHeadJointStateCommand.Request)
returns (GetHeadJointStateCommand.Feedback);
// Complete five-joint expression transition, with per-frame cancellation.
rpc SetHeadExpression(SetHeadExpressionCommand.Request)
returns (SetHeadExpressionCommand.Feedback);
// Play one configured preset by exact ID or exact name.
rpc PlayHeadExpression(PlayHeadExpressionCommand.Request)
returns (PlayHeadExpressionCommand.Feedback);
// 设置面部表情
rpc SetExpression(SetFacialExpression.Request) returns (SetFacialExpression.Feedback){};
@ -44,11 +57,4 @@ service BioHeadService {
rpc ExpressionYawn(ExpressionYawn.Request) returns (ExpressionYawn.Feedback){};
}

View File

@ -28,10 +28,6 @@ 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 {
@ -131,8 +127,6 @@ 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 {
@ -140,20 +134,9 @@ 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;

View File

@ -4,59 +4,6 @@ package cmvr.api;
import "google/protobuf/timestamp.proto";
enum CommandReasonCode {
COMMAND_REASON_CODE_UNSPECIFIED = 0;
COMMAND_REASON_CODE_NONE = 1;
COMMAND_REASON_CODE_INVALID_ARGUMENT = 2;
COMMAND_REASON_CODE_UNAUTHENTICATED = 3;
COMMAND_REASON_CODE_PERMISSION_DENIED = 4;
COMMAND_REASON_CODE_RECOVERY_RPC_DISABLED = 5;
COMMAND_REASON_CODE_DEVICE_NOT_FOUND = 6;
COMMAND_REASON_CODE_DEVICE_UNAVAILABLE = 7;
COMMAND_REASON_CODE_UNSUPPORTED_COMMAND = 8;
COMMAND_REASON_CODE_SYSTEM_STARTING = 9;
COMMAND_REASON_CODE_SYSTEM_STOPPING = 10;
COMMAND_REASON_CODE_SAFETY_LATCHED = 11;
COMMAND_REASON_CODE_SAFETY_STATE_MISSING = 12;
COMMAND_REASON_CODE_SAFETY_STATE_STALE = 13;
COMMAND_REASON_CODE_HARDWARE_UNSAFE = 14;
COMMAND_REASON_CODE_EMERGENCY_STOP_ACTIVE = 15;
COMMAND_REASON_CODE_PROTECTIVE_STOP_ACTIVE = 16;
COMMAND_REASON_CODE_DEVICE_DISCONNECTED = 17;
COMMAND_REASON_CODE_DEVICE_FAULT = 18;
COMMAND_REASON_CODE_DEVICE_NOT_READY = 19;
COMMAND_REASON_CODE_DEVICE_STILL_MOVING = 20;
COMMAND_REASON_CODE_CONTROL_BUSY = 21;
COMMAND_REASON_CODE_GENERATION_MISMATCH = 22;
COMMAND_REASON_CODE_COMMAND_ID_REQUIRED = 23;
COMMAND_REASON_CODE_COMMAND_ID_CONFLICT = 24;
COMMAND_REASON_CODE_RESULT_EVICTED = 25;
COMMAND_REASON_CODE_LEDGER_EXHAUSTED = 26;
COMMAND_REASON_CODE_BACKPRESSURE = 27;
COMMAND_REASON_CODE_DEADLINE_EXCEEDED_BEFORE_DISPATCH = 28;
COMMAND_REASON_CODE_OUTCOME_UNKNOWN = 29;
COMMAND_REASON_CODE_PARTICIPANT_TIMEOUT = 30;
COMMAND_REASON_CODE_STOP_UNCONFIRMED = 31;
COMMAND_REASON_CODE_RECOVERY_EPOCH_MISMATCH = 32;
COMMAND_REASON_CODE_RECOVERY_REASON_REQUIRED = 33;
COMMAND_REASON_CODE_RECOVERY_AUDIT_FAILED = 34;
COMMAND_REASON_CODE_INTERNAL_ERROR = 35;
}
enum CommandExecutionState {
COMMAND_EXECUTION_STATE_UNSPECIFIED = 0;
COMMAND_EXECUTION_STATE_RECEIVED = 1;
COMMAND_EXECUTION_STATE_RESERVED = 2;
COMMAND_EXECUTION_STATE_REJECTED_BEFORE_DISPATCH = 3;
COMMAND_EXECUTION_STATE_ADMITTED = 4;
COMMAND_EXECUTION_STATE_DISPATCHING = 5;
COMMAND_EXECUTION_STATE_ACCEPTED_BY_HARDWARE = 6;
COMMAND_EXECUTION_STATE_COMPLETED = 7;
COMMAND_EXECUTION_STATE_FAILED = 8;
COMMAND_EXECUTION_STATE_CANCELED_BEFORE_DISPATCH = 9;
COMMAND_EXECUTION_STATE_OUTCOME_UNKNOWN = 10;
}
message DeviceLifecycle {
enum Lifecycle {
STATE_INIT = 0;
@ -73,22 +20,12 @@ message CommandHeader {
message Request {
string device_id = 1; // 目标设备名称
google.protobuf.Timestamp timestamp = 2; // 请求时间
string command_id = 3;
string expected_service_instance_id = 4;
optional uint64 expected_device_generation = 5;
uint32 valid_for_ms = 6;
}
message Feedback {
bool success = 1; // 是否成功
string error_message = 2; // 错误信息(成功时为空)
google.protobuf.Timestamp timestamp = 3; // 回复时间
CommandReasonCode reason_code = 4;
string command_id = 5;
string service_instance_id = 6;
uint64 safety_epoch = 7;
uint64 device_generation = 8;
CommandExecutionState execution_state = 9;
}
}
@ -122,14 +59,21 @@ message ConfigParam {
}
}
// 设备厂商扩展 JSON 命令;JSON 内容及字段单位由具体设备命令定义。
message JsonDeviceCommand {
// JSON 命令请求。
message Request {
// 通用请求头,包含目标设备 ID 和请求时间戳。
CommandHeader.Request header = 1;
// JSON 格式的设备命令字符串,无单位。
string request_json = 2;
}
// JSON 命令响应。
message Feedback {
// 通用响应头,包含成功标志、错误信息和响应时间戳。
CommandHeader.Feedback header = 1;
// JSON 格式的设备响应字符串,无单位。
string response_json = 2;
}
}

View File

@ -1,57 +0,0 @@
syntax = "proto3";
import "cmvr/api/common.proto";
package cmvr.api;
message ConfigFileInfo {
string relative_path = 1;
uint64 size_bytes = 2;
int64 modified_unix_ms = 3;
string message_type = 4;
}
message ListConfigFilesCommand {
message Request {}
message Feedback {
CommandHeader.Feedback header = 1;
string config_root = 2;
repeated ConfigFileInfo files = 3;
}
}
message ReadConfigFileCommand {
message Request {
string relative_path = 1;
}
message Feedback {
CommandHeader.Feedback header = 1;
ConfigFileInfo file = 2;
string content = 3;
string revision = 4;
}
}
message ValidateConfigFileCommand {
message Request {
string relative_path = 1;
string content = 2;
}
message Feedback {
CommandHeader.Feedback header = 1;
string message_type = 2;
}
}
message SaveConfigFileCommand {
message Request {
string relative_path = 1;
string content = 2;
string expected_revision = 3;
}
message Feedback {
CommandHeader.Feedback header = 1;
string revision = 2;
int64 modified_unix_ms = 3;
}
}

View File

@ -1,12 +0,0 @@
syntax = "proto3";
import "cmvr/api/configuration_command.proto";
package cmvr.api;
service ConfigurationService {
rpc ListConfigFiles(ListConfigFilesCommand.Request) returns (ListConfigFilesCommand.Feedback);
rpc ReadConfigFile(ReadConfigFileCommand.Request) returns (ReadConfigFileCommand.Feedback);
rpc ValidateConfigFile(ValidateConfigFileCommand.Request) returns (ValidateConfigFileCommand.Feedback);
rpc SaveConfigFile(SaveConfigFileCommand.Request) returns (SaveConfigFileCommand.Feedback);
}

View File

@ -31,6 +31,7 @@ message SensorData {
INDEX = 3; // 食指
THUMB = 4; // 大拇指
PALM = 5; // 掌心
FINGER_UNSPECIFIED = 6; // 独立触觉传感器,不关联手指
}
// 部位类型(指中改为THUMB_MIDDLE以避免冲突)
@ -40,6 +41,7 @@ message SensorData {
PAD = 2; // 指腹
THUMB_MIDDLE = 3; // 大拇指指中(仅大拇指有)
PALM_PAD = 4; // 掌心部位(对应PalmTactileData)
PART_UNSPECIFIED = 5; // 独立触觉传感器,不关联手指部位
}
FingerType finger_type = 4; // 手指类型(掌心使用PALM)

View File

@ -14,12 +14,13 @@ enum DeviceType {
Microphone = 5;
Robot = 6;
Speaker = 7;
BioHead = 8;
Motor = 9;
MotorSystem = 10;
MujocoWorld = 11;
MujocoViewer = 12;
CanBus = 13;
Touch = 8;
BioHead = 9;
Motor = 10;
MotorSystem = 11;
MujocoWorld = 12;
MujocoViewer = 13;
CanBus = 14;
Unknown = 20;
}
@ -122,7 +123,6 @@ message ActionStep {
oneof command {
MoveJ.Request arm_move_j = 10;
MoveL.Request arm_move_l = 11;
MoveJPose.Request arm_move_j_pose = 13;
// Apply a saved coordinate before subsequent arm steps. Uses header.device_id,
// name and expected_revision (0 = latest); coordinate payload is not accepted.
// AUBO MoveL without legacy frame overrides follows this selection until switched.

View File

@ -1,18 +1,14 @@
syntax = "proto3";
import "cmvr/api/common.proto";
import "cmvr/api/system_command.proto";
package cmvr.api;
service SystemService {
rpc ExecuteActionQueue(ActionQueueCommand.Request) returns (ActionQueueCommand.Feedback) {}
rpc GetSystemInfo(GetSystemInfoCommand.Request) returns (GetSystemInfoCommand.Feedback) {}
rpc GetSystemStatus(GetSystemStatusCommand.Request) returns (GetSystemStatusCommand.Feedback) {}
rpc UpdateParams(UpdateParamsCommand.Request) returns (UpdateParamsCommand.Feedback) {}
rpc ExecuteJsonCommand(JsonDeviceCommand.Request) returns (JsonDeviceCommand.Feedback) {}
rpc StopAll(StopAllCommand.Request) returns (StopAllCommand.Feedback) {}
rpc ExecuteActionQueue(ActionQueueCommand.Request) returns (ActionQueueCommand.Feedback) {}
}

View File

@ -11,11 +11,11 @@ message MyAgvConfig {
int32 port = 3;
}
// 仙工 Robokit 系列 AGV 后端配置(包括 SRC1100)。
// 仙工 SEER Robokit AGV 后端配置。
message SeerRobokitAgvConfig {
// 设备 id。为空时通常由外层 AGVDeviceConfig.id 补齐。
string id = 1;
// SRC1100 控制器 IP 地址。
// SEER Robokit 控制器 IP 地址。
string ip = 2;
// 是否启用该后端配置。当前设备是否创建仍以设备管理器配置为准。
bool enable = 3;
@ -49,7 +49,7 @@ message SeerRobokitAgvConfig {
int32 map_update_interval_ms = 17;
// 统一地图更新缓存条数。0 表示使用适配器默认值;缓存满后会丢弃最旧更新。
uint32 map_update_history_size = 18;
// 控制器昵称。为空时使用设备 id。
// 抢占 SEER Robokit 控制权时上报的稳定昵称。为空时适配器使用 "cmvr-es:<device-id>"。
string control_nick_name = 19;
}
@ -62,7 +62,7 @@ message AGVDeviceConfig {
oneof backend {
// 示例/测试 AGV 后端。
MyAgvConfig my_agv = 10;
// 仙工 SRC1100 AGV 后端。
// 仙工 SEER Robokit AGV 后端。
SeerRobokitAgvConfig seer_robokit_agv = 11;
}
}

View File

@ -6,7 +6,9 @@ import "cmvr/config/pinocchio_dls_ik_config.proto";
import "cmvr/config/pinocchio_qp_ik_config.proto";
import "cmvr/config/srs_ik_config.proto";
import "cmvr/config/cartesian_motion_validation_config.proto";
import "cmvr/config/joint_motion_config.proto";
// Keep legacy TOPPRA configurations readable for existing linbo_dev devices.
enum ToppraPathType {
TOPPRA_PATH_TYPE_UNKNOWN = 0;
TOPPRA_PATH_TYPE_LINEAR = 1;
@ -14,6 +16,12 @@ enum ToppraPathType {
TOPPRA_PATH_TYPE_QUINTIC = 3;
TOPPRA_PATH_TYPE_NATURAL = 4;
}
message ToppraJointMotionPlannerConfig {
ToppraPathType path_type = 1;
double sample_period_s = 2;
int32 grid_size = 3;
int32 high_grid_size = 4;
}
message MotorRobotArmBackendConfig {
string motor_system_id = 2;
@ -43,11 +51,28 @@ message VendorRobotArmBackendConfig {
string tool_frame = 8;
string username = 9;
string password = 10;
// 仅在检测到一次真实硬件急停并确认急停输入已释放后,自动上电并使能。
// 默认 false;普通启动、普通掉电和软件急停不会触发自动使能。
bool auto_enable = 11;
}
message SpeedLAdaptiveSpeedConfig {
// 主动降低 speedL 目标速度以保留限位制动余量,默认关闭。
// 仅控制正常运动的提前降速;QP 失解后的制动始终生效。
bool enable = 1;
// 可行性预测时间,单位秒;未设置/0 使用 0.15,负值或非有限值无效。
double lookahead_s = 2;
// 自动降速后的目标比例低于此值时平滑停止并报告限速错误,不是速度下限。
// 有效范围 [0, 1];未设置/0 关闭该停止阈值。
double min_speed_ratio = 3;
}
message SpeedLPlannerConfig {
// Default true: preserve acceleration through same-axis velocity reversal.
optional bool continuous_linear_reversal = 21;
// Arm-level speedL limits. Command requests may lower, but not raise them.
// Linear units: m/s, m/s^2, m/s^3. Angular units: rad/s, rad/s^2, rad/s^3.
// Unset/zero values use the planner defaults; negative/non-finite values are rejected.
double linear_velocity_max = 1;
double linear_acceleration_max = 2;
double linear_jerk_max = 3;
@ -56,12 +81,13 @@ message SpeedLPlannerConfig {
double angular_jerk_max = 6;
double linear_target_replan_threshold = 8;
double angular_target_replan_threshold = 9;
double linear_reverse_cos_threshold = 10;
double linear_reverse_switch_speed_threshold = 11;
reserved 10, 11;
reserved "linear_reverse_cos_threshold", "linear_reverse_switch_speed_threshold";
optional bool enforce_joint_acceleration_limits = 17;
CartesianLineDeviationCheckConfig line_deviation_check = 18;
JointVelocityCheckConfig joint_velocity_check = 19;
CartesianVelocityFeasibilityCheckConfig cartesian_velocity_feasibility_check = 20;
SpeedLAdaptiveSpeedConfig adaptive_speed = 22;
}
message CartesianVelocityControllerConfig {
@ -70,24 +96,25 @@ message CartesianVelocityControllerConfig {
double stop_command_velocity_norm = 3;
double stop_measured_velocity_norm = 4;
double stop_acceleration = 5;
// 等待 Cartesian 速度运动停止的最长时间,单位为秒。
optional double stop_timeout_s = 6;
}
message ToppraJointMotionPlannerConfig {
ToppraPathType path_type = 1;
double sample_period_s = 2;
int32 grid_size = 3;
int32 high_grid_size = 4;
}
message MoveJConfig {
oneof algorithm {
ToppraJointMotionPlannerConfig toppra_joint_motion_planner = 1;
}
ToppraJointMotionPlannerConfig toppra_joint_motion_planner = 1;
reserved 7;
reserved "quintic_bspline_joint_motion_planner";
// MoveJ 轨迹发送完成后,等待关节实际状态稳定的最长时间,单位为秒。
optional double settle_timeout_s = 2;
// MoveJ 完成时允许的最大关节位置误差,单位为弧度。
optional double settle_position_tolerance_rad = 3;
// MoveJ 完成时允许的最大关节速度,单位为弧度/秒。
optional double settle_velocity_tolerance_rad_s = 4;
// 位置和速度连续满足条件的采样次数。
optional int32 settle_stable_sample_count = 5;
// MoveJ 轨迹位置限位检查的数值容差,单位 rad;默认 1e-5,0 表示严格检查。
optional double joint_limit_tolerance_rad = 6;
}
message MoveLPlannerConfig {
@ -132,6 +159,8 @@ message ArmMotionConfig {
MoveJConfig move_j = 1;
MoveLConfig move_l = 2;
SpeedLConfig speed_l = 4;
JointPathConfig joint_path = 5;
JointTrajectorySmootherConfig joint_trajectory_smoother = 6;
}
message RobotArmConfig {

View File

@ -1,6 +1,8 @@
syntax = "proto3";
package cmvr.config;
// 原 ESP32 头部的舵机分组配置。
message BioHeadServoGroupConfig {
string name = 1;
int32 address = 2;
@ -11,13 +13,47 @@ message BioHeadServoGroupConfig {
repeated double max_angles = 7;
}
// USB eRPC 服务 1 的单个舵机关节配置。
// 所有位置参数的单位均为弧度 rad。
message UsbHeadJointConfig {
// 与控制板固件中的舵机 ID 对应。
string id = 1;
// 允许下发的最小位置。
double min_position_rad = 2;
// 允许下发的最大位置。
double max_position_rad = 3;
// 显式调用 home 时使用的目标位置。
double home_position_rad = 4;
}
// USB eRPC 服务 1 的设备配置。
message UsbHeadErpcConfig {
// 应答超时,单位 ms。
// 后续驱动中:0 表示使用默认 2000 ms,最大允许 30000 ms。
uint32 response_timeout_ms = 1;
// 该设备允许控制的关节及其标定参数。
repeated UsbHeadJointConfig joints = 2;
}
// 头部设备配置。
message BioHeadRobotConfig {
string id = 1;
string serial_port = 2;
int32 baud_rate = 3;
// 原 ESP32 后端使用的配置,保留原字段编号。
repeated BioHeadServoGroupConfig servo_groups = 4;
// 配置此字段时,选择新增的 USB eRPC 后端。
// 未配置时,继续使用原 ESP32 后端。
UsbHeadErpcConfig usb_erpc = 5;
}
// 配置文件的根结构。
message BioHeadRobotRootConfig {
BioHeadRobotConfig bio_head = 1;
}

View File

@ -116,26 +116,6 @@ 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;
@ -146,8 +126,6 @@ message CameraDeviceConfig {
MechMindCameraConfig mechmind = 12;
MujocoCameraConfig mujoco = 13;
HikvisionCameraConfig hikvision = 14;
MvsCameraConfig mvs = 15;
AutoCameraConfig auto_camera = 16;
}
}

View File

@ -0,0 +1,40 @@
syntax = "proto3";
package cmvr.config;
message CollisionPairConfig {
string first = 1;
string second = 2;
}
message CollisionCheckerConfig {
reserved 3;
string urdf_path = 1;
repeated CollisionPairConfig ignored_pairs = 2;
}
message DistanceSamplingConfig {
double max_geometry_displacement_m = 1;
double max_check_period_s = 2;
}
message CollisionSafetyConfig {
double warning_distance_m = 1;
double stop_distance_m = 2;
}
message ProtectiveRecoveryConfig {
double clear_distance_m = 1;
double stable_period_s = 2;
double max_joint_velocity_rad_s = 3;
double max_joint_acceleration_rad_s2 = 4;
double history_duration_s = 5;
double max_distance_regression_m = 6;
}
message SelfCollisionMonitorConfig {
CollisionCheckerConfig checker = 10;
DistanceSamplingConfig sampling = 11;
CollisionSafetyConfig safety = 12;
ProtectiveRecoveryConfig recovery = 13;
}

View File

@ -21,8 +21,10 @@ message DeviceConfigEntry {
DEVICE_TYPE_AGV = 17;
DEVICE_TYPE_MUJOCO_WORLD = 18;
DEVICE_TYPE_MUJOCO_VIEWER = 19;
DEVICE_TYPE_TOUCH = 20;
}
// For DEVICE_TYPE_MOTOR_SYSTEM, this is the motor_group id selected from config_file.
string id = 1;
DeviceType type = 2;
string config_file = 3;
@ -30,11 +32,12 @@ message DeviceConfigEntry {
}
message DeviceManagerConfig {
reserved 20;
string name = 1;
string version = 2;
string description = 3;
repeated DeviceConfigEntry devices = 4;
reserved 20;
}
message DeviceManagerRootConfig {
DeviceManagerConfig device_manager = 1;

View File

@ -10,13 +10,13 @@ message RH56DFTPDexHandConfig{
int32 poll_interval_ms = 5;
}
enum PX6AXGen3PollingReadMode {
PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_AND_RESULTANT_FORCE = 0;
PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_FORCE = 1;
PX_6AX_GEN3_POLLING_READ_MODE_RESULTANT_FORCE = 2;
enum LegacyPX6AXGen3PollingReadMode {
LEGACY_PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_AND_RESULTANT_FORCE = 0;
LEGACY_PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_FORCE = 1;
LEGACY_PX_6AX_GEN3_POLLING_READ_MODE_RESULTANT_FORCE = 2;
}
message PX6AXGen3{
message LegacyPX6AXGen3{
reserved 10;
string id = 1;
@ -35,7 +35,9 @@ message PX6AXGen3{
string tactile_finger = 15;
string tactile_region = 16;
string sensor_name = 17;
PX6AXGen3PollingReadMode polling_read_mode = 18;
LegacyPX6AXGen3PollingReadMode polling_read_mode = 18;
// Maximum age since the sample's request was sent. 0 uses 50 ms.
// Independent of response_timeout_ms: stale cached data must fail promptly.
int32 max_sample_age_ms = 19;
}
@ -53,12 +55,16 @@ message OYMotionAP001Config {
message DexHandDeviceConfig {
string id = 1;
// Human-readable hardware model. This is metadata only and must not drive
// device behavior.
string model = 2;
// Whether this device provides real tactile sensor feedback. Motor-current
// estimates do not count as tactile feedback.
optional bool has_tactile_feedback = 3;
oneof backend {
RH56DFTPDexHandConfig rh56dftp = 10;
PX6AXGen3 px_6ax_gen3 = 11;
LegacyPX6AXGen3 px_6ax_gen3 = 11;
ZeroSimTouchDexHand zero_sim_touch = 12;
// Shared OYMotion backend for AP001, LiteS001 and compatible hands.
OYMotionAP001Config oymotion_ap001 = 13;

View File

@ -6,12 +6,6 @@ message GRPCServerConfig {
string port = 2;
bool enable_reflection = 3;
string id = 4;
// Bounds the continuity-oriented media queue before the gRPC stream skips
// ahead and waits for a new key frame. Zero uses the service default.
uint32 camera_stream_max_pending_frames = 5;
// Frames older than this monotonic age are not sent. Zero uses the service
// default so configurations written before these fields remain low-latency.
uint32 camera_stream_max_frame_age_ms = 6;
}
message GRPCServerRootConfig {
GRPCServerConfig grpc_server = 1;

View File

@ -33,7 +33,6 @@ message JointLimitAvoidanceConfig {
double gain = 2;
double margin_ratio = 3;
double max_push = 4;
double weight = 5;
}
message JointLimitPolicyConfig {

View File

@ -0,0 +1,41 @@
syntax = "proto3";
package cmvr.config;
import "cmvr/config/collision_config.proto";
message RrtConnectConfig {
// Omitted fields use planner defaults. Explicit values must be finite and positive.
optional double timeout_s = 1; // Default: 1.0 s.
optional double range_rad = 2; // Default: 0.2, Euclidean joint-space distance.
optional double collision_check_step_rad = 3; // Default: 0.02 rad per joint.
}
message QuinticBSplineConfig {
// Reference control-point spacing in Euclidean joint space; default 0.05 rad.
// Must be finite and positive. Actual control points are not equally spaced.
optional double control_point_spacing_rad = 1;
}
message JointTrajectorySmootherConfig {
// Sampling period in seconds; default 0.001, must be finite and positive.
optional double sample_period_s = 1;
oneof algorithm {
QuinticBSplineConfig quintic_bspline = 2;
}
}
enum JointPathAlgorithm {
JOINT_PATH_ALGORITHM_UNKNOWN = 0;
RRT_CONNECT = 1;
}
message JointPathConfig {
reserved 5, 6;
reserved "quintic_bspline";
JointPathAlgorithm algorithm = 2;
RrtConnectConfig rrt_connect = 1;
// Required by MotorRobotArm::moveP; each arm owns its checker.
CollisionCheckerConfig collision_checker = 3;
optional double minimum_distance_m = 4; // Default: 0.01 m.
}

View File

@ -12,6 +12,21 @@ message MotorConfigItem {
double limit_qdd = 6;
double encoder_counts_per_rev = 7;
double gear_ratio = 8;
LingkongMotorConfig lingkong = 9;
}
// Vendor CAN protocol, not CiA301 CANopen. Zero conversion values mean unknown.
message LingkongMotorConfig {
// MG: 66/4096 A/LSB; MF: 33/4096 A/LSB. Do not use for MS power data.
double current_amp_per_lsb = 1;
// Required to convert current to the common API's per-mille rated torque.
double rated_torque_current_a = 2;
// B1 indices 12/14: the supplied protocol manual does not define their units.
// Populate only after confirming the drive firmware's parameter units.
double acceleration_deg_s2_per_lsb = 3;
double speed_limit_deg_s_per_lsb = 4;
uint32 response_timeout_ms = 5;
double reached_position_tolerance_rad = 6;
}
message MotorList {
@ -81,6 +96,8 @@ enum MotorVendor {
MOTOR_VENDOR_TI5 = 1;
MOTOR_VENDOR_MUJOCO = 2;
MOTOR_VENDOR_EYOU = 3;
MOTOR_VENDOR_TCHL = 4;
MOTOR_VENDOR_LINGKONG = 5;
}
enum MotorProtocol {
@ -88,6 +105,8 @@ enum MotorProtocol {
MOTOR_PROTOCOL_CANOPEN = 1;
MOTOR_PROTOCOL_ETHERCAT_CIA402 = 2;
MOTOR_PROTOCOL_MUJOCO = 3;
MOTOR_PROTOCOL_LINGKONG_CAN = 4;
MOTOR_PROTOCOL_LINGKONG_CAN_V2_38 = 5;
}
message MotorGroupConfig {

View File

@ -36,16 +36,34 @@ message QuicEdgeTrackConfig {
// Zero uses QuicEdgeConfig.maximum_frame_bytes.
uint32 max_frame_bytes = 5;
// Protocol-neutral MediaSourceHub track ID. When empty, the service derives
// Protocol-neutral MediaSourceManager track ID. When empty, the service derives
// the default ID from source_kind and device_id (for example
// "right_hand_cam/video/color"). The Hub's descriptor is the authority for
// codec metadata and descriptor generation.
string source_track_id = 6;
}
message QuicEdgePlatformConfig {
// Stable operator-facing identifier used in logs and task status. It must be
// unique within the task and differ from QuicEdgeConfig.id when the
// backward-compatible primary endpoint is also configured.
string id = 1;
string server_host = 2;
uint32 server_port = 3;
QuicEdgeTlsConfig tls = 4;
// False keeps registration, heartbeat, IP and device-state reporting while
// preventing accidental duplication of configured media tracks.
bool enable_media = 5;
}
message QuicEdgeConfig {
string id = 1;
reserved 2;
// Backward-compatible primary platform endpoint. When configured, it runs
// alongside every endpoint in platforms. New configurations may leave these
// fields empty and declare every destination in platforms instead.
string server_host = 3;
uint32 server_port = 4;
string alpn = 5;
@ -87,6 +105,10 @@ message QuicEdgeConfig {
// Immutable robot product identity, for example:
// CN-CMVR-MBLRV1-CHAGAN-20260731-001.
string robot_id = 22;
// Every platform owns an independent QUIC connection, registration,
// heartbeat/ACK sequence and reconnect loop.
repeated QuicEdgePlatformConfig platforms = 23;
}
message QuicEdgeRootConfig {

View File

@ -2,32 +2,20 @@ syntax = "proto3";
package cmvr.config;
message CollisionPairConfig {
string first = 1;
string second = 2;
}
import "cmvr/config/collision_config.proto";
message SelfCollisionCheckerConfig {
string urdf_path = 1;
repeated CollisionPairConfig ignored_pairs = 2;
}
message DistanceSamplingConfig {
double max_geometry_displacement_m = 1;
double max_check_period_s = 2;
}
message CollisionSafetyConfig {
double warning_distance_m = 1;
double stop_distance_m = 2;
}
message SelfCollisionTaskConfig {
string id = 1;
string arm_id = 2;
SelfCollisionCheckerConfig checker = 10;
CollisionCheckerConfig checker = 10;
DistanceSamplingConfig sampling = 11;
CollisionSafetyConfig safety = 12;
ProtectiveRecoveryConfig recovery = 13;
}
message SelfCollisionTaskRootConfig {

View File

@ -8,6 +8,8 @@ message TaskConfigEntry {
TASK_TYPE_GRPC_SERVER = 3;
TASK_TYPE_SELF_COLLISION = 4;
TASK_TYPE_QUIC_EDGE = 5;
reserved 2;
reserved "TASK_TYPE_ARM_CONTROL";
}
enum TaskRunMode {

View File

@ -0,0 +1,63 @@
syntax = "proto3";
package cmvr.config;
enum PX6AXGen3PollingReadMode {
PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_AND_RESULTANT_FORCE = 0;
PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_FORCE = 1;
PX_6AX_GEN3_POLLING_READ_MODE_RESULTANT_FORCE = 2;
}
message PX6AXGen3{
reserved 10, 15, 16;
reserved "tactile_finger", "tactile_region";
string id = 1;
string serial_port = 2;
string sensor_model = 3;
int32 module_id = 4;
int32 baud_rate = 5;
int32 distributed_length = 6;
int32 resultant_length = 7;
int32 poll_interval_ms = 8;
bool auto_calibrate = 9;
int32 response_timeout_ms = 11;
int32 tactile_rows = 12;
int32 tactile_cols = 13;
int32 response_header_bytes = 14;
string sensor_name = 17;
PX6AXGen3PollingReadMode polling_read_mode = 18;
// Maximum age since the sample's request was sent. 0 uses 50 ms.
// Independent of response_timeout_ms: stale cached data must fail promptly.
int32 max_sample_age_ms = 19;
}
message ZeroSimTouch {
string id = 1;
}
message PX6AXGenXCan {
string id = 1;
int32 channel_id = 2;
// Unset uses the default standard CAN force frame ID, 0x600.
optional uint32 force_can_id = 3;
// Maximum age of the latest received sample. 0 uses 300 ms.
int32 max_sample_age_ms = 4;
}
message TouchDeviceConfig {
string id = 1;
oneof backend {
PX6AXGen3 px_6ax_gen3 = 10;
ZeroSimTouch zero_sim = 11;
PX6AXGenXCan px_6ax_genx_can = 12;
}
}
message TouchConfig {
repeated TouchDeviceConfig touches = 1;
}
message TouchRootConfig {
TouchConfig touch = 1;
}

View File

@ -11,17 +11,10 @@ message TouchScreenApriltagConfig {
optional TouchScreenTargetPointMethod target_point_method = 3;
}
message TouchScreenIbvsConfig {
optional string camera_link = 1;
optional double lambda = 2;
optional double mu = 3;
optional double qdot_max = 4;
.cmvr.common.Vec6 vmax6 = 5;
.cmvr.common.Vec6 amax6 = 6;
optional double twist_filter_alpha = 7;
.cmvr.common.Mat3 r_camera_to_visp = 12;
.cmvr.common.Mat3 r_camera_to_urdf = 13;
repeated string control_joint_names = 14;
message TouchScreenTaskPbvsConfig {
.cmvr.common.Vec3 position_gain = 1;
.cmvr.common.Vec3 rotation_gain = 2;
.cmvr.common.Vec6 vmax6 = 3;
.cmvr.common.Vec6 amax6 = 4;
optional double twist_filter_alpha = 5;
}

View File

@ -12,47 +12,131 @@ message TouchScreenInitJointPoint {
}
message TouchScreenTaskDevicesConfig {
reserved 1;
reserved "robot_id";
reserved 1, 2;
reserved "robot_id", "dexhand_id";
optional string arm_id = 4;
optional string dexhand_id = 2;
optional string camera_id = 3;
optional string arm_id = 4;
optional string external_camera_id = 5;
optional string touch_id = 6;
// Joint-controlled head/neck, exposed through the RobotArm interface.
optional string head_id = 7;
}
message TouchScreenTaskHeadInitializationConfig {
// Move the head once during task init(), before the task becomes ready.
// Unset/false preserves startup behavior for configurations without a head.
optional bool enable = 1;
repeated TouchScreenInitJointPoint joint_positions = 2;
optional double velocity = 3; // rad/s
optional double acceleration = 4; // rad/s^2
}
message TouchScreenTaskInitializationConfig {
enum MotionMethod {
USE_MOVEJ = 0;
USE_MOVEP = 1;
}
// 开始触控前回到配置的初始关节位置。
optional bool before_start = 1;
// 正常完成后回到配置的初始关节位置。
optional bool after_finish = 2;
repeated TouchScreenInitJointPoint joint_positions = 3;
optional double velocity = 4;
optional double acceleration = 5;
// 当前关节位置误差小于该值时可跳过初始位置回位,单位为弧度。
optional double skip_position_tolerance_rad = 6;
// 当前关节速度小于该值时才允许跳过初始位置回位,单位为弧度/秒。
optional double skip_velocity_tolerance_rad_s = 7;
// 失败后停止当前运动,再尝试回初始位置;未配置时关闭。
// 不解除急停/保护停止,回位结果不覆盖任务的原始失败原因。
optional bool after_failure = 8;
// 三个开关启用的回位动作统一使用此方式。省略时沿用旧配置行为:
// 开始前使用 MoveJ,正常完成和失败后使用 MoveP。
optional MotionMethod motion_method = 9;
// MoveJ 和 MoveP 回初始位时共用的关节加加速度上限(rad/s^3)。省略时使用 MotionOptions 默认值。
optional double jerk = 10;
}
message TouchScreenTaskTagConfig {
optional int32 id = 1;
optional double size_m = 2;
}
message TouchScreenTaskTagsConfig {
TouchScreenTaskTagConfig screen = 1;
TouchScreenTaskTagConfig hand = 2;
}
message TouchScreenTaskHandCameraConfig {
reserved 1;
reserved "camera_id";
optional TouchScreenDepthPolicy depth_policy = 2;
optional TouchScreenTargetPointMethod target_point_method = 3;
}
message TouchScreenTaskPerceptionConfig {
TouchScreenApriltagConfig apriltag = 1;
reserved 1, 2, 6;
reserved "apriltag", "external_apriltag", "external_camera";
TouchScreenTaskTagsConfig tags = 4;
TouchScreenTaskHandCameraConfig hand_camera = 5;
}
message TouchScreenAlignmentTargetConfig {
.cmvr.common.Vec3 position_in_camera = 1;
.cmvr.common.Vec3 rotation_vector = 2;
reserved 2;
reserved "rotation_vector";
// Target orientation of Hand Tag H relative to Screen Tag G.
// rx, ry and rz are fixed-axis (extrinsic) rotations about G.X, G.Y and G.Z,
// applied in that order, in radians.
.cmvr.common.Euler hand_orientation_G = 6;
optional TouchScreenAlignMode mode = 3;
.cmvr.common.Vec3 position_offset_G = 4;
.cmvr.common.Vec3 rotation_offset_G = 5;
}
message TouchScreenTaskAlignmentCalibrationConfig {
.cmvr.common.Mat4 hand_tag_to_tcp = 1;
reserved 2;
reserved "external_camera_to_base";
}
message TouchScreenTaskAlignmentConfig {
reserved 1;
reserved "kinematics";
TouchScreenIbvsConfig ibvs = 2;
TouchScreenAlignmentTargetConfig target = 3;
.cmvr.common.Vec6 error_threshold = 4;
optional int32 stable_frames = 5;
// Separate time limit for alignment and, when enabled, the pause after reaching.
// The pause timer starts on entering ALIGN_REACHED. Either timeout fails the
// task and attempts to return to initialization when after_failure is enabled.
optional double timeout_s = 6;
// Pause after alignment instead of starting touch, until timeout_s expires.
optional bool pause_when_reached = 7;
TouchScreenTaskPbvsConfig pbvs = 8;
TouchScreenTaskAlignmentCalibrationConfig calibration = 9;
}
message TouchScreenTaskApproachConfig {
// MoveP to alignment.target before PBVS; position_offset_G is in Screen G.
optional bool enable = 1;
optional double velocity = 2; // Joint velocity, rad/s.
optional double acceleration = 3; // Joint acceleration, rad/s^2.
optional double jerk = 4; // Joint jerk, rad/s^3.
optional double timeout_s = 5;
// Signed outward clearance from the screen plane, meters; TCP only, not the arm.
optional double minimum_clearance_m = 6;
}
message TouchScreenTouchSpeedLConfig {
.cmvr.common.Vec6 twist_tool = 1;
optional double acceleration = 2;
optional double max_distance_m = 3;
// Requested linear jerk during approach, m/s^3, capped by the arm's
// linear_jerk_max. Unset uses that arm limit.
optional double linear_jerk = 4;
}
message TouchScreenTouchMoveLConfig {
@ -65,9 +149,11 @@ message TouchScreenTouchMoveLConfig {
}
message TouchScreenTactileTriggerConfig {
optional TouchScreenFingerType finger = 1;
optional TouchScreenTactileRegion region = 2;
reserved 1, 2;
reserved "finger", "region";
optional TouchScreenTactileCriterion criterion = 3;
// Threshold in newtons (N), applied to the selected sensor's force criterion.
// Equality also triggers contact.
optional double force_threshold = 4;
}
@ -83,8 +169,15 @@ message TouchScreenTaskTouchConfig {
message TouchScreenTaskRetractConfig {
.cmvr.common.Vec6 twist_tool = 1;
// Requested acceleration, capped by the arm's speedL acceleration limits.
optional double acceleration = 2;
optional double duration_s = 3;
reserved 3;
reserved "duration_s";
// Signed displacement along the retract direction before stopping, in meters.
optional double distance_m = 4;
// Requested linear jerk for braking and reversal, m/s^3, capped by the arm's
// linear_jerk_max. Unset uses that arm limit.
optional double linear_jerk = 5;
}
message TouchScreenTaskConfig {
@ -95,6 +188,12 @@ message TouchScreenTaskConfig {
TouchScreenTaskTouchConfig touch = 5;
TouchScreenTaskRetractConfig retract = 6;
optional string id = 7;
// 是否在外部相机编码后的 gRPC 视频流中绘制坐标系,仅影响显示帧;未配置时默认开启。
optional bool debug_draw_coordinate_frames = 8;
// G/H 坐标轴长度,单位为米。
optional double debug_coordinate_axis_length_m = 9;
TouchScreenTaskApproachConfig approach = 10;
TouchScreenTaskHeadInitializationConfig head_initialization = 11;
}
message TouchScreenTaskRootConfig {

View File

@ -63,6 +63,7 @@ enum DeviceKind {
DEVICE_KIND_MOTOR_SYSTEM = 11;
DEVICE_KIND_ROBOT = 12;
DEVICE_KIND_SPEAKER = 13;
DEVICE_KIND_TOUCH = 14;
}
// DeviceManager's view of a configured entry. REGISTERED means that the
@ -197,7 +198,7 @@ message MediaTrackDescriptor {
string codec = 4;
uint64 codec_generation = 5;
// The exact MediaSourceHub track and the 32-bit token repeated in every
// The exact MediaSourceManager track and the 32-bit token repeated in every
// DATAGRAM header. The full generation remains on the reliable stream.
string source_track_id = 6;
uint32 codec_generation_token = 7;

View File

@ -0,0 +1,125 @@
syntax = "proto3";
package rbk.protocol;
// 仙工 SEER Robokit 3D 地图文件 0.3dsmap 的最小解析结构。
// 这里只保留转换统一地图所需字段,未声明字段由 protobuf 作为未知字段跳过。
// 地图坐标系下的三维位置,单位:米。
message Message_MapPos {
// X 坐标,单位:米。
double x = 1;
// Y 坐标,单位:米。
double y = 2;
// Z 坐标,单位:米。
double z = 3;
}
// 仙工地图头信息。
message Message_MapHeader {
// 地图类型,例如 2D-Map 或 3D-Map。
string map_type = 1;
// 地图名称,通常对应地图文件名。
string map_name = 2;
// 地图最小边界点,单位:米。
Message_MapPos min_pos = 3;
// 地图最大边界点,单位:米。
Message_MapPos max_pos = 4;
// 地图分辨率,单位:米。
double resolution = 5;
// 地图格式版本号。
string version = 8;
}
// 三维浮点向量。
message Vec3f {
// X 分量。
float x = 1;
// Y 分量。
float y = 2;
// Z 分量。
float z = 3;
}
// 三维整数向量。
message Vec3i {
// X 分量。
int32 x = 1;
// Y 分量。
int32 y = 2;
// Z 分量。
int32 z = 3;
}
// 仙工 3D 特征地图参数。
message FeatureMapParams {
// 激光测距标准差,单位:米。
float ranging_sigma = 1;
// 激光测角标准差,单位:度。
float angle_sigma = 2;
// 最大体素边长,单位:米。
float max_voxel_size = 3;
// 八叉树最大层数。
uint32 max_layer = 4;
// 平面协方差停止更新的点数阈值。
uint32 cov_fixed_pts_num = 5;
// 平面停止更新的点数阈值。
uint32 plane_fixed_pts_num = 6;
// 有效平面协方差最小特征值阈值。
float plane_min_eigen_value = 7;
// 每层评估平面所需的最少点数。
repeated int32 each_layer_least_pts_num = 8;
}
// 仙工 3D 平面特征。
message FeatureMapPlane {
// 平面中心点,单位:米。
Vec3f center = 1;
// 平面法向量。
Vec3f normal = 2;
// 平面方程 Ax + By + Cz + D = 0 中的 D。
float d = 3;
// 平面特征近似半径,单位:米。
float radius = 4;
// 平面协方差矩阵,按 6x6 展平。
repeated float plane_cov = 5;
}
// 仙工特征地图中的八叉树节点。
message OctoTree {
// 对应的平面 ID。
uint32 plane_id = 1;
// 子节点序列,-1 表示当前层无其他子节点。
repeated int32 child_id_list = 2;
}
// 同一外层体素位置下的八叉树节点集合。
message OctoTrees {
// 八叉树节点列表。
repeated OctoTree octo_tree = 1;
}
// 仙工 3D 特征地图。
message FeatureMap3D {
// 特征地图参数。
FeatureMapParams params = 1;
// 平面特征列表。
repeated FeatureMapPlane planes = 2;
// 每个外层体素对应的八叉树节点集合。
repeated OctoTrees octo_trees = 3;
// 最外层八叉树体素坐标。
repeated Vec3i voxel_locs = 4;
}
// 0.3dsmap 顶层消息。
message Message_Map3D {
// 地图目录或地图包内部目录名。
string map_directory = 1;
// 地图头信息。
Message_MapHeader header = 2;
// 普通 3D 点云点。
repeated Message_MapPos normal_pos3d_list = 3;
// 3D 特征地图。
FeatureMap3D feature_map_3d = 4;
}

View File

@ -60,10 +60,10 @@ ActionQueueTestWidget::ActionQueueTestWidget(RobotClient* client,QWidget* parent
grid->addWidget(new QLabel(QStringLiteral("速度"),group),4,0);grid->addWidget(m_speed,4,1);
grid->addWidget(new QLabel(QStringLiteral("加速度"),group),4,2);grid->addWidget(m_accel,4,3);
grid->addWidget(new QLabel(QStringLiteral("队列总超时"),group),4,4);grid->addWidget(m_deadline,4,5);
m_motion=new QComboBox(group);m_motion->addItem(QStringLiteral("MoveL · 直线运动"));m_motion->addItem(QStringLiteral("MoveJ · 末端位姿关节运动"));
m_motion=new QComboBox(group);m_motion->addItem(QStringLiteral("MoveL · 直线运动"));
grid->addWidget(new QLabel(QStringLiteral("运动方式"),group),5,0);grid->addWidget(m_motion,5,1,1,5);
layout->addWidget(group);
auto* tip=new QLabel(QStringLiteral("目标是所选坐标系下的完整绝对 TCP 位姿。队列先应用坐标系,再执行所选运动。MoveJ 经服务端 SDK 逆解,路径不保证直线;其速度/加速度是关节参数。"),this);
auto* tip=new QLabel(QStringLiteral("目标是所选坐标系下的完整绝对 TCP 位姿。队列先应用坐标系,再执行所选运动。当前服务端支持 MoveL 直线运动。"),this);
tip->setWordWrap(true);layout->addWidget(tip);
auto* buttons=new QHBoxLayout;
m_execute=new QPushButton(QStringLiteral("执行两步动作队列"),this);m_execute->setObjectName("primaryButton");
@ -136,7 +136,7 @@ void ActionQueueTestWidget::preview(){
const QJsonObject apply{{"header",header},{"name",m_coordinate->currentData().toString()},{"expected_revision",profile.value("revision").toVariant().toString()}};
QJsonObject move{{"header",header},{"target",target},{"options",QJsonObject{{"velocity",m_speed->value()},{"acceleration",m_accel->value()}}}};
if(m_jointMode){move.insert("user_coordinate_name",m_coordinate->currentData().toString());move.insert("user_coordinate_revision",profile.value("revision").toVariant().toString());}
const QJsonObject request{{"steps",QJsonArray{QJsonObject{{"arm_apply_user_coordinate",apply}},QJsonObject{{m_jointMode?"arm_move_j_pose":"arm_move_l",move}}}},{"total_timeout_ms",m_deadline->value()*1000}};
const QJsonObject request{{"steps",QJsonArray{QJsonObject{{"arm_apply_user_coordinate",apply}},QJsonObject{{"arm_move_l",move}}}},{"total_timeout_ms",m_deadline->value()*1000}};
m_request->setPlainText(QString::fromUtf8(QJsonDocument(request).toJson(QJsonDocument::Indented)));
}
void ActionQueueTestWidget::query(const QString& operation){
@ -157,8 +157,7 @@ void ActionQueueTestWidget::execute(){
// The exact transmitted headers are included in the visible request for diagnosis.
const auto now=QDateTime::currentMSecsSinceEpoch();
for(auto& step:*request.mutable_steps()){
auto* h=step.has_arm_move_l()?step.mutable_arm_move_l()->mutable_header():step.has_arm_move_j_pose()?step.mutable_arm_move_j_pose()->mutable_header():step.mutable_arm_apply_user_coordinate()->mutable_header();
h->set_command_id(QUuid::createUuid().toString(QUuid::WithoutBraces).toStdString());
auto* h=step.has_arm_move_l()?step.mutable_arm_move_l()->mutable_header():step.mutable_arm_apply_user_coordinate()->mutable_header();
h->mutable_timestamp()->set_seconds(now/1000);h->mutable_timestamp()->set_nanos((now%1000)*1000000);
}
m_request->setPlainText(json(request));m_response->clear();m_busy=true;

View File

@ -45,8 +45,9 @@ ApplicationSettings::ApplicationSettings(const QString &path)
const QJsonObject window = m_document.value("window").toObject();
m_options.rememberWindow = window.value("rememberGeometry").toBool(true);
m_options.startMaximized = window.value("startMaximized").toBool(true);
const int page = window.value("startupPage").toInt(0);
m_options.startupPage = (page == 0 || page == 1 || page == 2 || page == 11 || page == 16)
const int storedPage = window.value("startupPage").toInt(0);
const int page = storedPage == 16 ? 15 : storedPage;
m_options.startupPage = (page == 0 || page == 1 || page == 2 || page == 15)
? page : 0;
const QJsonObject log = m_document.value("log").toObject();
m_options.logMaximumLines = qBound(500, log.value("maximumLines").toInt(3000), 20000);
@ -180,10 +181,9 @@ void showApplicationSettings(QWidget *parent, const std::function<void()> &appli
auto *remember = new QCheckBox(QStringLiteral("记住窗口大小和位置"), &dialog);
auto *page = new QComboBox(&dialog);
page->addItem(QStringLiteral("系统概览"), 0);
page->addItem(QStringLiteral("设备管理"), 11);
page->addItem(QStringLiteral("机械臂"), 1);
page->addItem(QStringLiteral("相机"), 2);
page->addItem(QStringLiteral("任务编排"), 16);
page->addItem(QStringLiteral("任务编排"), 15);
startup->addRow(QStringLiteral("启动页面"), page);
startup->addRow(QStringLiteral("窗口"), maximized);
startup->addRow(QString(), remember);

View File

@ -189,11 +189,10 @@ void fillHeader(cmvr::api::CommandHeader_Request *header, const QString &deviceI
int timeoutMs)
{
header->set_device_id(deviceId.toStdString());
header->set_command_id(QUuid::createUuid().toString(QUuid::WithoutBraces).toStdString());
const qint64 milliseconds = QDateTime::currentMSecsSinceEpoch();
header->mutable_timestamp()->set_seconds(milliseconds / 1000);
header->mutable_timestamp()->set_nanos(static_cast<int>((milliseconds % 1000) * 1000000));
header->set_valid_for_ms(static_cast<unsigned>(timeoutMs));
Q_UNUSED(timeoutMs);
}
QVariantMap headerMap(const cmvr::api::CommandHeader_Feedback &header)
@ -204,13 +203,7 @@ QVariantMap headerMap(const cmvr::api::CommandHeader_Feedback &header)
{QStringLiteral("errorMessage"), QString::fromStdString(header.error_message())},
{QStringLiteral("timestamp"), QDateTime::fromMSecsSinceEpoch(
header.timestamp().seconds() * 1000 + header.timestamp().nanos() / 1000000,
Qt::UTC).toString(Qt::ISODateWithMs)},
{QStringLiteral("reasonCode"), QString::fromStdString(cmvr::api::CommandReasonCode_Name(header.reason_code()))},
{QStringLiteral("commandId"), QString::fromStdString(header.command_id())},
{QStringLiteral("serviceInstanceId"), QString::fromStdString(header.service_instance_id())},
{QStringLiteral("safetyEpoch"), QString::number(header.safety_epoch())},
{QStringLiteral("deviceGeneration"), QString::number(header.device_generation())},
{QStringLiteral("executionState"), QString::fromStdString(cmvr::api::CommandExecutionState_Name(header.execution_state()))}};
Qt::UTC).toString(Qt::ISODateWithMs)}};
}
QVariantMap feedbackMap(const cmvr::api::HeadJointCommand_Feedback &feedback)

View File

@ -391,7 +391,7 @@ void BioHeadWidget::setAvailableDevices(const QVariantList &devices)
for (const QVariant &value : devices) {
const QVariantMap device = value.toMap();
const QString id = device.value(QStringLiteral("deviceId")).toString();
if (device.value(QStringLiteral("type"), -1).toInt() == 8 && !id.isEmpty() && !ids.contains(id)) ids.append(id);
if (device.value(QStringLiteral("type"), -1).toInt() == 9 && !id.isEmpty() && !ids.contains(id)) ids.append(id);
}
QStringList existing;
for (int i = 0; i < m_device->count(); ++i) existing.append(m_device->itemData(i).toString());

File diff suppressed because it is too large Load Diff

View File

@ -1,163 +0,0 @@
#pragma once
#include <QVariantList>
#include <QVariantMap>
#include <QWidget>
#include <QHash>
#include <QStringList>
#include <memory>
namespace google {
namespace protobuf {
class DynamicMessageFactory;
class Message;
}
}
class QLabel;
class QGridLayout;
class QLineEdit;
class QListWidget;
class QListWidgetItem;
class QPlainTextEdit;
class QPushButton;
class QSpinBox;
class QTabWidget;
class QTableWidget;
class QTimer;
class QTreeWidget;
class QTreeWidgetItem;
class RobotClient;
class ConfigEditorWidget : public QWidget
{
Q_OBJECT
public:
explicit ConfigEditorWidget(RobotClient *client, QWidget *parent = nullptr);
~ConfigEditorWidget() override;
signals:
void deviceNavigationRequested(int deviceType, const QString &deviceId);
private slots:
void toggleConnection();
void refreshFiles();
void selectFile(QListWidgetItem *current, QListWidgetItem *previous);
void reloadCurrentFile();
void validateCurrentFile();
void saveCurrentFile();
void handleConnectionChanged(bool connected, const QString &detail);
void handleFilesReceived(const QString &configRoot, const QVariantList &files,
bool success, const QString &detail);
void handleFileReceived(const QString &relativePath, const QString &content,
const QString &revision, const QString &messageType,
bool success, const QString &detail);
void handleValidationFinished(const QString &relativePath, bool success,
const QString &detail);
void handleSaveFinished(const QString &relativePath, const QString &revision,
bool success, const QString &detail);
void handleEditorChanged();
void handleFieldItemChanged(QTreeWidgetItem *item, int column);
void rebuildEnableTable();
void handleEdgeConnectionChanged(bool connected, int latencyMs, const QString &detail);
void handleSystemStatus(double cpu, double memory, double disk,
const QVariantList &devices);
void handleSystemInfo(const QVariantMap &info);
void rebuildDeviceCards();
void toggleDeviceEditing();
private:
enum class ManagerKind { None, Device, Task };
bool confirmDiscardChanges();
void setBusy(bool busy);
void setStatus(const QString &text, bool error = false);
void clearCurrentFile();
void updateActions();
void rebuildFieldTree();
void appendMessageFields(QTreeWidgetItem *parent, google::protobuf::Message *message);
bool applyFieldValue(QTreeWidgetItem *item, const QString &text);
bool parseFieldDocument();
bool syncFieldTreeToText();
bool replaceEnableValue(int index, bool enabled);
ManagerKind managerKindForPath(const QString &path) const;
void beginDeviceConfigurationLoad();
void readNextOverviewConfiguration();
void buildEditableDevices();
void finishDeviceEditing();
void saveNextOverviewConfiguration();
void cancelDeviceEditing();
void addEditableDevice();
int editableDeviceIndex(const QString &uid) const;
void updateEditableDevice(const QString &uid, const QString &key,
const QVariant &value, bool rebuild = false);
void refreshEditableDeviceSchema(int index);
QVariantList brandOptionsForType(int managerType) const;
QVariantList parameterRowsForDevice(const QVariantMap &device) const;
bool prepareOverviewSave(QString *error);
RobotClient *m_client = nullptr;
QLineEdit *m_deviceSearchEdit = nullptr;
QPushButton *m_deviceRefreshButton = nullptr;
QPushButton *m_deviceEditButton = nullptr;
QLabel *m_deviceSectionHint = nullptr;
QLabel *m_edgeConnectionChip = nullptr;
QLabel *m_edgeSystemLabel = nullptr;
QLabel *m_onlineDeviceValue = nullptr;
QLabel *m_deviceTypeValue = nullptr;
QLabel *m_lastSyncValue = nullptr;
QLabel *m_deviceSectionTitle = nullptr;
QWidget *m_deviceGridHost = nullptr;
QGridLayout *m_deviceGrid = nullptr;
QVariantList m_devices;
QVariantList m_editDevices;
bool m_edgeConnected = false;
bool m_demoMode = false;
bool m_deviceEditMode = false;
bool m_deviceEditRequested = false;
bool m_overviewLoading = false;
bool m_overviewSaving = false;
QString m_edgeHost;
QString m_managerPath = QStringLiteral("manager/device_manager.pb.txt");
QString m_managerContent;
QString m_managerRevision;
QString m_managerMessageType;
QVariantList m_configurationFiles;
QHash<QString, QString> m_overviewContents;
QHash<QString, QString> m_overviewRevisions;
QHash<QString, QString> m_overviewMessageTypes;
QStringList m_overviewReadQueue;
QString m_overviewCurrentRead;
QStringList m_overviewSaveQueue;
QString m_overviewCurrentSave;
QHash<QString, QString> m_overviewSaveContents;
QHash<QString, QString> m_overviewSaveRevisions;
QLineEdit *m_hostEdit = nullptr;
QSpinBox *m_portSpin = nullptr;
QPushButton *m_connectButton = nullptr;
QPushButton *m_refreshButton = nullptr;
QListWidget *m_fileList = nullptr;
QLabel *m_rootLabel = nullptr;
QLabel *m_pathLabel = nullptr;
QLabel *m_typeLabel = nullptr;
QLabel *m_statusLabel = nullptr;
QTabWidget *m_editorTabs = nullptr;
QPlainTextEdit *m_textEditor = nullptr;
QTreeWidget *m_fieldTree = nullptr;
QTableWidget *m_enableTable = nullptr;
QPushButton *m_reloadButton = nullptr;
QPushButton *m_validateButton = nullptr;
QPushButton *m_saveButton = nullptr;
QTimer *m_parseTimer = nullptr;
QString m_currentPath;
QString m_revision;
bool m_connected = false;
bool m_busy = false;
bool m_loading = false;
bool m_dirty = false;
QString m_messageType;
std::unique_ptr<google::protobuf::DynamicMessageFactory> m_dynamicFactory;
std::unique_ptr<google::protobuf::Message> m_dynamicMessage;
};

View File

@ -7,6 +7,7 @@
// Shared by the UI RPC runner and the legacy worker; never opens a connection.
class DemoSimulator {
public:
DemoSimulator()=default;
struct Reply {bool ok=false;QJsonObject response;int delayMs=30;};
static DemoSimulator& instance();
void reset();

View File

@ -102,34 +102,36 @@ QJsonObject metadata(const QJsonObject &graph) {
return graph.value("cmvr").toObject();
}
void resources(QJsonObject &graph) {
auto nodes=graph.value("nodes").toArray();QJsonArray deviceSlotArray;QHash<QString,QString> deviceSlots;
const auto slot=[&](const QString &device,const QString &type) {
if(deviceSlots.contains(device))return deviceSlots.value(device);
const QString key="device_"+QString::fromLatin1(QCryptographicHash::hash(device.toUtf8(),QCryptographicHash::Sha256).toHex().left(16));
const QMap<QString,int> kinds{{QStringLiteral("机械臂"),2},{QStringLiteral("AGV"),1},{QStringLiteral("相机"),5},
{QStringLiteral("仿生头"),4},{QStringLiteral("麦克风"),9},{QStringLiteral("扬声器"),13},{QStringLiteral("电机"),10}};
QJsonObject s{{"slotKey",key},{"displayName",device},{"required",true},{"allowReuse",false},{"legacyDeviceId",device}};
s.insert("deviceKind",kinds.contains(type)?QJsonValue(kinds.value(type)):QJsonValue());deviceSlotArray.append(s);deviceSlots[device]=key;return key;
auto nodes=graph.value("nodes").toArray();QHash<QString,QString> deviceSlots,roleNames;QHash<QString,QJsonArray> roleSlots;
const auto slot=[&](const QString& role,const QString& device,const QString& type)->QString {
const QString identity=role+"/"+device;if(deviceSlots.contains(identity))return deviceSlots.value(identity);
const QString key=QStringLiteral("device_%1").arg(deviceSlots.size()+1);
const QHash<QString,int> kinds{{QStringLiteral("机械臂"),2},{QStringLiteral("AGV"),1},{QStringLiteral("相机"),5},{QStringLiteral("灵巧手"),7},
{QStringLiteral("仿生头"),4},{QStringLiteral("麦克风"),9},{QStringLiteral("扬声器"),15},{QStringLiteral("电机"),10}};
QJsonObject slot{{"slotKey",key},{"displayName",device},{"required",true},{"allowReuse",false},{"legacyDeviceId",device}};
slot.insert("deviceKind",kinds.contains(type)?QJsonValue(kinds.value(type)):QJsonValue());roleSlots[role].append(slot);deviceSlots[identity]=key;return key;
};
for(int i=0;i<nodes.size();++i) {
for(int i=0;i<nodes.size();++i){
auto n=nodes[i].toObject(),p=n.value("properties").toObject();if(p.value("nodeType")!="EDGE")continue;
const auto values=literals(p);QJsonObject target{{"roleKey","default_executor"},{"dispatchPolicy","ONE"}};
if(p.value("action")=="CMVR_ARM_POINT_BATCH") {
const QString robot=p.value("cmvrRobotId").toString("current");
const QString role=robot=="current"?QStringLiteral("default_executor"):robot.startsWith("role:")?robot.mid(5):QStringLiteral("robot_")+robot;
roleNames[role]=p.value("cmvrRobotName").toString(robot=="current"?QStringLiteral("执行机器人"):robot);
const auto values=literals(p);QJsonObject target{{"roleKey",role},{"dispatchPolicy","ONE"}};
if(p.value("action")=="CMVR_ARM_POINT_BATCH"){
const auto targets=QJsonDocument::fromJson(values.value("targetsJson").toString().toUtf8()).array();QJsonArray bindings;
for(int j=0;j<targets.size();++j)bindings.append(QJsonObject{{"parameterName",QStringLiteral("deviceId_%1").arg(j)},
{"slotKey",slot(targets[j].toObject().value("deviceId").toString(),QStringLiteral("机械臂"))}});
for(int j=0;j<targets.size();++j)bindings.append(QJsonObject{{"parameterName",QStringLiteral("deviceId_%1").arg(j)},{"slotKey",slot(role,targets[j].toObject().value("deviceId").toString(),QStringLiteral("机械臂"))}});
target.insert("deviceBindings",bindings);
}else target.insert("deviceSlotKey",slot(values.value("deviceId").toString(),p.value("cmvrDeviceType").toString()));
}else target.insert("deviceSlotKey",slot(role,values.value("deviceId").toString(),p.value("cmvrDeviceType").toString()));
p.insert("executionTarget",target);n.insert("properties",p);nodes[i]=n;
}
for(int i=0;i<nodes.size();++i)if(nodes[i].toObject().value("type")=="start") {
auto n=nodes[i].toObject(),p=n.value("properties").toObject();p.insert("schemaVersion",2);
p.insert("resourceRoles",QJsonArray{QJsonObject{{"roleKey","default_executor"},{"resourceType","ROBOT"},
{"displayName",QStringLiteral("执行机器人")},{"required",true},{"quantity",QJsonObject{{"min",1},{"max",1}}},{"deviceSlots",deviceSlotArray}}});
n.insert("properties",p);nodes[i]=n;
if(roleNames.isEmpty())roleNames["default_executor"]=QStringLiteral("执行机器人");
QJsonArray roles;auto keys=roleNames.keys();keys.sort();for(const auto& role:keys)roles.append(QJsonObject{{"roleKey",role},{"resourceType","ROBOT"},{"displayName",roleNames.value(role)},{"required",true},{"quantity",QJsonObject{{"min",1},{"max",1}}},{"deviceSlots",roleSlots.value(role)}});
for(int i=0;i<nodes.size();++i)if(nodes[i].toObject().value("type")=="start"){
auto n=nodes[i].toObject(),p=n.value("properties").toObject();p.insert("schemaVersion",2);p.insert("resourceRoles",roles);n.insert("properties",p);nodes[i]=n;
}
graph.insert("nodes",nodes);
}
}
namespace FreeScanInterop {
bool isGraph(const QJsonObject &document) {
@ -169,6 +171,8 @@ bool exportGraph(QJsonObject document,int groupIndex,QJsonObject &output,QString
const QString service=execution.value("service").toString(),method=execution.value("method").toString();
props.insert("action","CMVR_GRPC_UNARY");props.insert("nodeType","EDGE");
props.insert("cmvrDeviceType",item.value("deviceType"));
props.insert("cmvrRobotId",item.value("robotId").toString("current"));
if(item.contains("robotName"))props.insert("cmvrRobotName",item.value("robotName"));
props.insert("nodeParams",QJsonArray{parameter("deviceId",item.value("deviceId")),
parameter("service",service),parameter("method",method),
parameter("requestJson",QString::fromUtf8(QJsonDocument(execution.value("request").toObject()).toJson(QJsonDocument::Compact))),
@ -324,7 +328,13 @@ bool importGraph(const QJsonObject &input,QJsonObject &document,QString &error,b
require(draft||ended,QStringLiteral("流程必须连接到结束节点"));
return result;
};
const auto tasks=read({},0);require(visited.size()==lookup.size(),QStringLiteral("图中存在未连接节点、无入口循环或孤立容器"));
auto tasks=read({},0);
std::function<void(QJsonArray&)> restoreRobots=[&](QJsonArray& list){for(int i=0;i<list.size();++i){auto task=list[i].toObject();
if(task.value("kind")=="loop"){auto children=task.value("children").toArray();restoreRobots(children);task.insert("children",children);}
else {const auto p=lookup.value(task.value("id").toString()).value("properties").toObject();const QString role=p.value("executionTarget").toObject().value("roleKey").toString();
const QString robot=p.value("cmvrRobotId").toString(role.isEmpty()||role=="default_executor"?QStringLiteral("current"):QStringLiteral("role:")+role);task.insert("robotId",robot);if(p.contains("cmvrRobotName"))task.insert("robotName",p.value("cmvrRobotName"));}
list[i]=task;}};
restoreRobots(tasks);require(visited.size()==lookup.size(),QStringLiteral("图中存在未连接节点、无入口循环或孤立容器"));
const QString name=metadata(graph).value("name").toString(QStringLiteral("导入工作流"));
QJsonObject candidate{{"groups",QJsonArray{QJsonObject{{"id",uid()},{"name",name},{"nodes",tasks}}}}};
require(TaskApi::normalize(candidate,error),error);document=candidate;return true;

View File

@ -64,11 +64,10 @@ public:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override
{
workflowCardPaint(painter,boundingRect(),m_title,m_subtitle,
m_active?QColor("#20a36a"):m_loop?QColor("#a086d7"):QColor("#557799"),isSelected(),m_loop?25:0,
m_active?QColor("#20a36a"):m_loop?QColor("#a086d7"):QColor("#557799"),isSelected(),m_loop?36:0,
m_loop?QStringLiteral("loop"):QStringLiteral("arm"));
if(m_loop) {
painter->setPen(QColor("#73849a"));
painter->drawText(collapseButtonRect(),Qt::AlignCenter,m_collapsed?QStringLiteral("+"):QStringLiteral("−"));
workflowCollapseButton(painter,collapseButtonRect(),!m_collapsed,m_collapseHovered,m_collapsePressed);
}
}
protected:
@ -128,7 +127,7 @@ protected:
}
private:
QRectF collapseButtonRect() const { return QRectF(kNodeWidth - 34, 9, 22, 22); }
QRectF collapseButtonRect() const { return QRectF(kNodeWidth - 44, 18, 28, 28); }
QString m_id;
QString m_title;
@ -252,6 +251,11 @@ JointFlowEditor::JointFlowEditor(QWidget *parent) : QWidget(parent)
rebuildScene();emit changed();return true;
};
auto *pointCanvas=static_cast<WorkflowCanvas *>(m_view);
pointCanvas->undoRequested=[this]{restoreHistory(false);};
pointCanvas->redoRequested=[this]{restoreHistory(true);};
pointCanvas->canUndo=[this]{return m_editHistory.canUndo();};
pointCanvas->canRedo=[this]{return m_editHistory.canRedo();};
pointCanvas->nodeDeletionRequested=[this]{removeSelectedNode();};
pointCanvas->copyNodes=[this](const QSet<QString> &selection) {
QSet<QString> ids=selection;bool added=true;
while(added){added=false;for(const auto &n:m_nodes)if(!ids.contains(n.id)&&ids.contains(n.parentId)){ids.insert(n.id);added=true;}}
@ -294,7 +298,7 @@ JointFlowEditor::JointFlowEditor(QWidget *parent) : QWidget(parent)
return true;
};
static_cast<WorkflowCanvas *>(m_view)->connectionRemoved=[this](const QString &from,const QString &to) {
if(!m_view->isInteractive())return;WorkflowGraph::disconnect(m_graph,from,to);rebuildScene();emit changed();
if(!m_view->isInteractive())return;recordHistory();WorkflowGraph::disconnect(m_graph,from,to);rebuildScene();emit changed();
};
connect(m_scene, &QGraphicsScene::selectionChanged, this, [this]() {
for (QGraphicsItem *item : m_scene->selectedItems()) {
@ -310,6 +314,12 @@ JointFlowEditor::JointFlowEditor(QWidget *parent) : QWidget(parent)
m_selectedNodeId.clear();
notifyInsertionContext();
});
connect(this,&JointFlowEditor::changed,this,[this] {
if(m_restoringHistory||m_historyQueued)return;
m_historyQueued=true;
QTimer::singleShot(0,this,[this]{m_historyQueued=false;recordHistory();});
});
m_editHistory.reset(historyState());pointCanvas->refreshHistoryButtons();
}
JointFlowEditor::~JointFlowEditor()
@ -371,30 +381,14 @@ void JointFlowEditor::addLoopNode(const QString &nodeName, int loopCount,
void JointFlowEditor::removeSelectedNode()
{
if (!m_view->isInteractive()) return;
const QString id = selectedNodeId();
if (id.isEmpty())
return;
WorkflowGraph::removeNode(m_graph,id);
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();
if(!m_view->isInteractive())return;
QSet<QString> ids;for(auto* item:m_scene->selectedItems())if(nodeById(item->data(7010).toString()))ids.insert(item->data(7010).toString());
if(ids.isEmpty()&&!selectedNodeId().isEmpty())ids.insert(selectedNodeId());if(ids.isEmpty())return;
recordHistory();QStringList removing=ids.values();for(const auto& id:ids)WorkflowGraph::removeNode(m_graph,id);
for(int i=0;i<removing.size();++i)for(const auto& node:m_nodes)if(node.parentId==removing[i]&&!removing.contains(node.id))removing.append(node.id);
for(int i=m_nodes.size()-1;i>=0;--i)if(removing.contains(m_nodes[i].id))m_nodes.removeAt(i);
if(removing.contains(m_insertionParentId))setInsertionAtRoot();m_selectedNodeId.clear();
normalizeOrders(QString());layoutSiblings(QString());rebuildScene();emit changed();
}
void JointFlowEditor::removePointReferences(const QStringList &pointNames)
@ -482,7 +476,7 @@ void JointFlowEditor::appendJsonNode(QJsonArray &target, const Node &node) const
target.append(object);
}
bool JointFlowEditor::fromJson(const QJsonArray &array)
bool JointFlowEditor::fromJson(const QJsonArray &array,bool resetViewport)
{
QList<Node> loaded;
for (const QJsonValue &value : array) {
@ -509,8 +503,10 @@ bool JointFlowEditor::fromJson(const QJsonArray &array)
m_selectedNodeId.clear();
m_insertionParentId.clear();
rebuildScene();
resetView();
QTimer::singleShot(0, this, &JointFlowEditor::resetView);
if(resetViewport) {
resetView();QTimer::singleShot(0, this, &JointFlowEditor::resetView);
}
if(!m_restoringHistory){m_editHistory.reset(historyState());static_cast<WorkflowCanvas*>(m_view)->refreshHistoryButtons();}
return true;
}
@ -540,6 +536,7 @@ void JointFlowEditor::setEditingEnabled(bool enabled)
{
m_view->setInteractive(enabled);
if(m_inspector)m_inspector->setEnabled(enabled);
static_cast<WorkflowCanvas*>(m_view)->refreshHistoryButtons();
}
void JointFlowEditor::setGraphState(const QJsonObject &graph,bool reset)
{
@ -550,6 +547,20 @@ void JointFlowEditor::setGraphState(const QJsonObject &graph,bool reset)
if(!graph.isEmpty())node.intervalSeconds=WorkflowGraph::postWait(graph,node.id)/1000.;
}
rebuildScene();if(reset)resetView();
if(reset&&!m_restoringHistory){m_editHistory.reset(historyState());static_cast<WorkflowCanvas*>(m_view)->refreshHistoryButtons();}
}
void JointFlowEditor::recordHistory() {
if(m_restoringHistory||!m_view->isInteractive())return;
m_editHistory.push(historyState());static_cast<WorkflowCanvas*>(m_view)->refreshHistoryButtons();
}
void JointFlowEditor::restoreHistory(bool redo) {
if(!m_view->isInteractive())return;recordHistory();
if(redo?!m_editHistory.canRedo():!m_editHistory.canUndo())return;
const auto state=redo?m_editHistory.redo():m_editHistory.undo();
QScopedValueRollback<bool> guard(m_restoringHistory,true);
m_graph=state.value("graph").toObject();
fromJson(state.value("nodes").toArray(),false);
emit changed();m_editHistory.replaceCurrent(historyState());static_cast<WorkflowCanvas*>(m_view)->refreshHistoryButtons();
}
void JointFlowEditor::setActiveNode(const QString &nodeId) { m_activeNodeId = nodeId; rebuildScene(); }
@ -615,9 +626,15 @@ void JointFlowEditor::toggleLoopCollapsed(const QString &id)
if (!node || node->type != LoopNode)
return;
node->collapsed = !node->collapsed;
QTimer::singleShot(0, this, [this]() {
const bool expanded=!node->collapsed;
QTimer::singleShot(0, this, [this,id,expanded]() {
rebuildScene();
emit changed();
QTimer::singleShot(0,this,[this,id,expanded] {
const auto *current=nodeById(id);
if(!current||current->collapsed==expanded||!m_view->isInteractive())return;
static_cast<WorkflowCanvas*>(m_view)->focusLoop(id,m_graph,expanded);
});
});
}
@ -626,7 +643,9 @@ void JointFlowEditor::moveNode(const QString &id, const QPointF &position)
Node *node = nodeById(id);
if (!node) return;
if(!m_graph.isEmpty()) {
node->position=position;WorkflowGraph::position(m_graph,id,position+QPointF(kNodeWidth/2,kNodeHeight/2));
QHash<QString,QPointF> targets;for(auto* selected:m_scene->selectedItems())if(!selected->data(7010).toString().isEmpty())targets.insert(selected->data(7010).toString(),selected->sceneBoundingRect().center());
targets.insert(id,position+QPointF(kNodeWidth/2,kNodeHeight/2));WorkflowGraph::positions(m_graph,targets);
for(auto it=targets.begin();it!=targets.end();++it)if(auto* moved=nodeById(it.key()))moved->position=it.value()-QPointF(kNodeWidth/2,kNodeHeight/2);
rebuildScene();emit changed();return;
}
const QString parentId = node->parentId;
@ -721,6 +740,7 @@ void JointFlowEditor::rebuildScene()
{
const QPointF center = m_view->mapToScene(m_view->viewport()->rect().center());
const QSignalBlocker sceneBlocker(m_scene);
QSet<QString> selectedIds;for(auto* item:m_scene->selectedItems())selectedIds.insert(item->data(7010).toString());
m_scene->clear();
QHash<QString, FlowCardItem *> cards;
for (const Node &node : m_nodes) {
@ -738,8 +758,9 @@ void JointFlowEditor::rebuildScene()
const QString title = node.nodeName;
const QString executionUnit = node.type == LoopNode
? QStringLiteral("循环 × %1").arg(node.loopCount) : node.pointName;
const QString subtitle = QStringLiteral("执行点位:%1\n完成后等待 %2 s")
.arg(executionUnit).arg(node.intervalSeconds, 0, 'f', 1);
const QString subtitle = node.type==LoopNode
?QStringLiteral("重复执行 %1 次\n循环结束后等待 %2 s").arg(node.loopCount).arg(node.intervalSeconds,0,'f',1)
:QStringLiteral("执行点位:%1\n完成后等待 %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) {
@ -753,7 +774,7 @@ void JointFlowEditor::rebuildScene()
card->setPos(saved.isEmpty()?node.position:QPointF(saved.value("x").toDouble()-kNodeWidth/2,saved.value("y").toDouble()-kNodeHeight/2));
m_scene->addItem(card);
workflowPorts(card,node.id);
if (node.id == m_selectedNodeId)
if(selectedIds.contains(node.id)||(selectedIds.isEmpty()&&node.id==m_selectedNodeId))
card->setSelected(true);
cards.insert(node.id, card);
}
@ -789,7 +810,7 @@ void JointFlowEditor::rebuildScene()
while(parent){if(parent->collapsed)hidden=true;parent=nodeById(parent->parentId);}
if(hidden)continue;
auto *terminal=workflowTerminal(m_scene,id,type,QPointF(n.value("x").toDouble(),n.value("y").toDouble()));
terminal->moved=[this,id](const QPointF &center){QTimer::singleShot(0,this,[this,id,center]{if(m_view->isInteractive()){WorkflowGraph::position(m_graph,id,center);rebuildScene();emit changed();}});};
terminal->moved=[this,id](const QPointF &center){QTimer::singleShot(0,this,[this,id,center]{if(m_view->isInteractive()){QHash<QString,QPointF> targets;for(auto* selected:m_scene->selectedItems())if(!selected->data(7010).toString().isEmpty())targets.insert(selected->data(7010).toString(),selected->sceneBoundingRect().center());targets.insert(id,center);WorkflowGraph::positions(m_graph,targets);for(auto it=targets.begin();it!=targets.end();++it)if(auto* moved=nodeById(it.key()))moved->position=it.value()-QPointF(kNodeWidth/2,kNodeHeight/2);rebuildScene();emit changed();}});};
bounds[id]=terminal->sceneBoundingRect();
}
workflowContainers(m_scene,m_graph,bounds);

View File

@ -8,6 +8,7 @@
#include <QPointF>
#include <QWidget>
#include <functional>
#include "workflowhistory.h"
class QGraphicsScene;
class QGraphicsView;
@ -34,7 +35,7 @@ public:
QList<ExecutionStep> expandedSteps(QString *error = nullptr,
int maximumSteps = 100000) const;
QJsonArray toJson() const;
bool fromJson(const QJsonArray &array);
bool fromJson(const QJsonArray &array,bool resetViewport=true);
void clear();
void setActiveNode(const QString &nodeId);
void setAvailablePointNames(const QStringList &pointNames);
@ -95,4 +96,9 @@ private:
QString m_selectedNodeId;
QString m_insertionParentId;
QStringList m_availablePointNames;
WorkflowHistory m_editHistory;
bool m_restoringHistory=false,m_historyQueued=false;
QJsonObject historyState()const{return QJsonObject{{"nodes",toJson()},{"graph",m_graph}};}
void recordHistory();
void restoreHistory(bool redo);
};

View File

@ -10,6 +10,7 @@
#include "tactileheatmapwidget.h"
#include "jointfloweditor.h"
#include "taskorchestrationwidget.h"
#include "workflowrobotmanager.h"
#include "bioheadoperations.h"
#include "bioheadwidget.h"
#include "motordebugwidget.h"
@ -18,7 +19,6 @@
#include "agvmapviewwidget.h"
#include "agvmapeditorwidget.h"
#include "audiostreammanager.h"
#include "configeditorwidget.h"
#include "robotclient.h"
#include "quictestserver.h"
#include "rpcservicewidget.h"
@ -175,7 +175,7 @@ private:
bool pageUsesArmTelemetry(int index)
{
return index == 1 || index == 13 || index == 14 || index == 15;
return index == 1 || index == 12 || index == 13 || index == 14;
}
const QStringList kPageTitles = {
QStringLiteral("系统概览"), QStringLiteral("机械臂"),
@ -183,7 +183,7 @@ const QStringList kPageTitles = {
QStringLiteral("扬声器"), QStringLiteral("麦克风"),
QStringLiteral("灵巧手"), QStringLiteral("仿生头"),
QStringLiteral("HLC 控制"), QStringLiteral("接口调试"),
QStringLiteral("QUIC Server"), QStringLiteral("设备管理"),
QStringLiteral("QUIC Server"),
QStringLiteral("运行日志"), QStringLiteral("工具坐标标定"),
QStringLiteral("手眼标定"), QStringLiteral("末端操作"),
QStringLiteral("任务编排"), QStringLiteral("电机调试")
@ -200,7 +200,6 @@ const QStringList kPageSubtitles = {
QStringLiteral("触控坐标与最大作用力控制"),
QStringLiteral("测试服务原始请求与反馈"),
QStringLiteral("监听 edge 接入、注册、心跳与媒体数据报"),
QStringLiteral("设备清单以及 cmvr_es 项目配置的查看、校验与编辑"),
QStringLiteral("检查连接信息与 RPC 执行记录"),
QStringLiteral("机械臂工具中心点与工具坐标系标定入口"),
QStringLiteral("相机与机械臂坐标系的手眼标定入口"),
@ -310,7 +309,7 @@ MainWindow::MainWindow(QWidget *parent)
ui.systemNavButton, ui.armNavButton, ui.cameraNavButton,
ui.agvNavButton, ui.speakerNavButton, ui.microphoneNavButton,
ui.dexhandNavButton, ui.bioheadNavButton, ui.hlcNavButton,
ui.testNavButton, ui.quicNavButton, ui.configurationNavButton,
ui.testNavButton, ui.quicNavButton,
ui.diagnosticsNavButton
};
for (QPushButton *button : existingNavButtons)
@ -368,10 +367,7 @@ MainWindow::MainWindow(QWidget *parent)
QWidget *grpcContent = grpcSection.first;
QVBoxLayout *grpcLayout = grpcSection.second;
ui.configurationNavButton->setText(QStringLiteral("设备管理"));
ui.configurationNavButton->setObjectName(QStringLiteral("navSectionPageButton"));
ui.configurationNavButton->setProperty("navLevel", 1);
QPushButton *deviceGroupPageButton = ui.configurationNavButton;
QPushButton *deviceGroupPageButton = createGroupButton(QStringLiteral("设备"), grpcContent, 1);
const auto deviceSection = createNavContainer(grpcContent);
QWidget *deviceContent = deviceSection.first;
QVBoxLayout *deviceLayout = deviceSection.second;
@ -409,8 +405,7 @@ MainWindow::MainWindow(QWidget *parent)
complexLayout->addWidget(touchNavButton);
complexLayout->addWidget(ui.hlcNavButton);
ui.configurationNavButton->setParent(grpcContent);
grpcLayout->addWidget(ui.configurationNavButton);
grpcLayout->addWidget(deviceGroupPageButton);
grpcLayout->addWidget(deviceContent);
grpcLayout->addWidget(taskOrchestrationNavButton);
grpcLayout->addWidget(complexGroupButton);
@ -454,7 +449,7 @@ MainWindow::MainWindow(QWidget *parent)
ui.systemNavButton, ui.armNavButton, ui.cameraNavButton,
ui.agvNavButton, ui.speakerNavButton, ui.microphoneNavButton,
ui.dexhandNavButton, ui.bioheadNavButton, ui.hlcNavButton,
ui.testNavButton, ui.quicNavButton, ui.configurationNavButton,
ui.testNavButton, ui.quicNavButton,
ui.diagnosticsNavButton, toolCalibrationNavButton, handEyeNavButton, touchNavButton,
taskOrchestrationNavButton, motorNavButton
};
@ -470,7 +465,6 @@ MainWindow::MainWindow(QWidget *parent)
QStringLiteral(":/icons/crosshair.svg"),
QStringLiteral(":/icons/braces.svg"),
QStringLiteral(":/icons/radio-tower.svg"),
QStringLiteral(":/icons/folder-open.svg"),
QStringLiteral(":/icons/scroll-text.svg"),
QStringLiteral(":/icons/crosshair.svg"),
QStringLiteral(":/icons/camera.svg"), QStringLiteral(":/icons/crosshair.svg"),
@ -504,8 +498,8 @@ MainWindow::MainWindow(QWidget *parent)
QColor(QStringLiteral("#8995a1")), QColor(QStringLiteral("#ffffff")),
QColor(QStringLiteral("#66727d")), 16));
deviceGroupPageButton->setToolTip(
expanded ? QStringLiteral("打开设备管理并折叠设备目录")
: QStringLiteral("打开设备管理并展开设备目录"));
expanded ? QStringLiteral("折叠设备目录")
: QStringLiteral("展开设备目录"));
};
updateDeviceIcon();
connect(grpcGroupButton, &QPushButton::clicked, this,
@ -538,73 +532,6 @@ MainWindow::MainWindow(QWidget *parent)
m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.HlcService")));
m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.TestService")));
m_pages->addWidget(createQuicPage());
auto *deviceManager = new ConfigEditorWidget(m_client, m_pages);
m_pages->addWidget(deviceManager);
connect(deviceManager, &ConfigEditorWidget::deviceNavigationRequested, this,
[this](int deviceType, const QString &deviceId) {
int pageIndex = -1;
switch (deviceType) {
case 6:
pageIndex = 1;
if (m_armSideCombo) {
int index = m_armSideCombo->findData(deviceId);
if (index < 0) {
m_armSideCombo->addItem(deviceId, deviceId);
index = m_armSideCombo->count() - 1;
}
m_armSideCombo->setCurrentIndex(index);
} else if (m_armIdEdit) {
m_armIdEdit->setText(deviceId);
}
break;
case 2:
pageIndex = 2;
if (m_cameraDeviceCombo) {
int index = m_cameraDeviceCombo->findData(deviceId);
if (index < 0) {
m_cameraDeviceCombo->addItem(deviceId, deviceId);
index = m_cameraDeviceCombo->count() - 1;
}
m_cameraDeviceCombo->setCurrentIndex(index);
}
break;
case 3:
pageIndex = 6;
if (m_dexHandDeviceCombo) {
int index = m_dexHandDeviceCombo->findData(deviceId);
if (index < 0) {
m_dexHandDeviceCombo->addItem(deviceId, deviceId);
index = m_dexHandDeviceCombo->count() - 1;
}
m_dexHandDeviceCombo->setCurrentIndex(index);
}
break;
case 0:
pageIndex = 3;
if (m_agvIdEdit) m_agvIdEdit->setText(deviceId);
break;
case 7:
pageIndex = 4;
if (m_speakerIdEdit) m_speakerIdEdit->setText(deviceId);
break;
case 5:
pageIndex = 5;
if (m_microphoneIdEdit) m_microphoneIdEdit->setText(deviceId);
break;
case 8:
pageIndex = 7;
break;
default:
break;
}
if (pageIndex < 0)
return;
if (auto *rpcPage = qobject_cast<RpcServiceWidget *>(m_pages->widget(pageIndex)))
rpcPage->setDeviceId(deviceId);
if (auto *headPage = qobject_cast<BioHeadWidget *>(m_pages->widget(pageIndex)))
headPage->setDeviceId(deviceId);
selectPage(pageIndex);
});
m_pages->addWidget(createDiagnosticsPage());
// Fill the existing TCP navigation slot; keep page order and sidebar intact.
auto *tcpCalibration = new TcpCalibrationWidget(m_pages);
@ -714,15 +641,17 @@ MainWindow::MainWindow(QWidget *parent)
connect(m_taskOrchestration, &TaskOrchestrationWidget::statusMessage,
this, &MainWindow::appendLog);
auto* taskRpcRunner=new TaskRpcRunner(m_client,this);
connect(m_taskOrchestration,&TaskOrchestrationWidget::executionStopped,taskRpcRunner,&TaskRpcRunner::cancel);
m_workflowRobots=new WorkflowRobotManager(m_client,taskRpcRunner,m_taskOrchestration,this);
connect(m_taskOrchestration,&TaskOrchestrationWidget::manageRobotsRequested,this,[this]{m_workflowRobots->showDialog(m_taskOrchestration->window());});
connect(m_taskOrchestration,&TaskOrchestrationWidget::executionStopped,this,[this]{if(m_workflowRobots)m_workflowRobots->cancel();});
connect(m_taskOrchestration,&TaskOrchestrationWidget::workflowCallRequested,this,
[this,taskRpcRunner](const QString &token,const QJsonObject &execution) {
const auto generation=m_taskOrchestration->executionGeneration();
taskRpcRunner->runConcurrent(execution,[this,token,generation,execution](bool ok,const QString &response) {
m_workflowRobots->run(execution,[this,token,generation,execution](bool ok,const QString &response) {
if(generation!=m_taskOrchestration->executionGeneration())return;
QString detail;const bool success=TaskApi::responseSucceeded(ok,response,detail);
const auto method=execution.value("method").toString();
if(execution.value("service")=="cmvr.api.ArmService"&&(method=="torqueOn"||method=="torqueOff"))
if(execution.value("robotId").toString("current")=="current"&&execution.value("service")=="cmvr.api.ArmService"&&(method=="torqueOn"||method=="torqueOff"))
emit m_client->torqueFinished(execution.value("request").toObject().value("device_id").toString(),method=="torqueOn",success,detail);
m_taskOrchestration->completeWorkflowCall(token,success,detail);
});
@ -1330,6 +1259,8 @@ MainWindow::MainWindow(QWidget *parent)
MainWindow::~MainWindow()
{
if(m_workflowRobots)m_workflowRobots->cancel();
delete m_workflowRobots;m_workflowRobots=nullptr;
if (m_touchOperation) m_touchOperation->stop();
if (m_tcpJog) m_tcpJog->stop();
qApp->removeEventFilter(this);
@ -1651,7 +1582,7 @@ void MainWindow::selectPage(int index)
if (!m_pages || index < 0 || index >= kPageTitles.size())
return;
if (index != 1 && m_tcpJog) m_tcpJog->stop();
if (index != 15 && m_touchOperation) m_touchOperation->stop();
if (index != 14 && m_touchOperation) m_touchOperation->stop();
const int previousIndex = m_pages->currentIndex();
if (pageUsesArmTelemetry(previousIndex) && !pageUsesArmTelemetry(index))
setArmTelemetryEnabled(false);
@ -1945,11 +1876,7 @@ void MainWindow::configureAgvMapDirectConnection()
if (!m_client || !m_agvMapDirectMode || !m_agvMapDirectHost)
return;
const bool direct = m_agvMapDirectMode->currentData().toBool() && !m_demoCheck->isChecked();
QSettings settings;
const int storedPort = settings.value(QStringLiteral("configuration/port"), 50053).toInt();
const int configurationPort = storedPort == 50052 ? 50053 : storedPort;
m_client->configureAgvMapDirect(direct, m_agvMapDirectHost->text().trimmed(),
m_hostEdit->text().trimmed(), configurationPort);
m_client->configureAgvMapDirect(direct, m_agvMapDirectHost->text().trimmed());
m_agvDirectConfirmedMap.clear();
m_agvDirectSwitchDetail.clear();
m_agvMapSwitchRefreshToken = 0;
@ -2143,7 +2070,7 @@ void MainWindow::updateConnection(bool connected, int latencyMs, const QString &
m_jointPointCapturePending=false;
stopJointPointLoop(QStringLiteral("连接已断开"));
}
if (!connected && m_taskOrchestration)
if (!connected && m_taskOrchestration && m_taskOrchestration->runningUsesRobot("current"))
m_taskOrchestration->failActiveTask(
detail.isEmpty() ? QStringLiteral("gRPC 连接已断开") : detail);
if (!connected) {

View File

@ -42,6 +42,7 @@ class QTextEdit;
class QTimer;
class QVBoxLayout;
class TrendWidget;
class WorkflowRobotManager;
class RobotClient;
class QuicTestServer;
class UrdfViewerWidget;
@ -578,6 +579,7 @@ private:
QLabel *m_quicPeerValue = nullptr;
QTextEdit *m_quicLogView = nullptr;
WorkflowRobotManager* m_workflowRobots=nullptr;
QTextEdit *m_logView = nullptr;
QLabel *m_endpointValue = nullptr;
QLabel *m_backendValue = nullptr;

View File

@ -2492,9 +2492,9 @@ QWidget *MainWindow::createAgvPage()
mapConnectionRow->addWidget(m_agvMapDirectMode);
m_agvMapDirectHost = new QLineEdit(mapSelectorBar);
m_agvMapDirectHost->setObjectName(QStringLiteral("agvMapDirectHost"));
m_agvMapDirectHost->setPlaceholderText(QStringLiteral("车辆 IP(留空时从设备配置读取)"));
m_agvMapDirectHost->setPlaceholderText(QStringLiteral("车辆 IP(直连时必填)"));
m_agvMapDirectHost->setToolTip(QStringLiteral(
"填写车辆的 SEER 地址。留空时从配置服务读取当前设备的车辆地址和端口;手填时使用标准 SEER 端口。"));
"填写车辆的 SEER 地址,使用标准 SEER 端口。"));
m_agvMapDirectHost->setEnabled(false);
mapConnectionRow->addWidget(m_agvMapDirectHost, 1);
mapSelectionLayout->addLayout(mapConnectionRow);

View File

@ -170,7 +170,7 @@ MotorDebugWidget::MotorDebugWidget(RobotClient *client,QWidget *parent):QWidget(
m_connected=connected;resetSelection();if(!connected){QSignalBlocker a(m_manager),b(m_motor);m_manager->clear();m_motor->clear();m_status->setText(detail);}refreshControls();
});
connect(client,&RobotClient::systemStatusReceived,this,[this](double,double,double,const QVariantList &devices){
QStringList ids,old;for(const auto &v:devices)if(v.toMap().value("type").toInt()==10)ids.append(v.toMap().value("deviceId").toString());
QStringList ids,old;for(const auto &v:devices)if(v.toMap().value("type").toInt()==11)ids.append(v.toMap().value("deviceId").toString());
for(int i=0;i<m_manager->count();++i)old.append(m_manager->itemData(i).toString());if(ids==old)return;
const QString selected=m_manager->currentData().toString();
{QSignalBlocker b(m_manager);m_manager->clear();for(const auto &id:ids)m_manager->addItem(id,id);const int index=m_manager->findData(selected);if(index>=0)m_manager->setCurrentIndex(index);}

View File

@ -50,7 +50,6 @@
#include "cmvr/api/camera_service.grpc.pb.h"
#include "cmvr/api/dexhand_command.pb.h"
#include "cmvr/api/dexhand_service.grpc.pb.h"
#include "cmvr/api/configuration_service.grpc.pb.h"
#include "cmvr/api/microphone_command.pb.h"
#include "cmvr/api/microphone_service.grpc.pb.h"
#include "cmvr/api/speaker_command.pb.h"
@ -101,141 +100,6 @@ std::shared_ptr<grpc::Channel> createGrpcChannel(const std::string &endpoint)
return grpc::CreateCustomChannel(endpoint, grpc::InsecureChannelCredentials(), arguments);
}
// The map-only configuration lookup owns a separate channel. It never changes
// the configuration editor's connection or writes a configuration file.
class DirectMapRpcCancellation
{
public:
DirectMapRpcCancellation(grpc::ClientContext &context,
const std::shared_ptr<std::atomic<bool>> &cancel)
: m_thread([this, &context, cancel]() {
std::unique_lock<std::mutex> lock(m_mutex);
while (!m_finished) {
if (cancel->load()) {
context.TryCancel();
return;
}
m_condition.wait_for(lock, std::chrono::milliseconds(20));
}
}) {}
~DirectMapRpcCancellation()
{
{
std::lock_guard<std::mutex> lock(m_mutex);
m_finished = true;
}
m_condition.notify_all();
m_thread.join();
}
private:
std::mutex m_mutex;
std::condition_variable m_condition;
bool m_finished = false;
std::thread m_thread;
};
bool resolveDirectMapConnection(const QString &configHost, int configPort,
const QString &deviceId,
const std::shared_ptr<std::atomic<bool>> &cancel,
SeerAgvMapConnection &connection, QString &error)
{
if (configHost.isEmpty() || configPort < 1 || configPort > 65535) {
error = QStringLiteral("请填写车辆 IP,或设置可用的配置服务地址以读取 AGV 配置");
return false;
}
const QString host = configHost.contains(QLatin1Char(':'))
&& !configHost.startsWith(QLatin1Char('['))
? QLatin1Char('[') + configHost + QLatin1Char(']') : configHost;
auto stub = cmvr::api::ConfigurationService::NewStub(
createGrpcChannel(QStringLiteral("%1:%2").arg(host).arg(configPort).toStdString()));
cmvr::api::ListConfigFilesCommand::Request listRequest;
cmvr::api::ListConfigFilesCommand::Feedback listResponse;
grpc::ClientContext listContext;
listContext.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(3));
grpc::Status listStatus;
{
DirectMapRpcCancellation cancellation(listContext, cancel);
listStatus = stub->ListConfigFiles(&listContext, listRequest, &listResponse);
}
if (cancel->load()) {
error = QStringLiteral("地图直连配置读取已取消");
return false;
}
if (!listStatus.ok() || !listResponse.header().success()) {
error = QStringLiteral("无法读取 AGV 配置列表:%1;可手动填写车辆 IP")
.arg(QString::fromStdString(listStatus.ok()
? listResponse.header().error_message() : listStatus.error_message()));
return false;
}
int matches = 0;
for (const auto &file : listResponse.files()) {
if (file.message_type() != "cmvr.config.AGVRootConfig")
continue;
cmvr::api::ReadConfigFileCommand::Request readRequest;
readRequest.set_relative_path(file.relative_path());
cmvr::api::ReadConfigFileCommand::Feedback readResponse;
grpc::ClientContext readContext;
readContext.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(3));
grpc::Status readStatus;
{
DirectMapRpcCancellation cancellation(readContext, cancel);
readStatus = stub->ReadConfigFile(&readContext, readRequest, &readResponse);
}
if (cancel->load()) {
error = QStringLiteral("地图直连配置读取已取消");
return false;
}
if (!readStatus.ok() || !readResponse.header().success()) {
error = QStringLiteral("无法完整核查 AGV 配置 %1:%2;未连接车辆")
.arg(QString::fromStdString(file.relative_path()),
QString::fromStdString(readStatus.ok()
? readResponse.header().error_message() : readStatus.error_message()));
return false;
}
cmvr::config::AGVRootConfig root;
if (!google::protobuf::TextFormat::ParseFromString(readResponse.content(), &root)) {
error = QStringLiteral("AGV 配置 %1 解析失败;未连接车辆")
.arg(QString::fromStdString(file.relative_path()));
return false;
}
for (const auto &device : root.agv().agvs()) {
const QString configuredId = QString::fromStdString(device.id()).trimmed();
if (configuredId != deviceId)
continue;
++matches;
if (!device.has_seer_robokit_agv()) {
error = QStringLiteral("设备 %1 不是 SEER Robokit,不能使用地图直连").arg(deviceId);
return false;
}
const auto &seer = device.seer_robokit_agv();
const QString backendId = QString::fromStdString(seer.id()).trimmed();
if (!backendId.isEmpty() && backendId != deviceId) {
error = QStringLiteral("设备 %1 的内外配置 ID 不一致,未连接车辆").arg(deviceId);
return false;
}
connection.host = QString::fromStdString(seer.ip()).trimmed();
const int statusPort = seer.port_status() == 0 ? 19204 : seer.port_status();
const int controlPort = seer.port_control() == 0 ? 19205 : seer.port_control();
const int mapPort = seer.port_config() == 0 ? 19207 : seer.port_config();
if (connection.host.isEmpty() || statusPort < 1 || statusPort > 65535
|| controlPort < 1 || controlPort > 65535 || mapPort < 1 || mapPort > 65535) {
error = QStringLiteral("设备 %1 的车辆地址或端口无效,未连接车辆").arg(deviceId);
return false;
}
connection.statusPort = static_cast<quint16>(statusPort);
connection.controlPort = static_cast<quint16>(controlPort);
connection.configPort = static_cast<quint16>(mapPort);
}
}
if (matches != 1) {
error = matches == 0
? QStringLiteral("配置中未找到设备 %1 的 SEER 地址;可手动填写车辆 IP").arg(deviceId)
: QStringLiteral("设备 %1 在配置中有多个匹配,未连接车辆").arg(deviceId);
return false;
}
return !cancel->load();
}
cmvr::api::DeviceType deviceTypeFromKind(cmvr::api::DeviceKind kind,
cmvr::api::DeviceType fallback)
{
@ -288,8 +152,8 @@ QVariantList demoDeviceList()
{
QVariantList devices;
const QList<QVariantMap> definitions = {
{{"deviceId","bio_head"},{"type",8},{"driverType","DemoBioHead"},{"vendor","CMVR Demo"}},
{{"deviceId","motor_manager"},{"type",9},{"driverType","DemoMotor"},{"vendor","CMVR Demo"}},
{{"deviceId","bio_head"},{"type",9},{"driverType","DemoBioHead"},{"vendor","CMVR Demo"}},
{{"deviceId","motor_manager"},{"type",11},{"driverType","DemoMotor"},{"vendor","CMVR Demo"}},
{{QStringLiteral("deviceId"), QStringLiteral("right_arm")},
{QStringLiteral("type"), 6}, {QStringLiteral("deviceKind"), 2},
{QStringLiteral("driverType"), QStringLiteral("AuboARM")},
@ -445,8 +309,8 @@ public:
#endif
};
explicit BackendWorker(QObject *parent = nullptr)
: QObject(parent)
explicit BackendWorker(std::shared_ptr<DemoSimulator> simulator,QObject *parent = nullptr)
: QObject(parent),m_simulator(std::move(simulator))
{
m_pollTimer = new QTimer(this);
m_pollTimer->setInterval(100);
@ -495,7 +359,7 @@ public:
}
if (m_demoMode) {
DemoSimulator::instance().reset();
m_simulator->reset();
m_connected = true;
m_pollTimer->start();
emit connectionChanged(true, 8, QStringLiteral("演示数据源"));
@ -567,144 +431,6 @@ public:
emit logMessage(QStringLiteral("INFO"), QStringLiteral("连接已断开"));
}
void connectConfigurationServer(const QString &host, int port)
{
const QString trimmedHost = host.trimmed();
if (trimmedHost.isEmpty()) {
emit configurationConnectionChanged(false, QStringLiteral("主机地址不能为空"));
return;
}
#ifdef CMVR_WITH_GRPC
const std::string endpoint = QStringLiteral("%1:%2").arg(trimmedHost).arg(port).toStdString();
m_configChannel = createGrpcChannel(endpoint);
const auto deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(1500);
if (!m_configChannel->WaitForConnected(deadline)) {
m_configuration.reset();
m_configChannel.reset();
m_configConnected = false;
emit configurationConnectionChanged(
false, QStringLiteral("配置服务连接超时:%1").arg(QString::fromStdString(endpoint)));
return;
}
m_configuration = cmvr::api::ConfigurationService::NewStub(m_configChannel);
m_configConnected = true;
emit configurationConnectionChanged(
true, QStringLiteral("已连接配置服务:%1").arg(QString::fromStdString(endpoint)));
#else
Q_UNUSED(port)
emit configurationConnectionChanged(false, QStringLiteral("当前程序未编译 gRPC 支持"));
#endif
}
void disconnectConfigurationServer()
{
#ifdef CMVR_WITH_GRPC
m_configuration.reset();
m_configChannel.reset();
#endif
m_configConnected = false;
emit configurationConnectionChanged(false, QStringLiteral("配置服务已断开"));
}
void listConfigurationFiles()
{
#ifdef CMVR_WITH_GRPC
if (!ensureConfigurationConnected(QStringLiteral("读取配置列表")))
return;
cmvr::api::ListConfigFilesCommand::Request request;
cmvr::api::ListConfigFilesCommand::Feedback response;
grpc::ClientContext context;
setDeadline(context, 3000);
const grpc::Status status = m_configuration->ListConfigFiles(&context, request, &response);
const bool success = status.ok() && response.header().success();
QVariantList files;
if (success) {
for (const auto &file : response.files()) {
QVariantMap item;
item.insert(QStringLiteral("relativePath"), QString::fromStdString(file.relative_path()));
item.insert(QStringLiteral("sizeBytes"), QVariant::fromValue<qulonglong>(file.size_bytes()));
item.insert(QStringLiteral("modifiedUnixMs"), QVariant::fromValue<qlonglong>(file.modified_unix_ms()));
item.insert(QStringLiteral("messageType"), QString::fromStdString(file.message_type()));
files.append(item);
}
}
emit configurationFilesReceived(
QString::fromStdString(response.config_root()), files, success,
configurationError(status, response.header().error_message()));
#endif
}
void readConfigurationFile(const QString &relativePath)
{
#ifdef CMVR_WITH_GRPC
if (!ensureConfigurationConnected(QStringLiteral("读取配置文件")))
return;
cmvr::api::ReadConfigFileCommand::Request request;
request.set_relative_path(relativePath.toStdString());
cmvr::api::ReadConfigFileCommand::Feedback response;
grpc::ClientContext context;
setDeadline(context, 3000);
const grpc::Status status = m_configuration->ReadConfigFile(&context, request, &response);
const bool success = status.ok() && response.header().success();
emit configurationFileReceived(
relativePath,
success ? QString::fromStdString(response.content()) : QString(),
success ? QString::fromStdString(response.revision()) : QString(),
success ? QString::fromStdString(response.file().message_type()) : QString(),
success, configurationError(status, response.header().error_message()));
#else
Q_UNUSED(relativePath)
#endif
}
void validateConfigurationFile(const QString &relativePath, const QString &content)
{
#ifdef CMVR_WITH_GRPC
if (!ensureConfigurationConnected(QStringLiteral("校验配置文件")))
return;
cmvr::api::ValidateConfigFileCommand::Request request;
request.set_relative_path(relativePath.toStdString());
request.set_content(content.toStdString());
cmvr::api::ValidateConfigFileCommand::Feedback response;
grpc::ClientContext context;
setDeadline(context, 3000);
const grpc::Status status = m_configuration->ValidateConfigFile(&context, request, &response);
const bool success = status.ok() && response.header().success();
QString detail = configurationError(status, response.header().error_message());
if (success)
detail = QStringLiteral("配置有效:%1").arg(QString::fromStdString(response.message_type()));
emit configurationValidationFinished(relativePath, success, detail);
#else
Q_UNUSED(relativePath)
Q_UNUSED(content)
#endif
}
void saveConfigurationFile(const QString &relativePath, const QString &content,
const QString &expectedRevision)
{
#ifdef CMVR_WITH_GRPC
if (!ensureConfigurationConnected(QStringLiteral("保存配置文件")))
return;
cmvr::api::SaveConfigFileCommand::Request request;
request.set_relative_path(relativePath.toStdString());
request.set_content(content.toStdString());
request.set_expected_revision(expectedRevision.toStdString());
cmvr::api::SaveConfigFileCommand::Feedback response;
grpc::ClientContext context;
setDeadline(context, 5000);
const grpc::Status status = m_configuration->SaveConfigFile(&context, request, &response);
const bool success = status.ok() && response.header().success();
emit configurationSaveFinished(
relativePath, success ? QString::fromStdString(response.revision()) : QString(),
success, configurationError(status, response.header().error_message()));
#else
Q_UNUSED(relativePath)
Q_UNUSED(content)
Q_UNUSED(expectedRevision)
#endif
}
void setArmTelemetry(const QString &deviceId, bool enabled)
{
if (enabled && !ensureConnected(QStringLiteral("Arm Telemetry")))
@ -822,35 +548,19 @@ public:
else if (rpcFinished) rpcFinished(service,QString::number(token),false,why);
};
if (!ensureConnected(service) || !ensureDeviceId(service,deviceId)) { fail(QStringLiteral("设备未连接")); return; }
if (jointMove) { fail(QStringLiteral("当前服务端协议不提供末端位姿 MoveJ 接口")); return; }
if (m_demoMode) {
const QString op=parameters.value("operation").toString();
QJsonObject q{{"header",QJsonObject{{"device_id",deviceId}}},{"name",parameters.value("name").toString()}};
if(move){QJsonObject pose;const auto values=parameters.value("target").toList();const QStringList fields={"x","y","z","rx","ry","rz"};for(int i=0;i<qMin(values.size(),fields.size());++i)pose.insert(fields[i],values[i].toDouble());q.remove("name");q.insert("target",pose);const auto reply=DemoSimulator::instance().call("cmvr.api.ArmService",jointMove?"moveJPose":"moveL",q);finishDemoAfter(reply.delayMs,[this,command,reply]{if(m_connected&&m_demoMode)emit commandFinished(command,reply.ok,QStringLiteral("演示坐标系运动完成"));});return;}
if(move){QJsonObject pose;const auto values=parameters.value("target").toList();const QStringList fields={"x","y","z","rx","ry","rz"};for(int i=0;i<qMin(values.size(),fields.size());++i)pose.insert(fields[i],values[i].toDouble());q.remove("name");q.insert("target",pose);const auto reply=m_simulator->call("cmvr.api.ArmService",jointMove?"moveJPose":"moveL",q);finishDemoAfter(reply.delayMs,[this,command,reply]{if(m_connected&&m_demoMode)emit commandFinished(command,reply.ok,QStringLiteral("演示坐标系运动完成"));});return;}
const QMap<QString,QString> methods={{"list","ListUserCoordinateSystems"},{"get","GetUserCoordinateSystem"},{"create","CreateUserCoordinateSystem"},{"update","UpdateUserCoordinateSystem"},{"delete","DeleteUserCoordinateSystem"},{"apply","ApplyUserCoordinateSystem"},{"calibrate","CalibrateUserCoordinateSystem"}};
QString method=methods.value(op,"getPose");
if(op=="create"||op=="update"||op=="calibrate")q.insert("coordinate",QJsonObject{{"name",q.value("name")},{"user_pose",QJsonArray::fromVariantList(parameters.value("user_pose").toList())},{"tcp_offset",QJsonArray::fromVariantList(parameters.value("tcp_offset").toList())}});
if(method=="getPose")q.remove("name");const auto reply=DemoSimulator::instance().call("cmvr.api.ArmService",method,q);auto data=reply.response;data.insert("success",reply.ok);data.insert("operation",op);data.insert("device_id",deviceId);data.insert("simulation",true);
if(op=="pose"||op=="selected_pose"){QJsonArray p;const auto pose=DemoSimulator::instance().sample(deviceId).value("pose").toObject();for(const auto& name:QStringList{"x","y","z","rx","ry","rz"})p.append(pose.value(name));data.insert("pose",p);data.insert("reference",op=="selected_pose"?parameters.value("name").toString():QString("base"));data.insert("end_frame","tcp");data.insert("source","Demo");}
if(method=="getPose")q.remove("name");const auto reply=m_simulator->call("cmvr.api.ArmService",method,q);auto data=reply.response;data.insert("success",reply.ok);data.insert("operation",op);data.insert("device_id",deviceId);data.insert("simulation",true);
if(op=="pose"||op=="selected_pose"){QJsonArray p;const auto pose=m_simulator->sample(deviceId).value("pose").toObject();for(const auto& name:QStringList{"x","y","z","rx","ry","rz"})p.append(pose.value(name));data.insert("pose",p);data.insert("reference",op=="selected_pose"?parameters.value("name").toString():QString("base"));data.insert("end_frame","tcp");data.insert("source","Demo");}
if(rpcFinished)rpcFinished(service,QString::number(token),reply.ok,QString::fromUtf8(QJsonDocument(data).toJson(QJsonDocument::Compact)));return;
}
#ifdef CMVR_WITH_GRPC
if (jointMove) {
cmvr::api::MoveJPose::Request request;
fillHeader(request.mutable_header(),deviceId,kArmMotionTimeoutMs);
const auto values=parameters.value("target").toList();
const auto name=parameters.value("name").toString();
if(values.size()!=6 || name.isEmpty()){fail(QStringLiteral("Select a saved coordinate and a six-component absolute TCP target"));return;}
request.set_user_coordinate_name(name.toStdString());
request.set_user_coordinate_revision(parameters.value("revision").toString().toULongLong());
auto* p=request.mutable_target();
p->set_x(values[0].toDouble());p->set_y(values[1].toDouble());p->set_z(values[2].toDouble());
p->set_rx(values[3].toDouble());p->set_ry(values[4].toDouble());p->set_rz(values[5].toDouble());
request.mutable_options()->set_velocity(parameters.value("velocity").toDouble());
request.mutable_options()->set_acceleration(parameters.value("acceleration").toDouble());
startArmMotion<cmvr::api::MoveJPose::Request,cmvr::api::MoveJPose::Response>(command,std::move(request),
[](cmvr::api::ArmService::Stub& stub,grpc::ClientContext* context,const cmvr::api::MoveJPose::Request& q,cmvr::api::MoveJPose::Response* r){return stub.moveJPose(context,q,r);});
return;
}
if (move) {
cmvr::api::MoveL::Request request;
fillHeader(request.mutable_header(),deviceId,kArmMotionTimeoutMs);
@ -1458,7 +1168,7 @@ public:
{
const auto fail=[&](const QString &error) { motorRpcFinished(token,method,false,{},error); };
if (!m_connected || manager.isEmpty()) { fail(QStringLiteral("服务未连接或电机系统为空")); return; }
if (m_demoMode) {auto request=QJsonObject::fromVariantMap(params);request.insert("header",QJsonObject{{"device_id",manager}});request.insert("node_id",node);const auto reply=DemoSimulator::instance().call("cmvr.api.MotorService",method,request);const auto convert=[](const QJsonObject& data){QVariantMap out;for(auto i=data.begin();i!=data.end();++i){QString key=i.key();int underscore;while((underscore=key.indexOf('_'))>=0){key.remove(underscore,1);if(underscore<key.size())key[underscore]=key[underscore].toUpper();}out.insert(key,i.value().toVariant());}return out;};QVariantMap payload;
if (m_demoMode) {auto request=QJsonObject::fromVariantMap(params);request.insert("header",QJsonObject{{"device_id",manager}});request.insert("node_id",node);const auto reply=m_simulator->call("cmvr.api.MotorService",method,request);const auto convert=[](const QJsonObject& data){QVariantMap out;for(auto i=data.begin();i!=data.end();++i){QString key=i.key();int underscore;while((underscore=key.indexOf('_'))>=0){key.remove(underscore,1);if(underscore<key.size())key[underscore]=key[underscore].toUpper();}out.insert(key,i.value().toVariant());}return out;};QVariantMap payload;
if(method=="ListMotors"){QVariantList motors;for(const auto& m:reply.response.value("motors").toArray())motors<<convert(m.toObject());payload.insert("motors",motors);}else{payload.insert("info",convert(reply.response.value("info").toObject()));payload.insert("state",convert(reply.response.value("state").toObject()));payload.insert("reachedTarget",true);payload.insert("driverAcknowledged",true);}
motorRpcFinished(token,method,reply.ok,payload,QStringLiteral("演示电机反馈"));return;}
#ifdef CMVR_WITH_GRPC
@ -1534,7 +1244,7 @@ public:
if (error.isEmpty() && m_demoMode) {
for (const auto &id : devices) {
const auto names=armJointNamesForDevice(id);
const auto values=DemoSimulator::instance().sample(id).value("position").toArray().toVariantList();
const auto values=m_simulator->sample(id).value("position").toArray().toVariantList();
targets.append(QVariantMap{{"deviceId",id},{"jointNames",names},{"positions",values}});
}
emit jointPointCaptured(token,targets,true,QStringLiteral("演示点位"));
@ -1604,7 +1314,7 @@ public:
}
}
if (m_demoMode) {
for(const auto& value:targets){const auto t=value.toMap();DemoSimulator::instance().call("cmvr.api.ArmService","moveJ",{{"header",QJsonObject{{"device_id",t.value("deviceId").toString()}}},{"target",QJsonObject{{"position",QJsonArray::fromVariantList(t.value("positions").toList())}}}});}
for(const auto& value:targets){const auto t=value.toMap();m_simulator->call("cmvr.api.ArmService","moveJ",{{"header",QJsonObject{{"device_id",t.value("deviceId").toString()}}},{"target",QJsonObject{{"position",QJsonArray::fromVariantList(t.value("positions").toList())}}}});}
finishDemoAfter(1200,[this,token]{if(m_connected&&m_demoMode)emit jointPointMoveFinished(token,true,QStringLiteral("演示点位运动完成"));});return;
}
#ifdef CMVR_WITH_GRPC
@ -1748,7 +1458,7 @@ public:
return;
}
if (m_demoMode) {
const auto reply=DemoSimulator::instance().call("cmvr.api.ArmService","moveJ",{{"header",QJsonObject{{"device_id",deviceId}}},{"target",QJsonObject{{"position",QJsonArray::fromVariantList(positions)}}},{"options",QJsonObject{{"velocity",velocity},{"acceleration",acceleration}}}});
const auto reply=m_simulator->call("cmvr.api.ArmService","moveJ",{{"header",QJsonObject{{"device_id",deviceId}}},{"target",QJsonObject{{"position",QJsonArray::fromVariantList(positions)}}},{"options",QJsonObject{{"velocity",velocity},{"acceleration",acceleration}}}});
finishDemoAfter(reply.delayMs,[this,reply]{if(m_connected&&m_demoMode)emit commandFinished(QStringLiteral("MoveJ"),reply.ok,QStringLiteral("演示关节运动完成"));});return;
}
#ifdef CMVR_WITH_GRPC
@ -1794,7 +1504,7 @@ public:
if (!ensureDeviceId(command, deviceId))
return;
if (m_demoMode) {
const auto reply=DemoSimulator::instance().call("cmvr.api.ArmService","moveL",{{"header",QJsonObject{{"device_id",deviceId}}},{"target",QJsonObject::fromVariantMap(pose)}});
const auto reply=m_simulator->call("cmvr.api.ArmService","moveL",{{"header",QJsonObject{{"device_id",deviceId}}},{"target",QJsonObject::fromVariantMap(pose)}});
finishDemoAfter(reply.delayMs,[this,command,reply]{if(m_connected&&m_demoMode)emit commandFinished(command,reply.ok,QStringLiteral("演示末端运动完成"));});return;
}
#ifdef CMVR_WITH_GRPC
@ -1832,7 +1542,7 @@ public:
if (!ensureDeviceId(command, deviceId))
return;
if (m_demoMode) {
DemoSimulator::instance().call("cmvr.api.ArmService",enabled?"torqueOn":"torqueOff",{{"device_id",deviceId}});
m_simulator->call("cmvr.api.ArmService",enabled?"torqueOn":"torqueOff",{{"device_id",deviceId}});
if(torqueFinished)torqueFinished(deviceId,enabled,true,QStringLiteral("演示模式"));
emit commandFinished(command, true, enabled ? QStringLiteral("关节已使能") : QStringLiteral("关节已去使能"));
return;
@ -1860,7 +1570,7 @@ public:
if (!ensureDeviceId(QStringLiteral("Stop Motion"), deviceId))
return;
if (m_demoMode) {
DemoSimulator::instance().stop(deviceId);m_demoTargets.clear();
m_simulator->stop(deviceId);m_demoTargets.clear();
emit commandFinished(QStringLiteral("Stop Motion"), true, QStringLiteral("运动已停止"));
return;
}
@ -2202,14 +1912,11 @@ public:
const auto stamp=response.header().timestamp();
const qint64 serverNs=qint64(stamp.seconds())*1000000000+stamp.nanos();
const qint64 latest=frame.capture_utc_ns();
const qint64 earliest=frame.capture_earliest_utc_ns()>0?frame.capture_earliest_utc_ns():latest;
const qint64 earliest=latest;
const bool bounded=latest>0 && earliest>0 && earliest<=latest && stamp.seconds()>0
&& stamp.nanos()>=0 && stamp.nanos()<1000000000 && serverNs>=latest
&& serverNs-earliest<=1500000000 && receivedNs>=sentNs && receivedNs-sentNs<=1500000000;
if(touch && (!bounded || frame.camera_serial().empty() || !frame.camera_session_generation()
|| (frame.distortion_model()!="none" && frame.distortion_model()!="brown_conrady"))) {
reject(QStringLiteral("二维定位缺少真实相机身份、畸变模型或有界采集时刻")); return;
}
if(touch) { reject(QStringLiteral("当前服务端协议缺少二维定位所需的相机身份及畸变元数据")); return; }
if(bounded) capture={{"captureUtcNs",receivedNs-(serverNs-latest)},
{"captureEarliestLocalNs",sentNs-(serverNs-earliest)},{"serverCaptureUtcNs",latest},
{"captureTimeUncertaintyNs",receivedNs-sentNs+latest-earliest}};
@ -2218,16 +1925,16 @@ public:
{QStringLiteral("cx"), camera.cx()}, {QStringLiteral("cy"), camera.cy()},
{QStringLiteral("coeffs"), coefficients},
{QStringLiteral("width"), image.width()}, {QStringLiteral("height"), image.height()},
{QStringLiteral("distortionModelAvailable"), !frame.distortion_model().empty()},
{QStringLiteral("model"),QString::fromStdString(frame.distortion_model())},
{QStringLiteral("distortionModelAvailable"), false},
{QStringLiteral("model"),QString()},
{QStringLiteral("source"), QStringLiteral("CameraService.GetRGBImage.intrinsics")}};
// Older/current unary servers omit these fields. Preserve zero and
// advertise the absence; receipt time is not a camera capture time.
const bool captureTimestampAvailable = frame.capture_utc_ns() > 0;
QVariantMap metadata = {
{QStringLiteral("captureUtcNs"), static_cast<qint64>(frame.capture_utc_ns())},
{QStringLiteral("cameraSerial"),QString::fromStdString(frame.camera_serial())},
{QStringLiteral("cameraSessionGeneration"),qulonglong(frame.camera_session_generation())},
{QStringLiteral("cameraSerial"),QString()},
{QStringLiteral("cameraSessionGeneration"),qulonglong(0)},
{QStringLiteral("sourceSequence"), static_cast<quint64>(frame.source_sequence())},
{QStringLiteral("sourceFrameNumber"), static_cast<quint64>(frame.source_frame_number())},
{QStringLiteral("sourceTimestamp"), static_cast<quint64>(frame.source_timestamp())},
@ -2279,72 +1986,7 @@ public:
{
const auto reject=[&](const QString &detail) { touchRgbdImageReceived(token,cameraId,{},{},{},false,detail); };
if(m_demoMode||!m_connected||cameraId.trimmed().isEmpty()) { reject(QStringLiteral("请连接真实相机服务")); return; }
#ifdef CMVR_WITH_GRPC
if(!m_camera) { reject(QStringLiteral("相机服务不可用")); return; }
cmvr::api::GetRGBDImagesCommand::Request request;
fillHeader(request.mutable_header(),cameraId); request.set_require_metric_depth(true);
cmvr::api::GetRGBDImagesCommand::Feedback response;
grpc::ClientContext context; setDeadline(context,3000);
const qint64 sentNs=QDateTime::currentMSecsSinceEpoch()*1000000;
const auto status=m_camera->GetRGBDImages(&context,request,&response);
const qint64 receivedNs=QDateTime::currentMSecsSinceEpoch()*1000000;
if(!status.ok()||!response.header().success()) {
reject(QStringLiteral("GetRGBDImages:%1").arg(QString::fromStdString(status.ok()?response.header().error_message():status.error_message()))); return;
}
if(!response.has_depth_geometry()) {
reject(QStringLiteral("相机服务尚未提供公制深度元数据,请安装随上位机提供的 RGBD 服务补丁。")); return;
}
const auto &rgb=response.color_frame(); const auto &d=response.depth_frame();
const auto &g=response.depth_geometry(); const auto &k=response.intrinsics();
const auto &stamp=response.header().timestamp();
if(stamp.seconds()<=0||stamp.seconds()>std::numeric_limits<qint64>::max()/1000000000-1
||stamp.nanos()<0||stamp.nanos()>=1000000000||receivedNs<sentNs||receivedNs-sentNs>1500000000) {
reject(QStringLiteral("RGBD 服务响应时间戳无效或通信时间窗过大")); return;
}
const qint64 serverResponseNs=stamp.seconds()*1000000000+stamp.nanos();
const qint64 colorAgeNs=serverResponseNs-rgb.capture_utc_ns();
const qint64 depthAgeNs=serverResponseNs-d.capture_utc_ns();
if(colorAgeNs<0||depthAgeNs<0||colorAgeNs>1500000000||depthAgeNs>1500000000) {
reject(QStringLiteral("RGBD 采集时间与服务器时钟不一致或图像已过期")); return;
}
// Exposure timestamps and feedback time share the server clock. Map
// their ages to the client request/response interval; retain the full
// interval instead of assuming the two hosts have identical clocks.
const qint64 colorLatestNs=receivedNs-colorAgeNs, depthLatestNs=receivedNs-depthAgeNs;
const int bytes=d.type()==cmvr::api::FrameData::U16C1?2:d.type()==cmvr::api::FrameData::F32C1?4:0;
const qint64 pixels=qint64(rgb.width())*rgb.height();
const auto raw=[](const cmvr::api::FrameData &f) { return f.codec().empty()||f.codec()=="none"; };
if(rgb.width()<2||rgb.height()<2||rgb.width()>16384||rgb.height()>16384||pixels>kGrpcMaxMessageBytes/7
||rgb.type()!=cmvr::api::FrameData::U8C3||!bytes||!raw(rgb)||!raw(d)
||d.width()!=rgb.width()||d.height()!=rgb.height()
||rgb.data().size()!=quint64(pixels*3)||d.data().size()!=quint64(pixels*bytes)
||!g.aligned_to_color()||!g.color_axial_z()||g.byte_order()!="little"
||!std::isfinite(g.metres_per_unit())||g.metres_per_unit()<=0||g.metres_per_unit()>1
||rgb.capture_utc_ns()<=0||d.capture_utc_ns()<=0
||std::abs(rgb.capture_utc_ns()-d.capture_utc_ns())>33000000
||(g.distortion_model()!="none"&&g.distortion_model()!="brown_conrady")) {
reject(QStringLiteral("RGBD 格式、配准、时间戳或公制深度信息无效")); return;
}
QVariantList coeffs;
for(float value:k.coeffs()) { if(!std::isfinite(value)) { reject(QStringLiteral("RGB 内参无效")); return; } coeffs<<double(value); }
if(!std::isfinite(k.fx())||!std::isfinite(k.fy())||k.fx()<=0||k.fy()<=0
||!std::isfinite(k.cx())||!std::isfinite(k.cy())||coeffs.size()!=5) { reject(QStringLiteral("RGB 内参无效")); return; }
const QImage borrowed(reinterpret_cast<const uchar*>(rgb.data().data()),rgb.width(),rgb.height(),rgb.width()*3,QImage::Format_RGB888);
const QImage image=borrowed.rgbSwapped(); // Owning RGB image; raw transport is OpenCV BGR.
const QVariantMap intrinsics{{"fx",double(k.fx())},{"fy",double(k.fy())},{"cx",double(k.cx())},{"cy",double(k.cy())},
{"width",rgb.width()},{"height",rgb.height()},{"coeffs",coeffs},{"model",QString::fromStdString(g.distortion_model())}};
const QVariantMap metadata{{"cameraSerial",QString::fromStdString(rgb.camera_serial())},{"cameraSessionGeneration",qulonglong(rgb.camera_session_generation())},
{"captureUtcNs",colorLatestNs},{"depthCaptureUtcNs",depthLatestNs},
{"captureEarliestLocalNs",sentNs-colorAgeNs},{"depthCaptureEarliestLocalNs",sentNs-depthAgeNs},
{"serverCaptureUtcNs",qint64(rgb.capture_utc_ns())},{"serverDepthCaptureUtcNs",qint64(d.capture_utc_ns())},
{"serverResponseUtcNs",serverResponseNs},{"captureTimeUncertaintyNs",receivedNs-sentNs},
{"alignedToColor",true},{"colorAxialZ",true},{"byteOrder","little"},{"metresPerUnit",g.metres_per_unit()},
{"depthWidth",d.width()},{"depthHeight",d.height()},{"depthFloat32",bytes==4},
{"depthData",QByteArray(d.data().data(),int(d.data().size()))}};
touchRgbdImageReceived(token,cameraId,image,intrinsics,metadata,true,QStringLiteral("已获取同步公制 RGBD"));
#else
reject(QStringLiteral("当前构建未启用 gRPC"));
#endif
reject(QStringLiteral("当前服务端协议不提供公制深度元数据,无法执行 RGBD 定位"));
}
void depthSnapshot(const QString &cameraId)
@ -2898,7 +2540,7 @@ public:
return;
}
if (m_demoMode) {
const auto simulated=DemoSimulator::instance().sample(deviceId);const auto pose=simulated.value("pose").toObject();
const auto simulated=m_simulator->sample(deviceId);const auto pose=simulated.value("pose").toObject();
QVariantMap state = agvContext(deviceId);
state.insert(QStringLiteral("connected"), true);
state.insert(QStringLiteral("timestamp"), QDateTime::currentMSecsSinceEpoch() / 1000.0);
@ -3844,9 +3486,9 @@ public:
auto request=QJsonDocument::fromJson(requestJson.toUtf8()).object();
const auto* descriptor=google::protobuf::DescriptorPool::generated_pool()->FindServiceByName(serviceName.toStdString());
const auto* method=descriptor?descriptor->FindMethodByName(methodName.toStdString()):nullptr;
if(method&&method->input_type()->FindFieldByName("header")){auto h=request.value("header").toObject();h.insert("device_id",deviceId);h.remove("deviceId");request.insert("header",h);}
if(method&&method->input_type()&&method->input_type()->FindFieldByName("header")){auto h=request.value("header").toObject();h.insert("device_id",deviceId);h.remove("deviceId");request.insert("header",h);}
else if(!deviceId.isEmpty()){request.insert("device_id",deviceId);request.remove("deviceId");}
const auto reply=DemoSimulator::instance().call(serviceName,methodName,request);
const auto reply=m_simulator->call(serviceName,methodName,request);
finishDemoAfter(reply.delayMs,[this,serviceName,methodName,command,reply]{if(!m_connected||!m_demoMode)return;
emit rpcFinished(serviceName,methodName,reply.ok,QString::fromUtf8(QJsonDocument(reply.response).toJson(QJsonDocument::Compact)));
emit commandFinished(command,reply.ok,QStringLiteral("演示接口模拟完成,未发送网络请求"));});
@ -3858,7 +3500,7 @@ public:
serviceName.toStdString());
const google::protobuf::MethodDescriptor *method =
service ? service->FindMethodByName(methodName.toStdString()) : nullptr;
if (!method || !m_generic) {
if (!method || !method->input_type() || !method->output_type() || !m_generic) {
const QString error = QStringLiteral("找不到 RPC 描述符:%1").arg(command);
emit rpcFinished(serviceName, methodName, false,
QStringLiteral("{\"error\":\"%1\"}").arg(error));
@ -4052,15 +3694,6 @@ public:
std::function<void(const QString &, quint64, quint64, qint64)> audioStreamStatistics;
std::function<void(const QByteArray &, int, int, int, const QString &, qint64, int)>
audioFrameReceived;
std::function<void(bool, const QString &)> configurationConnectionChanged;
std::function<void(const QString &, const QVariantList &, bool, const QString &)>
configurationFilesReceived;
std::function<void(const QString &, const QString &, const QString &, const QString &,
bool, const QString &)> configurationFileReceived;
std::function<void(const QString &, bool, const QString &)>
configurationValidationFinished;
std::function<void(const QString &, const QString &, bool, const QString &)>
configurationSaveFinished;
std::function<void(const QString &, bool, const QString &)> commandFinished;
std::function<void(const QString&,bool,bool,const QString&)> torqueFinished;
std::function<void(const QString &, const QVariantList &, const QVariantMap &, bool, const QString &)>
@ -4071,24 +3704,8 @@ public:
std::function<void(const QString &, const QString &)> logMessage;
private:
std::shared_ptr<DemoSimulator> m_simulator;
#ifdef CMVR_WITH_GRPC
bool ensureConfigurationConnected(const QString &operation)
{
if (m_configConnected && m_configuration)
return true;
emit configurationConnectionChanged(
false, QStringLiteral("%1失败:配置服务未连接").arg(operation));
return false;
}
static QString configurationError(const grpc::Status &status,
const std::string &applicationError)
{
if (!status.ok())
return QString::fromStdString(status.error_message());
return QString::fromStdString(applicationError);
}
std::shared_ptr<ArmMotionSession> prepareArmMotionSession(const QString &command)
{
std::shared_ptr<ArmMotionSession> previous;
@ -4526,7 +4143,7 @@ private:
if (m_armPollingEnabled) {
QVariantList joints;
const QStringList jointNames = armJointNamesForDevice(m_armDeviceId);
const auto simulated=DemoSimulator::instance().sample(m_armDeviceId);
const auto simulated=m_simulator->sample(m_armDeviceId);
const auto positions=simulated.value("position").toArray();
for (int i = 0; i < jointNames.size(); ++i) {
const double phase = m_tick * 0.035 + i * 0.46;
@ -4600,9 +4217,7 @@ private:
const qint64 now = QDateTime::currentMSecsSinceEpoch();
header->mutable_timestamp()->set_seconds(now / 1000);
header->mutable_timestamp()->set_nanos(static_cast<int>((now % 1000) * 1000000));
header->set_command_id(
QUuid::createUuid().toString(QUuid::WithoutBraces).toStdString());
header->set_valid_for_ms(static_cast<quint32>(qMax(1, validForMs)));
Q_UNUSED(validForMs);
}
static void setDeadline(grpc::ClientContext &context, int milliseconds)
@ -5163,8 +4778,8 @@ private:
{QStringLiteral("distortionModelAvailable"), false},
{QStringLiteral("source"), QStringLiteral("CameraService.GetRGBImageStream.intrinsics")}};
packet.metadata = {
{QStringLiteral("cameraSerial"),QString::fromStdString(frame.camera_serial())},
{QStringLiteral("cameraSessionGeneration"),qulonglong(frame.camera_session_generation())},
{QStringLiteral("cameraSerial"),QString()},
{QStringLiteral("cameraSessionGeneration"),qulonglong(0)},
{QStringLiteral("kind"), QStringLiteral("rgb")},
{QStringLiteral("captureUtcNs"), static_cast<qint64>(frame.capture_utc_ns())},
{QStringLiteral("sourceSequence"), static_cast<quint64>(frame.source_sequence())},
@ -5487,7 +5102,6 @@ private:
}
std::shared_ptr<grpc::Channel> m_channel;
std::shared_ptr<grpc::Channel> m_configChannel;
std::unique_ptr<cmvr::api::ArmService::Stub> m_arm;
std::unique_ptr<cmvr::api::CameraService::Stub> m_camera;
std::unique_ptr<cmvr::api::DexHandService::Stub> m_dexHand;
@ -5495,7 +5109,6 @@ private:
std::unique_ptr<cmvr::api::AgvService::Stub> m_agv;
std::unique_ptr<cmvr::api::MicPhoneService::Stub> m_microphone;
std::unique_ptr<grpc::GenericStub> m_generic;
std::unique_ptr<cmvr::api::ConfigurationService::Stub> m_configuration;
bool m_jointTelemetryOnly = false;
QHash<QString, bool> m_legacyArmDiscovery;
QHash<QString, QPair<QString, QString>> m_armFrameDefaults;
@ -5528,7 +5141,6 @@ private:
int m_consecutivePollErrors = 0;
int m_channelFailureTicks = 0;
bool m_connected = false;
bool m_configConnected = false;
bool m_demoMode = true;
bool m_armPollingEnabled = false;
std::shared_ptr<ArmMotionSession> m_armMotionSession;
@ -5563,8 +5175,8 @@ private:
QVector<double> m_demoTargets;
};
RobotClient::RobotClient(QObject *parent)
: QObject(parent), m_worker(new BackendWorker)
RobotClient::RobotClient(QObject *parent,std::shared_ptr<DemoSimulator> simulator)
: QObject(parent), m_simulator(simulator?std::move(simulator):std::shared_ptr<DemoSimulator>(&DemoSimulator::instance(),[](DemoSimulator*){})), m_worker(new BackendWorker(m_simulator))
{
m_agvMapDirectWorker = new QObject;
m_agvMapDirectWorker->moveToThread(&m_agvMapDirectThread);
@ -5802,40 +5414,6 @@ RobotClient::RobotClient(QObject *parent)
emit audioFrameReceived(data, sampleRate, channels, format, codec, pts, samples);
}, Qt::QueuedConnection);
};
m_worker->configurationConnectionChanged = [this](bool connected, const QString &detail) {
QMetaObject::invokeMethod(this, [this, connected, detail]() {
emit configurationConnectionChanged(connected, detail);
}, Qt::QueuedConnection);
};
m_worker->configurationFilesReceived =
[this](const QString &root, const QVariantList &files, bool success,
const QString &detail) {
QMetaObject::invokeMethod(this, [this, root, files, success, detail]() {
emit configurationFilesReceived(root, files, success, detail);
}, Qt::QueuedConnection);
};
m_worker->configurationFileReceived =
[this](const QString &path, const QString &content, const QString &revision,
const QString &messageType, bool success, const QString &detail) {
QMetaObject::invokeMethod(
this, [this, path, content, revision, messageType, success, detail]() {
emit configurationFileReceived(path, content, revision, messageType,
success, detail);
}, Qt::QueuedConnection);
};
m_worker->configurationValidationFinished =
[this](const QString &path, bool success, const QString &detail) {
QMetaObject::invokeMethod(this, [this, path, success, detail]() {
emit configurationValidationFinished(path, success, detail);
}, Qt::QueuedConnection);
};
m_worker->configurationSaveFinished =
[this](const QString &path, const QString &revision, bool success,
const QString &detail) {
QMetaObject::invokeMethod(this, [this, path, revision, success, detail]() {
emit configurationSaveFinished(path, revision, success, detail);
}, Qt::QueuedConnection);
};
m_worker->torqueFinished=[this](const QString& deviceId,bool enabled,bool success,const QString& detail){
QMetaObject::invokeMethod(this,[this,deviceId,enabled,success,detail]{emit torqueFinished(deviceId,enabled,success,detail);},Qt::QueuedConnection);
};
@ -5998,19 +5576,6 @@ RobotClient::RobotClient(QObject *parent)
m_worker, &BackendWorker::startMicrophoneAudioStream);
connect(this, &RobotClient::microphoneAudioStreamStopRequested,
m_worker, &BackendWorker::stopMicrophoneAudioStream);
connect(this, &RobotClient::configurationConnectRequested,
m_worker, &BackendWorker::connectConfigurationServer);
connect(this, &RobotClient::configurationDisconnectRequested,
m_worker, &BackendWorker::disconnectConfigurationServer);
connect(this, &RobotClient::configurationFilesRequested,
m_worker, &BackendWorker::listConfigurationFiles);
connect(this, &RobotClient::configurationFileReadRequested,
m_worker, &BackendWorker::readConfigurationFile);
connect(this, &RobotClient::configurationFileValidateRequested,
m_worker, &BackendWorker::validateConfigurationFile);
connect(this, &RobotClient::configurationFileSaveRequested,
m_worker, &BackendWorker::saveConfigurationFile);
connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater);
m_thread.start();
}
@ -6025,7 +5590,6 @@ RobotClient::~RobotClient()
m_agvMapDirectThread.wait();
if (m_thread.isRunning()) {
QMetaObject::invokeMethod(m_worker, [this]() {
m_worker->disconnectConfigurationServer();
m_worker->disconnectFromServer();
}, Qt::BlockingQueuedConnection);
}
@ -6359,20 +5923,15 @@ void RobotClient::requestAgvInventory(const QString &deviceId)
emit agvInventoryRequested(deviceId);
}
void RobotClient::configureAgvMapDirect(bool enabled, const QString &vehicleHost,
const QString &configHost, int configPort)
void RobotClient::configureAgvMapDirect(bool enabled, const QString &vehicleHost)
{
const QString host = vehicleHost.trimmed();
const QString configurationHost = configHost.trimmed();
if (m_agvMapDirectEnabled == enabled && m_agvMapDirectHost == host
&& m_agvMapDirectConfigHost == configurationHost
&& m_agvMapDirectConfigPort == configPort)
)
return;
cancelAgvMapDirect();
m_agvMapDirectEnabled = enabled;
m_agvMapDirectHost = host;
m_agvMapDirectConfigHost = configurationHost;
m_agvMapDirectConfigPort = configPort;
}
void RobotClient::cancelAgvMapDirectRequests()
@ -6441,8 +6000,6 @@ void RobotClient::requestAgvMapDirect(DirectMapOperation operation, quint64 requ
return;
}
const QString vehicleHost = m_agvMapDirectHost;
const QString configHost = m_agvMapDirectConfigHost;
const int configPort = m_agvMapDirectConfigPort;
const QString id = deviceId.trimmed();
const QString map = mapName.trimmed();
m_agvMapDirectBusy = true;
@ -6452,8 +6009,7 @@ void RobotClient::requestAgvMapDirect(DirectMapOperation operation, quint64 requ
emit agvMapDirectBusyChanged(true);
interruptAgvManualVelocity();
if (!m_agvMapDirectEnabled || m_agvMapDirectDemo || m_agvMapDirectDevice != id
|| m_agvMapDirectHost != vehicleHost || m_agvMapDirectConfigHost != configHost
|| m_agvMapDirectConfigPort != configPort) {
|| m_agvMapDirectHost != vehicleHost) {
m_agvMapDirectBusy = false;
emit agvMapDirectBusyChanged(false);
reportFailure(QStringLiteral("地图直连上下文已变更,本次请求未发送"));
@ -6468,22 +6024,13 @@ void RobotClient::requestAgvMapDirect(DirectMapOperation operation, quint64 requ
m_agvMapDirectRequestMap = mapName;
const auto runDirect =
[this, operation, requestId, deviceId, mapName, content, generation, cancel,
vehicleHost, configHost, configPort, id, map]() {
vehicleHost, id, map]() {
SeerAgvMapConnection connection;
connection.host = vehicleHost;
connection.nickName = QStringLiteral("CMVRControlStation-map-%1").arg(id);
QString lookupError;
bool resolved = !connection.host.isEmpty();
#ifdef CMVR_WITH_GRPC
if (!resolved && !cancel->load())
resolved = resolveDirectMapConnection(configHost, configPort, id,
cancel, connection, lookupError);
#else
Q_UNUSED(configHost)
Q_UNUSED(configPort)
if (!resolved)
lookupError = QStringLiteral("当前程序未编译 gRPC 支持,请手动填写车辆 IP");
#endif
if (!resolved) lookupError = QStringLiteral("请填写车辆 IP 后再使用地图直连");
SeerAgvMapResult result;
if (cancel->load())
result.detail = QStringLiteral("地图直连操作已取消");
@ -6700,35 +6247,3 @@ void RobotClient::stopMicrophoneAudioStream()
{
emit microphoneAudioStreamStopRequested();
}
void RobotClient::connectConfigurationServer(const QString &host, int port)
{
emit configurationConnectRequested(host, port);
}
void RobotClient::disconnectConfigurationServer()
{
emit configurationDisconnectRequested();
}
void RobotClient::requestConfigurationFiles()
{
emit configurationFilesRequested();
}
void RobotClient::readConfigurationFile(const QString &relativePath)
{
emit configurationFileReadRequested(relativePath);
}
void RobotClient::validateConfigurationFile(const QString &relativePath,
const QString &content)
{
emit configurationFileValidateRequested(relativePath, content);
}
void RobotClient::saveConfigurationFile(const QString &relativePath, const QString &content,
const QString &expectedRevision)
{
emit configurationFileSaveRequested(relativePath, content, expectedRevision);
}

View File

@ -17,6 +17,7 @@
#include "videoframe.h"
class DemoSimulator;
class BackendWorker;
class RobotClient : public QObject
@ -24,7 +25,8 @@ class RobotClient : public QObject
Q_OBJECT
public:
explicit RobotClient(QObject *parent = nullptr);
explicit RobotClient(QObject *parent = nullptr,std::shared_ptr<DemoSimulator> simulator={});
std::shared_ptr<DemoSimulator> simulator()const{return m_simulator;}
~RobotClient() override;
bool grpcAvailable() const;
@ -108,8 +110,7 @@ public slots:
void cancelAgvManualVelocity();
void requestAgvAction(const QString &deviceId, const QString &action);
void requestAgvInventory(const QString &deviceId);
void configureAgvMapDirect(bool enabled, const QString &vehicleHost,
const QString &configHost, int configPort);
void configureAgvMapDirect(bool enabled, const QString &vehicleHost);
void cancelAgvMapDirectRequests();
void requestAgvSwitchMap(const QString &deviceId, const QString &mapName);
void requestAgvMapContent(quint64 requestId, const QString &deviceId,
@ -128,13 +129,6 @@ public slots:
void stopSpeakerAudioStream();
void startMicrophoneAudioStream(const QString &deviceId);
void stopMicrophoneAudioStream();
void connectConfigurationServer(const QString &host, int port);
void disconnectConfigurationServer();
void requestConfigurationFiles();
void readConfigurationFile(const QString &relativePath);
void validateConfigurationFile(const QString &relativePath, const QString &content);
void saveConfigurationFile(const QString &relativePath, const QString &content,
const QString &expectedRevision);
signals:
void torqueFinished(const QString& deviceId,bool enabled,bool success,const QString& detail);
@ -245,15 +239,6 @@ signals:
void speakerAudioStreamStopRequested();
void microphoneAudioStreamStartRequested(const QString &deviceId);
void microphoneAudioStreamStopRequested();
void configurationConnectRequested(const QString &host, int port);
void configurationDisconnectRequested();
void configurationFilesRequested();
void configurationFileReadRequested(const QString &relativePath);
void configurationFileValidateRequested(const QString &relativePath,
const QString &content);
void configurationFileSaveRequested(const QString &relativePath, const QString &content,
const QString &expectedRevision);
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.
@ -320,16 +305,6 @@ signals:
quint64 bytes, qint64 durationMs);
void audioFrameReceived(const QByteArray &data, int sampleRate, int channels,
int format, const QString &codec, qint64 pts, int samples);
void configurationConnectionChanged(bool connected, const QString &detail);
void configurationFilesReceived(const QString &configRoot, const QVariantList &files,
bool success, const QString &detail);
void configurationFileReceived(const QString &relativePath, const QString &content,
const QString &revision, const QString &messageType,
bool success, const QString &detail);
void configurationValidationFinished(const QString &relativePath, bool success,
const QString &detail);
void configurationSaveFinished(const QString &relativePath, const QString &revision,
bool success, const QString &detail);
void commandFinished(const QString &command, bool success, const QString &detail);
void logMessage(const QString &level, const QString &message);
@ -351,8 +326,6 @@ private:
bool m_agvMapDirectDemo = true;
bool m_agvMapDirectBusy = false;
QString m_agvMapDirectHost;
QString m_agvMapDirectConfigHost;
int m_agvMapDirectConfigPort = 50053;
QString m_agvMapDirectDevice;
quint64 m_agvMapDirectGeneration = 0;
std::shared_ptr<std::atomic<bool>> m_agvMapDirectCancel;
@ -361,6 +334,7 @@ private:
QString m_agvMapDirectRequestDevice;
QString m_agvMapDirectRequestMap;
QThread m_thread;
std::shared_ptr<DemoSimulator> m_simulator;
BackendWorker *m_worker = nullptr;
std::atomic<quint64> m_agvMapStreamGeneration{0};
QMutex m_videoFrameMutex;

View File

@ -4,6 +4,7 @@
#include "ui_rpcservicewidget.h"
#include <QComboBox>
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
@ -115,7 +116,7 @@ RpcServiceWidget::RpcServiceWidget(const QString &serviceName, RobotClient *clie
this, &RpcServiceWidget::handleResult);
connect(m_client, &RobotClient::connectionChanged, this,
[this](bool connected, int, const QString &) {
m_ui->executeButton->setEnabled(connected && m_ui->methodCombo->count() > 0);
m_ui->executeButton->setEnabled(connected && m_methodAvailable);
});
updateMethod();
}
@ -165,6 +166,14 @@ void RpcServiceWidget::updateMethod()
m_serviceName.toStdString());
const google::protobuf::MethodDescriptor *method =
service ? service->FindMethodByName(methodName.toStdString()) : nullptr;
m_methodAvailable = method && method->input_type() && method->output_type();
if (!m_methodAvailable) {
m_ui->methodDetailLabel->setText(QStringLiteral("接口定义不完整,当前不可用"));
m_ui->executeButton->setEnabled(false);
m_ui->requestEdit->clear();
qWarning() << "[RPC descriptor unavailable]" << m_serviceName << methodName;
return;
}
if (method) {
QString mode = QStringLiteral("Unary RPC");
if (method->client_streaming() && method->server_streaming())
@ -196,7 +205,7 @@ void RpcServiceWidget::resetRequest()
void RpcServiceWidget::executeRequest()
{
const QString methodName = m_ui->methodCombo->currentData().toString();
if (methodName.isEmpty())
if (methodName.isEmpty() || !m_methodAvailable)
return;
m_pendingMethod = methodName;
m_ui->executeButton->setEnabled(false);

View File

@ -33,4 +33,5 @@ private:
RobotClient *m_client = nullptr;
QString m_serviceName;
QString m_pendingMethod;
bool m_methodAvailable = false;
};

View File

@ -6,8 +6,8 @@
#include <QJsonDocument>
#include <QJsonArray>
TaskDeviceOptions::TaskDeviceOptions(RobotClient* client,TaskOrchestrationWidget* target,QObject* parent)
:QObject(parent),m_runner(new TaskRpcRunner(client,this)),m_target(target){
TaskDeviceOptions::TaskDeviceOptions(RobotClient* client,TaskOrchestrationWidget* target,QObject* parent,const QString& robotId)
:QObject(parent),m_runner(new TaskRpcRunner(client,this)),m_target(target),m_robotId(robotId){
connect(client,&RobotClient::connectionChanged,this,[this](bool connected,int,const QString&){
if(!connected){++m_epoch;m_queue.clear();m_pending.clear();m_runner->cancel();}
});
@ -55,7 +55,7 @@ void TaskDeviceOptions::next(){
guard->m_pending.remove(q.id+":"+q.method);
QString detail;
if(guard->m_target&&TaskApi::responseSucceeded(ok,response,detail))
guard->m_target->setDeviceInfo(q.id,decode(q.method,QJsonDocument::fromJson(response.toUtf8()).object()));
guard->m_target->setRobotDeviceInfo(guard->m_robotId,q.id,decode(q.method,QJsonDocument::fromJson(response.toUtf8()).object()));
}
guard->next();
});

View File

@ -11,7 +11,7 @@ class TaskOrchestrationWidget;
// Read-only discovery, separate from the task execution runner.
class TaskDeviceOptions final : public QObject {
public:
TaskDeviceOptions(RobotClient*,TaskOrchestrationWidget*,QObject* parent=nullptr);
TaskDeviceOptions(RobotClient*,TaskOrchestrationWidget*,QObject* parent=nullptr,const QString& robotId="current");
void load(const QString& deviceId,const QString& type);
static QVariantMap decode(const QString& method,const QJsonObject& response);
private:
@ -23,4 +23,5 @@ private:
QSet<QString> m_pending;
bool m_busy=false;
quint64 m_epoch=0;
QString m_robotId;
};

View File

@ -3,6 +3,11 @@
#include <QTableWidget>
#include <QHeaderView>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QTimer>
#include <QEvent>
#include <functional>
#include <QLabel>
#include <QLineEdit>
#include <QDoubleValidator>
@ -17,16 +22,19 @@ public:
explicit TaskJointEditor(QWidget* parent=nullptr):QWidget(parent) {
auto* layout=new QVBoxLayout(this);layout->setContentsMargins(0,0,0,0);
m_hint=new QLabel(this);m_hint->setWordWrap(true);layout->addWidget(m_hint);
m_table=new QTableWidget(0,3,this);m_table->setObjectName("taskJointTable");
m_table->setHorizontalHeaderLabels({QStringLiteral("关节名称"),QStringLiteral("目标角度(°)"),QStringLiteral("允许范围(°)")});
m_table=new QTableWidget(0,1,this);m_table->setObjectName("taskJointTable");
m_table->setHorizontalHeaderLabels({QStringLiteral("关节目标(°)")});
m_table->verticalHeader()->hide();m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
m_table->horizontalHeader()->setSectionResizeMode(0,QHeaderView::ResizeToContents);
m_table->horizontalHeader()->setSectionResizeMode(2,QHeaderView::ResizeToContents);
m_table->setShowGrid(false);
m_table->setStyleSheet("QTableWidget#taskJointTable::item { padding: 0px; }");
m_table->viewport()->installEventFilter(this);
m_table->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_table->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_table->setTextElideMode(Qt::ElideNone);
m_table->setMinimumHeight(150);m_table->setMaximumHeight(400);layout->addWidget(m_table);
m_table->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Fixed);layout->addWidget(m_table);
}
void setDevice(const QVariantMap& info,const QJsonArray& values={},bool checkLimits=true) {
m_checkLimits=checkLimits;m_table->setHorizontalHeaderLabels({QStringLiteral("关节名称"),checkLimits?QStringLiteral("目标角度(°)"):QStringLiteral("目标角速度(°/秒)"),checkLimits?QStringLiteral("允许范围(°)"):QStringLiteral("单位")});
m_checkLimits=checkLimits;m_table->setHorizontalHeaderLabels({checkLimits?QStringLiteral("逐关节目标角度(°)"):QStringLiteral("逐关节目标角速度(°/秒)")});
m_info=info;m_names=info.value("jointNames").toStringList();
// A server DOF is valid metadata; never guess six or seven axes.
if(m_names.isEmpty())for(int i=0;i<info.value("dof").toInt();++i)m_names<<QStringLiteral("关节 %1").arg(i+1);
@ -37,18 +45,27 @@ public:
QStringLiteral("逐关节填写角速度;保存时换算为弧度/秒。")));
if(mismatched)m_hint->setText(QStringLiteral("原目标数量与设备关节数不一致,请按当前关节列表重新填写。"));
for(int i=0;i<m_names.size();++i){
auto* name=new QTableWidgetItem(m_names[i]);name->setFlags(Qt::ItemIsEnabled);name->setToolTip(m_names[i]);m_table->setItem(i,0,name);
auto* edit=new QLineEdit(m_table);edit->setObjectName(QString("jointTarget_%1").arg(i));
auto* row=new QWidget(m_table);
auto* rowLayout=new QGridLayout(row);rowLayout->setContentsMargins(8,8,8,8);rowLayout->setHorizontalSpacing(8);rowLayout->setVerticalSpacing(4);
rowLayout->setColumnStretch(0,3);rowLayout->setColumnStretch(1,2);
QString displayName=m_names[i];displayName.replace("_",QString::fromUtf8("_\xE2\x80\x8B"));
auto* name=new QLabel(displayName,row);name->setTextFormat(Qt::PlainText);name->setWordWrap(true);name->setToolTip(m_names[i]);
name->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Preferred);rowLayout->addWidget(name,0,0);
auto* edit=new QLineEdit(row);edit->setObjectName(QString("jointTarget_%1").arg(i));
edit->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);edit->setMinimumWidth(72);
edit->setProperty("taskJointName",m_names[i]);
edit->setValidator(new QDoubleValidator(-1e12,1e12,9,edit));edit->setPlaceholderText(QStringLiteral("输入角度"));
if(!mismatched&&i<values.size()&&values[i].isDouble())edit->setText(QString::number(qRadiansToDegrees(values[i].toDouble()),'g',12));
m_table->setCellWidget(i,1,edit);m_edits<<edit;m_table->setRowHeight(i,44);
rowLayout->addWidget(edit,0,1);m_edits<<edit;
const auto limit=info.value("jointLimits").toMap().value(m_names[i]).toMap();
auto* range=new QTableWidgetItem(limit.isEmpty()?QStringLiteral("设备未提供"):
QStringLiteral("%1 ~ %2").arg(qRadiansToDegrees(limit.value("lower").toDouble()),0,'f',2).arg(qRadiansToDegrees(limit.value("upper").toDouble()),0,'f',2));
range->setFlags(Qt::ItemIsEnabled);if(!checkLimits)range->setText(QStringLiteral("角度/秒 → 弧度/秒"));m_table->setItem(i,2,range);
if(!limit.isEmpty()&&checkLimits) {
const QString range=QStringLiteral("%1 ~ %2°").arg(qRadiansToDegrees(limit.value("lower").toDouble()),0,'f',1).arg(qRadiansToDegrees(limit.value("upper").toDouble()),0,'f',1);
auto* rangeLabel=new QLabel(range,row);rangeLabel->setObjectName(QStringLiteral("mutedLabel"));rangeLabel->setToolTip(QStringLiteral("允许范围:")+range);
rangeLabel->setWordWrap(true);rowLayout->addWidget(rangeLabel,1,0,1,2);
}
m_table->setCellWidget(i,0,row);
}
m_table->setMinimumHeight(qMin(400,qMax(150,44*m_names.size()+42)));
fitRows();queueFit();
}
bool values(QJsonArray& result,QString& error) const {
result={};if(m_names.isEmpty()){error=QStringLiteral("请先获取所选设备的关节信息。");return false;}
@ -61,6 +78,30 @@ public:
}return true;
}
QJsonArray draft() const {QJsonArray out;for(auto* edit:m_edits){bool ok;const auto n=edit->text().toDouble(&ok);out.append(ok?QJsonValue(qDegreesToRadians(n)):QJsonValue());}return out;}
void setLayoutChangedHandler(std::function<void()> handler){m_layoutChanged=std::move(handler);}
protected:
bool eventFilter(QObject* watched,QEvent* event)override {
if(watched==m_table->viewport()&&event->type()==QEvent::Resize)queueFit();
return QWidget::eventFilter(watched,event);
}
void changeEvent(QEvent* event)override {
QWidget::changeEvent(event);
if(m_table&&(event->type()==QEvent::FontChange||event->type()==QEvent::StyleChange))queueFit();
}
private:
QLabel* m_hint;QTableWidget* m_table;QStringList m_names;QList<QLineEdit*> m_edits;QVariantMap m_info;bool m_checkLimits=true;
void queueFit(){if(m_fitPending)return;m_fitPending=true;QTimer::singleShot(0,this,[this]{m_fitPending=false;fitRows();});}
void fitRows(){
int height=m_table->horizontalHeader()->height()+2*m_table->frameWidth();
const int width=qMax(100,m_table->columnWidth(0));
for(int i=0;i<m_table->rowCount();++i)if(auto* row=m_table->cellWidget(i,0)){
const int preferred=row->layout()->heightForWidth(width);
const int rowHeight=qMax(row->minimumSizeHint().height(),preferred<0?row->sizeHint().height():preferred)+2;
m_table->setRowHeight(i,rowHeight);height+=rowHeight;
}
height=qMax(60,height);
if(m_table->height()!=height){m_table->setFixedHeight(height);updateGeometry();if(m_layoutChanged)m_layoutChanged();}
}
bool m_fitPending=false;
std::function<void()> m_layoutChanged;
QLabel* m_hint=nullptr;QTableWidget* m_table=nullptr;QStringList m_names;QList<QLineEdit*> m_edits;QVariantMap m_info;bool m_checkLimits=true;
};

View File

@ -60,7 +60,7 @@
namespace {
enum Roles { KindRole = Qt::UserRole, DeviceTypeRole, DeviceIdRole, ActionRole,
ParametersRole, WaitRole, WaitUnitRole, LoopCountRole, RunStateRole, CollapsedRole, NodeIdRole };
ParametersRole, WaitRole, WaitUnitRole, LoopCountRole, RunStateRole, CollapsedRole, NodeIdRole, RobotIdRole };
void restoreTaskExpansion(QTreeWidgetItem *item)
{
@ -92,7 +92,7 @@ public:
{
setFlags(ItemIsMovable | ItemIsSelectable | ItemSendsGeometryChanges);
setToolTip(title + QStringLiteral("\n") + subtitle
+ (loop ? QStringLiteral("\n右上角折叠;选中后点击“进入所选循环”可添加子节点") : QString()));
+ (loop ? QStringLiteral("\n点击右上角箭头展开/收起循环;展开后自动聚焦循环内容") : QString()));
setAcceptHoverEvents(true);
setCursor(Qt::OpenHandCursor);
setZValue(2);
@ -106,11 +106,10 @@ public:
const QString state=m_source->data(0,RunStateRole).toString();
const QColor accent=state=="failed"?QColor("#e05b64"):state=="success"?QColor("#20a36a"):
state=="running"?QColor("#357dff"):m_loop?QColor("#a086d7"):QColor("#557799");
workflowCardPaint(painter,boundingRect(),m_title,m_subtitle,accent,isSelected(),m_loop?25:0,
workflowCardPaint(painter,boundingRect(),m_title,m_subtitle,accent,isSelected(),m_loop?36:0,
m_loop?QStringLiteral("loop"):workflowDeviceIcon(m_source->data(0,DeviceTypeRole).toString()));
if(m_loop) {
painter->setPen(QColor("#73849a"));
painter->drawText(toggleRect(),Qt::AlignCenter,m_source->isExpanded()?QStringLiteral("−"):QStringLiteral("+"));
workflowCollapseButton(painter,toggleRect(),m_source->isExpanded(),m_toggleHovered,m_buttonPress);
}
}
protected:
@ -121,7 +120,7 @@ protected:
m_buttonPress = false;
if (m_loop && toggleRect().contains(event->pos())) {
m_buttonPress = true;
if (m_toggled) m_toggled(m_source);
update();
event->accept(); return;
}
setCursor(Qt::ClosedHandCursor);
@ -132,7 +131,11 @@ protected:
{
setCursor(Qt::OpenHandCursor);
m_dragging = false;
if (m_buttonPress) { m_buttonPress = false; event->accept(); return; }
if (m_buttonPress) {
m_buttonPress=false;update();
if(toggleRect().contains(event->pos())&&m_toggled)m_toggled(m_source);
event->accept();return;
}
QGraphicsItem::mouseReleaseEvent(event);
if ((event->screenPos() - m_startMouse).manhattanLength() >= QApplication::startDragDistance()) {
if (m_moved) m_moved(m_source, pos());
@ -144,6 +147,15 @@ protected:
if (m_edited) m_edited(m_source);
event->accept();
}
void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override {
const bool over=m_loop&&toggleRect().contains(event->pos());
if(over!=m_toggleHovered){m_toggleHovered=over;update();}
setCursor(over?Qt::PointingHandCursor:Qt::OpenHandCursor);
QGraphicsItem::hoverMoveEvent(event);
}
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override {
m_toggleHovered=false;setCursor(Qt::OpenHandCursor);update();QGraphicsItem::hoverLeaveEvent(event);
}
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override
{
if (change == ItemPositionChange && m_dragging) {
@ -153,7 +165,7 @@ protected:
}
private:
QRectF toggleRect() const { return QRectF(kTaskCardWidth - 35, 10, 22, 22); }
QRectF toggleRect() const { return QRectF(kTaskCardWidth - 44, 18, 28, 28); }
QTreeWidgetItem *m_source = nullptr;
QString m_title, m_subtitle;
bool m_loop = false;
@ -163,6 +175,7 @@ private:
QPointF m_startPos;
QPoint m_startMouse;
bool m_buttonPress = false;
bool m_toggleHovered = false;
bool m_dragging = false;
};
@ -285,8 +298,9 @@ QString deviceTypeName(int type)
case 3: return QStringLiteral("灵巧手");
case 7: return QStringLiteral("扬声器");
case 5: return QStringLiteral("麦克风");
case 8: return QStringLiteral("仿生头");
case 9: case 10: return QStringLiteral("电机");
case 8: return QStringLiteral("触摸设备");
case 9: return QStringLiteral("仿生头");
case 10: case 11: return QStringLiteral("电机");
default: return QStringLiteral("通用RPC");
}
}
@ -516,7 +530,7 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare
const auto info=TaskApi::definition(service,method);if(info.isEmpty())return;
const QString action=QStringLiteral("接口 · ")+method;
QString deviceId;
for(const auto &device:m_availableDevices) {
for(const auto &device:devicesForRobot(m_selectedRobotId)) {
const auto entry=device.toMap();
if(deviceTypeName(entry.value("type").toInt())==type){deviceId=entry.value("deviceId").toString();break;}
}
@ -524,7 +538,7 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare
QJsonObject params{{"service",service},{"method",method},{"request",QJsonObject{}},{"timeoutMs",info.value("defaultTimeoutMs").toInt(180000)}};
QTreeWidgetItem *item=new QTreeWidgetItem;item->setFlags(item->flags()&~Qt::ItemIsDropEnabled);
item->setData(0,NodeIdRole,QUuid::createUuid().toString(QUuid::WithoutBraces));
item->setData(0,KindRole,"task");item->setData(0,DeviceTypeRole,type);item->setData(0,DeviceIdRole,deviceId);item->setData(0,ActionRole,action);
item->setData(0,KindRole,"task");item->setData(0,RobotIdRole,m_selectedRobotId);item->setData(0,DeviceTypeRole,type);item->setData(0,DeviceIdRole,deviceId);item->setData(0,ActionRole,action);
item->setData(0,ParametersRole,QString::fromUtf8(QJsonDocument(params).toJson(QJsonDocument::Compact)));
item->setData(0,WaitRole,0);item->setData(0,WaitUnitRole,"ms");
item->setText(0,TaskUi::text("operations",method));item->setText(1,type);item->setText(2,type);item->setText(3,deviceId);item->setText(4,action);item->setText(5,"0 ms");
@ -559,6 +573,11 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare
});
static_cast<WorkflowCanvas *>(m_flowView)->componentDropped = createComponent;
auto *taskCanvas=static_cast<WorkflowCanvas *>(m_flowView);
taskCanvas->undoRequested=[this]{restoreHistory(false);};
taskCanvas->redoRequested=[this]{restoreHistory(true);};
taskCanvas->canUndo=[this]{return m_editHistory.canUndo();};
taskCanvas->canRedo=[this]{return m_editHistory.canRedo();};
taskCanvas->nodeDeletionRequested=[this]{removeSelected();};
taskCanvas->copyNodes=[this](const QSet<QString> &ids) {
auto part=WorkflowGraph::fragment(m_graph,ids);
if(part.value("nodes").toArray().isEmpty())return QJsonObject();
@ -584,10 +603,12 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare
save();return true;
};
static_cast<WorkflowCanvas *>(m_flowView)->connectionRemoved=[this](const QString &from,const QString &to) {
if(!m_runSteps.isEmpty())return;WorkflowGraph::disconnect(m_graph,from,to);save();
if(!m_runSteps.isEmpty())return;recordHistory();WorkflowGraph::disconnect(m_graph,from,to);save();
};
auto *inspector = new QWidget(workspace);
inspector->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Preferred);
auto *inspectorLayout = new QVBoxLayout(inspector);
inspectorLayout->setSizeConstraint(QLayout::SetNoConstraint);
auto *inspectorTitle = new QLabel(QStringLiteral("节点参数"), inspector);
inspectorTitle->setObjectName(QStringLiteral("sectionTitle"));
auto *nodeName = new QLineEdit(inspector);
@ -595,38 +616,61 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare
nodeSummary->setWordWrap(true); nodeSummary->setTextFormat(Qt::PlainText);
auto *applyName = new QPushButton(QStringLiteral("保存节点参数"), inspector);
auto *rpcEditor = new TaskProtoEditor(inspector);
auto *nodeDevice = new QComboBox(inspector);
auto* executionSettings=new QGroupBox(QStringLiteral("执行设置"),inspector);
auto* executionLayout=new QVBoxLayout(executionSettings);
executionLayout->setContentsMargins(10,16,10,10);executionLayout->setSpacing(7);
auto* robotLabel=new QLabel(QStringLiteral("由谁执行"),executionSettings);
auto* nodeRobot=new QComboBox(executionSettings);nodeRobot->setObjectName("workflowNodeRobot");configureComboPopup(nodeRobot);
auto* deviceLabel=new QLabel(QStringLiteral("使用设备"),executionSettings);
auto *nodeDevice = new QComboBox(executionSettings);
executionLayout->addWidget(robotLabel);executionLayout->addWidget(nodeRobot);executionLayout->addSpacing(3);executionLayout->addWidget(deviceLabel);executionLayout->addWidget(nodeDevice);
auto* manageRobots=new QPushButton(QStringLiteral("机器人管理"),panel);groups->addWidget(manageRobots);
connect(manageRobots,&QPushButton::clicked,this,&TaskOrchestrationWidget::manageRobotsRequested);m_editControls<<manageRobots;
nodeDevice->setObjectName(QStringLiteral("workflowNodeDevice"));
configureComboPopup(nodeDevice);
auto *timeout = new QSpinBox(inspector);timeout->setRange(1,1800000);timeout->setSuffix(QStringLiteral(" ms"));
auto *wait = new QSpinBox(inspector);wait->setRange(0,2147483647);wait->setSuffix(QStringLiteral(" ms"));
auto *loopCount = new QSpinBox(inspector);loopCount->setRange(1,100000);
auto *parameterForm=new QFormLayout;
parameterForm->addRow(QStringLiteral("执行设备"),nodeDevice);
parameterForm->setRowWrapPolicy(QFormLayout::WrapLongRows);
parameterForm->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
parameterForm->addRow(QStringLiteral("循环次数"),loopCount);
parameterForm->addRow(QStringLiteral("接口超时"),timeout);
parameterForm->addRow(QStringLiteral("完成后等待"),wait);
inspectorLayout->addWidget(inspectorTitle); inspectorLayout->addWidget(nodeName);
inspectorLayout->addWidget(nodeSummary);inspectorLayout->addLayout(parameterForm);inspectorLayout->addWidget(rpcEditor); inspectorLayout->addWidget(applyName);
inspectorLayout->addStretch();
const auto updateInspector = [this,nodeName,nodeSummary,applyName,rpcEditor,nodeDevice,timeout,wait,loopCount,parameterForm] {
inspectorLayout->addWidget(inspectorTitle);inspectorLayout->addWidget(nodeName);inspectorLayout->addWidget(nodeSummary);
inspectorLayout->addWidget(executionSettings);inspectorLayout->addLayout(parameterForm);
auto* parameterScroll=new QScrollArea(inspector);parameterScroll->setObjectName("workflowParameterScroll");parameterScroll->setWidgetResizable(true);
parameterScroll->setFrameShape(QFrame::NoFrame);parameterScroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);parameterScroll->setMinimumHeight(120);parameterScroll->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Ignored);
parameterScroll->setWidget(rpcEditor);inspectorLayout->addWidget(parameterScroll,1);inspectorLayout->addWidget(applyName);
const auto updateInspector = [this,nodeName,nodeSummary,applyName,rpcEditor,parameterScroll,nodeDevice,nodeRobot,executionSettings,timeout,wait,loopCount,parameterForm] {
auto *item=m_tree->currentItem();QString selected;
for(auto *graphic:m_flowScene->selectedItems())if(graphic->data(7000)=="sleep")selected=graphic->data(0).toString();
const auto extra=WorkflowGraph::node(m_graph,selected);const bool sleep=!selected.isEmpty();
nodeName->setProperty("sleepId",selected);
nodeName->setText(item ? item->text(0) : QString());
nodeSummary->setText(item ? QStringLiteral("类型:%1\n设备:%2\n操作:%3\n等待:%4")
.arg(item->text(1),item->text(3),TaskUi::operationTitle(item->data(0,DeviceTypeRole).toString(),item->text(4)),item->text(5)) : QStringLiteral("选择画布节点查看参数"));
nodeSummary->setText(item ? QStringLiteral("%1 · %2")
.arg(item->data(0,DeviceTypeRole).toString(),TaskUi::operationTitle(item->data(0,DeviceTypeRole).toString(),item->data(0,ActionRole).toString())) : QStringLiteral("选择画布节点查看参数"));
if(sleep){nodeName->setText(extra.value("properties").toObject().value("name").toString());nodeSummary->setText(QStringLiteral("等待节点 · 时长(毫秒)"));}
const bool editable=(item||sleep) && m_runSteps.isEmpty();
nodeName->setEnabled(editable);applyName->setEnabled(editable);
const bool loop=item&&item->data(0,KindRole)=="loop";
if(loop)nodeSummary->setText(QStringLiteral("循环控制\n本轮内部所有分支完成后,进入下一轮。"));
const QString robot=item?item->data(0,RobotIdRole).toString():m_selectedRobotId;
const QString robotId=robot.isEmpty()?QStringLiteral("current"):robot;
if(item)m_selectedRobotId=robotId;
{
const QSignalBlocker blocker(nodeRobot);nodeRobot->clear();
if(m_robots.isEmpty())nodeRobot->addItem(QStringLiteral("主界面机器人"),"current");
for(const auto& value:m_robots){const auto r=value.toMap();nodeRobot->addItem(r.value("name").toString()+(r.value("connected").toBool()?QString():QStringLiteral(" · 未连接")),r.value("id"));}
int index=nodeRobot->findData(robotId);if(index<0){nodeRobot->addItem(QStringLiteral("未绑定机器人 · ")+robotId,robotId);index=nodeRobot->count()-1;}nodeRobot->setCurrentIndex(index);
}
executionSettings->setVisible(item&&!loop);nodeRobot->setEnabled(editable);
{
const QSignalBlocker deviceBlocker(nodeDevice);
nodeDevice->clear();
if(item&&!loop) {
const QString requiredType=item->data(0,DeviceTypeRole).toString();
for(const QVariant &value:m_availableDevices) {
for(const QVariant &value:devicesForRobot(robotId)) {
const QVariantMap device=value.toMap();
if(deviceTypeName(device.value(QStringLiteral("type")).toInt())!=requiredType)continue;
const QString id=device.value(QStringLiteral("deviceId")).toString();
@ -638,15 +682,37 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare
}
}
nodeDevice->setVisible(item&&!loop);
parameterForm->labelForField(nodeDevice)->setVisible(item&&!loop);
nodeDevice->setEnabled(editable&&!nodeDevice->currentText().isEmpty());
loopCount->setVisible(loop);parameterForm->labelForField(loopCount)->setVisible(loop);loopCount->setValue(loop?item->data(0,LoopCountRole).toInt():1);
const auto params=item?QJsonDocument::fromJson(item->data(0,ParametersRole).toString().toUtf8()).object():QJsonObject();
const bool rpc=item&&!loop&&params.contains("service")&&params.contains("method");
rpcEditor->setVisible(rpc);timeout->setVisible(rpc);parameterForm->labelForField(timeout)->setVisible(rpc);
rpcEditor->setVisible(rpc);parameterScroll->setVisible(rpc);timeout->setVisible(rpc);parameterForm->labelForField(timeout)->setVisible(rpc);
rpcEditor->setProperty("service",rpc?params.value("service").toString():QString());
rpcEditor->setProperty("method",rpc?params.value("method").toString():QString());
if(rpc){rpcEditor->setDeviceContext(deviceInfo(item->data(0,DeviceIdRole).toString()));rpcEditor->setOperation(params.value("service").toString(),params.value("method").toString(),params.value("request").toObject());}
if(rpc){
const QString binding=item->data(0,NodeIdRole).toString()+"/"+robotId+"/"+item->data(0,DeviceIdRole).toString()+"/"+params.value("service").toString()+"/"+params.value("method").toString();
const auto context=robotDeviceInfo(robotId,item->data(0,DeviceIdRole).toString());
const auto request=params.value("request").toObject();
const bool sameBinding=rpcEditor->property("inspectorBinding").toString()==binding;
bool connected=false;for(const auto& value:m_robots)if(value.toMap().value("id")==robotId)connected=value.toMap().value("connected").toBool();
const bool wasConnected=rpcEditor->property("inspectorConnected").toBool();rpcEditor->setProperty("inspectorConnected",connected);
const bool sameRequest=rpcEditor->property("inspectorRequest").toJsonObject()==request;
if(!sameBinding||!sameRequest||rpcEditor->property("inspectorContext").toMap()!=context) {
// Polling must not replace an active form or discard partial input.
const auto draft=sameBinding&&sameRequest?rpcEditor->inputState():QVariantMap();
rpcEditor->setDeviceContext(context);
rpcEditor->setOperation(params.value("service").toString(),params.value("method").toString(),request);
if(!draft.isEmpty())rpcEditor->restoreInputState(draft);
rpcEditor->setProperty("inspectorBinding",binding);
rpcEditor->setProperty("inspectorRequest",request);
rpcEditor->setProperty("inspectorContext",context);
}
if(connected&&(!sameBinding||!wasConnected)&&!item->data(0,DeviceIdRole).toString().isEmpty())emit robotDeviceInfoRequested(robotId,item->data(0,DeviceIdRole).toString(),item->data(0,DeviceTypeRole).toString());
for(auto *form:rpcEditor->findChildren<QFormLayout*>()) {
form->setRowWrapPolicy(QFormLayout::WrapLongRows);
form->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
}
}
timeout->setValue(params.value("timeoutMs").toInt(180000));
wait->setValue(item?WorkflowGraph::postWait(m_graph,item->data(0,NodeIdRole).toString()):0);
if(sleep)wait->setValue(WorkflowGraph::delay(extra));
@ -656,12 +722,27 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare
connect(m_tree,&QTreeWidget::currentItemChanged,this,[updateInspector](QTreeWidgetItem*,QTreeWidgetItem*){updateInspector();});
connect(m_tree->model(),&QAbstractItemModel::dataChanged,this,[updateInspector]{updateInspector();});
connect(this,&TaskOrchestrationWidget::availableDevicesChanged,this,updateInspector);
connect(this,&TaskOrchestrationWidget::robotsChanged,this,updateInspector);
connect(this,&TaskOrchestrationWidget::robotDeviceInfoChanged,this,[this,updateInspector](const QString& robot,const QString& device){auto* item=m_tree->currentItem();if(item&&item->data(0,RobotIdRole).toString()==robot&&item->data(0,DeviceIdRole).toString()==device)updateInspector();});
connect(nodeRobot,QOverload<int>::of(&QComboBox::currentIndexChanged),this,[this,nodeRobot,updateInspector](int index){
auto* item=m_tree->currentItem();if(!item||index<0||!m_runSteps.isEmpty())return;
const QString robot=nodeRobot->currentData().toString();if(item->data(0,RobotIdRole).toString()==robot)return;
recordHistory();m_selectedRobotId=robot;
const QString required=item->data(0,DeviceTypeRole).toString();QString device;
for(const auto& value:devicesForRobot(robot)){auto d=value.toMap();if(deviceTypeName(d.value("type").toInt())==required){device=d.value("deviceId").toString();break;}}
{const QSignalBlocker blocker(m_tree->model());item->setData(0,RobotIdRole,robot);item->setData(0,DeviceIdRole,device);item->setText(3,device);
auto params=QJsonDocument::fromJson(item->data(0,ParametersRole).toString().toUtf8()).object();params.insert("request",QJsonObject());item->setData(0,ParametersRole,QString::fromUtf8(QJsonDocument(params).toJson(QJsonDocument::Compact)));}
updateInspector();save();
});
connect(this,&TaskOrchestrationWidget::deviceInfoChanged,this,[this,updateInspector](const QString& id){
auto* item=m_tree->currentItem();
if(item&&item->data(0,DeviceIdRole).toString()==id)updateInspector();
});
connect(nodeDevice,QOverload<int>::of(&QComboBox::currentIndexChanged),this,[this,nodeDevice,updateInspector](int index) {
auto *item=m_tree->currentItem();
if(!item||index<0||item->data(0,KindRole)=="loop"||!m_runSteps.isEmpty())return;
const QString id=nodeDevice->currentText().trimmed();if(id.isEmpty())return;
item->setData(0,DeviceIdRole,id);item->setText(3,id);
emit deviceInfoRequested(id,item->data(0,DeviceTypeRole).toString());
updateInspector();save();
});
connect(applyName,&QPushButton::clicked,this,[this,nodeName,rpcEditor,timeout,wait,loopCount] {
@ -685,18 +766,21 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare
if(WorkflowGraph::postWait(m_graph,item->data(0,NodeIdRole).toString())!=wait->value())WorkflowGraph::setWait(m_graph,item->data(0,NodeIdRole).toString(),wait->value());save();
});
updateInspector();
auto *inspectorScroll=new QScrollArea(workspace);inspectorScroll->setWidgetResizable(true);inspectorScroll->setFrameShape(QFrame::NoFrame);inspectorScroll->setWidget(inspector);inspector->setMinimumWidth(460);
inspectorScroll->setMinimumWidth(540);
inspectorScroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
auto *inspectorScroll=new QWidget(workspace);inspectorScroll->setObjectName("workflowInspectorSurface");
auto* inspectorSurfaceLayout=new QVBoxLayout(inspectorScroll);inspectorSurfaceLayout->setContentsMargins(0,0,0,0);inspectorSurfaceLayout->addWidget(inspector);
inspectorScroll->setMinimumWidth(280);
inspectorScroll->setMaximumWidth(520);
inspectorScroll->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Expanding);
inspectorScroll->setStyleSheet(QStringLiteral(
"QScrollArea{border:0;background:#f3f6fa;}"
"QWidget#workflowInspectorSurface{background:#f3f6fa;}QScrollArea{border:0;background:#f3f6fa;}"
"QScrollBar:vertical{width:8px;background:transparent;margin:4px 2px;}"
"QScrollBar::handle:vertical{min-height:28px;background:#c5d0df;border-radius:4px;}"
"QScrollBar::handle:vertical:hover{background:#91a5bd;}"
"QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;background:transparent;}"
"QScrollBar::add-page:vertical,QScrollBar::sub-page:vertical{background:transparent;}"));
workspace->addWidget(libraryPanel); workspace->addWidget(m_flowView); workspace->addWidget(inspectorScroll);
workspace->setStretchFactor(1,1); workspace->setSizes({270,1000,340});
workspace->setStretchFactor(0,0);workspace->setStretchFactor(1,1);workspace->setStretchFactor(2,0);
workspace->setSizes({260,1000,340});
workspace->setChildrenCollapsible(false);
layout->addWidget(workspace, 1);
m_editControls << libraryPanel << inspector;
@ -709,6 +793,14 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare
connect(toggle,&QPushButton::toggled,entry.second,&QWidget::setVisible);
if(entry.second==inspectorScroll) {
toggle->setChecked(false);inspectorScroll->hide();
connect(toggle,&QPushButton::toggled,this,[workspace,libraryPanel](bool visible) {
if(!visible)return;
QTimer::singleShot(0,workspace,[workspace,libraryPanel] {
const int left=libraryPanel->isVisible()?260:0;
const int width=workspace->width()-2*workspace->handleWidth();
workspace->setSizes({left,qMax(200,width-left-340),340});
});
});
connect(m_flowScene,&QGraphicsScene::selectionChanged,this,[this,toggle] {
if(!m_flowScene->selectedItems().isEmpty())toggle->setChecked(true);
});
@ -785,6 +877,7 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare
connect(m_stopButton, &QPushButton::clicked, this, [this]() { stopRun(QStringLiteral("已手动停止")); });
connect(m_runTimer, &QTimer::timeout, this, &TaskOrchestrationWidget::runNext);
load();
m_editHistory.reset(m_graph);static_cast<WorkflowCanvas*>(m_flowView)->refreshHistoryButtons();
if(!m_storageWritable)m_status->setText(QStringLiteral("任务文件读取/校验失败,原文件已保留,自动保存已禁用;可导出当前编辑内容或导入有效文件。"));
}
@ -844,10 +937,13 @@ bool TaskOrchestrationWidget::useSelectedLoopAsInsertionParent()
void TaskOrchestrationWidget::removeSelected()
{
if (!m_runSteps.isEmpty()) return;
QTreeWidgetItem *item = m_tree->currentItem();
if(!item){QString id;for(auto *graphic:m_flowScene->selectedItems())if(graphic->data(7000)=="sleep")id=graphic->data(0).toString();if(!id.isEmpty()){WorkflowGraph::removeNode(m_graph,id);save();}return;}
m_insertionParent = item->parent(); m_insertionIndex = -1;
WorkflowGraph::removeNode(m_graph,item->data(0,NodeIdRole).toString());delete item; save();
QSet<QString> ids;
for(auto* graphic:m_flowScene->selectedItems()){const QString id=graphic->data(7010).toString();const auto type=WorkflowGraph::node(m_graph,id).value("type").toString();if(!id.isEmpty()&&type!="start"&&type!="end"&&type!="subStart"&&type!="subEnd")ids.insert(id);}
if(ids.isEmpty()&&m_tree->currentItem())ids.insert(m_tree->currentItem()->data(0,NodeIdRole).toString());
if(ids.isEmpty())return;recordHistory();m_insertionParent=nullptr;m_insertionIndex=-1;
for(const auto& id:ids)WorkflowGraph::removeNode(m_graph,id);
std::function<void(QTreeWidgetItem*)> remove=[&](QTreeWidgetItem* parent){for(int i=parent->childCount()-1;i>=0;--i){auto* item=parent->child(i);if(ids.contains(item->data(0,NodeIdRole).toString()))delete item;else remove(item);}};
remove(m_tree->invisibleRootItem());save();
}
bool TaskOrchestrationWidget::appendCompiledSteps(const QJsonArray &nodes,
@ -926,7 +1022,7 @@ bool TaskOrchestrationWidget::prepareWorkflow(QHash<QString,QJsonObject> &execut
for(QTreeWidgetItemIterator it(m_tree);*it;++it) {
auto *item=*it;if(item->data(0,KindRole)!=QStringLiteral("task"))continue;
const auto parameters=QJsonDocument::fromJson(item->data(0,ParametersRole).toString().toUtf8()).object();
const auto execution=TaskApi::execution(item->data(0,DeviceTypeRole).toString(),item->data(0,ActionRole).toString(),item->data(0,DeviceIdRole).toString(),parameters);
auto execution=TaskApi::execution(item->data(0,DeviceTypeRole).toString(),item->data(0,ActionRole).toString(),item->data(0,DeviceIdRole).toString(),parameters);
if(execution.value("timeoutMs").toInt()<100||execution.value("timeoutMs").toInt()>1800000) {
error=QStringLiteral("接口超时应为100至1800000毫秒:")+item->text(0);return false;
}
@ -937,6 +1033,13 @@ bool TaskOrchestrationWidget::prepareWorkflow(QHash<QString,QJsonObject> &execut
if(item->data(0,DeviceIdRole).toString().isEmpty()||item->data(0,DeviceIdRole)==QStringLiteral("未绑定设备")) {
error=QStringLiteral("节点尚未绑定设备:")+item->text(0);return false;
}
const QString robot=item->data(0,RobotIdRole).toString().isEmpty()?QStringLiteral("current"):item->data(0,RobotIdRole).toString();
execution.insert("robotId",robot);
if(!m_robots.isEmpty()){
bool connected=false;for(const auto& v:m_robots)if(v.toMap().value("id")==robot)connected=v.toMap().value("connected").toBool();
bool present=false;for(const auto& v:devicesForRobot(robot))if(v.toMap().value("deviceId")==item->data(0,DeviceIdRole)&&deviceTypeName(v.toMap().value("type").toInt())==item->data(0,DeviceTypeRole).toString())present=true;
if(!connected||!present){error=QStringLiteral("节点“%1”的机器人未连接或设备不匹配").arg(item->text(0));return false;}
}
executions[item->data(0,NodeIdRole).toString()]=execution;
}
for(const auto &v:m_graph.value("nodes").toArray()) {
@ -959,6 +1062,7 @@ void TaskOrchestrationWidget::startRun()
m_history->clear();
for(auto *control:m_editControls)control->setEnabled(false);
m_flowView->setInteractive(false);m_runButton->setEnabled(false);m_stopButton->setEnabled(true);
static_cast<WorkflowCanvas*>(m_flowView)->refreshHistoryButtons();
m_status->setText(QStringLiteral("工作流运行中 · 分支并行,汇合等待全部前驱"));
m_runtime->nodeState=[this](const QString &id,const QString &state) {
for(QTreeWidgetItemIterator it(m_tree);*it;++it)if((*it)->data(0,NodeIdRole)==id)(*it)->setData(0,RunStateRole,state);
@ -1210,6 +1314,7 @@ void TaskOrchestrationWidget::stopRun(const QString &reason)
m_runTimer->stop(); m_runSteps.clear(); m_runIndex = 0; m_waitingForResult = false;
for (auto *control : m_editControls) control->setEnabled(true);
m_flowView->setInteractive(true);
static_cast<WorkflowCanvas*>(m_flowView)->refreshHistoryButtons();
m_runButton->setEnabled(true); m_stopButton->setEnabled(false);
m_status->setText(reason.isEmpty() ? QStringLiteral("未运行") : reason);
}
@ -1231,6 +1336,8 @@ QJsonObject TaskOrchestrationWidget::itemToJson(QTreeWidgetItem *item) const
object.insert(QStringLiteral("children"), children);
} else {
item->setFlags(item->flags() & ~Qt::ItemIsDropEnabled);
for(const auto& robot:m_robots)if(robot.toMap().value("id")==item->data(0,RobotIdRole))object.insert("robotName",robot.toMap().value("name").toString());
object.insert("robotId",item->data(0,RobotIdRole).toString().isEmpty()?QStringLiteral("current"):item->data(0,RobotIdRole).toString());
object.insert(QStringLiteral("deviceType"), item->data(0, DeviceTypeRole).toString());
object.insert(QStringLiteral("deviceId"), item->data(0, DeviceIdRole).toString());
object.insert(QStringLiteral("action"), item->data(0, ActionRole).toString());
@ -1257,6 +1364,7 @@ QTreeWidgetItem *TaskOrchestrationWidget::itemFromJson(const QJsonObject &object
const QString type = object.value(QStringLiteral("deviceType")).toString(); const QString id = object.value(QStringLiteral("deviceId")).toString();
const QString action = object.value(QStringLiteral("action")).toString(); const int wait = object.value(QStringLiteral("waitMs")).toInt();
const QString waitUnit = normalizedWaitUnit(object.value(QStringLiteral("waitUnit")).toString());
item->setData(0,RobotIdRole,object.value("robotId").toString("current"));
item->setData(0, DeviceTypeRole, type); item->setData(0, DeviceIdRole, id); item->setData(0, ActionRole, action);
item->setData(0, ParametersRole, QString::fromUtf8(QJsonDocument(object.value(QStringLiteral("parameters")).toObject()).toJson(QJsonDocument::Compact)));
item->setData(0, WaitRole, wait); item->setData(0, WaitUnitRole, waitUnit);
@ -1271,6 +1379,7 @@ void TaskOrchestrationWidget::rebuildFlowScene()
const QSignalBlocker blocker(m_flowScene);
const quint64 revision = ++m_sceneRevision;
QTreeWidgetItem *selected = m_tree->currentItem();
QSet<QString> selectedIds;for(auto* graphic:m_flowScene->selectedItems())selectedIds.insert(graphic->data(7010).toString());
m_flowScene->clear();
QHash<QTreeWidgetItem *, QPointF> positions;
QHash<QTreeWidgetItem *, qreal> widths;
@ -1328,7 +1437,18 @@ void TaskOrchestrationWidget::rebuildFlowScene()
[this, revision](QTreeWidgetItem *source) {
QTimer::singleShot(0, this, [this, source, revision]() {
if (revision != m_sceneRevision || !m_runSteps.isEmpty()) return;
source->setExpanded(!source->isExpanded()); save();
const QString id=source->data(0,NodeIdRole).toString();
const bool expanded=!source->isExpanded();
source->setExpanded(expanded);save();
QTimer::singleShot(0,this,[this,id,expanded] {
if(!m_runSteps.isEmpty())return;
for(QTreeWidgetItemIterator it(m_tree);*it;++it) {
if((*it)->data(0,NodeIdRole).toString()==id&&(*it)->isExpanded()==expanded) {
static_cast<WorkflowCanvas*>(m_flowView)->focusLoop(id,m_graph,expanded);
return;
}
}
});
});
});
card->setPos(it.value());
@ -1336,7 +1456,7 @@ void TaskOrchestrationWidget::rebuildFlowScene()
card->setData(7010,item->data(0,NodeIdRole));if(loop)card->setData(7011,QStringLiteral("loop"));
m_flowScene->addItem(card);
workflowPorts(card,item->data(0,NodeIdRole).toString());
if (item == selected) card->setSelected(true);
if(selectedIds.contains(item->data(0,NodeIdRole).toString())||(selectedIds.isEmpty()&&item==selected))card->setSelected(true);
}
auto link = [&](QTreeWidgetItem *from, QTreeWidgetItem *to, bool membership) {
if (!positions.contains(from) || !positions.contains(to)) return;
@ -1369,7 +1489,7 @@ void TaskOrchestrationWidget::rebuildFlowScene()
}
if(hidden)continue;
auto *terminal=workflowTerminal(m_flowScene,id,type,QPointF(n.value("x").toDouble(),n.value("y").toDouble()));
terminal->moved=[this,id](const QPointF &center){QTimer::singleShot(0,this,[this,id,center]{if(m_runSteps.isEmpty()){WorkflowGraph::position(m_graph,id,center);save();}});};
terminal->moved=[this,id](const QPointF &center){QTimer::singleShot(0,this,[this,id,center]{if(m_runSteps.isEmpty()){QHash<QString,QPointF> targets;for(auto* selected:m_flowScene->selectedItems())if(!selected->data(7010).toString().isEmpty())targets.insert(selected->data(7010).toString(),selected->sceneBoundingRect().center());targets.insert(id,center);WorkflowGraph::positions(m_graph,targets);save();}});};
if(type=="sleep")terminal->setToolTip(QStringLiteral("选中后在右侧修改等待时长;拖动端口连接执行顺序"));
bounds[id]=terminal->sceneBoundingRect();
}
@ -1389,7 +1509,8 @@ void TaskOrchestrationWidget::moveFlowItem(QTreeWidgetItem *item, const QPointF
{
if (!item || !m_runSteps.isEmpty()) return;
if(!m_graph.isEmpty()) {
WorkflowGraph::position(m_graph,item->data(0,NodeIdRole).toString(),position+QPointF(kTaskCardWidth/2,kTaskCardHeight/2));
QHash<QString,QPointF> targets;for(auto* selected:m_flowScene->selectedItems())if(!selected->data(7010).toString().isEmpty())targets.insert(selected->data(7010).toString(),selected->sceneBoundingRect().center());
targets.insert(item->data(0,NodeIdRole).toString(),position+QPointF(kTaskCardWidth/2,kTaskCardHeight/2));WorkflowGraph::positions(m_graph,targets);
save();return;
}
QTreeWidgetItem *parent = item->parent();
@ -1433,6 +1554,7 @@ void TaskOrchestrationWidget::setDeviceInfo(const QString& id,const QVariantMap&
void TaskOrchestrationWidget::setAvailableDevices(const QVariantList &devices)
{
if(m_availableDevices==devices)return;
m_availableDevices = devices;
emit availableDevicesChanged();
}
@ -1457,10 +1579,12 @@ void TaskOrchestrationWidget::activateGroup(int index)
if (m_switchingGroup || index < 0 || index >= m_groups.size()) return;
m_insertionParent = nullptr; m_insertionIndex = -1;
storeCurrentGroup(); m_activeGroup = index; m_tree->clear();
++m_historyEpoch;m_historyQueued=false;
m_graph=QJsonDocument::fromJson(m_groups.at(index).value("flowData").toString().toUtf8()).object();
for (const QJsonValue &node : m_groups.at(index).value(QStringLiteral("nodes")).toArray()) m_tree->addTopLevelItem(itemFromJson(node.toObject()));
for (int i = 0; i < m_tree->topLevelItemCount(); ++i) restoreTaskExpansion(m_tree->topLevelItem(i));
save();
m_editHistory.reset(m_graph);static_cast<WorkflowCanvas*>(m_flowView)->refreshHistoryButtons();
static_cast<WorkflowCanvas *>(m_flowView)->resetView();
QTimer::singleShot(0,this,[this]{static_cast<WorkflowCanvas *>(m_flowView)->resetView();});
}
@ -1534,6 +1658,12 @@ void TaskOrchestrationWidget::save()
QString error;if(!TaskApi::normalize(root,error)){emit statusMessage("ERROR",QStringLiteral("任务校验失败,未覆盖文件:")+error);return;}
m_groups.clear();for(const auto& group:root.value("groups").toArray())m_groups.append(group.toObject());
if(!syncGraph(error)){emit statusMessage("ERROR",QStringLiteral("图转换失败,原文件未覆盖:")+error);return;}
if(!m_restoringHistory&&!m_historyQueued) {
m_historyQueued=true;const auto epoch=m_historyEpoch;
QTimer::singleShot(0,this,[this,epoch] {
if(epoch!=m_historyEpoch)return;m_historyQueued=false;recordHistory();
});
}
QJsonArray records;
for(auto &group:m_groups) {
if(group.value("flowData").toString().isEmpty()) {
@ -1550,6 +1680,23 @@ void TaskOrchestrationWidget::save()
rebuildFlowScene();
}
void TaskOrchestrationWidget::recordHistory() {
if(m_restoringHistory||!m_runSteps.isEmpty())return;
m_editHistory.push(m_graph);static_cast<WorkflowCanvas*>(m_flowView)->refreshHistoryButtons();
}
void TaskOrchestrationWidget::restoreHistory(bool redo) {
if(!m_runSteps.isEmpty()||!m_storageWritable)return;
recordHistory();
if(redo?!m_editHistory.canRedo():!m_editHistory.canUndo())return;
const auto graph=redo?m_editHistory.redo():m_editHistory.undo();
QScopedValueRollback<bool> guard(m_restoringHistory,true);QString error;
if(!restoreGraph(graph,error)) {
if(redo)m_editHistory.undo();else m_editHistory.redo();
showTaskNotice(this,QStringLiteral("无法恢复编辑"),error);return;
}
save();m_editHistory.replaceCurrent(m_graph);static_cast<WorkflowCanvas*>(m_flowView)->refreshHistoryButtons();
}
void TaskOrchestrationWidget::exportDocument(){
if(!m_runSteps.isEmpty())return;
QString error;
@ -1590,3 +1737,18 @@ void TaskOrchestrationWidget::importDocument(){
m_switchingGroup=false;m_storageWritable=true;
if(m_groups.size()>first){m_groupCombo->setCurrentIndex(first);if(m_activeGroup!=first)activateGroup(first);}else save();
}
void TaskOrchestrationWidget::setRobots(const QVariantList& robots){if(m_robots==robots)return;m_robots=robots;emit robotsChanged();}
QVariantList TaskOrchestrationWidget::devicesForRobot(const QString& robot)const{
if(m_robots.isEmpty()&&(robot.isEmpty()||robot=="current"))return m_availableDevices;
for(const auto& value:m_robots)if(value.toMap().value("id").toString()==(robot.isEmpty()?QStringLiteral("current"):robot))return value.toMap().value("devices").toList();return {};
}
QVariantMap TaskOrchestrationWidget::robotDeviceInfo(const QString& robot,const QString& device)const{return robot.isEmpty()||robot=="current"?deviceInfo(device):m_robotDeviceInfo.value(robot).value(device);}
void TaskOrchestrationWidget::setRobotDeviceInfo(const QString& robot,const QString& device,const QVariantMap& info){
if(robot.isEmpty()||robot=="current"){setDeviceInfo(device,info);return;}
auto merged=m_robotDeviceInfo[robot].value(device);for(auto i=info.begin();i!=info.end();++i)if(i.key()!="jointNames"||!i.value().toStringList().isEmpty())merged.insert(i.key(),i.value());
if(merged==m_robotDeviceInfo[robot].value(device))return;m_robotDeviceInfo[robot][device]=merged;emit robotDeviceInfoChanged(robot,device);
}
void TaskOrchestrationWidget::clearRobotDeviceInfo(const QString& robot){if(robot=="current"){clearDeviceInfo();return;}const auto ids=m_robotDeviceInfo.value(robot).keys();m_robotDeviceInfo.remove(robot);for(const auto& id:ids)emit robotDeviceInfoChanged(robot,id);}
bool TaskOrchestrationWidget::runningUsesRobot(const QString& robot)const{if(m_runSteps.isEmpty())return false;for(QTreeWidgetItemIterator it(m_tree);*it;++it)if((*it)->data(0,KindRole)=="task"&&((*it)->data(0,RobotIdRole).toString().isEmpty()?QStringLiteral("current"):(*it)->data(0,RobotIdRole).toString())==robot)return true;return false;}

View File

@ -4,6 +4,7 @@
#include <QHash>
#include <QVariantList>
#include <QWidget>
#include "workflowhistory.h"
class QComboBox;
class QLabel;
@ -23,6 +24,12 @@ class TaskOrchestrationWidget final : public QWidget
public:
explicit TaskOrchestrationWidget(QWidget *parent = nullptr);
~TaskOrchestrationWidget() override;
bool runningUsesRobot(const QString& robot)const;
void setRobots(const QVariantList& robots);
QVariantList devicesForRobot(const QString& robot) const;
QVariantMap robotDeviceInfo(const QString& robot,const QString& device) const;
void setRobotDeviceInfo(const QString& robot,const QString& device,const QVariantMap& info);
void clearRobotDeviceInfo(const QString& robot);
void setAvailableDevices(const QVariantList &devices);
void setDeviceInfo(const QString &deviceId, const QVariantMap &info);
void clearDeviceInfo();
@ -46,6 +53,10 @@ public:
void completeWorkflowCall(const QString &token,bool success,const QString &detail);
signals:
void manageRobotsRequested();
void robotsChanged();
void robotDeviceInfoChanged(const QString& robot,const QString& device);
void robotDeviceInfoRequested(const QString& robot,const QString& device,const QString& type);
void executionStopped();
void workflowCallRequested(const QString &token,const QJsonObject &execution);
void cameraCapabilitiesChanged();
@ -97,6 +108,11 @@ private:
bool prepareWorkflow(QHash<QString,QJsonObject> &executions,QString &error) const;
WorkflowRuntime *m_runtime=nullptr;
QHash<QString,QString> m_workflowCalls;
WorkflowHistory m_editHistory;
bool m_restoringHistory=false,m_historyQueued=false;
quint64 m_historyEpoch=0;
void recordHistory();
void restoreHistory(bool redo);
QComboBox *m_groupCombo = nullptr;
QTreeWidget *m_tree = nullptr;
@ -121,6 +137,9 @@ private:
bool m_waitingForResult = false;
int m_currentWaitMs = 0;
QString m_currentWaitUnit = QStringLiteral("ms");
QVariantList m_robots;
QString m_selectedRobotId="current";
QHash<QString,QHash<QString,QVariantMap>> m_robotDeviceInfo;
QVariantList m_availableDevices;
QHash<QString,QVariantMap> m_deviceInfo;
QHash<QString, QVariantMap> m_cameraCapabilities;

View File

@ -240,7 +240,7 @@ public:
using QTabWidget::QTabWidget;
void fit(){if(!currentWidget())return;if(currentWidget()->layout())currentWidget()->layout()->activate();setFixedHeight(sizeHint().height()+8);updateGeometry();}
QSize sizeHint()const override{return currentWidget()?currentWidget()->sizeHint()+QSize(12,tabBar()->sizeHint().height()+12):QTabWidget::sizeHint();}
QSize minimumSizeHint()const override{return QSize(280,sizeHint().height());}
QSize minimumSizeHint()const override{return QSize(240,sizeHint().height());}
};
QString stateKey(const QWidget* widget,const QWidget* root){
QStringList path;for(auto* at=widget;at&&at!=root;at=at->parentWidget()){
@ -282,6 +282,7 @@ void TaskProtoEditor::setOperation(const QString& service,const QString& method,
connect(tabs,&QTabWidget::currentChanged,this,[this,tabs](int){tabs->fit();m_layout->invalidate();m_layout->activate();setFixedHeight(m_layout->sizeHint().height());updateGeometry();if(m_layoutChanged)m_layoutChanged();});
}else {auto* body=new QWidget(this);build(body,fields);m_layout->addWidget(body);body->show();}
m_read=[reads](QString& error){QJsonObject result;for(const auto& read:*reads){const auto part=read(error).toObject();if(!error.isEmpty())return QJsonObject();for(auto it=part.begin();it!=part.end();++it)result.insert(it.key(),it.value());}return result;};
for(auto* widget:findChildren<QWidget*>())if(auto* joints=dynamic_cast<TaskJointEditor*>(widget))joints->setLayoutChangedHandler([this]{refreshContentSize();});
m_layout->activate();setFixedHeight(m_layout->sizeHint().height());updateGeometry();
for(auto* group:findChildren<QGroupBox*>())if(group->isCheckable())connect(group,&QGroupBox::toggled,this,[this](bool){for(auto* tabs:findChildren<QTabWidget*>())if(auto* parameterTabs=dynamic_cast<ParameterTabs*>(tabs))parameterTabs->fit();m_layout->invalidate();m_layout->activate();setFixedHeight(m_layout->sizeHint().height());updateGeometry();if(m_layoutChanged)m_layoutChanged();});
}

View File

@ -15,13 +15,13 @@
#include <QUuid>
#include <QPointer>
#include <chrono>
TaskRpcRunner::TaskRpcRunner(RobotClient* client,QObject* parent):QObject(parent),m_client(client){
TaskRpcRunner::TaskRpcRunner(RobotClient* client,QObject* parent):QObject(parent),m_simulator(client?client->simulator():std::shared_ptr<DemoSimulator>(&DemoSimulator::instance(),[](DemoSimulator*){})),m_client(client){
if(!client)return;
connect(client,&RobotClient::connectRequested,this,[this](const QString& host,int port,bool demo){m_connected=false;cancel();m_demo=demo;m_endpoint=host.trimmed()+":"+QString::number(port);});
connect(client,&RobotClient::connectionChanged,this,[this](bool ok,int,const QString&){m_connected=ok;if(!ok)cancel();});
}
TaskRpcRunner::~TaskRpcRunner(){const auto parallel=m_parallel;m_parallel.clear();for(auto *runner:parallel){QObject::disconnect(runner,nullptr,this,nullptr);delete runner;}if(m_demoCompletion){DemoSimulator::instance().stop(m_demoDevice);m_demoCompletion={};++m_demoGeneration;}cancel();if(m_thread){m_thread->wait();delete m_thread;}}
void TaskRpcRunner::cancel(){const auto parallel=m_parallel;for(auto *runner:parallel)runner->cancel();if(m_context)m_context->TryCancel();if(m_demoCompletion){++m_demoGeneration;DemoSimulator::instance().stop(m_demoDevice);m_busy=false;auto done=std::move(m_demoCompletion);done(false,QStringLiteral("演示调用已取消"));}}
TaskRpcRunner::~TaskRpcRunner(){const auto parallel=m_parallel;m_parallel.clear();for(auto *runner:parallel){QObject::disconnect(runner,nullptr,this,nullptr);delete runner;}if(m_demoCompletion){m_simulator->stop(m_demoDevice);m_demoCompletion={};++m_demoGeneration;}cancel();if(m_thread){m_thread->wait();delete m_thread;}}
void TaskRpcRunner::cancel(){const auto parallel=m_parallel;for(auto *runner:parallel)runner->cancel();if(m_context)m_context->TryCancel();if(m_demoCompletion){++m_demoGeneration;m_simulator->stop(m_demoDevice);m_busy=false;auto done=std::move(m_demoCompletion);done(false,QStringLiteral("演示调用已取消"));}}
void TaskRpcRunner::runConcurrent(const QJsonObject &execution,std::function<void(bool,const QString&)> done) {
auto *runner=new TaskRpcRunner(m_client,this);
runner->m_endpoint=m_endpoint;runner->m_connected=m_connected;runner->m_demo=m_demo;
@ -38,13 +38,13 @@ void TaskRpcRunner::run(const QJsonObject& ex,std::function<void(bool,const QStr
if(m_demo){
const int timeout=ex.value("timeoutMs").toInt(180000);
if(timeout<100||timeout>1800000){done(false,QStringLiteral("接口超时无效"));return;}
auto simulatedRequest=pending;auto h=pendingDescriptor->FindFieldByName("header")?pending.value("header").toObject():pending;h.remove("commandId");h.insert("command_id",QUuid::createUuid().toString(QUuid::WithoutBraces));h.insert("timestamp",QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs));if(pendingDescriptor->FindFieldByName("header"))simulatedRequest.insert("header",h);else simulatedRequest=h;
const auto reply=DemoSimulator::instance().call(service,method,simulatedRequest);
auto simulatedRequest=pending;auto h=pendingDescriptor->FindFieldByName("header")?pending.value("header").toObject():pending;h.remove("commandId");h.remove("command_id");h.insert("timestamp",QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs));if(pendingDescriptor->FindFieldByName("header"))simulatedRequest.insert("header",h);else simulatedRequest=h;
const auto reply=m_simulator->call(service,method,simulatedRequest);
m_busy=true;m_demoDevice=target;m_demoCompletion=std::move(done);const quint64 generation=++m_demoGeneration;
const QPointer<TaskRpcRunner> guard(this);
QTimer::singleShot(qMin(timeout,reply.delayMs),this,[guard,generation,reply,timeout]{
if(!guard||generation!=guard->m_demoGeneration||!guard->m_demoCompletion)return;
const bool expired=timeout<reply.delayMs;if(expired)DemoSimulator::instance().stop(guard->m_demoDevice);
const bool expired=timeout<reply.delayMs;if(expired)guard->m_simulator->stop(guard->m_demoDevice);
guard->m_busy=false;auto completion=std::move(guard->m_demoCompletion);
completion(!expired&&reply.ok,expired?QStringLiteral("演示调用超时"):QString::fromUtf8(QJsonDocument(reply.response).toJson(QJsonDocument::Compact)));
});return;
@ -53,7 +53,7 @@ void TaskRpcRunner::run(const QJsonObject& ex,std::function<void(bool,const QStr
auto request=ex.value("request").toObject();const auto* descriptor=TaskApi::requestDescriptor(service,method);
const bool nested=descriptor->FindFieldByName("header")!=nullptr;
auto header=nested?request.value("header").toObject():request;
header.remove("commandId");header.insert("command_id",QUuid::createUuid().toString(QUuid::WithoutBraces));header.insert("timestamp",QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs));
header.remove("commandId");header.remove("command_id");header.insert("timestamp",QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs));
if(nested)request.insert("header",header);else request=header;
const int timeout=ex.value("timeoutMs").toInt(180000);if(timeout<100||timeout>1800000){done(false,QStringLiteral("接口超时无效"));return;}
if(m_thread){m_thread->wait();delete m_thread;}m_busy=true;

View File

@ -4,7 +4,7 @@
#include <memory>
#include <functional>
#include <QList>
class RobotClient;class QThread;
class DemoSimulator;class RobotClient;class QThread;
namespace grpc {class ClientContext;}
class TaskRpcRunner final:public QObject {
public:
@ -19,6 +19,7 @@ private:
quint64 m_demoGeneration=0;
QString m_demoDevice;
std::function<void(bool,const QString&)> m_demoCompletion;
std::shared_ptr<DemoSimulator> m_simulator;
RobotClient* m_client=nullptr;
QString m_endpoint;bool m_connected=false,m_demo=false,m_busy=false;
QThread* m_thread=nullptr;

View File

@ -160,8 +160,8 @@ void UserCoordinateWidget::updateActions(){
for(auto* button:m_captureButtons)button->setEnabled(ready&&!b);
m_calibration->setVisible(!b);m_tcpGroup->setVisible(!b);m_calibration->setEnabled(!m_busy);m_tcpGroup->setEnabled(!m_busy);
m_calibrate->setEnabled(ready&&!b);m_save->setEnabled(ready&&m_loadOk&&!b&&!m_name->text().trimmed().isEmpty());m_remove->setEnabled(ready&&m_loadOk&&!b&&i>=0);m_apply->setEnabled(ready&&m_loadOk&&saved);
m_move->setEnabled(applied&&m_targetReady);m_moveJoint->setEnabled(applied&&m_targetReady);
m_jointSpeed->setEnabled(!m_busy);m_jointAccel->setEnabled(!m_busy);
m_move->setEnabled(applied&&m_targetReady);m_moveJoint->setEnabled(false);m_moveJoint->setToolTip(QStringLiteral("当前服务端协议不提供末端位姿 MoveJ 接口"));
m_jointSpeed->setEnabled(false);m_jointAccel->setEnabled(false);
m_appliedState->setText(QStringLiteral("当前应用:%1%2").arg(m_appliedName.isEmpty()?QStringLiteral("尚未应用"):label(m_appliedName),applied?QString():QStringLiteral(" · 所选记录未应用或有未保存修改")));
}
void UserCoordinateWidget::send(const QString& operation){

View File

@ -23,6 +23,17 @@ inline void workflowVectorIcon(QPainter *p,const QRectF &rect,const QString &nam
renderers.insert(name,QSharedPointer<QSvgRenderer>::create(QStringLiteral(":/workflow-icons/")+name+QStringLiteral(".svg")));
renderers.value(name)->render(p,rect);
}
inline void workflowCollapseButton(QPainter *p,const QRectF &rect,bool expanded,bool hovered=false,bool pressed=false) {
p->save();p->setRenderHint(QPainter::Antialiasing);
p->setPen(QPen(hovered?QColor("#a58bd5"):QColor("#e4deef"),1));
p->setBrush(pressed?QColor("#e5d9fa"):hovered?QColor("#f0eafa"):QColor("#faf8fe"));
p->drawRoundedRect(rect,6,6);
const QPointF c=rect.center();QPainterPath arrow;
if(expanded){arrow.moveTo(c+QPointF(-4,-2));arrow.lineTo(c+QPointF(0,2));arrow.lineTo(c+QPointF(4,-2));}
else {arrow.moveTo(c+QPointF(-2,-4));arrow.lineTo(c+QPointF(2,0));arrow.lineTo(c+QPointF(-2,4));}
p->setPen(QPen(QColor("#8061b5"),1.8,Qt::SolidLine,Qt::RoundCap,Qt::RoundJoin));p->setBrush(Qt::NoBrush);p->drawPath(arrow);
p->restore();
}
inline void workflowCardPaint(QPainter *p,const QRectF &bounds,const QString &title,
const QString &detail,const QColor &accent,bool selected,
@ -69,26 +80,51 @@ inline void workflowContainers(QGraphicsScene *scene,const QJsonObject &graph,co
}
}
class WorkflowWire final : public QGraphicsPathItem {
public:
QPointF from,to;
bool membership=false;
qreal phase=0;
WorkflowWire(bool member):membership(member){setZValue(-1);setAcceptHoverEvents(true);}
void endpoints(const QPointF &a,const QPointF &b) {
if(a==from&&b==to&&!path().isEmpty())return;
from=a;to=b;QPainterPath curve(a);
if(membership)curve.cubicTo(a+QPointF(0,45),b-QPointF(0,45),b);
else {const qreal dx=qMax(qreal(24),qAbs(b.x()-a.x())/2);curve.cubicTo(a+QPointF(dx,0),b-QPointF(dx,0),b);}
setPath(curve);
}
QRectF boundingRect()const override{return path().boundingRect().adjusted(-9,-9,9,9);}
QPainterPath shape()const override {
QPainterPathStroker stroke;stroke.setWidth(14);return stroke.createStroke(path());
}
void paint(QPainter *p,const QStyleOptionGraphicsItem *,QWidget *) override {
p->save();p->setRenderHint(QPainter::Antialiasing);p->setBrush(Qt::NoBrush);
if(isSelected()||m_hovered){QPen halo(QColor(70,130,240,45),7);halo.setCosmetic(true);p->setPen(halo);p->drawPath(path());}
QPen base(membership?QColor("#b1bed0"):QColor("#d0def3"),1.4);base.setCosmetic(true);
p->setPen(base);p->drawPath(path());
const QColor color=isSelected()?QColor("#246bed"):QColor("#5a91cf");
if(!membership) {
QPen flow(color,isSelected()?2.2:1.7);flow.setCosmetic(true);flow.setDashPattern({5,5});flow.setDashOffset(-phase);
p->setPen(flow);p->drawPath(path());
}
const QPolygonF arrow=membership?(QPolygonF()<<to<<to+QPointF(-4,-7)<<to+QPointF(4,-7)):
(QPolygonF()<<to<<to+QPointF(-7,-4)<<to+QPointF(-7,4));
p->setPen(Qt::NoPen);p->setBrush(color);p->drawPolygon(arrow);p->restore();
}
protected:
void hoverEnterEvent(QGraphicsSceneHoverEvent *e)override{m_hovered=true;update();QGraphicsPathItem::hoverEnterEvent(e);}
void hoverLeaveEvent(QGraphicsSceneHoverEvent *e)override{m_hovered=false;update();QGraphicsPathItem::hoverLeaveEvent(e);}
private:bool m_hovered=false;
};
inline QGraphicsPathItem *workflowWire(QGraphicsScene *scene, const QPointF &from,
const QPointF &to, bool membership=false,
const QString &source={},const QString &target={}) {
QPainterPath path(from);
if(membership) path.cubicTo(from+QPointF(0,45),to-QPointF(0,45),to);
else {
const qreal dx=qMax(qreal(24),qAbs(to.x()-from.x())/2);
path.cubicTo(from+QPointF(dx,0),to-QPointF(dx,0),to);
}
const QColor color(membership ? "#9aabc0" : "#5a91cf");
auto *edge=scene->addPath(path,QPen(color,1.7));edge->setZValue(-1);
auto *edge=new WorkflowWire(membership);edge->endpoints(from,to);scene->addItem(edge);
if(!source.isEmpty()) {
edge->setFlag(QGraphicsItem::ItemIsSelectable,true);
edge->setData(7000,QStringLiteral("wire"));edge->setData(7001,source);edge->setData(7002,target);
edge->setToolTip(QStringLiteral("选中连线后按 Delete 删除,可重新连接"));
}
const QPolygonF arrow=membership
? QPolygonF() << to << to+QPointF(-4,-7) << to+QPointF(4,-7)
: QPolygonF() << to << to+QPointF(-7,-4) << to+QPointF(-7,4);
scene->addPolygon(arrow,QPen(color),QBrush(color))->setZValue(-1);
return edge;
}
inline void workflowPorts(QGraphicsItem *card,const QString &id,bool input=true,bool output=true) {
@ -129,6 +165,8 @@ inline WorkflowTerminal *workflowTerminal(QGraphicsScene *scene,const QString &i
const bool start=type=="start"||type=="subStart";
item->title=type=="sleep"?QStringLiteral("睡眠等待"):start?QStringLiteral("流程开始"):QStringLiteral("流程结束");
item->detail=type=="sleep"?QStringLiteral("等待指定时长后继续执行"):start?QStringLiteral("从此节点进入工作流"):QStringLiteral("当前工作流执行完成");
if(type=="subStart"){item->title=QStringLiteral("循环开始");item->detail=QStringLiteral("每轮从此处进入循环体");}
if(type=="subEnd"){item->title=QStringLiteral("循环结束");item->detail=QStringLiteral("本轮循环体执行结束");}
item->accent=type=="sleep"?QColor("#55b9db"):start?QColor("#20a36a"):QColor("#e05b64");
workflowPorts(item,id,!start,start||type=="sleep");return item;
}
@ -141,6 +179,8 @@ public:
std::function<void(const QString &,const QString &)> connectionRemoved;
std::function<QJsonObject(const QSet<QString> &)> copyNodes;
std::function<bool(const QJsonObject &,const QPointF &)> pasteNodes;
std::function<void()> undoRequested,redoRequested,nodeDeletionRequested;
std::function<bool()> canUndo,canRedo;
QPointF dropPosition;
QString dropContainer;
bool droppingFromPalette=false;
@ -158,6 +198,54 @@ public:
setTransformationAnchor(AnchorUnderMouse);
setResizeAnchor(NoAnchor);
setDragMode(RubberBandDrag);
m_wireClock.start();m_wireTimer=new QTimer(this);m_wireTimer->setInterval(33);
QObject::connect(m_wireTimer,&QTimer::timeout,this,[this] {
if(!isVisible()||!this->scene())return;
const auto visible=mapToScene(viewport()->rect()).boundingRect();
for(auto *item:this->scene()->items(visible,Qt::IntersectsItemBoundingRect))if(auto *wire=dynamic_cast<WorkflowWire*>(item)) {
if(!wire->membership&&wire->sceneBoundingRect().intersects(visible)) {
wire->phase=std::fmod(m_wireClock.elapsed()/45.,10.);wire->update();
}
}
});
for(const auto &key:{QStringLiteral("Ctrl+Z"),QStringLiteral("Ctrl+Y"),QStringLiteral("Ctrl+Shift+Z")}) {
// The point workflow's delete button is a sibling of its editor.
// Keep shortcuts active for that whole workflow panel as well.
QWidget *scope=parent&&parent->parentWidget()?parent->parentWidget():(parent?parent:this);
auto *shortcut=new QShortcut(QKeySequence(key),scope);
shortcut->setContext(Qt::WidgetWithChildrenShortcut);
QObject::connect(shortcut,&QShortcut::activated,this,[this,key] {historyAction(key!=QStringLiteral("Ctrl+Z"));});
}
}
void refreshWireEndpoints() {
if(!scene())return;
QHash<QString,QPointF> inputs,outputs;QList<WorkflowWire*> wires;
for(auto *item:scene()->items()) {
const auto role=item->data(7000).toString(),id=item->data(7001).toString();
if(role=="input")inputs[id]=item->sceneBoundingRect().center();
if(role=="output")outputs[id]=item->sceneBoundingRect().center();
if(auto *wire=dynamic_cast<WorkflowWire*>(item))wires.append(wire);
}
for(auto *wire:wires) {
const auto from=wire->data(7001).toString(),to=wire->data(7002).toString();
if(outputs.contains(from)&&inputs.contains(to))wire->endpoints(outputs[from],inputs[to]);
}
}
void historyAction(bool redo) {
QWidget *focus=QApplication::focusWidget();
if(auto *line=qobject_cast<QLineEdit*>(focus)){if(redo)line->redo();else line->undo();return;}
if(auto *text=qobject_cast<QTextEdit*>(focus)){if(redo)text->redo();else text->undo();return;}
if(auto *text=qobject_cast<QPlainTextEdit*>(focus)){if(redo)text->redo();else text->undo();return;}
if(auto *spin=qobject_cast<QAbstractSpinBox*>(focus)) {
if(auto *line=spin->findChild<QLineEdit*>()){if(redo)line->redo();else line->undo();}return;
}
if(!isInteractive())return;
if(redo){if(redoRequested)redoRequested();}else if(undoRequested)undoRequested();
refreshHistoryButtons();
}
void refreshHistoryButtons() {
if(m_undoButton)m_undoButton->setEnabled(isInteractive()&&canUndo&&canUndo());
if(m_redoButton)m_redoButton->setEnabled(isInteractive()&&canRedo&&canRedo());
}
void syncExtent() {
const QPointF center = mapToScene(viewport()->rect().center());
@ -176,11 +264,50 @@ public:
if (scene()->items().isEmpty()) resetView();
else fitInView(scene()->itemsBoundingRect().adjusted(-30,-30,30,30), Qt::KeepAspectRatio);
}
void focusLoop(const QString &id,const QJsonObject &graph,bool expanded) {
QSet<QString> ids{id};
if(expanded) {
bool added=true;
while(added) {
added=false;
for(const auto &v:graph.value("nodes").toArray()) {
const auto n=v.toObject();const auto child=n.value("id").toString();
if(!ids.contains(child)&&ids.contains(n.value("properties").toObject().value("parentId").toString())) {
ids.insert(child);added=true;
}
}
}
}
QRectF bounds;
for(auto *item:scene()->items()) {
if(!item->isVisible()||!ids.contains(item->data(7010).toString()))continue;
bounds=bounds.isNull()?item->sceneBoundingRect():bounds.united(item->sceneBoundingRect());
}
if(bounds.isEmpty()||viewport()->width()<80||viewport()->height()<80)return;
const qreal current=transform().m11();
if(current<=0)return;
qreal target=current;
if(expanded) {
m_loopZoom[id]=current;
const qreal fit=qMin((viewport()->width()-64.)/bounds.width(),(viewport()->height()-64.)/bounds.height());
target=qMin(current,fit);
}else if(m_loopZoom.contains(id))target=m_loopZoom.take(id);
if(target>0)scale(target/current,target/current);
centerOn(bounds.center());
viewport()->update();
}
QWidget *tools(QWidget *parent) {
auto *bar = new QWidget(parent); auto *layout = new QHBoxLayout(bar);
layout->setContentsMargins(0,0,0,0);
auto *hint = new QLabel(QStringLiteral("右键平移 · Ctrl+滚轮缩放"), bar);
hint->setObjectName("mutedLabel");hint->hide();bar->setToolTip(hint->text()+QStringLiteral(" · Ctrl+C / Ctrl+V 复制粘贴"));
m_undoButton=new QPushButton(QStringLiteral("撤销"),bar);m_redoButton=new QPushButton(QStringLiteral("重做"),bar);
m_undoButton->setObjectName("secondaryButton");m_redoButton->setObjectName("secondaryButton");
m_undoButton->setToolTip(QStringLiteral("撤销 Ctrl+Z"));m_redoButton->setToolTip(QStringLiteral("重做 Ctrl+Shift+Z / Ctrl+Y"));
layout->addWidget(m_undoButton);layout->addWidget(m_redoButton);
QObject::connect(m_undoButton,&QPushButton::clicked,this,[this]{if(isInteractive()&&undoRequested)undoRequested();refreshHistoryButtons();});
QObject::connect(m_redoButton,&QPushButton::clicked,this,[this]{if(isInteractive()&&redoRequested)redoRequested();refreshHistoryButtons();});
refreshHistoryButtons();
layout->addStretch();
for (int i=0;i<4;++i) {
auto *button = new QPushButton(QStringList{QStringLiteral("-"),QStringLiteral("+"),QStringLiteral("回到起点"),QStringLiteral("显示全部")}[i],bar);
@ -194,8 +321,10 @@ public:
protected:
void showEvent(QShowEvent *event) override {
QGraphicsView::showEvent(event);
m_wireTimer->start();
if(m_firstShow){m_firstShow=false;QTimer::singleShot(0,this,[this]{fitAll();});}
}
void hideEvent(QHideEvent *event)override{m_wireTimer->stop();QGraphicsView::hideEvent(event);}
void drawBackground(QPainter *painter, const QRectF &rect) override {
painter->fillRect(rect,QColor("#ffffff"));
if(transform().m11()<.3) return;
@ -212,9 +341,7 @@ protected:
m_preview=scene()->addPath(QPainterPath(m_wireStart),QPen(QColor("#3478e5"),2,Qt::DashLine));
m_preview->setZValue(20);event->accept();return;
}
if(event->button()==Qt::RightButton || event->button()==Qt::MiddleButton
|| (event->button()==Qt::LeftButton && !(event->modifiers()&Qt::ControlModifier)
&& (!item || !(item->flags()&QGraphicsItem::ItemIsSelectable)))) {
if(event->button()==Qt::RightButton || event->button()==Qt::MiddleButton) {
m_panning=true;m_last=event->pos();viewport()->setCursor(Qt::ClosedHandCursor);event->accept();return;
}
QGraphicsView::mousePressEvent(event);
@ -228,6 +355,7 @@ protected:
horizontalScrollBar()->setValue(horizontalScrollBar()->value()-delta.x());
verticalScrollBar()->setValue(verticalScrollBar()->value()-delta.y());event->accept();return;}
QGraphicsView::mouseMoveEvent(event);
refreshWireEndpoints();
}
void mouseReleaseEvent(QMouseEvent *event) override {
if(m_preview) {
@ -246,6 +374,8 @@ protected:
QGraphicsView::wheelEvent(event);
}
void keyPressEvent(QKeyEvent *event) override {
if(event->matches(QKeySequence::Undo)){historyAction(false);event->accept();return;}
if(event->matches(QKeySequence::Redo)||(event->key()==Qt::Key_Z&&(event->modifiers()&Qt::ControlModifier)&&(event->modifiers()&Qt::ShiftModifier))){historyAction(true);event->accept();return;}
if(event->matches(QKeySequence::Copy)&&copyNodes) {
QSet<QString> ids;
for(auto *item:scene()->selectedItems()) {
@ -274,6 +404,7 @@ protected:
from=item->data(7001).toString();to=item->data(7002).toString();break;
}
if(!from.isEmpty()){connectionRemoved(from,to);event->accept();return;}
if(nodeDeletionRequested){nodeDeletionRequested();event->accept();return;}
}
QGraphicsView::keyPressEvent(event);
}
@ -299,6 +430,9 @@ protected:
QGraphicsView::dropEvent(event);
}
private:
QTimer *m_wireTimer=nullptr;QElapsedTimer m_wireClock;
QPointer<QPushButton> m_undoButton,m_redoButton;
QHash<QString,qreal> m_loopZoom;
int m_pasteCount=0;
bool m_firstShow=true,m_panning=false; QPoint m_last;
QString m_connecting;QPointF m_wireStart;QGraphicsPathItem *m_preview=nullptr;

View File

@ -56,6 +56,12 @@ inline void position(QJsonObject &graph,const QString &id,const QPointF &center)
}
graph.insert("nodes",nodes);
}
// Move containers first so a selected child is positioned once in scene space.
inline void positions(QJsonObject& graph,const QHash<QString,QPointF>& targets){
auto ids=targets.keys();const auto depth=[&](const QString& id){int count=0;QString parent=node(graph,id).value("properties").toObject().value("parentId").toString();QSet<QString> seen;while(!parent.isEmpty()&&!seen.contains(parent)){seen.insert(parent);++count;parent=node(graph,parent).value("properties").toObject().value("parentId").toString();}return count;};
std::sort(ids.begin(),ids.end(),[&](const QString& a,const QString& b){return depth(a)<depth(b);});
for(const auto& id:ids)position(graph,id,targets.value(id));
}
inline QJsonObject remap(QJsonObject graph,QHash<QString,QString> ids) {
auto nodes=graph.value("nodes").toArray();for(const auto &v:nodes) {
const auto id=v.toObject().value("id").toString();if(!ids.contains(id))ids[id]=QUuid::createUuid().toString(QUuid::WithoutBraces);
@ -135,7 +141,7 @@ inline QJsonObject merge(QJsonObject fresh,const QJsonObject &previous) {
const bool terminal=type=="start"||type=="end"||type=="subStart"||type=="subEnd";
for(auto it=update.begin();it!=update.end();++it) {
if(terminal&&it.key()!="cmvrInterop"&&it.key()!="schemaVersion")continue;
if(it.key()=="executionTarget"&&properties.contains("executionTarget"))continue;
if(it.key()=="executionTarget"&&properties.contains("executionTarget")&&old.value("properties").toObject().value("cmvrRobotId").toString("current")==update.value("cmvrRobotId").toString("current"))continue;
properties.insert(it.key(),it.value());
}
n.insert("properties",properties);

34
src/workflowhistory.h Normal file
View File

@ -0,0 +1,34 @@
#pragma once
#include <QJsonDocument>
#include <QJsonObject>
#include <QVector>
class WorkflowHistory {
public:
void reset(const QJsonObject &state){m_states.clear();m_index=-1;m_bytes=0;push(state);}
bool push(const QJsonObject &state) {
const auto bytes=QJsonDocument(state).toJson(QJsonDocument::Compact);
if(m_index>=0&&m_states[m_index]==bytes)return false;
while(m_states.size()>m_index+1){m_bytes-=m_states.last().size();m_states.removeLast();}
m_states.append(bytes);m_bytes+=bytes.size();m_index=m_states.size()-1;
while(m_states.size()>1&&(m_states.size()>50||m_bytes>32*1024*1024)) {
m_bytes-=m_states.first().size();m_states.removeFirst();--m_index;
}
return true;
}
bool canUndo()const{return m_index>0;}
bool canRedo()const{return m_index>=0&&m_index+1<m_states.size();}
void replaceCurrent(const QJsonObject &state) {
if(m_index<0){push(state);return;}
m_bytes-=m_states[m_index].size();
m_states[m_index]=QJsonDocument(state).toJson(QJsonDocument::Compact);
m_bytes+=m_states[m_index].size();
}
QJsonObject undo(){if(canUndo())--m_index;return current();}
QJsonObject redo(){if(canRedo())++m_index;return current();}
QJsonObject current()const{return m_index<0?QJsonObject():QJsonDocument::fromJson(m_states[m_index]).object();}
private:
QVector<QByteArray> m_states;
int m_index=-1;
qint64 m_bytes=0;
};

109
src/workflowrobotmanager.h Normal file
View File

@ -0,0 +1,109 @@
#pragma once
#include "robotclient.h"
#include "demosimulator.h"
#include "taskrpcrunner.h"
#include "taskdeviceoptions.h"
#include "taskorchestrationwidget.h"
#include "appmessagebox.h"
#include "applicationstyle.h"
#include <QDialog>
#include <QCoreApplication>
#include <QTimer>
#include <QFileInfo>
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QTableWidget>
#include <QHeaderView>
#include <QPushButton>
#include <QLineEdit>
#include <QSpinBox>
#include <QComboBox>
#include <QVBoxLayout>
#include <QLabel>
#include <QJsonDocument>
#include <QJsonArray>
#include <QSaveFile>
#include <QFile>
#include <QDir>
#include <QUuid>
#include <QPointer>
#include <memory>
// Each registered robot owns its connection, inventory and concurrent RPC runner.
class WorkflowRobotManager final : public QObject {
public:
WorkflowRobotManager(RobotClient* current,TaskRpcRunner* runner,TaskOrchestrationWidget* target,QObject* parent=nullptr,const QString& path={})
:QObject(parent),m_target(target),m_path(path.isEmpty()?QDir(QCoreApplication::applicationDirPath()).filePath("data/workflow_robots.json"):path){
auto entry=std::make_shared<Entry>();entry->id="current";entry->name=QStringLiteral("主界面机器人");entry->client=current;entry->runner=runner;entry->options=new TaskDeviceOptions(current,target,this,"current");
m_entries.insert(entry->id,entry);watch(entry);
connect(target,&TaskOrchestrationWidget::robotDeviceInfoRequested,this,[this](const QString& robot,const QString& device,const QString& type){requestInfo(robot,device,type);});
QFile file(m_path);if(file.open(QIODevice::ReadOnly))for(const auto& value:QJsonDocument::fromJson(file.readAll()).array()){
const auto saved=value.toObject();if(saved.value("id").toString().isEmpty()||saved.value("id")=="current")continue;
addRobot(saved.value("name").toString(),saved.value("host").toString(),saved.value("port").toInt(50051),saved.value("demo").toBool(),saved.value("id").toString(),false);
}
publish();
}
~WorkflowRobotManager()override{
m_closing=true;
for(const auto& e:m_entries)if(e->id!="current"){delete e->runner;delete e->options;delete e->client;}
}
QString addRobot(const QString& name,const QString& host,int port,bool demo,const QString& id={},bool persist=true){
if(name.trimmed().isEmpty()||host.trimmed().isEmpty()||port<1||port>65535)return {};
auto e=std::make_shared<Entry>();e->id=id.isEmpty()?QUuid::createUuid().toString(QUuid::WithoutBraces):id;
if(m_entries.contains(e->id))return {};
e->name=name.trimmed();e->host=host.trimmed();e->port=port;e->demo=demo;e->client=new RobotClient(this,std::make_shared<DemoSimulator>());e->runner=new TaskRpcRunner(e->client,this);
e->options=new TaskDeviceOptions(e->client,m_target,this,e->id);m_entries.insert(e->id,e);watch(e);
if(persist)save();publish();return e->id;
}
bool editRobot(const QString& id,const QString& name,const QString& host,int port,bool demo){
auto e=m_entries.value(id);if(!e||id=="current"||name.trimmed().isEmpty()||host.trimmed().isEmpty()||port<1||port>65535)return false;
e->wantedConnection=false;e->runner->cancel();e->client->disconnectFromServer();e->connected=false;e->devices.clear();e->name=name.trimmed();e->host=host.trimmed();e->port=port;e->demo=demo;save();publish();return true;
}
void connectRobot(const QString& id){auto e=m_entries.value(id);if(e&&id!="current"){e->wantedConnection=true;e->client->connectToServer(e->host,e->port,e->demo);}}
void disconnectRobot(const QString& id){auto e=m_entries.value(id);if(e&&id!="current"){e->wantedConnection=false;e->runner->cancel();e->client->disconnectFromServer();}}
void removeRobot(const QString& id){auto e=m_entries.value(id);if(!e||id=="current")return;m_entries.remove(id);delete e->runner;delete e->options;delete e->client;save();publish();}
void cancel(){for(const auto& e:m_entries)e->runner->cancel();}
RobotClient* client(const QString& id)const{auto e=m_entries.value(id);return e?e->client:nullptr;}
void requestInfo(const QString& robot,const QString& device,const QString& type){auto e=m_entries.value(robot);if(!e||!e->connected)return;
if(e->options)e->options->load(device,type);if(type==QStringLiteral("机械臂"))e->client->requestArmInfo(device);
if(type==QStringLiteral("灵巧手"))e->client->requestDexHandStatus(device);
}
void run(const QJsonObject& execution,std::function<void(bool,const QString&)> done){
const QString id=execution.value("robotId").toString("current");auto e=m_entries.value(id);
if(!e||!e->connected){done(false,QStringLiteral("执行机器人未连接:%1").arg(e?e->name:id));return;}
const QString service=execution.value("service").toString();const auto request=execution.value("request").toObject();
const QString device=request.contains("header")?request.value("header").toObject().value("device_id").toString():request.value("device_id").toString();
bool present=false;for(const auto& v:e->devices)if(v.toMap().value("deviceId").toString()==device)present=true;
if(device.isEmpty()||!present){done(false,QStringLiteral("机器人“%1”上找不到设备“%2”,未发送请求").arg(e->name,device));return;}
e->runner->runConcurrent(execution,std::move(done));
}
QVariantList robots()const{QVariantList result;QStringList keys=m_entries.keys();keys.sort();keys.removeAll("current");keys.prepend("current");
for(const auto& id:keys){const auto e=m_entries.value(id);result<<QVariantMap{{"id",id},{"name",e->name},{"host",e->host},{"port",e->port},{"demo",e->demo},{"connected",e->connected},{"devices",e->devices}};}return result;
}
void showDialog(QWidget* parent){
QDialog dialog(parent);dialog.setWindowTitle(QStringLiteral("机器人管理"));dialog.resize(780,420);
auto* layout=new QVBoxLayout(&dialog);auto* hint=new QLabel(QStringLiteral("每台机器人独立连接 cmvr-es。节点只能选择所选机器人上的同类设备;保存连接信息不会自动连接。"),&dialog);hint->setWordWrap(true);layout->addWidget(hint);
auto* table=new QTableWidget(0,4,&dialog);table->setObjectName("workflowRobotTable");table->setHorizontalHeaderLabels({QStringLiteral("机器人"),QStringLiteral("服务地址"),QStringLiteral("状态"),QStringLiteral("设备数")});table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);table->verticalHeader()->hide();table->setSelectionBehavior(QAbstractItemView::SelectRows);table->setSelectionMode(QAbstractItemView::SingleSelection);table->setEditTriggers(QAbstractItemView::NoEditTriggers);layout->addWidget(table,1);
const auto refresh=[this,table]{QString selected;if(table->currentRow()>=0)selected=table->item(table->currentRow(),0)->data(Qt::UserRole).toString();const auto list=robots();table->setRowCount(list.size());int row=0;for(const auto& v:list){const auto r=v.toMap();auto* item=new QTableWidgetItem(r.value("name").toString());item->setData(Qt::UserRole,r.value("id"));table->setItem(row,0,item);table->setItem(row,1,new QTableWidgetItem(r.value("demo").toBool()?QStringLiteral("演示模式"):QString("%1:%2").arg(r.value("host").toString()).arg(r.value("port").toInt())));table->setItem(row,2,new QTableWidgetItem(r.value("connected").toBool()?QStringLiteral("已连接"):QStringLiteral("未连接")));table->setItem(row,3,new QTableWidgetItem(QString::number(r.value("devices").toList().size())));if(r.value("id")==selected)table->selectRow(row);++row;}};
auto* timer=new QTimer(&dialog);connect(timer,&QTimer::timeout,&dialog,refresh);timer->start(500);refresh();table->selectRow(0);
auto* actions=new QHBoxLayout;layout->addLayout(actions);const auto selected=[table]{return table->currentRow()<0?QString():table->item(table->currentRow(),0)->data(Qt::UserRole).toString();};
const auto editor=[this,&dialog,selected](bool edit){const QString id=edit?selected():QString();auto old=m_entries.value(id);if(edit&&(!old||id=="current")){AppMessageBox::information(&dialog,QStringLiteral("主界面机器人"),QStringLiteral("请在主界面修改这台机器人的连接。"));return;}
QDialog form(&dialog);form.setWindowTitle(edit?QStringLiteral("编辑机器人"):QStringLiteral("添加机器人"));auto* fields=new QFormLayout(&form);auto* name=new QLineEdit(old?old->name:QString(),&form);auto* host=new QLineEdit(old?old->host:QString(),&form);auto* port=new QSpinBox(&form);port->setRange(1,65535);port->setValue(old?old->port:50051);auto* mode=new QComboBox(&form);mode->addItem(QStringLiteral("真实机器人"),false);mode->addItem(QStringLiteral("演示机器人"),true);mode->setCurrentIndex(old&&old->demo?1:0);fields->addRow(QStringLiteral("名称"),name);fields->addRow(QStringLiteral("服务地址"),host);fields->addRow(QStringLiteral("端口"),port);fields->addRow(QStringLiteral("连接方式"),mode);
connect(mode,QOverload<int>::of(&QComboBox::currentIndexChanged),&form,[host,mode]{host->setEnabled(!mode->currentData().toBool());});
auto* buttons=new QDialogButtonBox(QDialogButtonBox::Save|QDialogButtonBox::Cancel,&form);fields->addRow(buttons);connect(buttons,&QDialogButtonBox::rejected,&form,&QDialog::reject);connect(buttons,&QDialogButtonBox::accepted,&form,[&,this]{const QString address=mode->currentData().toBool()?QStringLiteral("demo"):host->text().trimmed();if(name->text().trimmed().isEmpty()||address.isEmpty()){AppMessageBox::warning(&form,QStringLiteral("信息不完整"),QStringLiteral("请填写机器人名称和服务地址。"));return;}if(edit)editRobot(id,name->text(),address,port->value(),mode->currentData().toBool());else addRobot(name->text(),address,port->value(),mode->currentData().toBool());form.accept();});form.exec();};
for(const auto& caption:{QStringLiteral("添加"),QStringLiteral("编辑"),QStringLiteral("连接"),QStringLiteral("断开"),QStringLiteral("删除")}){auto* button=new QPushButton(caption,&dialog);actions->addWidget(button);connect(button,&QPushButton::clicked,&dialog,[&,caption]{if(caption==QStringLiteral("添加"))editor(false);else if(caption==QStringLiteral("编辑"))editor(true);else if(caption==QStringLiteral("连接"))connectRobot(selected());else if(caption==QStringLiteral("断开"))disconnectRobot(selected());else if(selected()!="current"&&AppMessageBox::question(&dialog,QStringLiteral("删除机器人"),QStringLiteral("删除连接记录?绑定到它的流程节点会保留,并提示重新选择机器人。"))==AppMessageBox::Yes)removeRobot(selected());refresh();});}
auto* close=new QDialogButtonBox(QDialogButtonBox::Close,&dialog);layout->addWidget(close);connect(close,&QDialogButtonBox::rejected,&dialog,&QDialog::reject);dialog.exec();
}
private:
struct Entry{QString id,name,host;int port=50051;bool demo=false,connected=false,wantedConnection=false;QVariantList devices;RobotClient* client=nullptr;TaskRpcRunner* runner=nullptr;TaskDeviceOptions* options=nullptr;};
void watch(const std::shared_ptr<Entry>& e){const QString id=e->id;
connect(e->client,&RobotClient::connectRequested,this,[this,id](const QString& host,int port,bool demo){auto e=m_entries.value(id);if(!e)return;e->wantedConnection=true;e->host=host;e->port=port;e->demo=demo;e->connected=false;e->devices.clear();publish();});
connect(e->client,&RobotClient::connectionChanged,this,[this,id](bool ok,int,const QString&){auto e=m_entries.value(id);if(!e||(!e->wantedConnection&&ok))return;e->connected=ok;if(!ok){e->devices.clear();if(m_target)m_target->clearRobotDeviceInfo(id);}publish();});
connect(e->client,&RobotClient::systemStatusReceived,this,[this,id](double,double,double,const QVariantList& devices){auto e=m_entries.value(id);if(!e||!e->connected||e->devices==devices)return;e->devices=devices;publish();});
connect(e->client,&RobotClient::armInfoReceived,this,[this,id](const QString& device,const QVariantMap& info){if(m_target)m_target->setRobotDeviceInfo(id,device,info);});
connect(e->client,&RobotClient::dexHandStatusReceived,this,[this,id](const QString& device,bool,bool,const QString&,const QVariantList& freedoms){QStringList names;QVariantList ids;for(const auto& value:freedoms){const int channel=value.toMap().value("id").toInt();ids<<channel;names<<QStringLiteral("关节 / 通道 %1").arg(channel);}if(m_target&&!names.isEmpty())m_target->setRobotDeviceInfo(id,device,{{"jointNames",names},{"channelIds",ids},{"dof",names.size()}});});
}
void publish(){if(!m_closing&&m_target)m_target->setRobots(robots());}
void save(){QJsonArray list;for(const auto& e:m_entries)if(e->id!="current")list.append(QJsonObject{{"id",e->id},{"name",e->name},{"host",e->host},{"port",e->port},{"demo",e->demo}});QDir().mkpath(QFileInfo(m_path).absolutePath());QSaveFile file(m_path);if(file.open(QIODevice::WriteOnly)){file.write(QJsonDocument(list).toJson());file.commit();}}
QPointer<TaskOrchestrationWidget> m_target;QString m_path;bool m_closing=false;QHash<QString,std::shared_ptr<Entry>> m_entries;
};

View File

@ -1301,7 +1301,7 @@ int main(int argc, char *argv[])
QMetaObject::invokeMethod(&window, "updateConnection", Qt::DirectConnection,
Q_ARG(bool, true), Q_ARG(int, 0), Q_ARG(QString, QStringLiteral("synthetic direct UI only")));
const auto disableDirectTransport = [&]() {
client->configureAgvMapDirect(false, QString(), host->text().trimmed(), 50053);
client->configureAgvMapDirect(false, QString());
};
disableDirectTransport();
const auto directContext = contextFor(fixtureDevice, false);

View File

@ -701,7 +701,7 @@ int main(int argc, char **argv)
const auto viewers = window.findChildren<UrdfViewerWidget *>();
for (const auto *viewer : viewers) if (viewer->modelPreviewEnabled()) { application.exit(2); return; }
window.grab().save(QStringLiteral("application-arm.png"));
QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection, Q_ARG(int, 16));
QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection, Q_ARG(int, 15));
application.processEvents();
window.grab().save(QStringLiteral("application-tasks.png"));
if (auto *tasks = window.findChild<TaskOrchestrationWidget *>()) {

View File

@ -68,7 +68,7 @@ public:
++states;
{ std::lock_guard<std::mutex> guard(mutex); stateDevices.push_back(request->header().device_id());
statePeers.push_back(context->peer()); }
stateValidityMs.store(static_cast<int>(request->header().valid_for_ms()));
stateValidityMs.store(static_cast<int>(0));
stateDeadlineMs.store(static_cast<int>(std::chrono::duration_cast<std::chrono::milliseconds>(
context->deadline() - std::chrono::system_clock::now()).count()));
const auto ready = std::chrono::steady_clock::now()
@ -287,7 +287,7 @@ void metadataAndExactWireValues()
check(wire.has_move() && wire.move().targets_size() == 1, "one slider sends exactly one target");
check(wire.move().targets(0).id() == "eye_l_up" && wire.move().targets(0).has_position_rad()
&& wire.move().targets(0).position_rad() == 0., "explicit zero survives the protobuf target oneof");
check(wire.header().device_id() == "usb_head" && !wire.header().command_id().empty(),
check(wire.header().device_id() == "usb_head" && wire.header().timestamp().seconds() > 0,
"device routing and a unique command ID reach the actual gRPC server");
check(h.call("mode", {{"mode", 0}}).success, "explicit IMMEDIATE mode is accepted");
const auto mode = h.fake.control();
@ -407,9 +407,9 @@ void customExpressionWireAndValidation()
check(wire.targets(i).id() == jointIds[i] && wire.targets(i).has_position_rad()
&& wire.targets(i).position_rad() == expected[i].toMap().value("positionRad").toDouble(),
"each custom target, including explicit zero, survives the actual protobuf wire");
check(wire.header().device_id() == "usb_head" && !wire.header().command_id().empty()
&& wire.header().timestamp().seconds() > 0 && wire.header().valid_for_ms() == 2700,
"custom execution preserves UUID, timestamp, device and duration-plus-two-seconds validity");
check(wire.header().device_id() == "usb_head" && wire.header().timestamp().seconds() > 0
&& wire.header().timestamp().seconds() > 0,
"custom execution preserves timestamp and device");
check(h.fake.expressionDeadlineMs > 1700 && h.fake.expressionDeadlineMs <= 2800,
"custom expression deadline is bounded by its transition duration plus two seconds");
check(h.fake.plays == 0 && h.fake.controls == 0,
@ -556,13 +556,13 @@ void sharedChannelSlowStateAndDiagnostics()
check(slow.success && slow.data.value("elapsedMs").toLongLong() >= 3100
&& slow.data.value("elapsedMs").toLongLong() < 5800 && ticks > 100,
"a 3.2-second read succeeds within the six-second budget while GUI events remain responsive");
check(h.fake.stateValidityMs == 6000 && h.fake.stateDeadlineMs > 5000 && h.fake.stateDeadlineMs <= 6100,
check(h.fake.stateDeadlineMs > 5000 && h.fake.stateDeadlineMs <= 6100,
"only the state read has a six-second header validity and RPC deadline");
check(slow.data.value("channelInstance").toString() == channelId && h.fake.oneStatePeer(),
"the delayed read preserves the held channel instead of reconnecting");
const auto moved = h.call("move", {{"id", "eye_l_up"}, {"positionRad", 0.}});
check(moved.success && h.fake.control().header().valid_for_ms() == 3000
check(moved.success && h.fake.control().header().timestamp().seconds() > 0
&& moved.data.value("channelInstance").toString() == channelId,
"a mutation still has its original three-second budget on the shared channel");
h.fake.holdPlay.store(true);

View File

@ -157,8 +157,8 @@ struct Page {
widget.reset(new BioHeadWidget(robot.get(), nullptr, path));
widget->resize(1660, 850); widget->show();
robot->connectRequested("127.0.0.1", port, false); robot->connectionChanged(true, 1, "loopback");
widget->setAvailableDevices({QVariantMap{{"deviceId", "usb_head"}, {"type", 8}},
QVariantMap{{"deviceId", "other_head"}, {"type", 8}}});
widget->setAvailableDevices({QVariantMap{{"deviceId", "usb_head"}, {"type", 9}},
QVariantMap{{"deviceId", "other_head"}, {"type", 9}}});
check(waitFor([&] { return spin(ids[4]) && button("bioheadEnableDebugButton")->isEnabled(); }),
"page receives current-device metadata");
tabs()->setCurrentIndex(1); pump();

View File

@ -209,8 +209,8 @@ int main(int argc, char **argv)
"no speaking or fake hardware stop button")) return false;
emit client.connectRequested("127.0.0.1", port, false);
emit client.connectionChanged(true, 1, "fixture");
page.setAvailableDevices({QVariantMap{{"deviceId", "usb_head"}, {"type", 8}},
QVariantMap{{"deviceId", "usb_head_2"}, {"type", 8}}});
page.setAvailableDevices({QVariantMap{{"deviceId", "usb_head"}, {"type", 9}},
QVariantMap{{"deviceId", "usb_head_2"}, {"type", 9}}});
if (!check(waitFor([&] { return spin(ids[4]) && preset->count() == 6; }),
"dynamic metadata and presets loaded")) return false;
for (int i = 0; i < 5; ++i) {

View File

@ -0,0 +1,24 @@
#include "workflowcanvas.h"
#include "workflowgraph.h"
#include <QApplication>
#include <QMouseEvent>
#include <QScrollBar>
#include <iostream>
#include <stdexcept>
static void check(bool ok,const char* reason){if(!ok)throw std::runtime_error(reason);}
static void mouse(QWidget* target,QEvent::Type type,const QPoint& point,Qt::MouseButton button,Qt::MouseButtons buttons,Qt::KeyboardModifiers modifiers=Qt::NoModifier){QMouseEvent event(type,point,target->mapToGlobal(point),button,buttons,modifiers);QApplication::sendEvent(target,&event);QApplication::processEvents();}
int main(int argc,char** argv){QApplication app(argc,argv);try{
QGraphicsScene scene;WorkflowCanvas canvas(&scene);canvas.resize(800,600);canvas.setSceneRect(-1000,-1000,3000,3000);canvas.show();canvas.centerOn(300,200);QApplication::processEvents();
auto* first=scene.addRect(100,100,100,70);auto* second=scene.addRect(300,100,100,70);for(auto* item:{first,second})item->setFlags(QGraphicsItem::ItemIsSelectable|QGraphicsItem::ItemIsMovable);
auto* view=canvas.viewport();const auto start=canvas.mapFromScene(QPointF(70,70)),end=canvas.mapFromScene(QPointF(440,200));
const int x=canvas.horizontalScrollBar()->value(),y=canvas.verticalScrollBar()->value();
mouse(view,QEvent::MouseButtonPress,start,Qt::LeftButton,Qt::LeftButton);mouse(view,QEvent::MouseMove,end,Qt::NoButton,Qt::LeftButton);mouse(view,QEvent::MouseButtonRelease,end,Qt::LeftButton,Qt::NoButton);
check(scene.selectedItems().size()==2,"left background drag selects both nodes");check(canvas.horizontalScrollBar()->value()==x&&canvas.verticalScrollBar()->value()==y,"left selection never pans");
const QPoint middle=canvas.mapFromScene(QPointF(150,130));mouse(view,QEvent::MouseButtonPress,middle,Qt::LeftButton,Qt::LeftButton,Qt::ControlModifier);mouse(view,QEvent::MouseButtonRelease,middle,Qt::LeftButton,Qt::NoButton,Qt::ControlModifier);check(!first->isSelected()&&second->isSelected(),"Ctrl click toggles one node without losing another");
mouse(view,QEvent::MouseButtonPress,QPoint(500,350),Qt::RightButton,Qt::RightButton);mouse(view,QEvent::MouseMove,QPoint(560,390),Qt::NoButton,Qt::RightButton);mouse(view,QEvent::MouseButtonRelease,QPoint(560,390),Qt::RightButton,Qt::NoButton);
check(canvas.horizontalScrollBar()->value()!=x&&canvas.verticalScrollBar()->value()!=y,"right drag pans canvas");check(second->isSelected(),"panning preserves selected nodes");
const QPoint before=canvas.mapFromScene(second->sceneBoundingRect().center());const auto position=second->pos();mouse(view,QEvent::MouseButtonPress,before,Qt::LeftButton,Qt::LeftButton);mouse(view,QEvent::MouseMove,before+QPoint(35,25),Qt::NoButton,Qt::LeftButton);mouse(view,QEvent::MouseButtonRelease,before+QPoint(35,25),Qt::LeftButton,Qt::NoButton);check(second->pos()!=position,"left drag still moves selected node");
QJsonObject grouped{{"nodes",QJsonArray{QJsonObject{{"id","loop"},{"x",100},{"y",100}},QJsonObject{{"id","a"},{"x",200},{"y",100},{"properties",QJsonObject{{"parentId","loop"}}}},QJsonObject{{"id","b"},{"x",300},{"y",100},{"properties",QJsonObject{{"parentId","loop"}}}}}}};
WorkflowGraph::positions(grouped,{{"loop",QPointF(150,150)},{"a",QPointF(250,150)},{"b",QPointF(350,150)}});check(WorkflowGraph::node(grouped,"a").value("x").toDouble()==250&&WorkflowGraph::node(grouped,"b").value("x").toDouble()==350,"selected loop and children move exactly once");
std::cout<<"PASS: left rubber-band multi-select, Ctrl toggle, right-button pan, preserved selection and node dragging\n";return 0;
}catch(const std::exception& e){std::cerr<<"FAIL: "<<e.what()<<"\n";return 1;}}

View File

@ -31,7 +31,7 @@ int main(int argc,char** argv){QCoreApplication app(argc,argv);try{
if(streaming)++stream;else{++unary;const bool success=TaskApi::responseSucceeded(true,QString::fromUtf8(QJsonDocument(reply.response).toJson()),detail);if(!success)std::cerr<<qPrintable(name+"."+rpc)<<" output="<<google::protobuf::DescriptorPool::generated_pool()->FindServiceByName(name.toStdString())->FindMethodByName(rpc.toStdString())->output_type()->full_name()<<": "<<QJsonDocument(reply.response).toJson().constData();CHECK(success);}
}
}
CHECK(unary==124&&stream==8);
CHECK(unary==123&&stream==8);
sim.reset();const QJsonObject movement{{"header",QJsonObject{{"device_id","right_arm"}}},{"target",QJsonObject{{"position",QJsonArray{1,0,0,0,0,0,0}}}}};
auto reply=sim.call("cmvr.api.ArmService","moveJ",movement);CHECK(reply.ok&&reply.delayMs>100);
QThread::msleep(150);auto snapshot=sim.sample("right_arm");const double mid=snapshot.value("position").toArray()[0].toDouble();CHECK(mid>0&&mid<1&&snapshot.value("moving").toBool());
@ -41,7 +41,7 @@ int main(int argc,char** argv){QCoreApplication app(argc,argv);try{
QObject::connect(&client,&RobotClient::systemStatusReceived,[&](double,double,double,const QVariantList& d){devices=d;});
client.connectToServer("",0,true);CHECK(waitFor([&]{return connected;}));client.requestSystemRefresh();
CHECK(waitFor([&]{return devices.size()>=8;}));QSet<int> types;for(const auto& value:devices)types.insert(value.toMap().value("type").toInt());
for(int type:{0,2,3,5,6,7,8,9})CHECK(types.contains(type));
for(int type:{0,2,3,5,6,7,9,11})CHECK(types.contains(type));
int telemetryCount=0;bool movingSeen=false;QObject::connect(&client,&RobotClient::telemetryReceived,[&](const QString&,const QVariantList&,const QVariantMap&,const QVariantMap& state){++telemetryCount;movingSeen=movingSeen||state.value("moving").toBool();});client.setArmTelemetry("right_arm",true);
auto run=[&](const QString& method,QJsonObject request={},int timeout=3000,bool cancel=false){
bool done=false,ok=false;QString response;
@ -58,7 +58,7 @@ int main(int argc,char** argv){QCoreApplication app(argc,argv);try{
CHECK(!sim.sample("right_arm").value("moving").toBool());
const auto expired=run("moveJ",{{"target",target}},100);CHECK(!expired.first);
const auto enabled=run("torqueOn"),enabledAgain=run("torqueOn");CHECK(enabled.first&&enabledAgain.first);
CHECK(QJsonDocument::fromJson(enabled.second.toUtf8()).object().value("command_id")!=QJsonDocument::fromJson(enabledAgain.second.toUtf8()).object().value("command_id"));
CHECK(!TaskApi::requestDescriptor("cmvr.api.ArmService","torqueOn")->FindFieldByName("command_id"));
client.disconnectFromServer();CHECK(waitFor([&]{return !connected;}));
std::cout<<"PASS: 124 unary + 8 streaming interface simulations, 8 device categories, smooth shared movement, completion, cancellation, timeout and unique IDs; no network/device connection\n";return 0;
std::cout<<"PASS: 123 unary + 8 streaming interface simulations, 8 device categories, smooth shared movement, completion, cancellation, timeout and current protocol headers; no network/device connection\n";return 0;
}catch(const std::exception& e){std::cerr<<"FAIL: "<<e.what()<<"\n";return 1;}}

View File

@ -0,0 +1,64 @@
#include <QtWidgets>
#include "freescaninterop.h"
#include "workflowgraph.h"
#include "jointpointdata.h"
#include <stdexcept>
static void check(bool value,const QString &message){if(!value)throw std::runtime_error(message.toUtf8().constData());}
static QJsonObject task(const QString &id,const QString &method) {
QJsonObject request{{"device_id","armA"}};
if(method=="moveJ")request={{"header",QJsonObject{{"device_id","armA"}}},{"target",QJsonObject{{"position",QJsonArray{0.1,0.2}}}},
{"options",QJsonObject{{"velocity",.2},{"acceleration",.3},{"asynchronous",false}}}};
return {{"id",id},{"kind","task"},{"name",id},{"deviceType",QStringLiteral("机械臂")},{"deviceId","armA"},
{"action",QStringLiteral("接口 · ")+method},{"waitMs",10},{"waitUnit","ms"},
{"parameters",QJsonObject{{"service","cmvr.api.ArmService"},{"method",method},{"request",request},{"timeoutMs",120000}}}};
}
int main(int argc,char **argv) {
QApplication app(argc,argv);try {
const auto move=task("move","moveJ");
QJsonObject doc{{"groups",QJsonArray{QJsonObject{{"id","flow"},{"name","互导"},
{"nodes",QJsonArray{task("enable","torqueOn"),QJsonObject{{"id","loop"},{"name","循环"},{"kind","loop"},{"count",2},{"waitMs",5},{"children",QJsonArray{move}}}}}}}}};
QString error;QJsonObject graph,back;
check(FreeScanInterop::exportGraph(doc,0,graph,error),error);
check(FreeScanInterop::importGraph(graph,back,error),error);
const auto imported=back["groups"].toArray().first().toObject()["nodes"].toArray();
check(imported.size()==2,"two top-level nodes");
check(imported[1].toObject()["count"]==2&&imported[1].toObject()["waitMs"]==5,"loop and final wait preserved");
check(imported[1].toObject()["children"].toArray().first().toObject()["waitMs"]==10,"per-iteration wait preserved");
check(WorkflowGraph::order(graph,error).value("")==QStringList({"enable","loop"}),"edge order");
QDir().mkpath("build/tests/interop-fixture");QFile fixture("build/tests/interop-fixture/workflow.json");
check(fixture.open(QIODevice::WriteOnly),"write fixture");fixture.write(QJsonDocument(graph).toJson());fixture.close();
auto disconnected=graph;auto edges=disconnected["edges"].toArray();edges.removeFirst();disconnected["edges"]=edges;
check(!FreeScanInterop::importGraph(disconnected,back,error),"disconnected run rejected");error.clear();
check(FreeScanInterop::importGraph(disconnected,back,error,false,true),"disconnected draft retained");
auto merged=WorkflowGraph::merge(graph,disconnected);
check(merged["edges"].toArray().size()==edges.size(),"saving does not recreate deleted edges");
WorkflowGraph::position(graph,"move",QPointF(2000,700));
check(WorkflowGraph::node(WorkflowGraph::merge(merged,graph),"move")["x"]==2000,"free position preserved");
RecordedJointPoint point;point.name="双臂点位";
JointPointTarget a;a.deviceId="armA";a.jointNames=QStringList{"J1","J2"};a.positions={.1,.2};
auto b=a;b.deviceId="armB";b.positions={.3,.4};point.arms={a,b};
QJsonArray native{QJsonObject{{"id","point"},{"type","single"},{"nodeName","双臂"},{"pointName",point.name},{"intervalSeconds",.1},{"order",0},{"x",40},{"y",40}}};
QJsonObject group{{"name","点位组"},{"points",QJsonArray{point.toJson()}},{"flows",QJsonArray{QJsonObject{{"name","流程"},{"flow",native},{"moveJVelocity",.1},{"moveJAcceleration",.2}}}}};
QJsonObject pointGraph,pointBack;
check(FreeScanInterop::exportPoints(group,0,pointGraph,error),error);
check(FreeScanInterop::importPoints(pointGraph,pointBack,error),error);
check(pointBack["points"].toArray().first().toObject()["arms"].toArray().size()==2,"parallel targets retained");
check(!FreeScanInterop::importGraph(pointGraph,back,error),"combined point cannot degrade to single task");
QFile batch("build/tests/interop-fixture/point.json");check(batch.open(QIODevice::WriteOnly),"write batch fixture");batch.write(QJsonDocument(pointGraph).toJson());
auto leading=graph;QString start;
for(const auto &v:leading.value("nodes").toArray())if(v.toObject().value("type")=="start")start=v.toObject().value("id").toString();
WorkflowGraph::setWait(leading,start,25);check(FreeScanInterop::importGraph(leading,back,error),error);
check(WorkflowGraph::leadingWait(leading,QString())==25,"initial delay retained");
RecordedJointPoint single;single.name="单臂";single.deviceId="armA";single.jointNames=a.jointNames;single.positions=a.positions;
auto sg=group;sg["points"]=QJsonArray{single.toJson()};auto sf=native;auto sn=sf[0].toObject();sn["pointName"]=single.name;sf[0]=sn;
sg["flows"]=QJsonArray{QJsonObject{{"name","流程"},{"flow",sf},{"moveJVelocity",.1},{"moveJAcceleration",.2}}};
check(FreeScanInterop::exportPoints(sg,0,pointGraph,error),error);
auto rebound=WorkflowGraph::node(pointGraph,"point"),properties=rebound["properties"].toObject();auto params=properties["nodeParams"].toArray();
for(int i=0;i<params.size();++i){auto p=params[i].toObject();if(p["name"]=="deviceId"){p["input"]="newArm";params[i]=p;}}
properties["nodeParams"]=params;rebound["properties"]=properties;WorkflowGraph::replaceNode(pointGraph,rebound);
check(FreeScanInterop::importPoints(pointGraph,pointBack,error),error);
bool reboundFound=false;for(const auto &v:pointBack["points"].toArray())if(v.toObject()["deviceId"]=="newArm")reboundFound=true;
check(reboundFound,"new device binding preserves recorded joint names");
puts("PASS real graph edges, loops and waits, draft preservation, free positions, full RPC payload and combined-point roundtrip");return 0;
}catch(const std::exception &error){fprintf(stderr,"FAIL %s\n",error.what());return 1;}
}

View File

@ -0,0 +1,75 @@
// Reproduce repeated device/model refreshes against the actual inspector.
// Includes the implementation for private role constants, without a RobotClient.
#include "../src/taskorchestrationwidget.cpp"
#include <QTabWidget>
#include <QPointer>
#include <iostream>
#include <stdexcept>
static void check(bool value,const char* message){if(!value)throw std::runtime_error(message);}
int main(int argc,char** argv){
QApplication app(argc,argv);ApplicationStyle::install(app);
try{
TaskOrchestrationWidget owner;
const QVariantMap metadata{{"jointNames",QStringList{"a","b","c","d","e","f"}}};
owner.setDeviceInfo("test_arm",metadata);
QVariantList devices{QVariantMap{{"deviceId","test_arm"},{"type",6}}};
owner.setAvailableDevices(devices);
QTreeWidget* tree=nullptr;
for(auto* candidate:owner.findChildren<QTreeWidget*>())if(candidate->columnCount()==6)tree=candidate;
check(tree,"hidden workflow tree exists");
auto makeNode=[&](const QString& id,double angle){
auto* item=new QTreeWidgetItem;
item->setText(0,id);item->setData(0,NodeIdRole,id);item->setData(0,KindRole,"task");
item->setData(0,DeviceTypeRole,QStringLiteral("机械臂"));item->setData(0,DeviceIdRole,"test_arm");
item->setData(0,ActionRole,QStringLiteral("接口 · moveJ"));
const QJsonObject request{{"target",QJsonObject{{"position",QJsonArray{angle,0,0,0,0,0}}}}};
item->setData(0,ParametersRole,QString::fromUtf8(QJsonDocument(QJsonObject{{"service","cmvr.api.ArmService"},{"method","moveJ"},{"request",request}}).toJson()));
tree->addTopLevelItem(item);return item;
};
auto* first=makeNode("first-node",0.);tree->setCurrentItem(first);
TaskProtoEditor* editor=nullptr;for(auto* widget:owner.findChildren<QWidget*>())if(auto* candidate=dynamic_cast<TaskProtoEditor*>(widget)){editor=candidate;break;}check(editor,"inspector editor exists");
auto* tabs=editor->findChild<QTabWidget*>();check(tabs&&tabs->count()>=2,"motion tabs exist");
int motion=-1;for(int i=0;i<tabs->count();++i)if(tabs->tabText(i)==QStringLiteral("运动设置"))motion=i;
check(motion>=0,"motion tab exists");tabs->setCurrentIndex(motion);
auto* table=editor->findChild<QTableWidget*>("taskJointTable");check(table,"joint editor exists");
auto* angle=editor->findChild<QLineEdit*>("jointTarget_0");check(angle,"joint input exists");angle->setText("12.");
QPointer<QTabWidget> originalTabs=tabs;
for(int i=0;i<5;++i){owner.setAvailableDevices(devices);first->setData(0,RunStateRole,QString::number(i));QApplication::processEvents();}
check(originalTabs&&originalTabs->currentIndex()==motion,"polls/model refreshes keep the live motion tab");
check(angle->text()=="12.","partial joint angle survives repeated refreshes");
devices.append(QVariantMap{{"deviceId","second_arm"},{"type",6}});owner.setAvailableDevices(devices);
check(originalTabs&&originalTabs->currentIndex()==motion,"device inventory change preserves live form");
owner.setDeviceInfo("test_arm",{{"jointLimits",QVariantMap{{"a",QVariantMap{{"lower",-2.0},{"upper",2.0}}}}}});
tabs=editor->findChild<QTabWidget*>();table=editor->findChild<QTableWidget*>("taskJointTable");
check(tabs&&tabs->tabText(tabs->currentIndex())==QStringLiteral("运动设置"),"metadata rebuild restores active tab");
check(editor->findChild<QLineEdit*>("jointTarget_0")->text()=="12.","metadata rebuild preserves unfinished input");
auto* second=makeNode("second-node",.5);tree->setCurrentItem(second);
table=editor->findChild<QTableWidget*>("taskJointTable");
check(editor->findChild<QLineEdit*>("jointTarget_0")->text()!="12.","different node does not inherit previous draft");
int covered=0;
for(const auto& serviceValue:TaskApi::catalog().value("services").toArray()) {
const auto service=serviceValue.toObject();
for(const auto& methodValue:service.value("methods").toArray()) {
const auto method=methodValue.toObject();
if(method.value("clientStreaming").toBool()||method.value("serverStreaming").toBool())continue;
auto* item=new QTreeWidgetItem;
item->setText(0,QString("interface-%1").arg(covered));item->setData(0,NodeIdRole,item->text(0));item->setData(0,KindRole,"task");
item->setData(0,DeviceTypeRole,service.value("deviceType").toString());item->setData(0,DeviceIdRole,"test_arm");
item->setData(0,ParametersRole,QString::fromUtf8(QJsonDocument(QJsonObject{{"service",service.value("service")},{"method",method.value("method")},{"request",QJsonObject()}}).toJson()));
tree->addTopLevelItem(item);tree->setCurrentItem(item);
auto* currentTabs=editor->findChild<QTabWidget*>();
if(currentTabs&&currentTabs->count()>1)currentTabs->setCurrentIndex(currentTabs->count()-1);
const auto edits=editor->findChildren<QLineEdit*>();
if(!edits.isEmpty())edits.first()->setText("12.");
const auto draft=editor->inputState();
for(int repeat=0;repeat<3;++repeat){devices[0]=QVariantMap{{"deviceId","test_arm"},{"type",6},{"poll",covered*3+repeat}};owner.setAvailableDevices(devices);item->setData(0,RunStateRole,QString::number(repeat));}
check(editor->inputState()==draft,qPrintable("poll reset: "+service.value("service").toString()+"."+method.value("method").toString()));
owner.setDeviceInfo("test_arm",{{"metadataRevision",++covered}});
check(editor->inputState()==draft,qPrintable("metadata reset: "+service.value("service").toString()+"."+method.value("method").toString()));
}
}
check(covered==123,"all unary interface nodes covered");
std::cout<<"PASS: "<<covered<<" unary node forms across 8 device categories retain active tabs and partial input on inventory/model/metadata refresh; node drafts isolated; no RPCs\n";
return 0;
}catch(const std::exception& error){std::cerr<<"FAIL: "<<error.what()<<"\n";return 1;}
}

View File

@ -0,0 +1,30 @@
#include "taskjointeditor.h"
#include "applicationstyle.h"
#include <QApplication>
#include <QElapsedTimer>
#include <QThread>
#include <iostream>
#include <stdexcept>
static void check(bool ok,const char* message){if(!ok)throw std::runtime_error(message);}
static void settle(){QElapsedTimer timer;timer.start();while(timer.elapsed()<120){QApplication::processEvents();QThread::msleep(2);}}
int main(int argc,char** argv){QApplication app(argc,argv);ApplicationStyle::install(app);try{
for(int fontSize:{13,18})for(int width:{220,280,340}){
TaskJointEditor editor;QFont font=editor.font();font.setPixelSize(fontSize);editor.setFont(font);
editor.setFixedWidth(width);
editor.setDevice({{"jointNames",QStringList{"R_SHOULDER_P","R_SHOULDER_R","RIGHT_SHOULDER_PITCH_JOINT_EXTENDED_NAME","R_ELBOW_R","R_WRIST_P","R_WRIST_Y","R_WRIST_R"}},
{"jointLimits",QVariantMap{{"R_SHOULDER_R",QVariantMap{{"lower",-2.},{"upper",2.}}}}}});
editor.show();settle();editor.adjustSize();settle();
auto* table=editor.findChild<QTableWidget*>("taskJointTable");check(table&&table->rowCount()==7,"all joints visible");
for(int i=0;i<table->rowCount();++i){
auto* row=table->cellWidget(i,0);auto* edit=row->findChild<QLineEdit*>();check(edit,"angle input exists");
const QRect cell=table->visualRect(table->model()->index(i,0));
const QRect input(edit->mapTo(table->viewport(),QPoint()),edit->size());
if(!cell.contains(input)){std::cerr<<"width="<<width<<" font="<<fontSize<<" row="<<i<<" cell="<<cell.x()<<","<<cell.y()<<","<<cell.width()<<","<<cell.height()<<" input="<<input.x()<<","<<input.y()<<","<<input.width()<<","<<input.height()<<"\n";}
check(cell.contains(input),"input rectangle fully inside row");check(edit->height()>=edit->minimumSizeHint().height(),"input fits theme minimum height");
for(auto* label:row->findChildren<QLabel*>())check(label->height()>=label->heightForWidth(label->width()),"joint name and limits fit their wrapped text");
check(table->viewport()->rect().contains(cell),"all joint rows fit without nested scrolling");
}
if(width==280&&fontSize==13)editor.grab().save("build/tests/joint-layout.png");
}
std::cout<<"PASS: seven named joints, long names, limits, 220/280/340 widths and 13/18px fonts; inputs fully contained; no nested scrollbar\n";return 0;
}catch(const std::exception& e){std::cerr<<"FAIL: "<<e.what()<<"\n";return 1;}}

View File

@ -0,0 +1,120 @@
#include <QtWidgets>
#include <stdexcept>
#define private public
#include "mainwindow.h"
#undef private
#include "jointfloweditor.h"
#include "applicationstyle.h"
static void check(bool value, const char *message) {
if (!value) throw std::runtime_error(message);
}
int main(int argc, char **argv) {
QApplication app(argc, argv);
ApplicationStyle::install(app);
QTemporaryDir settings;
QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, settings.path());
app.setOrganizationName("CMVR-Flows-Test");
app.setApplicationName("Isolated-Flows");
const QString path = QCoreApplication::applicationDirPath() + "/joint_programs.json";
QFile original(path);
const bool existed = original.exists();
original.open(QIODevice::ReadOnly);
const QByteArray backup = original.readAll();
original.close();
int result = 0;
try {
JointFlowEditor editor;
editor.addSingleNode("A", "A", 1);
const QJsonArray oldFlow = editor.toJson();
RecordedJointPoint seedPoint;seedPoint.name="A";seedPoint.deviceId="test_arm";seedPoint.jointNames=QStringList{"joint1"};seedPoint.positions={.1};
auto seedB=seedPoint;seedB.name="B";seedB.positions={.2};const QJsonArray validPoints{seedPoint.toJson(),seedB.toJson()};
QJsonObject oldGroup{{"name", "Legacy"}, {"points", validPoints},
{"flow", oldFlow}, {"moveJVelocity", .25}, {"moveJAcceleration", .5}};
QFile seed(path); check(seed.open(QIODevice::WriteOnly), "write fixture");
seed.write(QJsonDocument(QJsonObject{{"version", 2}, {"activeGroup", "Legacy"},
{"groups", QJsonArray{oldGroup, QJsonObject{{"name", "Other"}, {"points",validPoints}, {"flow", oldFlow}}}}}).toJson());
seed.close();
MainWindow window;
QSettings legacy(settings.filePath("legacy.ini"), QSettings::IniFormat);
window.loadJointPrograms(legacy);
check(window.m_jointProgramGroups[0].flows.size() == 1, "legacy default flow");
check(window.m_jointFlowEditor->toJson().first().toObject()["pointName"] == "A", "legacy nodes preserved");
window.storeCurrentJointProgramGroup();
auto &group = window.m_jointProgramGroups[0];
group.flows.append({"Second", {}, .6, .8});
window.activateJointProgramFlow(1);
check(window.m_jointFlowEditor->toJson().isEmpty(), "new flow independent");
check(window.m_jointFlowVelocitySpin->value() == .6, "per-flow velocity");
window.m_jointFlowEditor->addSingleNode("B", "B", 2);
const QJsonArray secondFlow = window.m_jointFlowEditor->toJson();
window.activateJointProgramFlow(0);
check(window.m_jointFlowEditor->toJson().first().toObject()["pointName"] == "A", "switch preserves original");
check(window.m_jointFlowVelocitySpin->value() == .25, "restore original velocity");
check(window.m_jointFlowAccelerationSpin->value() == .5, "legacy acceleration preserved");
window.activateJointProgramFlow(1);
window.saveJointPrograms();
window.loadJointPrograms(legacy);
check(window.m_jointProgramGroups[0].activeFlow == 1, "active flow persisted");
check(window.m_jointFlowEditor->toJson().first().toObject()["id"] == secondFlow.first().toObject()["id"], "second flow persisted");
check(window.m_jointProgramGroups[1].flows.size() == 1, "inactive old group migrated");
auto copy = window.m_jointProgramGroups[0];
copy.flows[0].nodes = {};
check(!window.m_jointProgramGroups[0].flows[0].nodes.isEmpty(), "group copy independent");
RecordedJointPoint a;
a.name = "A"; a.deviceId = "test_arm";
a.jointNames = QStringList{QStringLiteral("joint1")}; a.positions = {0.1};
RecordedJointPoint b = a; b.name = "B"; b.positions = {0.2};
window.m_recordedJointPoints = {a, b};
window.refreshRecordedJointPoints();
window.m_jointFlowEditor->addSingleNode("custom label", "A", 3);
QString error;
check(!window.renameRecordedJointPoint(0, "B", &error), "reject duplicate name");
check(!window.renameRecordedJointPoint(0, " ", &error), "reject blank name");
check(window.renameRecordedJointPoint(0, "Renamed", &error), "rename point");
for (const auto &flow : window.m_jointProgramGroups[0].flows) {
bool found = false;
for (const auto &value : flow.nodes) {
const auto node = value.toObject();
check(node.value("pointName") != "A", "no stale references");
found = found || node.value("pointName") == "Renamed";
}
check(found, "rename updates every flow");
}
auto *header = window.m_jointPointTable->verticalHeader();
header->moveSection(0, 1);
check(window.m_recordedJointPoints[0].name == "B"
&& window.m_recordedJointPoints[1].name == "Renamed", "header drag reorders data");
check(header->logicalIndex(0) == 0, "header and model order agree");
window.loadJointPrograms(legacy);
check(window.m_recordedJointPoints[0].name == "B"
&& window.m_recordedJointPoints[1].positions == a.positions,
"point order and angles survive reload");
window.m_jointPointMovePending = true;
check(!window.moveRecordedJointPoint(0, 1)
&& !window.renameRecordedJointPoint(0, "Blocked", &error), "block edits during motion");
window.m_jointPointMovePending = false;
if (argc > 1) {
window.m_jointFlowDialog->show();
window.m_jointFlowDialog->resize(1120, 740);
QApplication::processEvents();
window.m_jointFlowDialog->grab().save("build/tests/joint-flow-small.png");
window.m_jointFlowDialog->resize(1480, 920);
QApplication::processEvents();
window.m_jointFlowDialog->grab().save("build/tests/joint-flow-large.png");
}
puts("PASS old JSON migration, independent flows and parameters, switching, persistence and group copying");
puts("PASS point renaming across flows, duplicate/blank rejection, row drag persistence and motion guard");
} catch (const std::exception &error) {
fprintf(stderr, "FAIL: %s\n", error.what());
result = 1;
}
if (existed) {
QFile restore(path); restore.open(QIODevice::WriteOnly); restore.write(backup);
} else {
QFile::remove(path);
}
return result;
}

View File

@ -0,0 +1,67 @@
#include <QtWidgets>
#include "jointfloweditor.h"
#include "applicationstyle.h"
#include "workflowcanvas.h"
#include <stdexcept>
static void check(bool value, const char *message) {
if (!value) throw std::runtime_error(message);
}
static void pan(QGraphicsView *view, Qt::MouseButton button) {
const QPoint from(380, 150), to(180, 110);
QMouseEvent press(QEvent::MouseButtonPress, from, button, button, Qt::NoModifier);
QApplication::sendEvent(view->viewport(), &press);
QMouseEvent move(QEvent::MouseMove, to, Qt::NoButton, button, Qt::NoModifier);
QApplication::sendEvent(view->viewport(), &move);
QMouseEvent release(QEvent::MouseButtonRelease, to, button, Qt::NoButton, Qt::NoModifier);
QApplication::sendEvent(view->viewport(), &release);
}
int main(int argc, char **argv) {
QApplication app(argc, argv); ApplicationStyle::install(app);
try {
JointFlowEditor editor;
editor.resize(1050, 430); editor.show(); QApplication::processEvents();
editor.setAvailablePointNames({QStringLiteral("Point")});
auto *canvas=editor.findChild<QGraphicsView *>();
QMimeData component;component.setData("application/x-cmvr-workflow-component","point:Point");
QDragEnterEvent drag(QPoint(100,100),Qt::CopyAction,&component,Qt::LeftButton,Qt::NoModifier);
QApplication::sendEvent(canvas->viewport(),&drag);
QDropEvent drop(QPointF(100,100),Qt::CopyAction,&component,Qt::LeftButton,Qt::NoModifier);
QApplication::sendEvent(canvas->viewport(),&drop);
check(editor.toJson().size()==1,"point palette drop creates node");
editor.setEditingEnabled(false);
static_cast<WorkflowCanvas *>(canvas)->componentDropped("point:Point");
check(editor.toJson().size()==1,"execution guard blocks drop");
editor.setEditingEnabled(true);editor.clear();
for (int i = 0; i < 80; ++i) editor.addSingleNode(QString::number(i), "Point", 1);
QApplication::processEvents();
auto *view = editor.findChild<QGraphicsView *>();
const auto nodes = editor.toJson();
const QRectF last(nodes.last().toObject()["x"].toDouble(), 40, 190, 76);
check(view->mapToScene(view->viewport()->rect()).boundingRect().contains(last), "new node revealed");
editor.resetView();
for (const auto button : {Qt::RightButton, Qt::MiddleButton}) {
const int before = view->horizontalScrollBar()->value(); pan(view, button);
check(view->horizontalScrollBar()->value() > before, "pan moves viewport");
}
const QPointF center = view->mapToScene(view->viewport()->rect().center());
editor.setActiveNode(nodes.last().toObject()["id"].toString());
check(QLineF(center, view->mapToScene(view->viewport()->rect().center())).length() < 3,
"redraw preserves panned viewport");
QWheelEvent wheel(QPointF(300, 150), QPointF(300, 150), QPoint(), QPoint(0, 120),
Qt::NoButton, Qt::ControlModifier, Qt::NoScrollPhase, false);
QApplication::sendEvent(view->viewport(), &wheel);
check(view->transform().m11() > 1, "Ctrl wheel zoom");
editor.fitAll();
check(view->mapToScene(view->viewport()->rect()).boundingRect().contains(view->scene()->itemsBoundingRect()),
"fit shows all 80 cards");
editor.grab().save("build/tests/canvas-many.png");
QJsonArray shortFlow{nodes.first()};
check(editor.fromJson(shortFlow), "load another flow"); QApplication::processEvents();
check(qAbs(view->transform().m11() - 1) < .001, "switch resets zoom");
check(view->viewport()->rect().contains(view->mapFromScene(QPointF(40, 40))), "switch reveals start");
editor.grab().save("build/tests/canvas-switch.png");
check(editor.toJson() == shortFlow, "view changes leave saved flow intact");
puts("PASS 80-node canvas, right/middle pan gestures and left selection, Ctrl-wheel zoom, fit-all, redraw stability and flow switch reset");
return 0;
} catch (const std::exception &error) { fprintf(stderr, "FAIL: %s\n", error.what()); return 1; }
}

View File

@ -224,7 +224,7 @@ int main(int argc, char **argv)
before = blockWorker();
client.requestAgvManualVelocity(22, device, 1.1, 0.0, 0.0);
client.configureAgvMapDirect(true, QString(), QStringLiteral("127.0.0.1"), port);
client.configureAgvMapDirect(true, QString());
client.requestAgvMapContent(900, device, QStringLiteral("fixture_map"));
require(directBusy, "direct map is busy before old worker barrier drains");
client.requestAgvManualVelocity(23, device, 1.2, 0.0, 0.0);
@ -234,7 +234,7 @@ int main(int argc, char **argv)
waitAck(22);
require(!acks[22][0].success && service.velocities == before, "direct map busy invalidates queued manual packet");
waitFor([&]() { return mapDone && !directBusy; }, "fake config discovery rejects without vehicle sockets");
client.configureAgvMapDirect(false, QString(), QStringLiteral("127.0.0.1"), port);
client.configureAgvMapDirect(false, QString());
before = blockWorker();
client.requestAgvManualVelocity(24, device, 1.3, 0.0, 0.0);

View File

@ -1,7 +1,6 @@
#include "seeragvmapclient_fake.h"
#include "robotclient.h"
#include "cmvr/api/agv_service.grpc.pb.h"
#include "cmvr/api/configuration_service.grpc.pb.h"
#include <grpcpp/grpcpp.h>
@ -34,48 +33,6 @@ void pumpFor(int milliseconds)
}
}
// The existing configuration API is used only to discover three random
// loopback ports. It never serves or changes a real configuration file.
class FakeConfiguration final : public cmvr::api::ConfigurationService::Service {
public:
explicit FakeConfiguration(const FakeRobot &robot)
{
m_content = QStringLiteral("agv { agvs { id: \"fixture_seer\" seer_robokit_agv { "
"id: \"fixture_seer\" ip: \"127.0.0.1\" enable: true "
"port_status: %1 port_control: %2 port_config: %3 } } }")
.arg(robot.connection.statusPort).arg(robot.connection.controlPort)
.arg(robot.connection.configPort).toStdString();
}
grpc::Status ListConfigFiles(grpc::ServerContext *,
const cmvr::api::ListConfigFilesCommand::Request *,
cmvr::api::ListConfigFilesCommand::Feedback *response) override
{
++lists;
response->mutable_header()->set_success(true);
auto *file = response->add_files();
file->set_relative_path("test/agv.pbtxt");
file->set_message_type("cmvr.config.AGVRootConfig");
return grpc::Status::OK;
}
grpc::Status ReadConfigFile(grpc::ServerContext *,
const cmvr::api::ReadConfigFileCommand::Request *request,
cmvr::api::ReadConfigFileCommand::Feedback *response) override
{
++reads;
require(request->relative_path() == "test/agv.pbtxt", "bridge reads only discovered fake config path");
response->mutable_header()->set_success(true);
response->set_content(m_content);
return grpc::Status::OK;
}
std::atomic<int> lists{0};
std::atomic<int> reads{0};
private:
std::string m_content;
};
// Record legacy map calls so tests prove the enabled bridge bypasses their
// body packaging, while disabled direct mode still uses this existing API.
class FakeLegacyAgv final : public cmvr::api::AgvService::Service {
@ -136,14 +93,13 @@ public:
class FakeServices final {
public:
explicit FakeServices(const FakeRobot &robot) : configuration(robot)
explicit FakeServices(const FakeRobot &)
{
grpc::ServerBuilder builder;
builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port);
builder.RegisterService(&configuration);
builder.RegisterService(&legacy);
server = builder.BuildAndStart();
require(server && port > 0, "fake configuration and legacy services bind loopback ephemeral port");
require(server && port > 0, "fake legacy services bind loopback ephemeral port");
}
~FakeServices()
{
@ -151,7 +107,6 @@ public:
server->Wait();
}
FakeConfiguration configuration;
FakeLegacyAgv legacy;
int port = 0;
std::unique_ptr<grpc::Server> server;
@ -210,14 +165,14 @@ struct Capture {
void configure(RobotClient &client, Capture &capture, FakeServices &services, bool enabled = true, bool demo = false)
{
client.configureAgvMapDirect(enabled, QString(), QStringLiteral("127.0.0.1"), services.port);
client.configureAgvMapDirect(enabled, QStringLiteral("127.0.0.1"));
client.connectToServer(QStringLiteral("127.0.0.1"), services.port, demo);
waitFor([&] { return capture.connected; }, "RobotClient connects to loopback or local Demo source");
}
void successfulChain()
{
FakeRobot robot;
FakeRobot robot(Fault::None, true);
robot.state.fragment.store(true);
FakeServices services(robot);
RobotClient client;
@ -254,8 +209,6 @@ void successfulChain()
require(!capture.busy && capture.busyEvents.size() == 8, "four operations each open and close busy state");
require(robot.state.uploads == 1 && robot.state.switches == 1 && robot.state.reads == 2,
"callback chain sends exactly one mutation per operation");
require(services.configuration.reads == 4 && services.configuration.lists == 4,
"bridge uses existing read-only config API to resolve selected device");
require(services.legacy.uploads == 0 && services.legacy.switches == 0 && services.legacy.reads == 0,
"enabled map bridge bypasses old map gRPC wrapper");
std::lock_guard<std::mutex> lock(robot.state.captureMutex);
@ -266,7 +219,7 @@ void successfulChain()
void definiteErrors()
{
{
FakeRobot robot(Fault::HeaderRejected);
FakeRobot robot(Fault::HeaderRejected, true);
FakeServices services(robot);
RobotClient client;
Capture capture(client);
@ -279,7 +232,7 @@ void definiteErrors()
require(robot.state.uploads == 1 && services.legacy.uploads == 0, "save rejection has no hidden legacy fallback or resend");
}
{
FakeRobot robot(Fault::LoadRejected);
FakeRobot robot(Fault::LoadRejected, true);
FakeServices services(robot);
RobotClient client;
Capture capture(client);
@ -295,7 +248,7 @@ void definiteErrors()
void busyAndContextCancellation()
{
FakeRobot robot;
FakeRobot robot(Fault::None, true);
robot.state.readDelayMs.store(500);
FakeServices services(robot);
RobotClient client;
@ -327,7 +280,7 @@ void busyAndContextCancellation()
void legacyAndDemoPaths()
{
{
FakeRobot robot;
FakeRobot robot(Fault::None, true);
FakeServices services(robot);
RobotClient client;
Capture capture(client);
@ -339,11 +292,11 @@ void legacyAndDemoPaths()
require(capture.readEvents[30][0].success && capture.saveEvents[31][0].success
&& services.legacy.reads == 1 && services.legacy.uploads == 1,
"existing gRPC map interface still works when direct mode disabled");
require(robot.state.reads == 0 && robot.state.uploads == 0 && services.configuration.lists == 0,
require(robot.state.reads == 0 && robot.state.uploads == 0,
"disabled direct mode opens no TCP or config discovery requests");
}
{
FakeRobot robot;
FakeRobot robot(Fault::None, true);
FakeServices services(robot);
RobotClient client;
Capture capture(client);
@ -360,7 +313,7 @@ void legacyAndDemoPaths()
"Demo save/read/switch still completes with direct option enabled");
require(capture.busyEvents.empty() && capture.confirmations.empty()
&& robot.state.reads == 0 && robot.state.uploads == 0 && robot.state.switches == 0
&& services.configuration.lists == 0 && services.legacy.uploads == 0,
&& services.legacy.uploads == 0,
"Demo uses neither real map TCP nor config lookup nor legacy network writes");
}
std::cout << "PASS unchanged legacy gRPC and local Demo map paths\n";
@ -369,7 +322,7 @@ void legacyAndDemoPaths()
void backendQueueBarrier()
{
{
FakeRobot robot;
FakeRobot robot(Fault::None, true);
FakeServices services(robot);
RobotClient client;
Capture capture(client);
@ -382,7 +335,7 @@ void backendQueueBarrier()
client.requestAgvVelocity(deviceId, 0.3, 0.0, 0.0);
pumpFor(300);
require(capture.busy && capture.rejectedVelocities == 1, "busy map operation blocks newly requested motion");
require(services.configuration.lists == 0 && robot.state.acquires == 0 && robot.state.uploads == 0,
require(robot.state.acquires == 0 && robot.state.uploads == 0,
"direct lookup, authority and map upload all wait for prior backend worker commands");
services.legacy.holdVelocity.store(false);
waitFor([&] { return !capture.saveEvents[50].empty(); }, "queued old motions drain before direct map operation");
@ -392,7 +345,7 @@ void backendQueueBarrier()
"only preexisting motions and exactly one map mutation were dispatched");
}
{
FakeRobot robot;
FakeRobot robot(Fault::None, true);
FakeServices services(robot);
RobotClient client;
Capture capture(client);
@ -407,7 +360,7 @@ void backendQueueBarrier()
services.legacy.holdVelocity.store(false);
waitFor([&] { return !capture.busy; }, "cancelled backend barrier drains boundedly");
pumpFor(100);
require(capture.saveEvents[51].size() == 1 && services.configuration.lists == 0
require(capture.saveEvents[51].size() == 1
&& robot.state.acquires == 0 && robot.state.uploads == 0,
"cancelled barrier never runs direct lookup or mutation and produces no late result");
}
@ -423,6 +376,6 @@ int main(int argc, char **argv)
busyAndContextCancellation();
legacyAndDemoPaths();
backendQueueBarrier();
std::cout << "PASS RobotClient SEER map bridge integration: only ephemeral loopback services used\n";
std::cout << "PASS RobotClient SEER map bridge integration: loopback services only; standard vehicle ports and ephemeral gRPC port\n";
return 0;
}

View File

@ -19,9 +19,10 @@ if not compiler:
raise SystemExit("Add the selected Qt Kit MinGW bin directory to PATH first")
Path("build/tests").mkdir(parents=True, exist_ok=True)
test = sys.argv[1] if len(sys.argv) > 1 else "taskapi_test"
if test not in {"taskapi_test", "taskrpcrunner_test", "task_device_ui_test", "demosimulator_test",
if test not in {"workflow_robot_test", "canvas_selection_test", "joint_layout_test", "inspector_refresh_test", "startup_test", "robotclient_seer_map_integration_test", "taskapi_test", "taskrpcrunner_test", "task_device_ui_test", "demosimulator_test",
"bioheadexpressionstore_test", "bioheadjointclient_test",
"bioheadwidget_test", "bioheadlocalexpressions_test"}:
"bioheadwidget_test", "bioheadlocalexpressions_test", "joint_program_flows_test",
"jointflow_canvas_test", "freescaninterop_test", "workflow_storage_test"}:
raise SystemExit("Unknown test")
obj = "build/tests/" + test + ".o"
with Path("build/tests/taskapi-build.log").open("w") as log:
@ -33,7 +34,7 @@ with Path("build/tests/taskapi-build.log").open("w") as log:
object_script = Path("object_script.CmvrControlStation_updated.Release")
objects = object_script.read_text().splitlines()
objects = [p for p in objects if p.strip() != "build/release/obj/main.o"] + [obj]
if test == "task_device_ui_test":
if test in {"task_device_ui_test", "inspector_refresh_test", "workflow_robot_test"}:
objects = [p for p in objects if p.strip() != "build/release/obj/taskorchestrationwidget.o"]
response_file = Path("build/tests/taskapi-objects")
response_file.write_text("\n".join(objects))

View File

@ -138,7 +138,7 @@ struct Fixture {
// only to loopback; no fixture can contact a configured real robot.
class FakePort final {
public:
explicit FakePort(Fixture &fixture) : m_fixture(fixture)
explicit FakePort(Fixture &fixture, quint16 listenPort = 0) : m_fixture(fixture), m_listenPort(listenPort)
{
m_thread = std::thread([this] { serve(); });
QElapsedTimer elapsed;
@ -203,7 +203,7 @@ private:
void serve()
{
QTcpServer listener;
if (!listener.listen(QHostAddress::LocalHost, 0)) {
if (!listener.listen(QHostAddress::LocalHost, m_listenPort)) {
m_failed.store(true);
return;
}
@ -240,14 +240,15 @@ private:
Fixture &m_fixture;
std::atomic<bool> m_stop{false};
std::atomic<bool> m_failed{false};
quint16 m_listenPort = 0;
std::atomic<int> m_port{0};
std::thread m_thread;
};
class FakeRobot final {
public:
explicit FakeRobot(Fault fault = Fault::None)
: state(fault), status(state), control(state), config(state)
explicit FakeRobot(Fault fault = Fault::None, bool standardPorts = false)
: state(fault), status(state, standardPorts ? 19204 : 0), control(state, standardPorts ? 19205 : 0), config(state, standardPorts ? 19207 : 0)
{
connection.host = QStringLiteral("127.0.0.1");
connection.statusPort = status.port();

34
tests/startup_test.cpp Normal file
View File

@ -0,0 +1,34 @@
#include "mainwindow.h"
#include "robotclient.h"
#include "applicationstyle.h"
#include <QApplication>
#include <QCheckBox>
#include <QStackedWidget>
#include <QSettings>
#include <QTemporaryDir>
#include <QTimer>
#include <google/protobuf/descriptor.h>
#include <iostream>
int main(int argc,char** argv) {
QApplication app(argc,argv);
app.setOrganizationName("CMVR-Startup-Test");app.setApplicationName("Startup-Test");
QTemporaryDir settings;
QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings::setPath(QSettings::IniFormat,QSettings::UserScope,settings.path());
QSettings initial;initial.setValue("connection/demo",false);initial.sync();
ApplicationStyle::install(app);
const auto* pool=google::protobuf::DescriptorPool::generated_pool();
if(pool->FindServiceByName("cmvr.api.ConfigurationService")) {std::cerr<<"FAIL: deleted service is still linked\n";return 1;}
MainWindow window;
for(auto* client:window.findChildren<RobotClient*>())client->disconnectFromServer();
auto* pages=window.findChild<QStackedWidget*>("pages");
if(!pages||pages->count()!=17) {std::cerr<<"FAIL: page count\n";return 2;}
for(int i=0;i<17;++i) {
if(!QMetaObject::invokeMethod(&window,"selectPage",Qt::DirectConnection,Q_ARG(int,i))||pages->currentIndex()!=i){std::cerr<<"FAIL: navigation "<<i<<"\n";return 3;}
}
if(window.findChild<QWidget*>("configurationNavButton")){std::cerr<<"FAIL: deleted navigation\n";return 4;}
window.show();QTimer::singleShot(1000,&app,&QCoreApplication::quit);
const int code=app.exec();
std::cout<<"PASS: Release main window constructed, shown and closed; 17 pages aligned; deleted config service and navigation absent; no physical device commands\n";
return code;
}

View File

@ -125,6 +125,7 @@ int main(int argc,char** argv){
});
const bool accepted=editTaskDialog(&owner,name,type,id,action,params,wait,unit,devices,{});check(accepted,qPrintable(failure));
check(std::abs(params.value("positions").toArray()[0].toDouble()-M_PI/4)<1e-10,"saved legacy request remains radians");
if(argc>1){owner.resize(1480,920);owner.show();QApplication::processEvents();owner.grab().save("build/tests/task-workspace.png");}
std::printf("PASS: 124 forms; joint/motor/station/map/coordinate selectors; tabs and one scroll area; no clipping or footer overlap; partial-input retention; JSON requests; no RPCs\n");return 0;
}catch(const std::exception& e){std::fprintf(stderr,"FAIL: %s\n",e.what());return 1;}
}

View File

@ -14,6 +14,9 @@ QJsonObject task(const QString& action,const QJsonObject& request={}){
QJsonObject flow(const QJsonArray& nodes){return {{"version",1},{"groups",QJsonArray{QJsonObject{{"name","offline example"},{"nodes",nodes}}}}};}
int main(){try{
QString error;
CHECK(!TaskApi::requestDescriptor("cmvr.api.ArmService","moveJPose"));
CHECK(!TaskApi::validateRequest("cmvr.api.ArmService","moveJ",{{"header",QJsonObject{{"device_id","arm"},{"command_id","obsolete"}}}},error));
error.clear();
const auto catalog=TaskApi::catalog();CHECK(catalog.value("services").toArray().size()==8);
int unary=0,streams=0;for(const auto& service:catalog.value("services").toArray())for(const auto& method:service.toObject().value("methods").toArray()){
const auto m=method.toObject();if(m.value("clientStreaming").toBool()||m.value("serverStreaming").toBool())++streams;else ++unary;
@ -47,12 +50,12 @@ int main(){try{
CHECK(simple.value("request").toObject().value("device_id")=="arm-b");CHECK(!simple.value("request").toObject().contains("header"));
CHECK(TaskApi::validateRequest("cmvr.api.ArmService","torqueOn",simple.value("request").toObject(),error));
auto apply=task(QString::fromUtf8("接口 · ApplyUserCoordinateSystem"),{{"name",QString::fromUtf8("测试坐标系")},{"expected_revision","0"}});
auto pose=task(QString::fromUtf8("接口 · moveJPose"),{{"user_coordinate_name",QString::fromUtf8("测试坐标系")},{"user_coordinate_revision","0"},{"target",QJsonObject{{"x",.1},{"y",.2},{"z",.3},{"rx",0},{"ry",0},{"rz",0}}},{"options",QJsonObject{{"velocity",.1},{"acceleration",.5}}}});
auto pose=task(QString::fromUtf8("接口 · moveL"),{{"user_coordinate_name",QString::fromUtf8("测试坐标系")},{"user_coordinate_revision","0"},{"target",QJsonObject{{"x",.1},{"y",.2},{"z",.3},{"rx",0},{"ry",0},{"rz",0}}},{"options",QJsonObject{{"velocity",.1},{"acceleration",.5}}}});
auto sample=flow(QJsonArray{apply,QJsonObject{{"kind","loop"},{"name","repeat"},{"count",2},{"children",QJsonArray{pose}}}});
CHECK(TaskApi::normalize(sample,error));
auto tamper=sample;auto groups=tamper.value("groups").toArray();auto group=groups[0].toObject();auto nodes=group.value("nodes").toArray();auto node=nodes[0].toObject();auto ex=node.value("execution").toObject();ex.insert("method","torqueOn");node.insert("execution",ex);nodes[0]=node;group.insert("nodes",nodes);groups[0]=group;tamper.insert("groups",groups);CHECK(!TaskApi::normalize(tamper,error));
auto unknown=flow(QJsonArray{task("unknown")});CHECK(!TaskApi::normalize(unknown,error));
auto invalid=flow(QJsonArray{task(QString::fromUtf8("接口 · moveJPose"),{{"not_a_field",1}})});CHECK(!TaskApi::normalize(invalid,error));
auto invalid=flow(QJsonArray{task(QString::fromUtf8("接口 · moveL"),{{"not_a_field",1}})});CHECK(!TaskApi::normalize(invalid,error));
auto tooMany=flow(QJsonArray{QJsonObject{{"kind","loop"},{"count",100000},{"children",QJsonArray{task("MoveJ"),task("MoveJ")}}}});CHECK(!TaskApi::normalize(tooMany,error));
auto badPolicy=sample;badPolicy.insert("executionPolicy",QJsonObject{{"onError","continue"}});CHECK(!TaskApi::normalize(badPolicy,error));
QString detail;CHECK(!TaskApi::responseSucceeded(true,R"({"header":{"success":false,"errorMessage":"IK failed"}})",detail));CHECK(detail=="IK failed");
@ -61,6 +64,5 @@ int main(){try{
auto fixture=sample;auto fixedGroups=fixture.value("groups").toArray();auto fixedGroup=fixedGroups[0].toObject();fixedGroup.insert("id","example-group");auto fixedNodes=fixedGroup.value("nodes").toArray();auto fixedApply=fixedNodes[0].toObject();fixedApply.insert("id","example-apply");fixedNodes[0]=fixedApply;auto fixedLoop=fixedNodes[1].toObject();fixedLoop.insert("id","example-loop");auto fixedChildren=fixedLoop.value("children").toArray();auto fixedPose=fixedChildren[0].toObject();fixedPose.insert("id","example-movej-pose");fixedChildren[0]=fixedPose;fixedLoop.insert("children",fixedChildren);fixedNodes[1]=fixedLoop;fixedGroup.insert("nodes",fixedNodes);fixedGroups[0]=fixedGroup;fixture.insert("groups",fixedGroups);sample=fixture;
QDir().mkpath("docs/task-flow");
for(const auto& pair:QList<QPair<QString,QJsonObject>>{{"task_operations.json",catalog},{"example.task.json",sample}}){QFile file("docs/task-flow/"+pair.first);CHECK(file.open(QIODevice::WriteOnly));file.write(QJsonDocument(pair.second).toJson(QJsonDocument::Indented));}
QFile saved("bin/release/data/task_orchestration.json");if(saved.open(QIODevice::ReadOnly)){auto doc=QJsonDocument::fromJson(saved.readAll()).object();CHECK(TaskApi::normalize(doc,error));}
std::cout<<"PASS: "<<unary<<" unary interfaces, "<<streams<<" streaming definitions; typed descriptors, legacy migration, id stability, header placement, loop limits, ambiguity rejection, business errors, existing-file read-only validation and example/catalog export; no network or hardware calls\n";
std::cout<<"PASS: "<<unary<<" unary interfaces, "<<streams<<" streaming definitions; typed descriptors, legacy migration, id stability, header placement, loop limits, ambiguity rejection, business errors, example/catalog export; no network or hardware calls\n";
}catch(const std::exception& e){std::cerr<<"FAIL: "<<e.what()<<"\n";return 1;}return 0;}

View File

@ -20,7 +20,7 @@ public:
if(ctx->IsCancelled())return {grpc::StatusCode::CANCELLED,"fake canceled"};r->mutable_header()->set_success(true);return grpc::Status::OK;
}
grpc::Status torqueOn(grpc::ServerContext*,const cmvr::api::CommandHeader::Request* q,cmvr::api::CommandHeader::Feedback* r)override{
receivedHeader.store(q->device_id()=="fake-arm"&&!q->command_id().empty()&&q->timestamp().seconds()>0);r->set_success(true);return grpc::Status::OK;
receivedHeader.store(q->device_id()=="fake-arm"&&q->timestamp().seconds()>0);r->set_success(true);return grpc::Status::OK;
}
grpc::Status ExecuteJsonCommand(grpc::ServerContext*,const cmvr::api::JsonDeviceCommand::Request*,cmvr::api::JsonDeviceCommand::Feedback* r)override{
r->mutable_header()->set_success(true);r->set_response_json("{\"coordinate_api_version\":"+std::to_string(capability.load())+",\"movel_target_mode\":\"absolute_selected_frame\"}");return grpc::Status::OK;
@ -44,5 +44,5 @@ int main(int argc,char** argv){QCoreApplication app(argc,argv);try{
fake.capability=4;auto moved=run("moveL",custom);CHECK(TaskApi::responseSucceeded(moved.first,moved.second,detail));CHECK(fake.motions==1);
fake.block=true;auto canceled=run("GetArmInfo",{},true);CHECK(!canceled.first);fake.block=false;
auto again=run("GetArmInfo");CHECK(TaskApi::responseSucceeded(again.first,again.second,detail));
server->Shutdown();std::cout<<"PASS: real async loopback Unary RPC, nested/direct headers, fresh command IDs, valid response JSON, coordinate handshake rejection, fake motion dispatch, cancellation and subsequent calls; no hardware\n";
server->Shutdown();std::cout<<"PASS: real async loopback Unary RPC, nested/direct headers, current protocol timestamps, valid response JSON, coordinate handshake rejection, fake motion dispatch, cancellation and subsequent calls; no hardware\n";
}catch(const std::exception& e){std::cerr<<"FAIL: "<<e.what()<<"\n";return 1;}return 0;}

View File

@ -0,0 +1,82 @@
#include "../src/taskorchestrationwidget.cpp"
#include "workflowrobotmanager.h"
#include "cmvr/api/system_service.grpc.pb.h"
#include "cmvr/api/arm_service.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <QTemporaryDir>
#include <QElapsedTimer>
#include <QThread>
#include <atomic>
#include <iostream>
#include <stdexcept>
static void check(bool ok,const char* reason){if(!ok)throw std::runtime_error(reason);}
static void waitFor(std::function<bool()> predicate,const char* reason,int limit=6000){QElapsedTimer t;t.start();while(!predicate()&&t.elapsed()<limit){QApplication::processEvents();QThread::msleep(2);}check(predicate(),reason);}
class FakeSystem final:public cmvr::api::SystemService::Service{
public:
grpc::Status GetSystemInfo(grpc::ServerContext*,const cmvr::api::GetSystemInfoCommand::Request*,cmvr::api::GetSystemInfoCommand::Feedback* r)override{r->mutable_header()->set_success(true);r->set_system_name("loopback robot");return grpc::Status::OK;}
grpc::Status GetSystemStatus(grpc::ServerContext*,const cmvr::api::GetSystemStatusCommand::Request*,cmvr::api::GetSystemStatusCommand::Feedback* r)override{r->mutable_header()->set_success(true);auto* d=r->add_device_list();d->set_device_id("shared_arm");d->set_device_type(cmvr::api::Robot);d->set_device_kind(cmvr::api::DEVICE_KIND_ARM);auto* c=r->add_device_list();c->set_device_id("camera_only");c->set_device_type(cmvr::api::Camera);c->set_device_kind(cmvr::api::DEVICE_KIND_CAMERA);return grpc::Status::OK;}
};
class FakeArm final:public cmvr::api::ArmService::Service{
public:std::atomic<int> calls{0};int joints=6;
grpc::Status torqueOn(grpc::ServerContext*,const cmvr::api::CommandHeader::Request* q,cmvr::api::CommandHeader::Feedback* r)override{if(q->device_id()!="shared_arm")return {grpc::StatusCode::INVALID_ARGUMENT,"wrong robot device"};++calls;r->set_success(true);return grpc::Status::OK;}
grpc::Status GetArmInfo(grpc::ServerContext*,const cmvr::api::GetArmInfo::Request*,cmvr::api::GetArmInfo::Response* r)override{r->mutable_header()->set_success(true);r->set_dof(joints);for(int i=0;i<joints;++i)r->add_joint_names("joint_"+std::to_string(i));return grpc::Status::OK;}
};
struct FakeRobot{
FakeSystem system;FakeArm arm;int port=0;std::unique_ptr<grpc::Server> server;
explicit FakeRobot(int joints){arm.joints=joints;grpc::ServerBuilder b;b.AddListeningPort("127.0.0.1:0",grpc::InsecureServerCredentials(),&port);b.RegisterService(&system);b.RegisterService(&arm);server=b.BuildAndStart();check(server&&port,"fake robot starts");}
~FakeRobot(){server->Shutdown();server->Wait();}
};
struct StorageGuard{
QString path=QCoreApplication::applicationDirPath()+"/data/task_orchestration.json";QByteArray content;bool existed=false;
StorageGuard(){QFile f(path);existed=f.exists();if(f.open(QIODevice::ReadOnly))content=f.readAll();f.close();QFile::remove(path);}
~StorageGuard(){if(existed){QFile f(path);if(f.open(QIODevice::WriteOnly))f.write(content);}else QFile::remove(path);}
};
int main(int argc,char** argv){QApplication app(argc,argv);ApplicationStyle::install(app);StorageGuard storage;try{
QTemporaryDir files;FakeRobot first(6),second(7);TaskOrchestrationWidget target;RobotClient current;TaskRpcRunner currentRunner(&current);
const QString path=files.filePath("robots.json");QString a,b;
{
WorkflowRobotManager manager(&current,&currentRunner,&target,nullptr,path);
a=manager.addRobot("Robot A","127.0.0.1",first.port,false);b=manager.addRobot("Robot B","127.0.0.1",second.port,false);
check(!a.isEmpty()&&!b.isEmpty()&&a!=b,"distinct persistent robot identities");manager.connectRobot(a);manager.connectRobot(b);
waitFor([&]{return target.devicesForRobot(a).size()==2&&target.devicesForRobot(b).size()==2;},"each robot has its own discovered inventory");
const auto execution=[&](const QString& robot){auto e=TaskApi::execution(QStringLiteral("机械臂"),QStringLiteral("接口 · torqueOn"),"shared_arm",{});e.insert("robotId",robot);return e;};
const auto call=[&](QJsonObject e){bool done=false,success=false;manager.run(e,[&](bool ok,const QString& response){QString error;success=TaskApi::responseSucceeded(ok,response,error);done=true;});waitFor([&]{return done;},"routed call completed");return success;};
check(call(execution(a))&&first.arm.calls==1&&second.arm.calls==0,"same device ID routes only to robot A");
check(call(execution(b))&&first.arm.calls==1&&second.arm.calls==1,"same device ID routes only to robot B");
manager.requestInfo(a,"shared_arm",QStringLiteral("机械臂"));manager.requestInfo(b,"shared_arm",QStringLiteral("机械臂"));
waitFor([&]{return target.robotDeviceInfo(a,"shared_arm").value("jointNames").toStringList().size()==6&&target.robotDeviceInfo(b,"shared_arm").value("jointNames").toStringList().size()==7;},"same-named devices keep distinct joint metadata");
QTreeWidget* tree=nullptr;for(auto* t:target.findChildren<QTreeWidget*>())if(t->columnCount()==6)tree=t;check(tree,"inspector tree found");
auto* node=new QTreeWidgetItem;node->setText(0,"isolated arm");node->setData(0,NodeIdRole,"isolated");node->setData(0,KindRole,"task");node->setData(0,RobotIdRole,a);node->setData(0,DeviceTypeRole,QStringLiteral("机械臂"));node->setData(0,DeviceIdRole,"shared_arm");node->setData(0,ActionRole,QStringLiteral("接口 · moveJ"));
node->setData(0,ParametersRole,QString::fromUtf8(QJsonDocument(QJsonObject{{"service","cmvr.api.ArmService"},{"method","moveJ"},{"request",QJsonObject()}}).toJson()));tree->addTopLevelItem(node);tree->setCurrentItem(node);
auto* robotChoice=target.findChild<QComboBox*>("workflowNodeRobot");auto* deviceChoice=target.findChild<QComboBox*>("workflowNodeDevice");check(robotChoice&&deviceChoice,"separate robot and device selectors exist");check(deviceChoice->count()==1&&deviceChoice->currentText()=="shared_arm","arm node excludes camera inventory");
auto jointRows=[&]{for(auto* w:target.findChildren<QWidget*>())if(auto* e=dynamic_cast<TaskProtoEditor*>(w)){if(auto* t=e->findChild<QTableWidget*>("taskJointTable"))return t->rowCount();}return -1;};
check(jointRows()==6,"robot A inspector shows six joints");robotChoice->setCurrentIndex(robotChoice->findData(b));QApplication::processEvents();check(jointRows()==7&&node->data(0,RobotIdRole)==b,"switching robot selects its seven-joint device");
target.resize(1500,900);target.show();for(auto* button:target.findChildren<QPushButton*>())if(button->text()==QStringLiteral("节点参数"))button->setChecked(true);QElapsedTimer settle;settle.start();while(settle.elapsed()<200){QApplication::processEvents();QThread::msleep(2);}QPushButton* saveButton=nullptr;for(auto* button:target.findChildren<QPushButton*>())if(button->text()==QStringLiteral("保存节点参数"))saveButton=button;
check(saveButton&&target.rect().contains(QRect(saveButton->mapTo(&target,QPoint()),saveButton->size())),"parameter save stays visible in fixed inspector footer");
auto* parameterScroll=target.findChild<QScrollArea*>("workflowParameterScroll");check(parameterScroll,"input parameters have their own scroll area");parameterScroll->verticalScrollBar()->setValue(parameterScroll->verticalScrollBar()->maximum());QApplication::processEvents();
check(robotChoice->isVisible()&&target.rect().contains(QRect(robotChoice->mapTo(&target,QPoint()),robotChoice->size())),"robot selection remains visible while parameters scroll");
parameterScroll->verticalScrollBar()->setValue(0);QApplication::processEvents();target.grab().save("build/tests/workflow-layout.png");
target.clearRobotDeviceInfo(a);robotChoice->setCurrentIndex(robotChoice->findData(a));waitFor([&]{return jointRows()==6;},"selecting a robot automatically reloads its joint metadata");
// Round-trip local robot binding into the same role/device-slot structure used by the web editor.
QJsonArray nodes;for(const auto& robot:QStringList{a,b}){auto e=execution(robot);e.remove("robotId");nodes.append(QJsonObject{{"id",robot},{"kind","task"},{"name",robot},{"robotId",robot},{"robotName",robot==a?"Robot A":"Robot B"},{"deviceType",QStringLiteral("机械臂")},{"deviceId","shared_arm"},{"action",QStringLiteral("接口 · torqueOn")},{"parameters",QJsonObject{{"service","cmvr.api.ArmService"},{"method","torqueOn"},{"request",QJsonObject()}}},{"execution",e}});}
QJsonObject graph,restored;QString error;check(FreeScanInterop::exportGraph({{"groups",QJsonArray{QJsonObject{{"name","two robots"},{"nodes",nodes}}}}},0,graph,error),qPrintable(error));
int roles=0;for(const auto& n:graph.value("nodes").toArray())if(n.toObject().value("type")=="start")roles=n.toObject().value("properties").toObject().value("resourceRoles").toArray().size();check(roles==2,"web export has two independent robot roles");
auto changed=graph;auto changedNodes=changed.value("nodes").toArray();QJsonObject destination;
for(const auto& n:changedNodes)if(n.toObject().value("id")==b)destination=n.toObject().value("properties").toObject().value("executionTarget").toObject();
for(int i=0;i<changedNodes.size();++i){auto n=changedNodes[i].toObject();if(n.value("id")==a){auto p=n.value("properties").toObject();p.insert("cmvrRobotId",b);p.insert("executionTarget",destination);n.insert("properties",p);changedNodes[i]=n;}}
changed.insert("nodes",changedNodes);const auto merged=WorkflowGraph::merge(changed,graph);check(WorkflowGraph::node(merged,a).value("properties").toObject().value("executionTarget").toObject().value("roleKey")==destination.value("roleKey"),"changing robot also changes persisted web execution role");
check(FreeScanInterop::importGraph(graph,restored,error),qPrintable(error));auto roundTrip=restored.value("groups").toArray()[0].toObject().value("nodes").toArray();check(roundTrip[0].toObject().value("robotId")==a&&roundTrip[1].toObject().value("robotId")==b,"robot IDs survive export/import");
manager.disconnectRobot(a);waitFor([&]{return target.devicesForRobot(a).isEmpty();},"disconnect A clears only A devices");check(!call(execution(a))&&call(execution(b)),"disconnect A never redirects its request to connected B");
manager.connectRobot(a);waitFor([&]{return target.robotDeviceInfo(a,"shared_arm").value("jointNames").toStringList().size()==6;},"reconnecting an already selected robot automatically reloads metadata");
manager.removeRobot(a);check(!manager.client(a)&&manager.client(b),"removal does not affect another connection");
const auto demoA=manager.addRobot("Demo A","demo",50051,true),demoB=manager.addRobot("Demo B","demo",50051,true);manager.connectRobot(demoA);manager.connectRobot(demoB);
waitFor([&]{return target.devicesForRobot(demoA).size()>=8&&target.devicesForRobot(demoB).size()>=8;},"two independent demo inventories");
auto simA=manager.client(demoA)->simulator(),simB=manager.client(demoB)->simulator();check(simA!=simB,"demo robots have separate simulated worlds");
simA->call("cmvr.api.ArmService","moveJ",{{"header",QJsonObject{{"device_id","right_arm"}}},{"target",QJsonObject{{"position",QJsonArray{1.,0.,0.,0.,0.,0.,0.}}}}});
check(simA->sample("right_arm").value("moving").toBool()&&!simB->sample("right_arm").value("moving").toBool(),"demo movement does not leak into another robot with the same device ID");
}
{
WorkflowRobotManager restored(&current,&currentRunner,&target,nullptr,path);check(restored.client(b)&&!restored.client(a),"robot registry persists add/remove");for(const auto& v:restored.robots())check(!v.toMap().value("connected").toBool(),"saved robots never auto-connect at startup");
}
std::cout<<"PASS: two loopback cmvr-es servers, same device ID isolated RPC routes/metadata, separate selectors, 6/7 joint switch, web role round-trip, independent disconnect/remove, isolated demo motion and persistent registry; no real devices\n";return 0;
}catch(const std::exception& e){std::cerr<<"FAIL: "<<e.what()<<"\n";return 1;}}

View File

@ -0,0 +1,37 @@
#include <QtWidgets>
#include <stdexcept>
#define private public
#include "taskorchestrationwidget.h"
#undef private
#include "workflowcanvas.h"
#include "workflowgraph.h"
#include "taskprotoeditor.h"
#include "applicationstyle.h"
static void check(bool value,const char *message){if(!value)throw std::runtime_error(message);}
int main(int argc,char **argv){QApplication app(argc,argv);ApplicationStyle::install(app);
const QString storage=QCoreApplication::applicationDirPath()+"/data/task_orchestration.json";
QFile old(storage);const bool existed=old.exists();old.open(QIODevice::ReadOnly);const auto backup=old.readAll();old.close();int status=0;
try {QFile fixture("build/tests/interop-fixture/workflow.json");check(fixture.open(QIODevice::ReadOnly),"fixture");auto graph=QJsonDocument::fromJson(fixture.readAll()).object();
TaskOrchestrationWidget w;QString error;check(w.restoreGraph(graph,error),qPrintable(error));w.save();
w.setDeviceInfo("armA",QVariantMap{{"jointNames",QStringList{"J1","J2"}}});w.resize(1480,920);w.show();QApplication::processEvents();
auto *canvas=static_cast<WorkflowCanvas *>(w.m_flowView);QGraphicsItem *move=nullptr;
for(auto *item:w.m_flowScene->items())if(item->data(7010)=="move")move=item;
check(move,"device node rendered");move->setSelected(true);QApplication::processEvents();
bool visibleEditor=false;for(auto *editor:w.findChildren<TaskProtoEditor *>())visibleEditor|=editor->isVisible();check(visibleEditor,"typed parameter editor in sidebar");
w.grab().save("build/tests/workflow-graph-ui.png");
QString start;for(const auto &v:w.m_graph.value("nodes").toArray())if(v.toObject().value("type")=="start")start=v.toObject().value("id").toString();
const auto childBefore=WorkflowGraph::node(w.m_graph,"move");const auto loopBefore=WorkflowGraph::node(w.m_graph,"loop");
const QPointF delta(77,133);WorkflowGraph::position(w.m_graph,"loop",QPointF(loopBefore["x"].toDouble(),loopBefore["y"].toDouble())+delta);
check(WorkflowGraph::node(w.m_graph,"move")["x"].toDouble()==childBefore["x"].toDouble()+77,"moving container moves children");
canvas->connectionRemoved(start,"enable");check(!w.m_graph.value("edges").toArray().isEmpty(),"remaining edges");
QFile saved(storage);check(saved.open(QIODevice::ReadOnly),"storage");auto root=QJsonDocument::fromJson(saved.readAll()).object();
check(root.contains("flows")&&!root.contains("groups")&&!root.contains("version"),"canonical flow records");
auto record=root.value("flows").toArray().at(w.m_activeGroup).toObject();auto persisted=QJsonDocument::fromJson(record.value("flowData").toString().toUtf8()).object();
check(persisted==w.m_graph,"saved exact graph");
TaskOrchestrationWidget reopened;check(reopened.m_graph==persisted,"reopen preserves disconnected draft and positions");
QString source;for(const auto &v:reopened.m_graph.value("edges").toArray())if(v.toObject().value("targetNodeId")=="enable")source=v.toObject().value("sourceNodeId").toString();check(source.isEmpty(),"deleted edge not reconstructed on reload");
check(canvas->connectionRequested(start,"enable",error),qPrintable(error));w.save();check(!WorkflowGraph::order(w.m_graph,error).isEmpty(),qPrintable(error));
puts("PASS canonical storage, exact disconnected draft reload, deleted-edge persistence, container movement and typed sidebar");
}catch(const std::exception &e){fprintf(stderr,"FAIL %s\n",e.what());status=1;}
if(existed){QFile restore(storage);restore.open(QIODevice::WriteOnly);restore.write(backup);}else QFile::remove(storage);return status;
}

View File

@ -84,7 +84,6 @@
<item><widget class="QPushButton" name="hlcNavButton"><property name="text"><string>HLC 控制</string></property><property name="checkable"><bool>true</bool></property><property name="iconSize"><size><width>18</width><height>18</height></size></property><property name="objectName"><string>navButton</string></property></widget></item>
<item><widget class="QPushButton" name="testNavButton"><property name="text"><string>接口调试</string></property><property name="checkable"><bool>true</bool></property><property name="iconSize"><size><width>18</width><height>18</height></size></property><property name="objectName"><string>navButton</string></property></widget></item>
<item><widget class="QPushButton" name="quicNavButton"><property name="text"><string>QUIC Server</string></property><property name="checkable"><bool>true</bool></property><property name="iconSize"><size><width>18</width><height>18</height></size></property><property name="objectName"><string>navButton</string></property></widget></item>
<item><widget class="QPushButton" name="configurationNavButton"><property name="text"><string>项目配置</string></property><property name="checkable"><bool>true</bool></property><property name="iconSize"><size><width>18</width><height>18</height></size></property><property name="objectName"><string>navButton</string></property></widget></item>
<item><widget class="QPushButton" name="diagnosticsNavButton"><property name="text"><string>运行日志</string></property><property name="checkable"><bool>true</bool></property><property name="iconSize"><size><width>18</width><height>18</height></size></property><property name="objectName"><string>navButton</string></property></widget></item>
<item><spacer name="sidebarSpacer"><property name="orientation"><enum>Qt::Vertical</enum></property><property name="sizeHint" stdset="0"><size><width>20</width><height>40</height></size></property></spacer></item>
<item><widget class="QLabel" name="connectionTitle"><property name="text"><string>服务端连接</string></property><property name="objectName"><string>sidebarLabel</string></property></widget></item>