diff --git a/CMakeLists.txt b/CMakeLists.txt index 85867fe..133f680 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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 diff --git a/CmvrControlStation.pro b/CmvrControlStation.pro index a1bcc44..f7aa554 100644 --- a/CmvrControlStation.pro +++ b/CmvrControlStation.pro @@ -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 diff --git a/README.md b/README.md index 18383c6..740a8aa 100644 --- a/README.md +++ b/README.md @@ -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+左键追加/取消选择、右键拖动画布,左键仍可拖动节点和连接端口。框选节点支持整体拖动和批量删除,删除可撤销。节点参数面板固定显示执行设置和保存按钮,输入参数单独滚动;关节名与角度并排显示,限位单独显示,行高随字体和名称换行调整。 diff --git a/docs/task-flow/example.server-export.json b/docs/task-flow/example.server-export.json index be7ca39..b7f9f54 100644 --- a/docs/task-flow/example.server-export.json +++ b/docs/task-flow/example.server-export.json @@ -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", diff --git a/docs/task-flow/example.task.json b/docs/task-flow/example.task.json index 624a7af..58d3774 100644 --- a/docs/task-flow/example.task.json +++ b/docs/task-flow/example.task.json @@ -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, diff --git a/docs/task-flow/task-flow.schema.json b/docs/task-flow/task-flow.schema.json index edef6d7..db766bc 100644 --- a/docs/task-flow/task-flow.schema.json +++ b/docs/task-flow/task-flow.schema.json @@ -1046,238 +1046,6 @@ }, "timestamp": { "$ref": "#/$defs/message.google.protobuf.Timestamp" - }, - "reason_code": { - "enum": [ - "COMMAND_REASON_CODE_UNSPECIFIED", - "COMMAND_REASON_CODE_NONE", - "COMMAND_REASON_CODE_INVALID_ARGUMENT", - "COMMAND_REASON_CODE_UNAUTHENTICATED", - "COMMAND_REASON_CODE_PERMISSION_DENIED", - "COMMAND_REASON_CODE_RECOVERY_RPC_DISABLED", - "COMMAND_REASON_CODE_DEVICE_NOT_FOUND", - "COMMAND_REASON_CODE_DEVICE_UNAVAILABLE", - "COMMAND_REASON_CODE_UNSUPPORTED_COMMAND", - "COMMAND_REASON_CODE_SYSTEM_STARTING", - "COMMAND_REASON_CODE_SYSTEM_STOPPING", - "COMMAND_REASON_CODE_SAFETY_LATCHED", - "COMMAND_REASON_CODE_SAFETY_STATE_MISSING", - "COMMAND_REASON_CODE_SAFETY_STATE_STALE", - "COMMAND_REASON_CODE_HARDWARE_UNSAFE", - "COMMAND_REASON_CODE_EMERGENCY_STOP_ACTIVE", - "COMMAND_REASON_CODE_PROTECTIVE_STOP_ACTIVE", - "COMMAND_REASON_CODE_DEVICE_DISCONNECTED", - "COMMAND_REASON_CODE_DEVICE_FAULT", - "COMMAND_REASON_CODE_DEVICE_NOT_READY", - "COMMAND_REASON_CODE_DEVICE_STILL_MOVING", - "COMMAND_REASON_CODE_CONTROL_BUSY", - "COMMAND_REASON_CODE_GENERATION_MISMATCH", - "COMMAND_REASON_CODE_COMMAND_ID_REQUIRED", - "COMMAND_REASON_CODE_COMMAND_ID_CONFLICT", - "COMMAND_REASON_CODE_RESULT_EVICTED", - "COMMAND_REASON_CODE_LEDGER_EXHAUSTED", - "COMMAND_REASON_CODE_BACKPRESSURE", - "COMMAND_REASON_CODE_DEADLINE_EXCEEDED_BEFORE_DISPATCH", - "COMMAND_REASON_CODE_OUTCOME_UNKNOWN", - "COMMAND_REASON_CODE_PARTICIPANT_TIMEOUT", - "COMMAND_REASON_CODE_STOP_UNCONFIRMED", - "COMMAND_REASON_CODE_RECOVERY_EPOCH_MISMATCH", - "COMMAND_REASON_CODE_RECOVERY_REASON_REQUIRED", - "COMMAND_REASON_CODE_RECOVERY_AUDIT_FAILED", - "COMMAND_REASON_CODE_INTERNAL_ERROR", - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25, - 26, - 27, - 28, - 29, - 30, - 31, - 32, - 33, - 34, - 35 - ] - }, - "reasonCode": { - "enum": [ - "COMMAND_REASON_CODE_UNSPECIFIED", - "COMMAND_REASON_CODE_NONE", - "COMMAND_REASON_CODE_INVALID_ARGUMENT", - "COMMAND_REASON_CODE_UNAUTHENTICATED", - "COMMAND_REASON_CODE_PERMISSION_DENIED", - "COMMAND_REASON_CODE_RECOVERY_RPC_DISABLED", - "COMMAND_REASON_CODE_DEVICE_NOT_FOUND", - "COMMAND_REASON_CODE_DEVICE_UNAVAILABLE", - "COMMAND_REASON_CODE_UNSUPPORTED_COMMAND", - "COMMAND_REASON_CODE_SYSTEM_STARTING", - "COMMAND_REASON_CODE_SYSTEM_STOPPING", - "COMMAND_REASON_CODE_SAFETY_LATCHED", - "COMMAND_REASON_CODE_SAFETY_STATE_MISSING", - "COMMAND_REASON_CODE_SAFETY_STATE_STALE", - "COMMAND_REASON_CODE_HARDWARE_UNSAFE", - "COMMAND_REASON_CODE_EMERGENCY_STOP_ACTIVE", - "COMMAND_REASON_CODE_PROTECTIVE_STOP_ACTIVE", - "COMMAND_REASON_CODE_DEVICE_DISCONNECTED", - "COMMAND_REASON_CODE_DEVICE_FAULT", - "COMMAND_REASON_CODE_DEVICE_NOT_READY", - "COMMAND_REASON_CODE_DEVICE_STILL_MOVING", - "COMMAND_REASON_CODE_CONTROL_BUSY", - "COMMAND_REASON_CODE_GENERATION_MISMATCH", - "COMMAND_REASON_CODE_COMMAND_ID_REQUIRED", - "COMMAND_REASON_CODE_COMMAND_ID_CONFLICT", - "COMMAND_REASON_CODE_RESULT_EVICTED", - "COMMAND_REASON_CODE_LEDGER_EXHAUSTED", - "COMMAND_REASON_CODE_BACKPRESSURE", - "COMMAND_REASON_CODE_DEADLINE_EXCEEDED_BEFORE_DISPATCH", - "COMMAND_REASON_CODE_OUTCOME_UNKNOWN", - "COMMAND_REASON_CODE_PARTICIPANT_TIMEOUT", - "COMMAND_REASON_CODE_STOP_UNCONFIRMED", - "COMMAND_REASON_CODE_RECOVERY_EPOCH_MISMATCH", - "COMMAND_REASON_CODE_RECOVERY_REASON_REQUIRED", - "COMMAND_REASON_CODE_RECOVERY_AUDIT_FAILED", - "COMMAND_REASON_CODE_INTERNAL_ERROR", - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25, - 26, - 27, - 28, - 29, - 30, - 31, - 32, - 33, - 34, - 35 - ] - }, - "command_id": { - "type": "string" - }, - "commandId": { - "type": "string" - }, - "service_instance_id": { - "type": "string" - }, - "serviceInstanceId": { - "type": "string" - }, - "safety_epoch": { - "type": "string", - "pattern": "^[0-9]+$" - }, - "safetyEpoch": { - "type": "string", - "pattern": "^[0-9]+$" - }, - "device_generation": { - "type": "string", - "pattern": "^[0-9]+$" - }, - "deviceGeneration": { - "type": "string", - "pattern": "^[0-9]+$" - }, - "execution_state": { - "enum": [ - "COMMAND_EXECUTION_STATE_UNSPECIFIED", - "COMMAND_EXECUTION_STATE_RECEIVED", - "COMMAND_EXECUTION_STATE_RESERVED", - "COMMAND_EXECUTION_STATE_REJECTED_BEFORE_DISPATCH", - "COMMAND_EXECUTION_STATE_ADMITTED", - "COMMAND_EXECUTION_STATE_DISPATCHING", - "COMMAND_EXECUTION_STATE_ACCEPTED_BY_HARDWARE", - "COMMAND_EXECUTION_STATE_COMPLETED", - "COMMAND_EXECUTION_STATE_FAILED", - "COMMAND_EXECUTION_STATE_CANCELED_BEFORE_DISPATCH", - "COMMAND_EXECUTION_STATE_OUTCOME_UNKNOWN", - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10 - ] - }, - "executionState": { - "enum": [ - "COMMAND_EXECUTION_STATE_UNSPECIFIED", - "COMMAND_EXECUTION_STATE_RECEIVED", - "COMMAND_EXECUTION_STATE_RESERVED", - "COMMAND_EXECUTION_STATE_REJECTED_BEFORE_DISPATCH", - "COMMAND_EXECUTION_STATE_ADMITTED", - "COMMAND_EXECUTION_STATE_DISPATCHING", - "COMMAND_EXECUTION_STATE_ACCEPTED_BY_HARDWARE", - "COMMAND_EXECUTION_STATE_COMPLETED", - "COMMAND_EXECUTION_STATE_FAILED", - "COMMAND_EXECUTION_STATE_CANCELED_BEFORE_DISPATCH", - "COMMAND_EXECUTION_STATE_OUTCOME_UNKNOWN", - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10 - ] } }, "additionalProperties": false, @@ -1289,54 +1057,6 @@ "errorMessage" ] } - }, - { - "not": { - "required": [ - "reason_code", - "reasonCode" - ] - } - }, - { - "not": { - "required": [ - "command_id", - "commandId" - ] - } - }, - { - "not": { - "required": [ - "service_instance_id", - "serviceInstanceId" - ] - } - }, - { - "not": { - "required": [ - "safety_epoch", - "safetyEpoch" - ] - } - }, - { - "not": { - "required": [ - "device_generation", - "deviceGeneration" - ] - } - }, - { - "not": { - "required": [ - "execution_state", - "executionState" - ] - } } ] }, @@ -1351,36 +1071,6 @@ }, "timestamp": { "$ref": "#/$defs/message.google.protobuf.Timestamp" - }, - "command_id": { - "type": "string" - }, - "commandId": { - "type": "string" - }, - "expected_service_instance_id": { - "type": "string" - }, - "expectedServiceInstanceId": { - "type": "string" - }, - "expected_device_generation": { - "type": "string", - "pattern": "^[0-9]+$" - }, - "expectedDeviceGeneration": { - "type": "string", - "pattern": "^[0-9]+$" - }, - "valid_for_ms": { - "type": "integer", - "minimum": 0, - "maximum": 4294967295 - }, - "validForMs": { - "type": "integer", - "minimum": 0, - "maximum": 4294967295 } }, "additionalProperties": false, @@ -1392,38 +1082,6 @@ "deviceId" ] } - }, - { - "not": { - "required": [ - "command_id", - "commandId" - ] - } - }, - { - "not": { - "required": [ - "expected_service_instance_id", - "expectedServiceInstanceId" - ] - } - }, - { - "not": { - "required": [ - "expected_device_generation", - "expectedDeviceGeneration" - ] - } - }, - { - "not": { - "required": [ - "valid_for_ms", - "validForMs" - ] - } } ] }, @@ -1562,84 +1220,6 @@ } ] }, - "message.cmvr.api.DepthGeometry": { - "type": "object", - "properties": { - "metres_per_unit": { - "type": "number" - }, - "metresPerUnit": { - "type": "number" - }, - "aligned_to_color": { - "type": "boolean" - }, - "alignedToColor": { - "type": "boolean" - }, - "color_axial_z": { - "type": "boolean" - }, - "colorAxialZ": { - "type": "boolean" - }, - "byte_order": { - "type": "string" - }, - "byteOrder": { - "type": "string" - }, - "distortion_model": { - "type": "string" - }, - "distortionModel": { - "type": "string" - } - }, - "additionalProperties": false, - "allOf": [ - { - "not": { - "required": [ - "metres_per_unit", - "metresPerUnit" - ] - } - }, - { - "not": { - "required": [ - "aligned_to_color", - "alignedToColor" - ] - } - }, - { - "not": { - "required": [ - "color_axial_z", - "colorAxialZ" - ] - } - }, - { - "not": { - "required": [ - "byte_order", - "byteOrder" - ] - } - }, - { - "not": { - "required": [ - "distortion_model", - "distortionModel" - ] - } - } - ] - }, "message.cmvr.api.DexHandState": { "type": "object", "properties": { @@ -2422,34 +2002,6 @@ "sourceFrameNumber": { "type": "string", "pattern": "^[0-9]+$" - }, - "camera_serial": { - "type": "string" - }, - "cameraSerial": { - "type": "string" - }, - "camera_session_generation": { - "type": "string", - "pattern": "^[0-9]+$" - }, - "cameraSessionGeneration": { - "type": "string", - "pattern": "^[0-9]+$" - }, - "distortion_model": { - "type": "string" - }, - "distortionModel": { - "type": "string" - }, - "capture_earliest_utc_ns": { - "type": "string", - "pattern": "^-?[0-9]+$" - }, - "captureEarliestUtcNs": { - "type": "string", - "pattern": "^-?[0-9]+$" } }, "additionalProperties": false, @@ -2501,38 +2053,6 @@ "sourceFrameNumber" ] } - }, - { - "not": { - "required": [ - "camera_serial", - "cameraSerial" - ] - } - }, - { - "not": { - "required": [ - "camera_session_generation", - "cameraSessionGeneration" - ] - } - }, - { - "not": { - "required": [ - "distortion_model", - "distortionModel" - ] - } - }, - { - "not": { - "required": [ - "capture_earliest_utc_ns", - "captureEarliestUtcNs" - ] - } } ] }, @@ -3265,12 +2785,6 @@ }, "intrinsics": { "$ref": "#/$defs/message.cmvr.api.CameraIntrinsics" - }, - "depth_geometry": { - "$ref": "#/$defs/message.cmvr.api.DepthGeometry" - }, - "depthGeometry": { - "$ref": "#/$defs/message.cmvr.api.DepthGeometry" } }, "additionalProperties": false, @@ -3290,14 +2804,6 @@ "depthFrame" ] } - }, - { - "not": { - "required": [ - "depth_geometry", - "depthGeometry" - ] - } } ] }, @@ -3306,25 +2812,9 @@ "properties": { "header": { "$ref": "#/$defs/message.cmvr.api.CommandHeader.Request" - }, - "require_metric_depth": { - "type": "boolean" - }, - "requireMetricDepth": { - "type": "boolean" } }, - "additionalProperties": false, - "allOf": [ - { - "not": { - "required": [ - "require_metric_depth", - "requireMetricDepth" - ] - } - } - ] + "additionalProperties": false }, "message.cmvr.api.GetRGBDImagesStreamCommand.Feedback": { "type": "object", @@ -3973,7 +3463,7 @@ "not": { "required": [ "move", - "position_gain" + "positionGain" ] } }, @@ -3981,7 +3471,7 @@ "not": { "required": [ "move", - "positionGain" + "position_gain" ] } }, @@ -4013,7 +3503,7 @@ "not": { "required": [ "move", - "cancel_expression" + "cancelExpression" ] } }, @@ -4021,7 +3511,7 @@ "not": { "required": [ "move", - "cancelExpression" + "cancel_expression" ] } }, @@ -4045,7 +3535,7 @@ "not": { "required": [ "home", - "position_gain" + "positionGain" ] } }, @@ -4053,7 +3543,7 @@ "not": { "required": [ "home", - "positionGain" + "position_gain" ] } }, @@ -4085,7 +3575,7 @@ "not": { "required": [ "home", - "cancel_expression" + "cancelExpression" ] } }, @@ -4093,7 +3583,7 @@ "not": { "required": [ "home", - "cancelExpression" + "cancel_expression" ] } }, @@ -4109,7 +3599,7 @@ "not": { "required": [ "mode", - "position_gain" + "positionGain" ] } }, @@ -4117,7 +3607,7 @@ "not": { "required": [ "mode", - "positionGain" + "position_gain" ] } }, @@ -4145,14 +3635,6 @@ ] } }, - { - "not": { - "required": [ - "mode", - "cancel_expression" - ] - } - }, { "not": { "required": [ @@ -4164,8 +3646,8 @@ { "not": { "required": [ - "constraints", - "position_gain" + "mode", + "cancel_expression" ] } }, @@ -4177,6 +3659,14 @@ ] } }, + { + "not": { + "required": [ + "constraints", + "position_gain" + ] + } + }, { "not": { "required": [ @@ -4205,7 +3695,7 @@ "not": { "required": [ "constraints", - "cancel_expression" + "cancelExpression" ] } }, @@ -4213,23 +3703,7 @@ "not": { "required": [ "constraints", - "cancelExpression" - ] - } - }, - { - "not": { - "required": [ - "position_gain", - "updatePeriod" - ] - } - }, - { - "not": { - "required": [ - "position_gain", - "update_period" + "cancel_expression" ] } }, @@ -4253,7 +3727,15 @@ "not": { "required": [ "position_gain", - "reconnect" + "updatePeriod" + ] + } + }, + { + "not": { + "required": [ + "position_gain", + "update_period" ] } }, @@ -4269,6 +3751,22 @@ "not": { "required": [ "position_gain", + "reconnect" + ] + } + }, + { + "not": { + "required": [ + "positionGain", + "cancelExpression" + ] + } + }, + { + "not": { + "required": [ + "positionGain", "cancel_expression" ] } @@ -4284,19 +3782,11 @@ { "not": { "required": [ - "positionGain", + "position_gain", "cancel_expression" ] } }, - { - "not": { - "required": [ - "positionGain", - "cancelExpression" - ] - } - }, { "not": { "required": [ @@ -4317,7 +3807,7 @@ "not": { "required": [ "updatePeriod", - "cancel_expression" + "cancelExpression" ] } }, @@ -4325,14 +3815,6 @@ "not": { "required": [ "updatePeriod", - "cancelExpression" - ] - } - }, - { - "not": { - "required": [ - "update_period", "cancel_expression" ] } @@ -4348,7 +3830,7 @@ { "not": { "required": [ - "reconnect", + "update_period", "cancel_expression" ] } @@ -4360,6 +3842,14 @@ "cancelExpression" ] } + }, + { + "not": { + "required": [ + "reconnect", + "cancel_expression" + ] + } } ] }, @@ -5297,62 +4787,6 @@ }, "additionalProperties": false }, - "message.cmvr.api.MoveJPose.Request": { - "type": "object", - "properties": { - "header": { - "$ref": "#/$defs/message.cmvr.api.CommandHeader.Request" - }, - "target": { - "$ref": "#/$defs/message.cmvr.api.CartesianPose" - }, - "options": { - "$ref": "#/$defs/message.cmvr.api.MotionOptions" - }, - "user_coordinate_name": { - "type": "string" - }, - "userCoordinateName": { - "type": "string" - }, - "user_coordinate_revision": { - "type": "string", - "pattern": "^[0-9]+$" - }, - "userCoordinateRevision": { - "type": "string", - "pattern": "^[0-9]+$" - } - }, - "additionalProperties": false, - "allOf": [ - { - "not": { - "required": [ - "user_coordinate_name", - "userCoordinateName" - ] - } - }, - { - "not": { - "required": [ - "user_coordinate_revision", - "userCoordinateRevision" - ] - } - } - ] - }, - "message.cmvr.api.MoveJPose.Response": { - "type": "object", - "properties": { - "header": { - "$ref": "#/$defs/message.cmvr.api.CommandHeader.Feedback" - } - }, - "additionalProperties": false - }, "message.cmvr.api.MoveL.Request": { "type": "object", "properties": { @@ -6202,12 +5636,14 @@ "INDEX", "THUMB", "PALM", + "FINGER_UNSPECIFIED", 0, 1, 2, 3, 4, - 5 + 5, + 6 ] }, "fingerType": { @@ -6218,12 +5654,14 @@ "INDEX", "THUMB", "PALM", + "FINGER_UNSPECIFIED", 0, 1, 2, 3, 4, - 5 + 5, + 6 ] }, "part_type": { @@ -6233,11 +5671,13 @@ "PAD", "THUMB_MIDDLE", "PALM_PAD", + "PART_UNSPECIFIED", 0, 1, 2, 3, - 4 + 4, + 5 ] }, "partType": { @@ -6247,11 +5687,13 @@ "PAD", "THUMB_MIDDLE", "PALM_PAD", + "PART_UNSPECIFIED", 0, 1, 2, 3, - 4 + 4, + 5 ] }, "sensor_name": { @@ -8258,7 +7700,7 @@ { "not": { "required": [ - "map2d", + "map_2d", "map3d" ] } @@ -8266,7 +7708,7 @@ { "not": { "required": [ - "map2d", + "map_2d", "map_3d" ] } @@ -8274,7 +7716,7 @@ { "not": { "required": [ - "map_2d", + "map2d", "map3d" ] } @@ -8282,7 +7724,7 @@ { "not": { "required": [ - "map_2d", + "map2d", "map_3d" ] } @@ -8363,7 +7805,6 @@ "cmvr.api.ArmService.torqueOff", "cmvr.api.ArmService.torqueOn", "cmvr.api.ArmService.clearFault", - "cmvr.api.ArmService.moveJPose", "cmvr.api.ArmService.moveJ", "cmvr.api.ArmService.moveL", "cmvr.api.ArmService.ListBaseFrame", @@ -8772,59 +8213,6 @@ } } }, - { - "if": { - "properties": { - "operationId": { - "const": "cmvr.api.ArmService.moveJPose" - } - } - }, - "then": { - "properties": { - "parameters": { - "type": "object", - "required": [ - "service", - "method", - "request" - ], - "properties": { - "service": { - "const": "cmvr.api.ArmService" - }, - "method": { - "const": "moveJPose" - }, - "request": { - "$ref": "#/$defs/message.cmvr.api.MoveJPose.Request" - }, - "timeoutMs": { - "type": "integer", - "minimum": 100, - "maximum": 1800000 - } - } - }, - "execution": { - "properties": { - "kind": { - "const": "grpc_unary" - }, - "service": { - "const": "cmvr.api.ArmService" - }, - "method": { - "const": "moveJPose" - }, - "request": { - "$ref": "#/$defs/message.cmvr.api.MoveJPose.Request" - } - } - } - } - } - }, { "if": { "properties": { diff --git a/docs/task-flow/task_operations.json b/docs/task-flow/task_operations.json index e166644..09da10c 100644 --- a/docs/task-flow/task_operations.json +++ b/docs/task-flow/task_operations.json @@ -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", diff --git a/protos/cmvr/api/arm_command.proto b/protos/cmvr/api/arm_command.proto index 5b44712..353766b 100644 --- a/protos/cmvr/api/arm_command.proto +++ b/protos/cmvr/api/arm_command.proto @@ -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; } -} diff --git a/protos/cmvr/api/arm_service.proto b/protos/cmvr/api/arm_service.proto index d75fa4b..2defa9f 100644 --- a/protos/cmvr/api/arm_service.proto +++ b/protos/cmvr/api/arm_service.proto @@ -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); diff --git a/protos/cmvr/api/biohead_service.proto b/protos/cmvr/api/biohead_service.proto index 59b8c39..bac6e66 100644 --- a/protos/cmvr/api/biohead_service.proto +++ b/protos/cmvr/api/biohead_service.proto @@ -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){}; - - - - - - - -} +} \ No newline at end of file diff --git a/protos/cmvr/api/camera_command.proto b/protos/cmvr/api/camera_command.proto index adb8468..26fcdc0 100644 --- a/protos/cmvr/api/camera_command.proto +++ b/protos/cmvr/api/camera_command.proto @@ -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; diff --git a/protos/cmvr/api/common.proto b/protos/cmvr/api/common.proto index 64988d4..ac469f0 100644 --- a/protos/cmvr/api/common.proto +++ b/protos/cmvr/api/common.proto @@ -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; } } diff --git a/protos/cmvr/api/configuration_command.proto b/protos/cmvr/api/configuration_command.proto deleted file mode 100644 index e696e82..0000000 --- a/protos/cmvr/api/configuration_command.proto +++ /dev/null @@ -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; - } -} diff --git a/protos/cmvr/api/configuration_service.proto b/protos/cmvr/api/configuration_service.proto deleted file mode 100644 index a45ed4f..0000000 --- a/protos/cmvr/api/configuration_service.proto +++ /dev/null @@ -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); -} diff --git a/protos/cmvr/api/dexhand_command.proto b/protos/cmvr/api/dexhand_command.proto index 8ff1bb3..9ff4c78 100644 --- a/protos/cmvr/api/dexhand_command.proto +++ b/protos/cmvr/api/dexhand_command.proto @@ -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) diff --git a/protos/cmvr/api/system_command.proto b/protos/cmvr/api/system_command.proto index 163d35a..a729590 100644 --- a/protos/cmvr/api/system_command.proto +++ b/protos/cmvr/api/system_command.proto @@ -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. diff --git a/protos/cmvr/api/system_service.proto b/protos/cmvr/api/system_service.proto index 87914d9..4dbb72d 100644 --- a/protos/cmvr/api/system_service.proto +++ b/protos/cmvr/api/system_service.proto @@ -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) {} } diff --git a/protos/cmvr/config/agv_config/agv_config.proto b/protos/cmvr/config/agv_config/agv_config.proto index 3309cf1..4e579b7 100644 --- a/protos/cmvr/config/agv_config/agv_config.proto +++ b/protos/cmvr/config/agv_config/agv_config.proto @@ -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:"。 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; } } diff --git a/protos/cmvr/config/arm_config/arm_config.proto b/protos/cmvr/config/arm_config/arm_config.proto index 8fc2147..7ae6e8e 100644 --- a/protos/cmvr/config/arm_config/arm_config.proto +++ b/protos/cmvr/config/arm_config/arm_config.proto @@ -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 { diff --git a/protos/cmvr/config/biohead_config/biohead_config.proto b/protos/cmvr/config/biohead_config/biohead_config.proto index 543a96e..65605da 100644 --- a/protos/cmvr/config/biohead_config/biohead_config.proto +++ b/protos/cmvr/config/biohead_config/biohead_config.proto @@ -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; -} -message BioHeadRobotRootConfig { - BioHeadRobotConfig bio_head = 1; + + // 配置此字段时,选择新增的 USB eRPC 后端。 + // 未配置时,继续使用原 ESP32 后端。 + UsbHeadErpcConfig usb_erpc = 5; } +// 配置文件的根结构。 +message BioHeadRobotRootConfig { + BioHeadRobotConfig bio_head = 1; +} \ No newline at end of file diff --git a/protos/cmvr/config/camera_config/camera_config.proto b/protos/cmvr/config/camera_config/camera_config.proto index a9b4079..49f5075 100644 --- a/protos/cmvr/config/camera_config/camera_config.proto +++ b/protos/cmvr/config/camera_config/camera_config.proto @@ -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; } } diff --git a/protos/cmvr/config/collision_config.proto b/protos/cmvr/config/collision_config.proto new file mode 100644 index 0000000..30b5ead --- /dev/null +++ b/protos/cmvr/config/collision_config.proto @@ -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; +} diff --git a/protos/cmvr/config/device_manager_config/device_manager_config.proto b/protos/cmvr/config/device_manager_config/device_manager_config.proto index 09ec3e8..e5d58a5 100644 --- a/protos/cmvr/config/device_manager_config/device_manager_config.proto +++ b/protos/cmvr/config/device_manager_config/device_manager_config.proto @@ -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; diff --git a/protos/cmvr/config/dexhand_config/dexhand_config.proto b/protos/cmvr/config/dexhand_config/dexhand_config.proto index 9d894d0..85aabfa 100644 --- a/protos/cmvr/config/dexhand_config/dexhand_config.proto +++ b/protos/cmvr/config/dexhand_config/dexhand_config.proto @@ -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; diff --git a/protos/cmvr/config/grpc_server_config/grpc_server_config.proto b/protos/cmvr/config/grpc_server_config/grpc_server_config.proto index 0650c73..11ad801 100644 --- a/protos/cmvr/config/grpc_server_config/grpc_server_config.proto +++ b/protos/cmvr/config/grpc_server_config/grpc_server_config.proto @@ -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; diff --git a/protos/cmvr/config/joint_limits_config.proto b/protos/cmvr/config/joint_limits_config.proto index c3da751..268c05a 100644 --- a/protos/cmvr/config/joint_limits_config.proto +++ b/protos/cmvr/config/joint_limits_config.proto @@ -33,7 +33,6 @@ message JointLimitAvoidanceConfig { double gain = 2; double margin_ratio = 3; double max_push = 4; - double weight = 5; } message JointLimitPolicyConfig { diff --git a/protos/cmvr/config/joint_motion_config.proto b/protos/cmvr/config/joint_motion_config.proto new file mode 100644 index 0000000..f9c42ab --- /dev/null +++ b/protos/cmvr/config/joint_motion_config.proto @@ -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. +} diff --git a/protos/cmvr/config/motor_config/motor_config.proto b/protos/cmvr/config/motor_config/motor_config.proto index 7c166df..b173c5e 100644 --- a/protos/cmvr/config/motor_config/motor_config.proto +++ b/protos/cmvr/config/motor_config/motor_config.proto @@ -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 { diff --git a/protos/cmvr/config/quic_edge_config/quic_edge_config.proto b/protos/cmvr/config/quic_edge_config/quic_edge_config.proto index 48486a9..8a26f1d 100644 --- a/protos/cmvr/config/quic_edge_config/quic_edge_config.proto +++ b/protos/cmvr/config/quic_edge_config/quic_edge_config.proto @@ -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 { diff --git a/protos/cmvr/config/self_collision_task_config/self_collision_task_config.proto b/protos/cmvr/config/self_collision_task_config/self_collision_task_config.proto index ded6d8c..a92f653 100644 --- a/protos/cmvr/config/self_collision_task_config/self_collision_task_config.proto +++ b/protos/cmvr/config/self_collision_task_config/self_collision_task_config.proto @@ -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 { diff --git a/protos/cmvr/config/task_manager_config/task_manager_config.proto b/protos/cmvr/config/task_manager_config/task_manager_config.proto index 8c60e37..b2f1782 100644 --- a/protos/cmvr/config/task_manager_config/task_manager_config.proto +++ b/protos/cmvr/config/task_manager_config/task_manager_config.proto @@ -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 { diff --git a/protos/cmvr/config/touch_config/touch_config.proto b/protos/cmvr/config/touch_config/touch_config.proto new file mode 100644 index 0000000..a7b0874 --- /dev/null +++ b/protos/cmvr/config/touch_config/touch_config.proto @@ -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; +} diff --git a/protos/cmvr/config/touch_screen_algorithm_config.proto b/protos/cmvr/config/touch_screen_algorithm_config.proto index e7e577f..c7c72bf 100644 --- a/protos/cmvr/config/touch_screen_algorithm_config.proto +++ b/protos/cmvr/config/touch_screen_algorithm_config.proto @@ -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; } diff --git a/protos/cmvr/config/touch_screen_task_config/touch_screen_task_config.proto b/protos/cmvr/config/touch_screen_task_config/touch_screen_task_config.proto index c48681a..d5cdb8a 100644 --- a/protos/cmvr/config/touch_screen_task_config/touch_screen_task_config.proto +++ b/protos/cmvr/config/touch_screen_task_config/touch_screen_task_config.proto @@ -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 { diff --git a/protos/cmvr/quic_edge/v1/quic_edge.proto b/protos/cmvr/quic_edge/v1/quic_edge.proto index 48f3a32..296df43 100644 --- a/protos/cmvr/quic_edge/v1/quic_edge.proto +++ b/protos/cmvr/quic_edge/v1/quic_edge.proto @@ -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; diff --git a/protos/rbk/protocol/seer_robokit_map3d.proto b/protos/rbk/protocol/seer_robokit_map3d.proto new file mode 100644 index 0000000..c5d8c6f --- /dev/null +++ b/protos/rbk/protocol/seer_robokit_map3d.proto @@ -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; +} + diff --git a/src/actionqueuetestwidget.cpp b/src/actionqueuetestwidget.cpp index 40b4849..7c25aee 100644 --- a/src/actionqueuetestwidget.cpp +++ b/src/actionqueuetestwidget.cpp @@ -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; diff --git a/src/applicationsettings.cpp b/src/applicationsettings.cpp index e9132a6..3395e78 100644 --- a/src/applicationsettings.cpp +++ b/src/applicationsettings.cpp @@ -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 &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); diff --git a/src/bioheadjointclient.cpp b/src/bioheadjointclient.cpp index 06ce50b..4c03046 100644 --- a/src/bioheadjointclient.cpp +++ b/src/bioheadjointclient.cpp @@ -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((milliseconds % 1000) * 1000000)); - header->set_valid_for_ms(static_cast(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) diff --git a/src/bioheadwidget.cpp b/src/bioheadwidget.cpp index 57a2b5f..ce502c0 100644 --- a/src/bioheadwidget.cpp +++ b/src/bioheadwidget.cpp @@ -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()); diff --git a/src/configeditorwidget.cpp b/src/configeditorwidget.cpp deleted file mode 100644 index 876fdeb..0000000 --- a/src/configeditorwidget.cpp +++ /dev/null @@ -1,2602 +0,0 @@ -#include "configeditorwidget.h" - -#include "robotclient.h" -#include "uiicons.h" - -#include "cmvr/config/device_manager_config/device_manager_config.pb.h" -#include "cmvr/config/task_manager_config/task_manager_config.pb.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "appmessagebox.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace { -constexpr int kPathRole = Qt::UserRole; -constexpr int kMessageRole = Qt::UserRole + 1; -constexpr int kFieldRole = Qt::UserRole + 2; -constexpr int kIndexRole = Qt::UserRole + 3; -constexpr int kPreviousValueRole = Qt::UserRole + 4; - -struct DevicePresentation { - QString name; - QString icon; - QString accent; -}; - -QString scalarValue(const google::protobuf::Message *message, - const google::protobuf::FieldDescriptor *field, int index); - -class DeviceCardFrame final : public QFrame -{ -public: - using QFrame::QFrame; - std::function activated; - -protected: - void mouseReleaseEvent(QMouseEvent *event) override - { - QFrame::mouseReleaseEvent(event); - if (event->button() == Qt::LeftButton && rect().contains(event->pos()) && activated) - activated(); - } -}; - -int managerTypeForApiType(int type) -{ - switch (type) { - case 0: return 17; - case 2: return 13; - case 3: return 14; - case 5: return 15; - case 6: return 12; - case 7: return 16; - case 8: return 8; - case 10: return 9; - case 11: return 18; - case 12: return 19; - default: return 0; - } -} - -int apiTypeForManagerType(int type) -{ - switch (type) { - case 17: return 0; - case 13: return 2; - case 14: return 3; - case 15: return 5; - case 12: return 6; - case 16: return 7; - case 8: return 8; - case 9: return 10; - case 18: return 11; - case 19: return 12; - default: return 20; - } -} - -QString defaultMessageTypeForManagerType(int type) -{ - switch (type) { - case 17: return QStringLiteral("cmvr.config.AGVRootConfig"); - case 12: return QStringLiteral("cmvr.config.ArmRootConfig"); - case 13: return QStringLiteral("cmvr.config.CameraRootConfig"); - case 14: return QStringLiteral("cmvr.config.DexHandRootConfig"); - case 15: return QStringLiteral("cmvr.config.MicroPhoneRootConfig"); - case 16: return QStringLiteral("cmvr.config.SpeakerRootConfig"); - case 8: return QStringLiteral("cmvr.config.BioHeadRobotRootConfig"); - default: return QString(); - } -} - -QString typeFolderForManagerType(int type) -{ - switch (type) { - case 17: return QStringLiteral("agv"); - case 12: return QStringLiteral("arm"); - case 13: return QStringLiteral("camera"); - case 14: return QStringLiteral("dexhand"); - case 15: return QStringLiteral("microphone"); - case 16: return QStringLiteral("speaker"); - case 8: return QStringLiteral("biohead"); - default: return QString(); - } -} - -std::unique_ptr createMessage(const QString &messageType, - const QString &content, - QString *error = nullptr) -{ - const auto *descriptor = google::protobuf::DescriptorPool::generated_pool() - ->FindMessageTypeByName(messageType.toStdString()); - if (!descriptor) { - if (error) - *error = QStringLiteral("本机未注册配置消息类型 %1").arg(messageType); - return {}; - } - const auto *prototype = google::protobuf::MessageFactory::generated_factory() - ->GetPrototype(descriptor); - if (!prototype) { - if (error) - *error = QStringLiteral("无法创建配置消息 %1").arg(messageType); - return {}; - } - std::unique_ptr message(prototype->New()); - if (!content.trimmed().isEmpty() - && !google::protobuf::TextFormat::ParseFromString(content.toStdString(), message.get())) { - if (error) - *error = QStringLiteral("配置内容与 %1 不兼容").arg(messageType); - return {}; - } - return message; -} - -google::protobuf::Message *deviceEntry(google::protobuf::Message *root, - const QString &deviceId, bool create) -{ - if (!root) - return nullptr; - const auto *rootDescriptor = root->GetDescriptor(); - const auto *rootReflection = root->GetReflection(); - const google::protobuf::FieldDescriptor *rootField = nullptr; - for (int index = 0; index < rootDescriptor->field_count(); ++index) { - if (rootDescriptor->field(index)->cpp_type() - == google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) { - rootField = rootDescriptor->field(index); - break; - } - } - if (!rootField) - return nullptr; - auto *container = rootReflection->MutableMessage(root, rootField); - const auto *containerDescriptor = container->GetDescriptor(); - const auto *containerReflection = container->GetReflection(); - const google::protobuf::FieldDescriptor *listField = nullptr; - for (int index = 0; index < containerDescriptor->field_count(); ++index) { - const auto *field = containerDescriptor->field(index); - if (field->is_repeated() - && field->cpp_type() == google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) { - listField = field; - break; - } - } - if (!listField) - return container; - - const int count = containerReflection->FieldSize(*container, listField); - for (int index = 0; index < count; ++index) { - auto *entry = containerReflection->MutableRepeatedMessage(container, listField, index); - const auto *idField = entry->GetDescriptor()->FindFieldByName("id"); - if (idField && QString::fromStdString(entry->GetReflection()->GetString(*entry, idField)) - == deviceId) - return entry; - } - return create ? containerReflection->AddMessage(container, listField) : nullptr; -} - -void removeDeviceEntries(google::protobuf::Message *root, const QSet &deviceIds) -{ - if (!root || deviceIds.isEmpty()) - return; - const auto *rootField = root->GetDescriptor()->field_count() > 0 - ? root->GetDescriptor()->field(0) : nullptr; - if (!rootField || rootField->cpp_type() - != google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) - return; - auto *container = root->GetReflection()->MutableMessage(root, rootField); - const google::protobuf::FieldDescriptor *listField = nullptr; - for (int index = 0; index < container->GetDescriptor()->field_count(); ++index) { - const auto *field = container->GetDescriptor()->field(index); - if (field->is_repeated() - && field->cpp_type() == google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) { - listField = field; - break; - } - } - if (!listField) - return; - const auto *reflection = container->GetReflection(); - for (int index = reflection->FieldSize(*container, listField) - 1; index >= 0; --index) { - const auto &entry = reflection->GetRepeatedMessage(*container, listField, index); - const auto *idField = entry.GetDescriptor()->FindFieldByName("id"); - if (!idField) - continue; - const QString id = QString::fromStdString(entry.GetReflection()->GetString(entry, idField)); - if (!deviceIds.contains(id)) - continue; - const int last = reflection->FieldSize(*container, listField) - 1; - if (index != last) - reflection->SwapElements(container, listField, index, last); - reflection->RemoveLast(container, listField); - } -} - -google::protobuf::Message *selectBackend(google::protobuf::Message *entry, - const QString &backendName, int brandNumber) -{ - if (!entry) - return nullptr; - const auto *oneof = entry->GetDescriptor()->FindOneofByName("backend"); - if (!oneof) - return entry; - const auto *field = entry->GetDescriptor()->FindFieldByName(backendName.toStdString()); - if (!field || field->containing_oneof() != oneof) - return nullptr; - auto *backend = entry->GetReflection()->MutableMessage(entry, field); - if (brandNumber >= 0) { - const auto *brandField = backend->GetDescriptor()->FindFieldByName("brand"); - if (brandField && brandField->cpp_type() - == google::protobuf::FieldDescriptor::CPPTYPE_ENUM) { - if (const auto *brand = brandField->enum_type()->FindValueByNumber(brandNumber)) - backend->GetReflection()->SetEnum(backend, brandField, brand); - } - } - return backend; -} - -void appendParameterRows(google::protobuf::Message *message, const QString &prefix, - QVariantList *rows) -{ - if (!message || !rows) - return; - const auto *descriptor = message->GetDescriptor(); - const auto *reflection = message->GetReflection(); - using Field = google::protobuf::FieldDescriptor; - for (int fieldIndex = 0; fieldIndex < descriptor->field_count(); ++fieldIndex) { - const auto *field = descriptor->field(fieldIndex); - if (field->name() == "id") - continue; - if (field->containing_oneof()) { - const auto *active = reflection->GetOneofFieldDescriptor( - *message, field->containing_oneof()); - if (active != field) - continue; - } - const QString fieldName = QString::fromStdString(field->name()); - const QString path = prefix.isEmpty() ? fieldName : prefix + QLatin1Char('.') + fieldName; - if (field->cpp_type() == Field::CPPTYPE_MESSAGE) { - if (field->is_repeated()) { - const int count = reflection->FieldSize(*message, field); - for (int index = 0; index < count; ++index) - appendParameterRows(reflection->MutableRepeatedMessage(message, field, index), - path + QStringLiteral("[%1]").arg(index), rows); - } else { - if (!reflection->HasField(*message, field)) - continue; - appendParameterRows(reflection->MutableMessage(message, field), path, rows); - } - continue; - } - const int count = field->is_repeated() ? reflection->FieldSize(*message, field) : 1; - const int rowCount = std::max(count, 1); - for (int index = 0; index < rowCount; ++index) { - QVariantMap row; - row.insert(QStringLiteral("path"), field->is_repeated() - ? path + QStringLiteral("[%1]").arg(index) : path); - row.insert(QStringLiteral("label"), row.value(QStringLiteral("path"), path)); - row.insert(QStringLiteral("value"), count == 0 ? QString() - : scalarValue(message, field, field->is_repeated() ? index : -1)); - row.insert(QStringLiteral("type"), static_cast(field->cpp_type())); - row.insert(QStringLiteral("secret"), fieldName.contains(QStringLiteral("password"), - Qt::CaseInsensitive)); - if (field->cpp_type() == Field::CPPTYPE_ENUM) { - QVariantList values; - for (int enumIndex = 0; enumIndex < field->enum_type()->value_count(); ++enumIndex) - values.append(QString::fromStdString(field->enum_type()->value(enumIndex)->name())); - row.insert(QStringLiteral("options"), values); - } - rows->append(row); - } - } -} - -bool setScalarField(google::protobuf::Message *message, - const google::protobuf::FieldDescriptor *field, - int repeatedIndex, const QString &text) -{ - if (!message || !field) - return false; - auto *reflection = message->GetReflection(); - const bool repeated = field->is_repeated(); - while (repeated && reflection->FieldSize(*message, field) <= repeatedIndex) { - using Field = google::protobuf::FieldDescriptor; - switch (field->cpp_type()) { - case Field::CPPTYPE_BOOL: reflection->AddBool(message, field, false); break; - case Field::CPPTYPE_INT32: reflection->AddInt32(message, field, 0); break; - case Field::CPPTYPE_INT64: reflection->AddInt64(message, field, 0); break; - case Field::CPPTYPE_UINT32: reflection->AddUInt32(message, field, 0); break; - case Field::CPPTYPE_UINT64: reflection->AddUInt64(message, field, 0); break; - case Field::CPPTYPE_FLOAT: reflection->AddFloat(message, field, 0); break; - case Field::CPPTYPE_DOUBLE: reflection->AddDouble(message, field, 0); break; - case Field::CPPTYPE_STRING: reflection->AddString(message, field, std::string()); break; - case Field::CPPTYPE_ENUM: reflection->AddEnum(message, field, field->enum_type()->value(0)); break; - case Field::CPPTYPE_MESSAGE: return false; - } - } - bool ok = true; - using Field = google::protobuf::FieldDescriptor; - switch (field->cpp_type()) { - case Field::CPPTYPE_BOOL: { - const bool value = text.compare(QStringLiteral("true"), Qt::CaseInsensitive) == 0 - || text == QStringLiteral("1"); - repeated ? reflection->SetRepeatedBool(message, field, repeatedIndex, value) - : reflection->SetBool(message, field, value); - break; - } - case Field::CPPTYPE_INT32: { - const int value = text.toInt(&ok); - if (ok) repeated ? reflection->SetRepeatedInt32(message, field, repeatedIndex, value) - : reflection->SetInt32(message, field, value); - break; - } - case Field::CPPTYPE_INT64: { - const qlonglong value = text.toLongLong(&ok); - if (ok) repeated ? reflection->SetRepeatedInt64(message, field, repeatedIndex, value) - : reflection->SetInt64(message, field, value); - break; - } - case Field::CPPTYPE_UINT32: { - const uint value = text.toUInt(&ok); - if (ok) repeated ? reflection->SetRepeatedUInt32(message, field, repeatedIndex, value) - : reflection->SetUInt32(message, field, value); - break; - } - case Field::CPPTYPE_UINT64: { - const qulonglong value = text.toULongLong(&ok); - if (ok) repeated ? reflection->SetRepeatedUInt64(message, field, repeatedIndex, value) - : reflection->SetUInt64(message, field, value); - break; - } - case Field::CPPTYPE_FLOAT: { - const float value = text.toFloat(&ok); - if (ok) repeated ? reflection->SetRepeatedFloat(message, field, repeatedIndex, value) - : reflection->SetFloat(message, field, value); - break; - } - case Field::CPPTYPE_DOUBLE: { - const double value = text.toDouble(&ok); - if (ok) repeated ? reflection->SetRepeatedDouble(message, field, repeatedIndex, value) - : reflection->SetDouble(message, field, value); - break; - } - case Field::CPPTYPE_STRING: - repeated ? reflection->SetRepeatedString(message, field, repeatedIndex, text.toStdString()) - : reflection->SetString(message, field, text.toStdString()); - break; - case Field::CPPTYPE_ENUM: { - const auto *value = field->enum_type()->FindValueByName(text.toStdString()); - ok = value != nullptr; - if (ok) repeated ? reflection->SetRepeatedEnum(message, field, repeatedIndex, value) - : reflection->SetEnum(message, field, value); - break; - } - case Field::CPPTYPE_MESSAGE: - return false; - } - return ok; -} - -bool setParameterValue(google::protobuf::Message *message, const QString &path, - const QString &value) -{ - if (!message || path.isEmpty()) - return false; - const QString head = path.section(QLatin1Char('.'), 0, 0); - const QString tail = path.section(QLatin1Char('.'), 1); - static const QRegularExpression indexedPattern( - QStringLiteral("^([A-Za-z_][A-Za-z0-9_]*)(?:\\[(\\d+)\\])?$")); - const auto match = indexedPattern.match(head); - if (!match.hasMatch()) - return false; - const QString name = match.captured(1); - const int index = match.captured(2).isEmpty() ? -1 : match.captured(2).toInt(); - const auto *field = message->GetDescriptor()->FindFieldByName(name.toStdString()); - if (!field) - return false; - if (tail.isEmpty()) - return setScalarField(message, field, index, value); - if (field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) - return false; - auto *reflection = message->GetReflection(); - google::protobuf::Message *child = nullptr; - if (field->is_repeated()) { - if (index < 0 || index >= reflection->FieldSize(*message, field)) - return false; - child = reflection->MutableRepeatedMessage(message, field, index); - } else { - child = reflection->MutableMessage(message, field); - } - return setParameterValue(child, tail, value); -} - -QString printMessage(const google::protobuf::Message &message) -{ - std::string output; - google::protobuf::TextFormat::Printer printer; - printer.SetUseUtf8StringEscaping(true); - if (!printer.PrintToString(message, &output)) - return QString(); - return QString::fromStdString(output); -} - -DevicePresentation presentationForDeviceType(int type) -{ - switch (type) { - case 0: - return {QStringLiteral("AGV"), QStringLiteral(":/icons/move.svg"), - QStringLiteral("#7c5ce7")}; - case 1: - return {QStringLiteral("电池"), QStringLiteral(":/icons/activity.svg"), - QStringLiteral("#d98b21")}; - case 2: - return {QStringLiteral("相机"), QStringLiteral(":/icons/camera.svg"), - QStringLiteral("#2479d8")}; - case 3: - return {QStringLiteral("灵巧手"), QStringLiteral(":/icons/hand.svg"), - QStringLiteral("#a554c7")}; - case 4: - return {QStringLiteral("夹爪"), QStringLiteral(":/icons/hand.svg"), - QStringLiteral("#bd5f8a")}; - case 5: - return {QStringLiteral("麦克风"), QStringLiteral(":/icons/mic.svg"), - QStringLiteral("#168aa2")}; - case 6: - return {QStringLiteral("机械臂"), QStringLiteral(":/icons/bot.svg"), - QStringLiteral("#e26c2d")}; - case 7: - return {QStringLiteral("扬声器"), QStringLiteral(":/icons/volume-2.svg"), - QStringLiteral("#1c9a68")}; - case 8: - return {QStringLiteral("仿生头"), QStringLiteral(":/icons/scan-face.svg"), - QStringLiteral("#d05e8d")}; - case 9: - return {QStringLiteral("电机"), QStringLiteral(":/icons/activity.svg"), - QStringLiteral("#b36b26")}; - case 10: - return {QStringLiteral("电机系统"), QStringLiteral(":/icons/activity.svg"), - QStringLiteral("#a55b24")}; - case 11: - return {QStringLiteral("MuJoCo 世界"), QStringLiteral(":/icons/braces.svg"), - QStringLiteral("#596f8f")}; - case 12: - return {QStringLiteral("MuJoCo 查看器"), QStringLiteral(":/icons/braces.svg"), - QStringLiteral("#61799a")}; - case 13: - return {QStringLiteral("CAN 总线"), QStringLiteral(":/icons/activity.svg"), - QStringLiteral("#596b78")}; - default: - return {QStringLiteral("未知设备"), QStringLiteral(":/icons/braces.svg"), - QStringLiteral("#6f7b87")}; - } -} - -DevicePresentation presentationForManagerType(int managerType, int apiType) -{ - if (managerType == 8) - return {QStringLiteral("仿生头"), QStringLiteral(":/icons/scan-face.svg"), - QStringLiteral("#d05e8d")}; - return presentationForDeviceType(apiType); -} - -QTableWidgetItem *readOnlyItem(const QString &text) -{ - auto *item = new QTableWidgetItem(text); - item->setFlags(item->flags() & ~Qt::ItemIsEditable); - return item; -} - -quintptr pointerValue(const QVariant &value) -{ - return static_cast(value.toULongLong()); -} - -QString fieldTypeName(const google::protobuf::FieldDescriptor *field) -{ - using Field = google::protobuf::FieldDescriptor; - if (field->is_repeated()) { - if (field->cpp_type() == Field::CPPTYPE_MESSAGE) - return QStringLiteral("message[]"); - return QString::fromLatin1(field->type_name()) + QStringLiteral("[]"); - } - return QString::fromLatin1(field->type_name()); -} - -QString enumValueName(const google::protobuf::EnumValueDescriptor *value) -{ - return value ? QString::fromStdString(value->name()) : QString(); -} - -QString scalarValue(const google::protobuf::Message *message, - const google::protobuf::FieldDescriptor *field, - int index) -{ - const auto *reflection = message->GetReflection(); - const bool repeated = field->is_repeated(); - using Field = google::protobuf::FieldDescriptor; - switch (field->cpp_type()) { - case Field::CPPTYPE_BOOL: - return (repeated ? reflection->GetRepeatedBool(*message, field, index) - : reflection->GetBool(*message, field)) - ? QStringLiteral("true") : QStringLiteral("false"); - case Field::CPPTYPE_INT32: - return QString::number(repeated ? reflection->GetRepeatedInt32(*message, field, index) - : reflection->GetInt32(*message, field)); - case Field::CPPTYPE_INT64: - return QString::number(static_cast( - repeated ? reflection->GetRepeatedInt64(*message, field, index) - : reflection->GetInt64(*message, field))); - case Field::CPPTYPE_UINT32: - return QString::number(repeated ? reflection->GetRepeatedUInt32(*message, field, index) - : reflection->GetUInt32(*message, field)); - case Field::CPPTYPE_UINT64: - return QString::number(static_cast( - repeated ? reflection->GetRepeatedUInt64(*message, field, index) - : reflection->GetUInt64(*message, field))); - case Field::CPPTYPE_FLOAT: - return QString::number(repeated ? reflection->GetRepeatedFloat(*message, field, index) - : reflection->GetFloat(*message, field), 'g', 9); - case Field::CPPTYPE_DOUBLE: - return QString::number(repeated ? reflection->GetRepeatedDouble(*message, field, index) - : reflection->GetDouble(*message, field), 'g', 17); - case Field::CPPTYPE_STRING: - return QString::fromUtf8((repeated ? reflection->GetRepeatedString(*message, field, index) - : reflection->GetString(*message, field)).data()); - case Field::CPPTYPE_ENUM: { - const auto *value = repeated - ? reflection->GetRepeatedEnum(*message, field, index) - : reflection->GetEnum(*message, field); - return enumValueName(value); - } - case Field::CPPTYPE_MESSAGE: - break; - } - return QString(); -} - -void setItemMetadata(QTreeWidgetItem *item, google::protobuf::Message *message, - const google::protobuf::FieldDescriptor *field, int index, - const QString &value) -{ - item->setData(1, kMessageRole, - QVariant::fromValue(reinterpret_cast(message))); - item->setData(1, kFieldRole, - QVariant::fromValue(reinterpret_cast(field))); - item->setData(1, kIndexRole, index); - item->setData(1, kPreviousValueRole, value); -} -} - -ConfigEditorWidget::~ConfigEditorWidget() = default; - -ConfigEditorWidget::ConfigEditorWidget(RobotClient *client, QWidget *parent) - : QWidget(parent), m_client(client) -{ - auto *layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - layout->setSpacing(0); - - auto *pageTabs = new QTabWidget(this); - pageTabs->setObjectName(QStringLiteral("deviceManagementTabs")); - pageTabs->setDocumentMode(true); - - auto *overviewScroll = new QScrollArea(pageTabs); - overviewScroll->setObjectName(QStringLiteral("deviceOverviewScroll")); - overviewScroll->setWidgetResizable(true); - overviewScroll->setFrameShape(QFrame::NoFrame); - auto *overviewPage = new QWidget(overviewScroll); - overviewPage->setObjectName(QStringLiteral("deviceOverviewPage")); - auto *overviewLayout = new QVBoxLayout(overviewPage); - overviewLayout->setContentsMargins(24, 18, 24, 24); - overviewLayout->setSpacing(14); - - auto *hero = new QFrame(overviewPage); - hero->setObjectName(QStringLiteral("deviceOverviewHero")); - auto *heroLayout = new QHBoxLayout(hero); - heroLayout->setContentsMargins(22, 18, 22, 18); - heroLayout->setSpacing(18); - auto *heroTextLayout = new QVBoxLayout; - heroTextLayout->setSpacing(5); - auto *heroEyebrow = new QLabel(QStringLiteral("gRPC · SYSTEM SERVICE"), hero); - heroEyebrow->setObjectName(QStringLiteral("deviceHeroEyebrow")); - auto *heroTitle = new QLabel(QStringLiteral("边缘端设备中心"), hero); - heroTitle->setObjectName(QStringLiteral("deviceHeroTitle")); - auto *heroDescription = new QLabel( - QStringLiteral("自动发现 cmvr-es 注册的在线设备,并在同一入口管理远端配置。"), hero); - heroDescription->setObjectName(QStringLiteral("deviceHeroDescription")); - heroDescription->setWordWrap(true); - m_edgeSystemLabel = new QLabel(QStringLiteral("等待获取边缘端系统信息"), hero); - m_edgeSystemLabel->setObjectName(QStringLiteral("deviceSystemIdentity")); - heroTextLayout->addWidget(heroEyebrow); - heroTextLayout->addWidget(heroTitle); - heroTextLayout->addWidget(heroDescription); - heroTextLayout->addWidget(m_edgeSystemLabel); - heroLayout->addLayout(heroTextLayout, 1); - - auto *heroActions = new QVBoxLayout; - heroActions->setSpacing(10); - heroActions->setAlignment(Qt::AlignRight | Qt::AlignVCenter); - m_edgeConnectionChip = new QLabel(QStringLiteral("● 边缘端未连接"), hero); - m_edgeConnectionChip->setObjectName(QStringLiteral("edgeConnectionChip")); - m_edgeConnectionChip->setProperty("connected", false); - m_edgeConnectionChip->setAlignment(Qt::AlignCenter); - m_deviceRefreshButton = new QPushButton(QStringLiteral("刷新设备"), hero); - m_deviceRefreshButton->setObjectName(QStringLiteral("deviceRefreshButton")); - m_deviceRefreshButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/rotate-ccw.svg"))); - m_deviceRefreshButton->setEnabled(false); - heroActions->addWidget(m_edgeConnectionChip); - heroActions->addWidget(m_deviceRefreshButton); - heroLayout->addLayout(heroActions); - overviewLayout->addWidget(hero); - - auto *metricsLayout = new QHBoxLayout; - metricsLayout->setSpacing(12); - const auto addMetricCard = [metricsLayout, overviewPage](const QString &label, - const QString &value, - const QString ¬e, - const QString &accent, - QLabel **valueLabel) { - auto *card = new QFrame(overviewPage); - card->setObjectName(QStringLiteral("deviceMetricCard")); - card->setProperty("accent", accent); - auto *cardLayout = new QVBoxLayout(card); - cardLayout->setContentsMargins(16, 13, 16, 13); - cardLayout->setSpacing(3); - auto *labelWidget = new QLabel(label, card); - labelWidget->setObjectName(QStringLiteral("deviceMetricLabel")); - auto *valueWidget = new QLabel(value, card); - valueWidget->setObjectName(QStringLiteral("deviceMetricValue")); - auto *noteWidget = new QLabel(note, card); - noteWidget->setObjectName(QStringLiteral("deviceMetricNote")); - cardLayout->addWidget(labelWidget); - cardLayout->addWidget(valueWidget); - cardLayout->addWidget(noteWidget); - metricsLayout->addWidget(card, 1); - *valueLabel = valueWidget; - }; - addMetricCard(QStringLiteral("在线设备"), QStringLiteral("--"), - QStringLiteral("GetSystemStatus 实时返回"), QStringLiteral("green"), - &m_onlineDeviceValue); - addMetricCard(QStringLiteral("设备类型"), QStringLiteral("--"), - QStringLiteral("按 DeviceType 自动归类"), QStringLiteral("blue"), - &m_deviceTypeValue); - addMetricCard(QStringLiteral("最近同步"), QStringLiteral("--:--:--"), - QStringLiteral("在线状态每秒自动更新"), QStringLiteral("orange"), - &m_lastSyncValue); - overviewLayout->addLayout(metricsLayout); - - auto *deviceHeader = new QHBoxLayout; - deviceHeader->setContentsMargins(2, 4, 2, 0); - auto *deviceHeaderText = new QVBoxLayout; - deviceHeaderText->setSpacing(2); - m_deviceSectionTitle = new QLabel(QStringLiteral("在线设备"), overviewPage); - m_deviceSectionTitle->setObjectName(QStringLiteral("deviceSectionTitle")); - m_deviceSectionHint = new QLabel( - QStringLiteral("设备 ID 与类型由边缘端 DeviceManager 注册信息生成"), overviewPage); - m_deviceSectionHint->setObjectName(QStringLiteral("deviceSectionHint")); - deviceHeaderText->addWidget(m_deviceSectionTitle); - deviceHeaderText->addWidget(m_deviceSectionHint); - deviceHeader->addLayout(deviceHeaderText, 1); - m_deviceEditButton = new QPushButton(QStringLiteral("修改"), overviewPage); - m_deviceEditButton->setObjectName(QStringLiteral("deviceEditButton")); - m_deviceEditButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/edit-3.svg"))); - m_deviceEditButton->setEnabled(false); - deviceHeader->addWidget(m_deviceEditButton); - m_deviceSearchEdit = new QLineEdit(overviewPage); - m_deviceSearchEdit->setObjectName(QStringLiteral("deviceSearchEdit")); - m_deviceSearchEdit->setPlaceholderText(QStringLiteral("搜索设备 ID 或类型")); - m_deviceSearchEdit->setClearButtonEnabled(true); - m_deviceSearchEdit->setMinimumWidth(240); - deviceHeader->addWidget(m_deviceSearchEdit); - overviewLayout->addLayout(deviceHeader); - - m_deviceGridHost = new QWidget(overviewPage); - m_deviceGridHost->setObjectName(QStringLiteral("deviceGridHost")); - m_deviceGrid = new QGridLayout(m_deviceGridHost); - m_deviceGrid->setContentsMargins(0, 0, 0, 0); - m_deviceGrid->setHorizontalSpacing(12); - m_deviceGrid->setVerticalSpacing(12); - overviewLayout->addWidget(m_deviceGridHost); - overviewLayout->addStretch(1); - overviewScroll->setWidget(overviewPage); - pageTabs->addTab(overviewScroll, QStringLiteral("设备总览")); - - auto *configPage = new QWidget(pageTabs); - auto *configLayout = new QVBoxLayout(configPage); - configLayout->setContentsMargins(24, 18, 24, 18); - configLayout->setSpacing(12); - - auto *connectionBar = new QWidget(configPage); - connectionBar->setObjectName(QStringLiteral("panel")); - auto *connectionLayout = new QHBoxLayout(connectionBar); - connectionLayout->setContentsMargins(16, 12, 16, 12); - connectionLayout->setSpacing(8); - auto *hostLabel = new QLabel(QStringLiteral("配置服务"), connectionBar); - hostLabel->setObjectName(QStringLiteral("sectionTitle")); - connectionLayout->addWidget(hostLabel); - m_hostEdit = new QLineEdit(connectionBar); - m_hostEdit->setPlaceholderText(QStringLiteral("设备地址")); - m_hostEdit->setMinimumWidth(180); - m_portSpin = new QSpinBox(connectionBar); - m_portSpin->setRange(1, 65535); - m_portSpin->setButtonSymbols(QAbstractSpinBox::NoButtons); - m_portSpin->setFixedWidth(76); - QSettings settings; - m_hostEdit->setText(settings.value(QStringLiteral("configuration/host"), - QStringLiteral("192.168.28.248")).toString()); - const int savedConfigurationPort = settings.value( - QStringLiteral("configuration/port"), 50053).toInt(); - m_portSpin->setValue(savedConfigurationPort == 50052 ? 50053 : savedConfigurationPort); - connectionLayout->addWidget(m_hostEdit, 1); - connectionLayout->addWidget(m_portSpin); - m_connectButton = new QPushButton(QStringLiteral("连接"), connectionBar); - m_connectButton->setObjectName(QStringLiteral("primaryButton")); - m_refreshButton = new QPushButton(QStringLiteral("刷新"), connectionBar); - m_refreshButton->setEnabled(false); - connectionLayout->addWidget(m_connectButton); - connectionLayout->addWidget(m_refreshButton); - configLayout->addWidget(connectionBar); - - auto *splitter = new QSplitter(Qt::Horizontal, configPage); - splitter->setChildrenCollapsible(false); - m_fileList = new QListWidget(splitter); - m_fileList->setMinimumWidth(260); - m_fileList->setMaximumWidth(380); - m_fileList->setAlternatingRowColors(true); - - auto *editorPanel = new QWidget(splitter); - auto *editorLayout = new QVBoxLayout(editorPanel); - editorLayout->setContentsMargins(12, 0, 0, 0); - editorLayout->setSpacing(8); - m_rootLabel = new QLabel(QStringLiteral("远端根目录:--"), editorPanel); - m_rootLabel->setObjectName(QStringLiteral("mutedLabel")); - m_rootLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); - m_pathLabel = new QLabel(QStringLiteral("未选择配置文件"), editorPanel); - m_pathLabel->setObjectName(QStringLiteral("sectionTitle")); - m_pathLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); - m_typeLabel = new QLabel(QStringLiteral("--"), editorPanel); - m_typeLabel->setObjectName(QStringLiteral("mutedLabel")); - editorLayout->addWidget(m_rootLabel); - editorLayout->addWidget(m_pathLabel); - editorLayout->addWidget(m_typeLabel); - - m_editorTabs = new QTabWidget(editorPanel); - m_textEditor = new QPlainTextEdit(m_editorTabs); - m_textEditor->setProperty("codeEditor", true); - m_textEditor->setLineWrapMode(QPlainTextEdit::NoWrap); - m_textEditor->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); - m_textEditor->setPlaceholderText(QStringLiteral("选择左侧配置文件后在此编辑")); - m_textEditor->setEnabled(false); - m_editorTabs->addTab(m_textEditor, QStringLiteral("原始配置")); - m_fieldTree = new QTreeWidget(m_editorTabs); - m_fieldTree->setColumnCount(3); - m_fieldTree->setHeaderLabels({QStringLiteral("字段名"), QStringLiteral("值"), QStringLiteral("类型")}); - m_fieldTree->setAlternatingRowColors(true); - m_fieldTree->setRootIsDecorated(true); - m_fieldTree->setUniformRowHeights(true); - m_fieldTree->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); - m_fieldTree->header()->setSectionResizeMode(1, QHeaderView::Stretch); - m_fieldTree->header()->setSectionResizeMode(2, QHeaderView::ResizeToContents); - m_fieldTree->setEditTriggers(QAbstractItemView::DoubleClicked | - QAbstractItemView::EditKeyPressed | - QAbstractItemView::SelectedClicked); - m_editorTabs->addTab(m_fieldTree, QStringLiteral("字段编辑")); - m_enableTable = new QTableWidget(m_editorTabs); - m_enableTable->setColumnCount(4); - m_enableTable->setHorizontalHeaderLabels( - {QStringLiteral("ID"), QStringLiteral("类型"), QStringLiteral("配置文件"), - QStringLiteral("启用")}); - m_enableTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); - m_enableTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); - m_enableTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); - m_enableTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents); - m_enableTable->verticalHeader()->setVisible(false); - m_enableTable->setSelectionBehavior(QAbstractItemView::SelectRows); - m_enableTable->setEditTriggers(QAbstractItemView::NoEditTriggers); - m_editorTabs->addTab(m_enableTable, QStringLiteral("启用项")); - m_editorTabs->setTabEnabled(2, false); - editorLayout->addWidget(m_editorTabs, 1); - - auto *actionLayout = new QHBoxLayout; - m_statusLabel = new QLabel(QStringLiteral("未连接配置服务"), editorPanel); - m_statusLabel->setObjectName(QStringLiteral("mutedLabel")); - m_statusLabel->setWordWrap(true); - actionLayout->addWidget(m_statusLabel, 1); - m_reloadButton = new QPushButton(QStringLiteral("重新加载"), editorPanel); - m_validateButton = new QPushButton(QStringLiteral("校验"), editorPanel); - m_saveButton = new QPushButton(QStringLiteral("保存到设备"), editorPanel); - m_saveButton->setObjectName(QStringLiteral("primaryButton")); - actionLayout->addWidget(m_reloadButton); - actionLayout->addWidget(m_validateButton); - actionLayout->addWidget(m_saveButton); - editorLayout->addLayout(actionLayout); - splitter->addWidget(m_fileList); - splitter->addWidget(editorPanel); - splitter->setStretchFactor(0, 0); - splitter->setStretchFactor(1, 1); - configLayout->addWidget(splitter, 1); - pageTabs->addTab(configPage, QStringLiteral("配置管理")); - layout->addWidget(pageTabs, 1); - - m_parseTimer = new QTimer(this); - m_parseTimer->setSingleShot(true); - m_parseTimer->setInterval(250); - connect(m_parseTimer, &QTimer::timeout, this, &ConfigEditorWidget::rebuildEnableTable); - connect(m_connectButton, &QPushButton::clicked, this, &ConfigEditorWidget::toggleConnection); - connect(m_refreshButton, &QPushButton::clicked, this, &ConfigEditorWidget::refreshFiles); - connect(m_fileList, &QListWidget::currentItemChanged, - this, &ConfigEditorWidget::selectFile); - connect(m_reloadButton, &QPushButton::clicked, this, &ConfigEditorWidget::reloadCurrentFile); - connect(m_validateButton, &QPushButton::clicked, this, &ConfigEditorWidget::validateCurrentFile); - connect(m_saveButton, &QPushButton::clicked, this, &ConfigEditorWidget::saveCurrentFile); - connect(m_textEditor, &QPlainTextEdit::textChanged, - this, &ConfigEditorWidget::handleEditorChanged); - connect(m_fieldTree, &QTreeWidget::itemChanged, - this, &ConfigEditorWidget::handleFieldItemChanged); - connect(m_deviceRefreshButton, &QPushButton::clicked, - m_client, &RobotClient::requestSystemRefresh); - connect(m_deviceSearchEdit, &QLineEdit::textChanged, - this, &ConfigEditorWidget::rebuildDeviceCards); - connect(m_deviceEditButton, &QPushButton::clicked, - this, &ConfigEditorWidget::toggleDeviceEditing); - connect(m_client, &RobotClient::connectionChanged, - this, &ConfigEditorWidget::handleEdgeConnectionChanged); - connect(m_client, &RobotClient::systemStatusReceived, - this, &ConfigEditorWidget::handleSystemStatus); - connect(m_client, &RobotClient::systemInfoReceived, - this, &ConfigEditorWidget::handleSystemInfo); - connect(m_client, &RobotClient::configurationConnectionChanged, - this, &ConfigEditorWidget::handleConnectionChanged); - connect(m_client, &RobotClient::configurationFilesReceived, - this, &ConfigEditorWidget::handleFilesReceived); - connect(m_client, &RobotClient::configurationFileReceived, - this, &ConfigEditorWidget::handleFileReceived); - connect(m_client, &RobotClient::configurationValidationFinished, - this, &ConfigEditorWidget::handleValidationFinished); - connect(m_client, &RobotClient::configurationSaveFinished, - this, &ConfigEditorWidget::handleSaveFinished); - rebuildDeviceCards(); - updateActions(); -} - -void ConfigEditorWidget::handleEdgeConnectionChanged(bool connected, int latencyMs, - const QString &detail) -{ - m_edgeConnected = connected; - m_demoMode = connected && detail == QStringLiteral("演示数据源"); - if (connected && !m_demoMode) { - const QString endpoint = detail.trimmed(); - const int separator = endpoint.lastIndexOf(QLatin1Char(':')); - m_edgeHost = separator > 0 ? endpoint.left(separator) : endpoint; - if (!m_edgeHost.isEmpty()) - m_hostEdit->setText(m_edgeHost); - } - m_deviceRefreshButton->setEnabled(connected); - if (!m_deviceEditMode && !m_overviewLoading && !m_deviceEditRequested) - m_deviceEditButton->setEnabled(connected); - m_edgeConnectionChip->setProperty("connected", connected); - m_edgeConnectionChip->setText(connected - ? QStringLiteral("● 边缘端在线 · %1 ms").arg(latencyMs) - : QStringLiteral("● 边缘端未连接")); - m_edgeConnectionChip->setToolTip(detail); - m_edgeConnectionChip->style()->unpolish(m_edgeConnectionChip); - m_edgeConnectionChip->style()->polish(m_edgeConnectionChip); - - if (!connected) { - if (m_deviceEditMode) - cancelDeviceEditing(); - m_devices.clear(); - m_onlineDeviceValue->setText(QStringLiteral("--")); - m_deviceTypeValue->setText(QStringLiteral("--")); - m_lastSyncValue->setText(QStringLiteral("--:--:--")); - m_edgeSystemLabel->setText(QStringLiteral("等待获取边缘端系统信息")); - rebuildDeviceCards(); - return; - } - m_client->requestSystemRefresh(); -} - -void ConfigEditorWidget::handleSystemStatus(double cpu, double memory, double disk, - const QVariantList &devices) -{ - Q_UNUSED(cpu) - Q_UNUSED(memory) - Q_UNUSED(disk) - m_devices = devices; - std::sort(m_devices.begin(), m_devices.end(), [](const QVariant &left, - const QVariant &right) { - const QVariantMap leftDevice = left.toMap(); - const QVariantMap rightDevice = right.toMap(); - const int leftType = leftDevice.value(QStringLiteral("type"), 20).toInt(); - const int rightType = rightDevice.value(QStringLiteral("type"), 20).toInt(); - if (leftType != rightType) - return leftType < rightType; - return leftDevice.value(QStringLiteral("deviceId")).toString() - .localeAwareCompare(rightDevice.value(QStringLiteral("deviceId")).toString()) < 0; - }); - QSet types; - for (const QVariant &entry : m_devices) - types.insert(entry.toMap().value(QStringLiteral("type"), 20).toInt()); - m_onlineDeviceValue->setText(QString::number(m_devices.size())); - m_deviceTypeValue->setText(QString::number(types.size())); - m_lastSyncValue->setText(QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss"))); - if (m_deviceEditMode) { - QSet onlineIds; - for (const QVariant &value : m_devices) - onlineIds.insert(value.toMap().value(QStringLiteral("deviceId")).toString()); - for (int index = 0; index < m_editDevices.size(); ++index) { - QVariantMap item = m_editDevices.at(index).toMap(); - item.insert(QStringLiteral("online"), - onlineIds.contains(item.value(QStringLiteral("deviceId")).toString())); - m_editDevices[index] = item; - } - // 编辑中的控件不能随每秒一次的 GetSystemStatus 被销毁重建,否则 - // QComboBox 的弹出列表和正在输入的文本都会自动关闭或丢失焦点。 - return; - } - rebuildDeviceCards(); -} - -void ConfigEditorWidget::handleSystemInfo(const QVariantMap &info) -{ - const QString name = info.value(QStringLiteral("name"), QStringLiteral("cmvr-es")).toString(); - const QString version = info.value(QStringLiteral("version"), QStringLiteral("--")).toString(); - const QString description = info.value(QStringLiteral("description")).toString().trimmed(); - QString identity = QStringLiteral("%1 · %2").arg(name, version); - if (!description.isEmpty()) - identity += QStringLiteral(" · %1").arg(description); - m_edgeSystemLabel->setText(identity); -} - -void ConfigEditorWidget::rebuildDeviceCards() -{ - while (QLayoutItem *item = m_deviceGrid->takeAt(0)) { - if (item->widget()) - item->widget()->deleteLater(); - delete item; - } - - const QString filter = m_deviceSearchEdit - ? m_deviceSearchEdit->text().trimmed() : QString(); - const QVariantList sourceDevices = m_deviceEditMode ? m_editDevices : m_devices; - QVariantList visibleDevices; - for (const QVariant &entry : sourceDevices) { - const QVariantMap device = entry.toMap(); - const int managerType = device.value(QStringLiteral("managerType"), - managerTypeForApiType(device.value(QStringLiteral("type"), 20).toInt())).toInt(); - const DevicePresentation presentation = presentationForManagerType( - managerType, device.value(QStringLiteral("type"), 20).toInt()); - const QString searchable = device.value(QStringLiteral("deviceId")).toString() - + QLatin1Char(' ') + presentation.name - + QLatin1Char(' ') + device.value(QStringLiteral("typeName")).toString() - + QLatin1Char(' ') + device.value(QStringLiteral("deviceKindName")).toString() - + QLatin1Char(' ') + device.value(QStringLiteral("driverType")).toString() - + QLatin1Char(' ') + device.value(QStringLiteral("vendor")).toString(); - if (filter.isEmpty() || searchable.contains(filter, Qt::CaseInsensitive)) - visibleDevices.append(device); - } - - m_deviceSectionTitle->setText(filter.isEmpty() - ? QStringLiteral("在线设备 · %1").arg(sourceDevices.size()) - : QStringLiteral("搜索结果 · %1").arg(visibleDevices.size())); - - if (visibleDevices.isEmpty() && !m_deviceEditMode) { - auto *emptyState = new QFrame(m_deviceGridHost); - emptyState->setObjectName(QStringLiteral("deviceEmptyState")); - auto *emptyLayout = new QVBoxLayout(emptyState); - emptyLayout->setContentsMargins(20, 34, 20, 34); - emptyLayout->setAlignment(Qt::AlignCenter); - auto *emptyIcon = new QLabel(emptyState); - emptyIcon->setPixmap(UiIcons::tintedPixmap(QStringLiteral(":/icons/radio-tower.svg"), - QColor(QStringLiteral("#91a0ad")), 34)); - emptyIcon->setAlignment(Qt::AlignCenter); - auto *emptyTitle = new QLabel(emptyState); - emptyTitle->setObjectName(QStringLiteral("deviceEmptyTitle")); - emptyTitle->setAlignment(Qt::AlignCenter); - auto *emptyHint = new QLabel(emptyState); - emptyHint->setObjectName(QStringLiteral("deviceEmptyHint")); - emptyHint->setAlignment(Qt::AlignCenter); - if (!filter.isEmpty()) { - emptyTitle->setText(QStringLiteral("没有匹配的设备")); - emptyHint->setText(QStringLiteral("请尝试其他设备 ID 或类型关键词")); - } else if (!m_edgeConnected) { - emptyTitle->setText(QStringLiteral("等待连接边缘端")); - emptyHint->setText(QStringLiteral("请先在顶部连接 cmvr-es gRPC 服务")); - } else { - emptyTitle->setText(QStringLiteral("暂未发现在线设备")); - emptyHint->setText(QStringLiteral("GetSystemStatus 尚未返回已注册设备")); - } - emptyLayout->addWidget(emptyIcon); - emptyLayout->addWidget(emptyTitle); - emptyLayout->addWidget(emptyHint); - m_deviceGrid->addWidget(emptyState, 0, 0, 1, 3); - return; - } - - constexpr int columns = 3; - for (int index = 0; index < visibleDevices.size(); ++index) { - const QVariantMap device = visibleDevices.at(index).toMap(); - const QString uid = device.value(QStringLiteral("uid")).toString(); - const QString deviceId = device.value(QStringLiteral("deviceId"), - QStringLiteral("--")).toString(); - const int deviceType = device.value(QStringLiteral("type"), 20).toInt(); - const int managerType = device.value(QStringLiteral("managerType"), - managerTypeForApiType(deviceType)).toInt(); - const DevicePresentation presentation = presentationForManagerType(managerType, deviceType); - - auto *card = new DeviceCardFrame(m_deviceGridHost); - card->setObjectName(QStringLiteral("deviceCard")); - card->setProperty("accent", presentation.accent); - card->setProperty("editing", m_deviceEditMode); - card->setMinimumHeight(m_deviceEditMode ? 218 : 142); - auto *cardLayout = new QVBoxLayout(card); - cardLayout->setContentsMargins(16, 14, 16, 14); - cardLayout->setSpacing(9); - - auto *cardHeader = new QHBoxLayout; - auto *iconBadge = new QLabel(card); - iconBadge->setObjectName(QStringLiteral("deviceIconBadge")); - iconBadge->setFixedSize(38, 38); - iconBadge->setAlignment(Qt::AlignCenter); - iconBadge->setPixmap(UiIcons::tintedPixmap(presentation.icon, - QColor(presentation.accent), 20)); - auto *typeLayout = new QVBoxLayout; - typeLayout->setSpacing(1); - auto *typeLabel = new QLabel(presentation.name, card); - typeLabel->setObjectName(QStringLiteral("deviceCardType")); - QString deviceMetadata = device.value(QStringLiteral("vendor")).toString().trimmed(); - const QString driverType = device.value(QStringLiteral("driverType")).toString().trimmed(); - if (!driverType.isEmpty()) { - if (!deviceMetadata.isEmpty()) - deviceMetadata += QStringLiteral(" · "); - deviceMetadata += driverType; - } - if (deviceMetadata.isEmpty()) - deviceMetadata = QStringLiteral("gRPC DEVICE"); - auto *protocolLabel = new QLabel(deviceMetadata, card); - protocolLabel->setObjectName(QStringLiteral("deviceCardProtocol")); - protocolLabel->setToolTip(deviceMetadata); - typeLayout->addWidget(typeLabel); - typeLayout->addWidget(protocolLabel); - auto *onlineChip = new QLabel(QStringLiteral("● 在线"), card); - onlineChip->setObjectName(QStringLiteral("deviceOnlineChip")); - onlineChip->setAlignment(Qt::AlignCenter); - if (m_deviceEditMode && !device.value(QStringLiteral("online"), true).toBool()) { - onlineChip->setText(QStringLiteral("● 待保存")); - onlineChip->setProperty("pending", true); - } - cardHeader->addWidget(iconBadge); - cardHeader->addLayout(typeLayout, 1); - cardHeader->addWidget(onlineChip); - if (m_deviceEditMode) { - auto *deleteButton = new QToolButton(card); - deleteButton->setObjectName(QStringLiteral("deviceDeleteButton")); - deleteButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/trash-2.svg"))); - deleteButton->setToolTip(QStringLiteral("删除设备")); - connect(deleteButton, &QToolButton::clicked, this, [this, uid, deviceId]() { - const auto answer = AppMessageBox::question( - this, QStringLiteral("删除设备"), - QStringLiteral("确定从 DeviceManager 配置中删除设备“%1”吗?").arg(deviceId), - AppMessageBox::Yes | AppMessageBox::No, AppMessageBox::No); - if (answer != AppMessageBox::Yes) - return; - const int editIndex = editableDeviceIndex(uid); - if (editIndex >= 0) - m_editDevices.removeAt(editIndex); - rebuildDeviceCards(); - }); - cardHeader->addWidget(deleteButton); - } - cardLayout->addLayout(cardHeader); - - if (!m_deviceEditMode) { - auto *idLabel = new QLabel(deviceId, card); - idLabel->setObjectName(QStringLiteral("deviceCardId")); - idLabel->setToolTip(deviceId); - auto *sourceLabel = new QLabel(QStringLiteral("点击进入设备控制 →"), card); - sourceLabel->setObjectName(QStringLiteral("deviceCardSource")); - cardLayout->addWidget(idLabel); - cardLayout->addWidget(sourceLabel); - card->setCursor(Qt::PointingHandCursor); - card->activated = [this, deviceType, managerType, deviceId]() { - emit deviceNavigationRequested( - managerType == 8 ? 8 : deviceType, deviceId); - }; - const auto transparent = [](QWidget *widget) { - widget->setAttribute(Qt::WA_TransparentForMouseEvents); - }; - transparent(iconBadge); - transparent(typeLabel); - transparent(protocolLabel); - transparent(onlineChip); - transparent(idLabel); - transparent(sourceLabel); - } else { - auto *fields = new QGridLayout; - fields->setHorizontalSpacing(10); - fields->setVerticalSpacing(5); - const auto fieldLabel = [card](const QString &text) { - auto *label = new QLabel(text, card); - label->setObjectName(QStringLiteral("deviceConfigFieldLabel")); - return label; - }; - fields->addWidget(fieldLabel(QStringLiteral("设备 ID")), 0, 0); - fields->addWidget(fieldLabel(QStringLiteral("设备类型")), 0, 1); - fields->addWidget(fieldLabel(QStringLiteral("品牌 / 驱动")), 0, 2); - auto *idEdit = new QLineEdit(deviceId, card); - idEdit->setObjectName(QStringLiteral("deviceConfigInput")); - auto *typeCombo = new QComboBox(card); - typeCombo->setObjectName(QStringLiteral("deviceConfigCombo")); - const QList> deviceTypes = { - {QStringLiteral("机械臂"), 12}, {QStringLiteral("相机"), 13}, - {QStringLiteral("AGV"), 17}, {QStringLiteral("扬声器"), 16}, - {QStringLiteral("麦克风"), 15}, {QStringLiteral("灵巧手"), 14}, - {QStringLiteral("仿生头"), 8}}; - for (const auto &option : deviceTypes) - typeCombo->addItem(option.first, option.second); - const int typeIndex = typeCombo->findData(managerType); - if (typeIndex >= 0) - typeCombo->setCurrentIndex(typeIndex); - auto *brandCombo = new QComboBox(card); - brandCombo->setObjectName(QStringLiteral("deviceConfigCombo")); - const QVariantList brands = brandOptionsForType(managerType); - for (const QVariant &value : brands) { - const QVariantMap brand = value.toMap(); - brandCombo->addItem(brand.value(QStringLiteral("label")).toString(), brand); - } - const QString selectedBrand = device.value(QStringLiteral("brandKey")).toString(); - for (int brandIndex = 0; brandIndex < brandCombo->count(); ++brandIndex) { - if (brandCombo->itemData(brandIndex).toMap().value(QStringLiteral("key")).toString() - == selectedBrand) { - brandCombo->setCurrentIndex(brandIndex); - break; - } - } - fields->addWidget(idEdit, 1, 0); - fields->addWidget(typeCombo, 1, 1); - fields->addWidget(brandCombo, 1, 2); - fields->setColumnStretch(0, 5); - fields->setColumnStretch(1, 4); - fields->setColumnStretch(2, 5); - cardLayout->addLayout(fields); - - auto *parameterButton = new QPushButton(card); - parameterButton->setObjectName(QStringLiteral("deviceParameterToggle")); - const QVariantList parameters = device.value(QStringLiteral("parameters")).toList(); - const bool expanded = device.value(QStringLiteral("expanded")).toBool(); - parameterButton->setText(QStringLiteral("配置参数 · %1 项").arg(parameters.size())); - parameterButton->setIcon(UiIcons::icon(expanded - ? QStringLiteral(":/icons/chevron-up.svg") - : QStringLiteral(":/icons/chevron-down.svg"))); - connect(parameterButton, &QPushButton::clicked, this, [this, uid, expanded]() { - for (int row = 0; row < m_editDevices.size(); ++row) { - QVariantMap item = m_editDevices.at(row).toMap(); - item.insert(QStringLiteral("expanded"), false); - m_editDevices[row] = item; - } - updateEditableDevice(uid, QStringLiteral("expanded"), !expanded, true); - }); - cardLayout->addWidget(parameterButton); - - if (expanded) { - auto *parameterHost = new QWidget(card); - parameterHost->setObjectName(QStringLiteral("deviceParameterHost")); - auto *parameterLayout = new QGridLayout(parameterHost); - parameterLayout->setContentsMargins(10, 9, 10, 9); - parameterLayout->setHorizontalSpacing(10); - parameterLayout->setVerticalSpacing(6); - auto *nameHeader = new QLabel(QStringLiteral("字段"), parameterHost); - auto *valueHeader = new QLabel(QStringLiteral("值"), parameterHost); - nameHeader->setObjectName(QStringLiteral("deviceParameterHeader")); - valueHeader->setObjectName(QStringLiteral("deviceParameterHeader")); - parameterLayout->addWidget(nameHeader, 0, 0); - parameterLayout->addWidget(valueHeader, 0, 1); - for (int row = 0; row < parameters.size(); ++row) { - const QVariantMap parameter = parameters.at(row).toMap(); - auto *nameLabel = new QLabel( - parameter.value(QStringLiteral("label")).toString(), parameterHost); - nameLabel->setObjectName(QStringLiteral("deviceParameterName")); - nameLabel->setToolTip(parameter.value(QStringLiteral("path")).toString()); - parameterLayout->addWidget(nameLabel, row + 1, 0); - const int cppType = parameter.value(QStringLiteral("type")).toInt(); - const QVariantList options = parameter.value(QStringLiteral("options")).toList(); - if (!options.isEmpty()) { - auto *input = new QComboBox(parameterHost); - input->setObjectName(QStringLiteral("deviceParameterInput")); - for (const QVariant &option : options) - input->addItem(option.toString()); - input->setCurrentText(parameter.value(QStringLiteral("value")).toString()); - connect(input, &QComboBox::currentTextChanged, this, - [this, uid, row](const QString &value) { - const int deviceIndex = editableDeviceIndex(uid); - if (deviceIndex < 0) - return; - QVariantMap item = m_editDevices.at(deviceIndex).toMap(); - QVariantList rows = item.value(QStringLiteral("parameters")).toList(); - if (row >= rows.size()) - return; - QVariantMap parameter = rows.at(row).toMap(); - parameter.insert(QStringLiteral("value"), value); - rows[row] = parameter; - item.insert(QStringLiteral("parameters"), rows); - m_editDevices[deviceIndex] = item; - }); - parameterLayout->addWidget(input, row + 1, 1); - } else if (cppType == google::protobuf::FieldDescriptor::CPPTYPE_BOOL) { - auto *input = new QCheckBox(parameterHost); - input->setObjectName(QStringLiteral("deviceParameterCheck")); - input->setChecked(parameter.value(QStringLiteral("value")).toString() - == QStringLiteral("true")); - connect(input, &QCheckBox::toggled, this, [this, uid, row](bool checked) { - const int deviceIndex = editableDeviceIndex(uid); - if (deviceIndex < 0) - return; - QVariantMap item = m_editDevices.at(deviceIndex).toMap(); - QVariantList rows = item.value(QStringLiteral("parameters")).toList(); - QVariantMap parameter = rows.at(row).toMap(); - parameter.insert(QStringLiteral("value"), checked - ? QStringLiteral("true") : QStringLiteral("false")); - rows[row] = parameter; - item.insert(QStringLiteral("parameters"), rows); - m_editDevices[deviceIndex] = item; - }); - parameterLayout->addWidget(input, row + 1, 1, Qt::AlignLeft); - } else { - auto *input = new QLineEdit( - parameter.value(QStringLiteral("value")).toString(), parameterHost); - input->setObjectName(QStringLiteral("deviceParameterInput")); - if (parameter.value(QStringLiteral("secret")).toBool()) - input->setEchoMode(QLineEdit::PasswordEchoOnEdit); - connect(input, &QLineEdit::textChanged, this, - [this, uid, row](const QString &value) { - const int deviceIndex = editableDeviceIndex(uid); - if (deviceIndex < 0) - return; - QVariantMap item = m_editDevices.at(deviceIndex).toMap(); - QVariantList rows = item.value(QStringLiteral("parameters")).toList(); - if (row >= rows.size()) - return; - QVariantMap parameter = rows.at(row).toMap(); - parameter.insert(QStringLiteral("value"), value); - rows[row] = parameter; - item.insert(QStringLiteral("parameters"), rows); - m_editDevices[deviceIndex] = item; - }); - parameterLayout->addWidget(input, row + 1, 1); - } - } - parameterLayout->setColumnStretch(0, 4); - parameterLayout->setColumnStretch(1, 6); - auto *parameterScroll = new QScrollArea(card); - parameterScroll->setObjectName(QStringLiteral("deviceParameterScroll")); - parameterScroll->setFrameShape(QFrame::NoFrame); - parameterScroll->setWidgetResizable(true); - parameterScroll->setWidget(parameterHost); - parameterScroll->setMinimumHeight(90); - parameterScroll->setMaximumHeight(250); - cardLayout->addWidget(parameterScroll); - } - - connect(idEdit, &QLineEdit::textChanged, this, [this, uid](const QString &value) { - updateEditableDevice(uid, QStringLiteral("deviceId"), value.trimmed()); - }); - connect(typeCombo, QOverload::of(&QComboBox::activated), this, - [this, uid, typeCombo](int comboIndex) { - const int editIndex = editableDeviceIndex(uid); - if (editIndex < 0 || comboIndex < 0) - return; - QVariantMap item = m_editDevices.at(editIndex).toMap(); - const int nextManagerType = typeCombo->itemData(comboIndex).toInt(); - item.insert(QStringLiteral("managerType"), nextManagerType); - item.insert(QStringLiteral("type"), apiTypeForManagerType(nextManagerType)); - m_editDevices[editIndex] = item; - refreshEditableDeviceSchema(editIndex); - QTimer::singleShot(0, this, &ConfigEditorWidget::rebuildDeviceCards); - }); - connect(brandCombo, QOverload::of(&QComboBox::activated), this, - [this, uid, brandCombo](int comboIndex) { - const int editIndex = editableDeviceIndex(uid); - if (editIndex < 0 || comboIndex < 0) - return; - QVariantMap item = m_editDevices.at(editIndex).toMap(); - const QVariantMap brand = brandCombo->itemData(comboIndex).toMap(); - item.insert(QStringLiteral("brandKey"), brand.value(QStringLiteral("key"))); - item.insert(QStringLiteral("backend"), brand.value(QStringLiteral("backend"))); - item.insert(QStringLiteral("brandNumber"), brand.value(QStringLiteral("brandNumber"), -1)); - item.insert(QStringLiteral("configFile"), brand.value(QStringLiteral("configFile"))); - m_editDevices[editIndex] = item; - refreshEditableDeviceSchema(editIndex); - QTimer::singleShot(0, this, &ConfigEditorWidget::rebuildDeviceCards); - }); - } - m_deviceGrid->addWidget(card, index / columns, index % columns); - } - if (m_deviceEditMode && filter.isEmpty()) { - auto *addCard = new DeviceCardFrame(m_deviceGridHost); - addCard->setObjectName(QStringLiteral("deviceAddCard")); - addCard->setCursor(Qt::PointingHandCursor); - addCard->setMinimumHeight(218); - auto *addLayout = new QVBoxLayout(addCard); - addLayout->setAlignment(Qt::AlignCenter); - auto *addIcon = new QLabel(addCard); - addIcon->setObjectName(QStringLiteral("deviceAddIcon")); - addIcon->setPixmap(UiIcons::tintedPixmap(QStringLiteral(":/icons/plus.svg"), - QColor(QStringLiteral("#337ee8")), 30)); - addIcon->setAlignment(Qt::AlignCenter); - auto *addTitle = new QLabel(QStringLiteral("增加新设备"), addCard); - addTitle->setObjectName(QStringLiteral("deviceAddTitle")); - auto *addHint = new QLabel(QStringLiteral("添加 DeviceManager 配置项"), addCard); - addHint->setObjectName(QStringLiteral("deviceAddHint")); - addHint->setAlignment(Qt::AlignCenter); - addLayout->addWidget(addIcon); - addLayout->addWidget(addTitle, 0, Qt::AlignCenter); - addLayout->addWidget(addHint, 0, Qt::AlignCenter); - addCard->activated = [this]() { addEditableDevice(); }; - addIcon->setAttribute(Qt::WA_TransparentForMouseEvents); - addTitle->setAttribute(Qt::WA_TransparentForMouseEvents); - addHint->setAttribute(Qt::WA_TransparentForMouseEvents); - const int addIndex = visibleDevices.size(); - m_deviceGrid->addWidget(addCard, addIndex / columns, addIndex % columns); - } - for (int column = 0; column < columns; ++column) - m_deviceGrid->setColumnStretch(column, 1); -} - -QVariantList ConfigEditorWidget::brandOptionsForType(int managerType) const -{ - const QString folder = typeFolderForManagerType(managerType); - const auto resolvePath = [this, folder](const QString &preferred) { - for (const QVariant &value : m_configurationFiles) { - if (value.toMap().value(QStringLiteral("relativePath")).toString() == preferred) - return preferred; - } - for (const QVariant &value : m_configurationFiles) { - const QString path = value.toMap().value(QStringLiteral("relativePath")).toString(); - if (path.contains(QStringLiteral("/devices/%1/").arg(folder)) - || path.startsWith(QStringLiteral("devices/%1/").arg(folder))) - return path; - } - return preferred; - }; - const auto option = [](const QString &key, const QString &label, - const QString &backend, int brandNumber, - const QString &configFile) { - QVariantMap value; - value.insert(QStringLiteral("key"), key); - value.insert(QStringLiteral("label"), label); - value.insert(QStringLiteral("backend"), backend); - value.insert(QStringLiteral("brandNumber"), brandNumber); - value.insert(QStringLiteral("configFile"), configFile); - return value; - }; - - QVariantList result; - switch (managerType) { - case 17: { - const QString path = resolvePath(QStringLiteral("devices/agv/agv.pb.txt")); - result << option(QStringLiteral("seer"), QStringLiteral("仙工 · Robokit / SRC1100"), - QStringLiteral("seer_robokit_agv"), -1, path) - << option(QStringLiteral("generic_agv"), QStringLiteral("通用 / 测试 AGV"), - QStringLiteral("my_agv"), -1, path); - break; - } - case 12: - result << option(QStringLiteral("aubo"), QStringLiteral("AUBO"), - QStringLiteral("vendor"), 1, - resolvePath(QStringLiteral("devices/arm/aubo_arm.pb.txt"))) - << option(QStringLiteral("huayan"), QStringLiteral("华沿 Elfin"), - QStringLiteral("vendor"), 2, - resolvePath(QStringLiteral("devices/arm/huayan_arm.pb.txt"))); - for (const QVariant &value : m_configurationFiles) { - const QString path = value.toMap().value(QStringLiteral("relativePath")).toString(); - if (!path.contains(QStringLiteral("devices/arm/")) - || path.endsWith(QStringLiteral("aubo_arm.pb.txt")) - || path.endsWith(QStringLiteral("huayan_arm.pb.txt"))) - continue; - QString name = QFileInfo(path).fileName(); - name.remove(QStringLiteral(".pb.txt")); - result << option(QStringLiteral("motor:%1").arg(path), - QStringLiteral("电机 / %1").arg(name), - QStringLiteral("motor"), -1, path); - } - if (result.size() == 2) { - result << option(QStringLiteral("motor"), QStringLiteral("电机 / 通用机械臂"), - QStringLiteral("motor"), -1, - resolvePath(QStringLiteral("devices/arm/arm.pb.txt"))); - } - break; - case 13: { - const QString path = resolvePath(QStringLiteral("devices/camera/camera.pb.txt")); - result << option(QStringLiteral("hikvision"), QStringLiteral("海康威视"), QStringLiteral("hikvision"), -1, path) - << option(QStringLiteral("realsense"), QStringLiteral("Intel RealSense"), QStringLiteral("realsense"), -1, path) - << option(QStringLiteral("mechmind"), QStringLiteral("梅卡曼德 Mech-Mind"), QStringLiteral("mechmind"), -1, path) - << option(QStringLiteral("uvc"), QStringLiteral("UVC / USB 相机"), QStringLiteral("uvc"), -1, path) - << option(QStringLiteral("mujoco_camera"), QStringLiteral("MuJoCo 虚拟相机"), QStringLiteral("mujoco"), -1, path); - break; - } - case 14: { - const QString path = resolvePath(QStringLiteral("devices/dexhand/dexhand.pb.txt")); - result << option(QStringLiteral("rh56dftp"), QStringLiteral("因时 RH56DFTP"), QStringLiteral("rh56dftp"), -1, path) - << option(QStringLiteral("px6ax"), QStringLiteral("PX-6AX Gen3"), QStringLiteral("px_6ax_gen3"), -1, path) - << option(QStringLiteral("zero_sim_touch"), QStringLiteral("ZeroSimTouch"), QStringLiteral("zero_sim_touch"), -1, path); - break; - } - case 15: - result << option(QStringLiteral("ffmpeg_microphone"), QStringLiteral("FFmpeg / USB Audio"), - QStringLiteral("ffmpeg"), -1, - resolvePath(QStringLiteral("devices/microphone/microphone.pb.txt"))); - break; - case 16: - result << option(QStringLiteral("ffmpeg_speaker"), QStringLiteral("FFmpeg / USB Audio"), - QStringLiteral("ffmpeg"), -1, - resolvePath(QStringLiteral("devices/speaker/speaker.pb.txt"))); - break; - case 8: - result << option(QStringLiteral("biohead"), QStringLiteral("串口仿生头"), QString(), -1, - resolvePath(QStringLiteral("devices/biohead/bio_head.pb.txt"))); - break; - default: - break; - } - return result; -} - -QVariantList ConfigEditorWidget::parameterRowsForDevice(const QVariantMap &device) const -{ - const QString path = device.value(QStringLiteral("configFile")).toString(); - const int managerType = device.value(QStringLiteral("managerType")).toInt(); - const QString messageType = m_overviewMessageTypes.value( - path, defaultMessageTypeForManagerType(managerType)); - QString error; - auto root = createMessage(messageType, m_overviewContents.value(path), &error); - if (!root) - return {}; - auto *entry = deviceEntry(root.get(), device.value(QStringLiteral("deviceId")).toString(), true); - if (!entry) - return {}; - if (const auto *idField = entry->GetDescriptor()->FindFieldByName("id")) - entry->GetReflection()->SetString(entry, idField, - device.value(QStringLiteral("deviceId")).toString().toStdString()); - auto *backend = selectBackend(entry, device.value(QStringLiteral("backend")).toString(), - device.value(QStringLiteral("brandNumber"), -1).toInt()); - if (!backend) - return {}; - if (const auto *idField = backend->GetDescriptor()->FindFieldByName("id")) - backend->GetReflection()->SetString(backend, idField, - device.value(QStringLiteral("deviceId")).toString().toStdString()); - QVariantList rows; - appendParameterRows(entry, QString(), &rows); - return rows; -} - -int ConfigEditorWidget::editableDeviceIndex(const QString &uid) const -{ - for (int index = 0; index < m_editDevices.size(); ++index) { - if (m_editDevices.at(index).toMap().value(QStringLiteral("uid")).toString() == uid) - return index; - } - return -1; -} - -void ConfigEditorWidget::updateEditableDevice(const QString &uid, const QString &key, - const QVariant &value, bool rebuild) -{ - const int index = editableDeviceIndex(uid); - if (index < 0) - return; - QVariantMap device = m_editDevices.at(index).toMap(); - device.insert(key, value); - m_editDevices[index] = device; - if (rebuild) - rebuildDeviceCards(); -} - -void ConfigEditorWidget::refreshEditableDeviceSchema(int index) -{ - if (index < 0 || index >= m_editDevices.size()) - return; - QVariantMap device = m_editDevices.at(index).toMap(); - const QVariantList brands = brandOptionsForType( - device.value(QStringLiteral("managerType")).toInt()); - QVariantMap selected; - const QString key = device.value(QStringLiteral("brandKey")).toString(); - for (const QVariant &value : brands) { - if (value.toMap().value(QStringLiteral("key")).toString() == key) { - selected = value.toMap(); - break; - } - } - if (selected.isEmpty() && !brands.isEmpty()) - selected = brands.first().toMap(); - device.insert(QStringLiteral("brandKey"), selected.value(QStringLiteral("key"))); - device.insert(QStringLiteral("backend"), selected.value(QStringLiteral("backend"))); - device.insert(QStringLiteral("brandNumber"), selected.value(QStringLiteral("brandNumber"), -1)); - device.insert(QStringLiteral("configFile"), selected.value(QStringLiteral("configFile"))); - device.insert(QStringLiteral("parameters"), parameterRowsForDevice(device)); - m_editDevices[index] = device; -} - -void ConfigEditorWidget::addEditableDevice() -{ - QVariantMap device; - device.insert(QStringLiteral("uid"), QUuid::createUuid().toString(QUuid::WithoutBraces)); - int suffix = 1; - QString id; - QSet used; - for (const QVariant &value : m_editDevices) - used.insert(value.toMap().value(QStringLiteral("deviceId")).toString()); - do { - id = QStringLiteral("new_robot_%1").arg(suffix++); - } while (used.contains(id)); - device.insert(QStringLiteral("deviceId"), id); - device.insert(QStringLiteral("originalId"), QString()); - device.insert(QStringLiteral("managerType"), 12); - device.insert(QStringLiteral("type"), 6); - device.insert(QStringLiteral("online"), false); - device.insert(QStringLiteral("enable"), true); - device.insert(QStringLiteral("expanded"), true); - m_editDevices.append(device); - refreshEditableDeviceSchema(m_editDevices.size() - 1); - rebuildDeviceCards(); -} - -void ConfigEditorWidget::buildEditableDevices() -{ - m_editDevices.clear(); - cmvr::config::DeviceManagerRootConfig manager; - const bool managerReady = m_managerContent.trimmed().isEmpty() - || google::protobuf::TextFormat::ParseFromString(m_managerContent.toStdString(), &manager); - if (!managerReady) { - AppMessageBox::critical(this, QStringLiteral("读取设备配置"), - QStringLiteral("DeviceManager 配置格式与当前上位机协议不兼容。")); - cancelDeviceEditing(); - return; - } - - for (const QVariant &value : m_devices) { - const QVariantMap live = value.toMap(); - const QString id = live.value(QStringLiteral("deviceId")).toString(); - QVariantMap device = live; - device.insert(QStringLiteral("uid"), QUuid::createUuid().toString(QUuid::WithoutBraces)); - device.insert(QStringLiteral("originalId"), id); - device.insert(QStringLiteral("online"), true); - device.insert(QStringLiteral("expanded"), false); - int managerType = managerTypeForApiType(live.value(QStringLiteral("type"), 20).toInt()); - QString configFile; - bool enabled = true; - for (const auto &entry : manager.device_manager().devices()) { - if (QString::fromStdString(entry.id()) != id) - continue; - managerType = static_cast(entry.type()); - configFile = QString::fromStdString(entry.config_file()); - enabled = entry.enable(); - break; - } - device.insert(QStringLiteral("managerType"), managerType); - device.insert(QStringLiteral("type"), apiTypeForManagerType(managerType)); - device.insert(QStringLiteral("configFile"), configFile); - device.insert(QStringLiteral("enable"), enabled); - - const QVariantList brands = brandOptionsForType(managerType); - QVariantMap selected; - QString activeBackend; - int activeBrand = -1; - if (!configFile.isEmpty()) { - const QString messageType = m_overviewMessageTypes.value( - configFile, defaultMessageTypeForManagerType(managerType)); - auto root = createMessage(messageType, m_overviewContents.value(configFile)); - auto *entry = deviceEntry(root.get(), id, false); - if (entry) { - if (const auto *oneof = entry->GetDescriptor()->FindOneofByName("backend")) { - const auto *active = entry->GetReflection()->GetOneofFieldDescriptor(*entry, oneof); - if (active) { - activeBackend = QString::fromStdString(active->name()); - const auto &backend = entry->GetReflection()->GetMessage(*entry, active); - const auto *brandField = backend.GetDescriptor()->FindFieldByName("brand"); - if (brandField) - activeBrand = backend.GetReflection()->GetEnumValue(backend, brandField); - } - } - } - } - for (const QVariant &brandValue : brands) { - const QVariantMap brand = brandValue.toMap(); - const bool samePath = configFile.isEmpty() - || brand.value(QStringLiteral("configFile")).toString() == configFile; - const bool sameBackend = activeBackend.isEmpty() - || brand.value(QStringLiteral("backend")).toString() == activeBackend; - const int brandNumber = brand.value(QStringLiteral("brandNumber"), -1).toInt(); - const bool sameBrand = activeBrand < 0 || brandNumber < 0 || brandNumber == activeBrand; - if (samePath && sameBackend && sameBrand) { - selected = brand; - break; - } - } - if (selected.isEmpty() && !brands.isEmpty()) - selected = brands.first().toMap(); - device.insert(QStringLiteral("brandKey"), selected.value(QStringLiteral("key"))); - device.insert(QStringLiteral("backend"), selected.value(QStringLiteral("backend"))); - device.insert(QStringLiteral("brandNumber"), selected.value(QStringLiteral("brandNumber"), -1)); - if (configFile.isEmpty()) - device.insert(QStringLiteral("configFile"), selected.value(QStringLiteral("configFile"))); - device.insert(QStringLiteral("parameters"), parameterRowsForDevice(device)); - m_editDevices.append(device); - } - m_deviceEditMode = true; - m_deviceEditRequested = false; - m_overviewLoading = false; - m_deviceEditButton->setEnabled(true); - m_deviceEditButton->setText(QStringLiteral("完成")); - m_deviceEditButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/check.svg"))); - m_deviceEditButton->setObjectName(QStringLiteral("deviceEditButtonActive")); - m_deviceSectionHint->setText( - QStringLiteral("正在编辑 DeviceManager 配置;完成后将保存并上传到 cmvr-es")); - m_deviceSearchEdit->clear(); - rebuildDeviceCards(); -} - -void ConfigEditorWidget::beginDeviceConfigurationLoad() -{ - m_overviewLoading = true; - m_deviceEditRequested = false; - m_deviceEditButton->setEnabled(false); - m_deviceEditButton->setText(QStringLiteral("加载中…")); - m_configurationFiles.clear(); - m_overviewContents.clear(); - m_overviewRevisions.clear(); - m_overviewMessageTypes.clear(); - m_client->requestConfigurationFiles(); -} - -void ConfigEditorWidget::readNextOverviewConfiguration() -{ - if (m_overviewReadQueue.isEmpty()) { - m_overviewCurrentRead.clear(); - buildEditableDevices(); - return; - } - m_overviewCurrentRead = m_overviewReadQueue.takeFirst(); - m_client->readConfigurationFile(m_overviewCurrentRead); -} - -void ConfigEditorWidget::toggleDeviceEditing() -{ - if (m_deviceEditMode) { - finishDeviceEditing(); - return; - } - if (!m_edgeConnected) { - AppMessageBox::information(this, QStringLiteral("设备配置"), - QStringLiteral("请先连接 cmvr-es,再修改设备配置。")); - return; - } - if (m_demoMode) { - m_managerContent.clear(); - m_configurationFiles.clear(); - m_overviewContents.clear(); - m_overviewMessageTypes.clear(); - buildEditableDevices(); - return; - } - if (!m_connected) { - m_deviceEditRequested = true; - m_deviceEditButton->setEnabled(false); - m_deviceEditButton->setText(QStringLiteral("连接配置服务…")); - const QString host = m_edgeHost.isEmpty() ? m_hostEdit->text().trimmed() : m_edgeHost; - m_client->connectConfigurationServer(host, m_portSpin->value()); - return; - } - beginDeviceConfigurationLoad(); -} - -void ConfigEditorWidget::cancelDeviceEditing() -{ - m_deviceEditMode = false; - m_deviceEditRequested = false; - m_overviewLoading = false; - m_overviewSaving = false; - m_editDevices.clear(); - m_deviceEditButton->setEnabled(m_edgeConnected); - m_deviceEditButton->setText(QStringLiteral("修改")); - m_deviceEditButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/edit-3.svg"))); - m_deviceEditButton->setObjectName(QStringLiteral("deviceEditButton")); - m_deviceSectionHint->setText( - QStringLiteral("设备 ID 与类型由边缘端 DeviceManager 注册信息生成")); - rebuildDeviceCards(); -} - -bool ConfigEditorWidget::prepareOverviewSave(QString *error) -{ - cmvr::config::DeviceManagerRootConfig manager; - if (!google::protobuf::TextFormat::ParseFromString(m_managerContent.toStdString(), &manager)) { - if (error) - *error = QStringLiteral("无法解析 DeviceManager 配置"); - return false; - } - - QSet originalIds; - for (const QVariant &value : m_devices) - originalIds.insert(value.toMap().value(QStringLiteral("deviceId")).toString()); - QSet currentIds; - for (const QVariant &value : m_editDevices) { - const QString id = value.toMap().value(QStringLiteral("deviceId")).toString().trimmed(); - if (id.isEmpty()) { - if (error) - *error = QStringLiteral("设备 ID 不能为空"); - return false; - } - if (currentIds.contains(id)) { - if (error) - *error = QStringLiteral("设备 ID “%1” 重复").arg(id); - return false; - } - currentIds.insert(id); - } - - QSet affectedPaths; - auto *entries = manager.mutable_device_manager()->mutable_devices(); - for (int index = entries->size() - 1; index >= 0; --index) { - if (!originalIds.contains(QString::fromStdString(entries->Get(index).id()))) - continue; - affectedPaths.insert(QString::fromStdString(entries->Get(index).config_file())); - entries->DeleteSubrange(index, 1); - } - for (const QVariant &value : m_editDevices) { - const QVariantMap device = value.toMap(); - const QString path = device.value(QStringLiteral("configFile")).toString(); - if (path.isEmpty()) { - if (error) - *error = QStringLiteral("设备 “%1” 没有可用配置文件") - .arg(device.value(QStringLiteral("deviceId")).toString()); - return false; - } - affectedPaths.insert(path); - auto *entry = entries->Add(); - entry->set_id(device.value(QStringLiteral("deviceId")).toString().toStdString()); - entry->set_type(static_cast( - device.value(QStringLiteral("managerType")).toInt())); - entry->set_config_file(path.toStdString()); - entry->set_enable(device.value(QStringLiteral("enable"), true).toBool()); - } - - m_overviewSaveContents.clear(); - m_overviewSaveRevisions.clear(); - for (const QString &path : qAsConst(affectedPaths)) { - if (path.isEmpty()) - continue; - if (!m_overviewContents.contains(path) || !m_overviewRevisions.contains(path)) { - if (error) - *error = QStringLiteral("尚未加载配置文件 %1,无法安全保存").arg(path); - return false; - } - int managerType = 0; - for (const QVariant &value : m_editDevices) { - if (value.toMap().value(QStringLiteral("configFile")).toString() == path) { - managerType = value.toMap().value(QStringLiteral("managerType")).toInt(); - break; - } - } - const QString messageType = m_overviewMessageTypes.value( - path, defaultMessageTypeForManagerType(managerType)); - QString parseError; - auto root = createMessage(messageType, m_overviewContents.value(path), &parseError); - if (!root) { - if (error) - *error = QStringLiteral("%1:%2").arg(path, parseError); - return false; - } - removeDeviceEntries(root.get(), originalIds); - int directEntryCount = 0; - for (const QVariant &value : m_editDevices) { - const QVariantMap device = value.toMap(); - if (device.value(QStringLiteral("configFile")).toString() != path) - continue; - if (device.value(QStringLiteral("managerType")).toInt() == 8 && ++directEntryCount > 1) { - if (error) - *error = QStringLiteral("仿生头配置文件当前只支持一个设备"); - return false; - } - const QString id = device.value(QStringLiteral("deviceId")).toString().trimmed(); - auto *entry = deviceEntry(root.get(), id, true); - if (!entry) { - if (error) - *error = QStringLiteral("无法在 %1 中创建设备 %2").arg(path, id); - return false; - } - if (const auto *idField = entry->GetDescriptor()->FindFieldByName("id")) - entry->GetReflection()->SetString(entry, idField, id.toStdString()); - auto *backend = selectBackend(entry, - device.value(QStringLiteral("backend")).toString(), - device.value(QStringLiteral("brandNumber"), -1).toInt()); - if (!backend) { - if (error) - *error = QStringLiteral("设备 %1 的品牌驱动与配置协议不匹配").arg(id); - return false; - } - if (const auto *idField = backend->GetDescriptor()->FindFieldByName("id")) - backend->GetReflection()->SetString(backend, idField, id.toStdString()); - const QVariantList parameters = device.value(QStringLiteral("parameters")).toList(); - for (const QVariant ¶meterValue : parameters) { - const QVariantMap parameter = parameterValue.toMap(); - const QString parameterPath = parameter.value(QStringLiteral("path")).toString(); - const QString parameterText = parameter.value(QStringLiteral("value")).toString(); - if (parameterText.isEmpty() && parameterPath.endsWith(QLatin1Char(']'))) - continue; - if (!setParameterValue(entry, parameterPath, parameterText)) { - if (error) - *error = QStringLiteral("设备 %1 的参数 %2 格式不正确") - .arg(id, parameterPath); - return false; - } - } - } - const QString serialized = printMessage(*root); - if (serialized.isEmpty()) { - if (error) - *error = QStringLiteral("无法序列化 %1").arg(path); - return false; - } - m_overviewSaveContents.insert(path, serialized); - m_overviewSaveRevisions.insert(path, m_overviewRevisions.value(path)); - } - - const QString managerSerialized = printMessage(manager); - if (managerSerialized.isEmpty()) { - if (error) - *error = QStringLiteral("无法序列化 DeviceManager 配置"); - return false; - } - m_overviewSaveContents.insert(m_managerPath, managerSerialized); - m_overviewSaveRevisions.insert(m_managerPath, m_managerRevision); - m_overviewSaveQueue = m_overviewSaveContents.keys(); - m_overviewSaveQueue.removeAll(m_managerPath); - std::sort(m_overviewSaveQueue.begin(), m_overviewSaveQueue.end()); - m_overviewSaveQueue.append(m_managerPath); - return true; -} - -void ConfigEditorWidget::finishDeviceEditing() -{ - if (m_demoMode) { - QVariantList demoDevices; - for (const QVariant &value : m_editDevices) { - const QVariantMap configured = value.toMap(); - QVariantMap live; - live.insert(QStringLiteral("deviceId"), configured.value(QStringLiteral("deviceId"))); - live.insert(QStringLiteral("type"), configured.value(QStringLiteral("type"))); - live.insert(QStringLiteral("typeName"), QStringLiteral("DEVICE_TYPE_DEMO")); - demoDevices.append(live); - } - m_devices = demoDevices; - cancelDeviceEditing(); - AppMessageBox::information(this, QStringLiteral("演示模式"), - QStringLiteral("演示配置已应用到当前界面;未写入远端文件。")); - return; - } - QString error; - if (!prepareOverviewSave(&error)) { - AppMessageBox::warning(this, QStringLiteral("无法保存设备配置"), error); - return; - } - m_overviewSaving = true; - m_deviceEditButton->setEnabled(false); - m_deviceEditButton->setText(QStringLiteral("保存中…")); - saveNextOverviewConfiguration(); -} - -void ConfigEditorWidget::saveNextOverviewConfiguration() -{ - if (m_overviewSaveQueue.isEmpty()) { - m_overviewSaving = false; - m_overviewCurrentSave.clear(); - cancelDeviceEditing(); - m_client->requestSystemRefresh(); - AppMessageBox::information( - this, QStringLiteral("设备配置已保存"), - QStringLiteral("配置文件已上传到 cmvr-es。配置重载/重启功能将在后续接入。")); - return; - } - m_overviewCurrentSave = m_overviewSaveQueue.takeFirst(); - m_client->saveConfigurationFile( - m_overviewCurrentSave, - m_overviewSaveContents.value(m_overviewCurrentSave), - m_overviewSaveRevisions.value(m_overviewCurrentSave)); -} - -void ConfigEditorWidget::toggleConnection() -{ - if (m_connected) { - if (!confirmDiscardChanges()) - return; - m_client->disconnectConfigurationServer(); - return; - } - if (m_hostEdit->text().trimmed().isEmpty()) { - setStatus(QStringLiteral("设备地址不能为空"), true); - return; - } - QSettings settings; - settings.setValue(QStringLiteral("configuration/host"), m_hostEdit->text().trimmed()); - settings.setValue(QStringLiteral("configuration/port"), m_portSpin->value()); - setBusy(true); - setStatus(QStringLiteral("正在连接配置服务...")); - m_client->connectConfigurationServer(m_hostEdit->text(), m_portSpin->value()); -} - -void ConfigEditorWidget::refreshFiles() -{ - if (!m_connected || !confirmDiscardChanges()) - return; - setBusy(true); - setStatus(QStringLiteral("正在读取远端配置列表...")); - m_client->requestConfigurationFiles(); -} - -void ConfigEditorWidget::selectFile(QListWidgetItem *current, QListWidgetItem *previous) -{ - if (!current) - return; - const QString nextPath = current->data(kPathRole).toString(); - if (nextPath == m_currentPath) - return; - if (!confirmDiscardChanges()) { - const QSignalBlocker blocker(m_fileList); - m_fileList->setCurrentItem(previous); - return; - } - setBusy(true); - setStatus(QStringLiteral("正在读取 %1...").arg(nextPath)); - m_client->readConfigurationFile(nextPath); -} - -void ConfigEditorWidget::reloadCurrentFile() -{ - if (m_currentPath.isEmpty() || !confirmDiscardChanges()) - return; - setBusy(true); - m_client->readConfigurationFile(m_currentPath); -} - -void ConfigEditorWidget::validateCurrentFile() -{ - if (m_currentPath.isEmpty()) - return; - setBusy(true); - setStatus(QStringLiteral("正在校验 %1...").arg(m_currentPath)); - m_client->validateConfigurationFile(m_currentPath, m_textEditor->toPlainText()); -} - -void ConfigEditorWidget::saveCurrentFile() -{ - if (m_currentPath.isEmpty() || m_revision.isEmpty()) - return; - setBusy(true); - setStatus(QStringLiteral("正在保存 %1...").arg(m_currentPath)); - m_client->saveConfigurationFile(m_currentPath, m_textEditor->toPlainText(), m_revision); -} - -void ConfigEditorWidget::handleConnectionChanged(bool connected, const QString &detail) -{ - m_connected = connected; - setBusy(false); - m_hostEdit->setEnabled(!connected); - m_portSpin->setEnabled(!connected); - m_connectButton->setText(connected ? QStringLiteral("断开") : QStringLiteral("连接")); - setStatus(detail, !connected && detail != QStringLiteral("配置服务已断开")); - if (connected && m_deviceEditRequested) { - beginDeviceConfigurationLoad(); - } else if (connected) { - refreshFiles(); - } - else { - if (m_deviceEditRequested || m_overviewLoading) { - m_deviceEditRequested = false; - m_overviewLoading = false; - m_deviceEditButton->setEnabled(m_edgeConnected); - m_deviceEditButton->setText(QStringLiteral("修改")); - } - m_fileList->clear(); - m_rootLabel->setText(QStringLiteral("远端根目录:--")); - clearCurrentFile(); - } - updateActions(); -} - -void ConfigEditorWidget::handleFilesReceived(const QString &configRoot, - const QVariantList &files, - bool success, const QString &detail) -{ - setBusy(false); - if (!success) { - if (m_overviewLoading) { - m_overviewLoading = false; - m_deviceEditButton->setEnabled(true); - m_deviceEditButton->setText(QStringLiteral("修改")); - } - setStatus(detail.isEmpty() ? QStringLiteral("读取配置列表失败") : detail, true); - return; - } - if (m_overviewLoading) { - Q_UNUSED(configRoot) - m_configurationFiles = files; - m_overviewReadQueue.clear(); - m_managerPath.clear(); - const QSet supportedFolders = { - QStringLiteral("agv"), QStringLiteral("arm"), QStringLiteral("camera"), - QStringLiteral("dexhand"), QStringLiteral("microphone"), - QStringLiteral("speaker"), QStringLiteral("biohead")}; - for (const QVariant &value : files) { - const QVariantMap file = value.toMap(); - const QString path = file.value(QStringLiteral("relativePath")).toString(); - m_overviewMessageTypes.insert(path, - file.value(QStringLiteral("messageType")).toString()); - if (path.endsWith(QStringLiteral("device_manager.pb.txt"))) { - m_managerPath = path; - continue; - } - const QString normalized = QDir::fromNativeSeparators(path); - for (const QString &folder : supportedFolders) { - if (normalized.contains(QStringLiteral("devices/%1/").arg(folder))) { - m_overviewReadQueue.append(path); - break; - } - } - } - if (m_managerPath.isEmpty()) { - m_overviewLoading = false; - m_deviceEditButton->setEnabled(true); - m_deviceEditButton->setText(QStringLiteral("修改")); - AppMessageBox::warning(this, QStringLiteral("读取设备配置"), - QStringLiteral("远端配置列表中未找到 device_manager.pb.txt。")); - return; - } - m_overviewReadQueue.prepend(m_managerPath); - readNextOverviewConfiguration(); - return; - } - const QSignalBlocker blocker(m_fileList); - m_fileList->clear(); - clearCurrentFile(); - for (const QVariant &value : files) { - const QVariantMap file = value.toMap(); - const QString path = file.value(QStringLiteral("relativePath")).toString(); - auto *item = new QListWidgetItem(path, m_fileList); - item->setData(kPathRole, path); - item->setToolTip(QStringLiteral("%1\n%2 bytes\n%3") - .arg(file.value(QStringLiteral("messageType")).toString()) - .arg(file.value(QStringLiteral("sizeBytes")).toULongLong()) - .arg(QDateTime::fromMSecsSinceEpoch( - file.value(QStringLiteral("modifiedUnixMs")).toLongLong()).toString(Qt::ISODate))); - } - m_rootLabel->setText(QStringLiteral("远端根目录:%1").arg(configRoot)); - setStatus(QStringLiteral("已读取 %1 个配置文件").arg(files.size())); - updateActions(); -} - -void ConfigEditorWidget::handleFileReceived(const QString &relativePath, - const QString &content, - const QString &revision, - const QString &messageType, - bool success, const QString &detail) -{ - setBusy(false); - if (m_overviewLoading && relativePath == m_overviewCurrentRead) { - if (!success) { - m_overviewLoading = false; - m_deviceEditButton->setEnabled(true); - m_deviceEditButton->setText(QStringLiteral("修改")); - AppMessageBox::warning(this, QStringLiteral("读取设备配置"), - detail.isEmpty() ? QStringLiteral("读取 %1 失败").arg(relativePath) - : detail); - return; - } - m_overviewContents.insert(relativePath, content); - m_overviewRevisions.insert(relativePath, revision); - m_overviewMessageTypes.insert(relativePath, messageType); - if (relativePath == m_managerPath) { - m_managerContent = content; - m_managerRevision = revision; - m_managerMessageType = messageType; - } - readNextOverviewConfiguration(); - return; - } - if (!success) { - setStatus(detail.isEmpty() ? QStringLiteral("读取配置文件失败") : detail, true); - return; - } - m_loading = true; - m_currentPath = relativePath; - m_revision = revision; - m_messageType = messageType; - m_textEditor->setPlainText(content); - m_textEditor->document()->setModified(false); - m_loading = false; - m_dirty = false; - m_pathLabel->setText(relativePath); - m_typeLabel->setText(QStringLiteral("消息类型:%1 版本:%2") - .arg(messageType, revision)); - rebuildFieldTree(); - rebuildEnableTable(); - setStatus(QStringLiteral("配置已加载")); - updateActions(); -} - -void ConfigEditorWidget::handleValidationFinished(const QString &relativePath, - bool success, - const QString &detail) -{ - if (relativePath != m_currentPath) - return; - setBusy(false); - setStatus(detail.isEmpty() ? (success ? QStringLiteral("配置有效") - : QStringLiteral("配置无效")) : detail, - !success); -} - -void ConfigEditorWidget::handleSaveFinished(const QString &relativePath, - const QString &revision, - bool success, - const QString &detail) -{ - if (m_overviewSaving && relativePath == m_overviewCurrentSave) { - if (!success) { - m_overviewSaving = false; - m_deviceEditButton->setEnabled(true); - m_deviceEditButton->setText(QStringLiteral("完成")); - AppMessageBox::critical( - this, QStringLiteral("保存设备配置失败"), - QStringLiteral("%1\n%2\n\n已成功保存的文件不会自动回滚,请刷新后再试。") - .arg(relativePath, detail.isEmpty() ? QStringLiteral("远端拒绝保存") : detail)); - return; - } - m_overviewRevisions.insert(relativePath, revision); - saveNextOverviewConfiguration(); - return; - } - if (relativePath != m_currentPath) - return; - setBusy(false); - if (!success) { - setStatus(detail.isEmpty() ? QStringLiteral("保存失败") : detail, true); - return; - } - m_revision = revision; - m_dirty = false; - m_textEditor->document()->setModified(false); - m_typeLabel->setText(m_typeLabel->text().section(QStringLiteral(" 版本:"), 0, 0) - + QStringLiteral(" 版本:") + revision); - setStatus(QStringLiteral("已保存到远端项目配置文件")); - updateActions(); -} - -void ConfigEditorWidget::handleEditorChanged() -{ - if (m_loading || m_currentPath.isEmpty()) - return; - m_dirty = true; - m_parseTimer->start(); - updateActions(); -} - -bool ConfigEditorWidget::parseFieldDocument() -{ - m_dynamicMessage.reset(); - m_dynamicFactory.reset(); - if (m_messageType.isEmpty() || m_textEditor->toPlainText().trimmed().isEmpty()) - return false; - - const auto *descriptor = google::protobuf::DescriptorPool::generated_pool() - ->FindMessageTypeByName(m_messageType.toStdString()); - if (!descriptor) - return false; - m_dynamicFactory = std::make_unique(); - const auto *prototype = m_dynamicFactory->GetPrototype(descriptor); - if (!prototype) - return false; - m_dynamicMessage.reset(prototype->New()); - if (!google::protobuf::TextFormat::ParseFromString( - m_textEditor->toPlainText().toStdString(), m_dynamicMessage.get())) { - m_dynamicMessage.reset(); - return false; - } - return true; -} - -void ConfigEditorWidget::appendMessageFields(QTreeWidgetItem *parent, - google::protobuf::Message *message) -{ - if (!parent || !message) - return; - const auto *descriptor = message->GetDescriptor(); - const auto *reflection = message->GetReflection(); - using Field = google::protobuf::FieldDescriptor; - - for (int fieldIndex = 0; fieldIndex < descriptor->field_count(); ++fieldIndex) { - const auto *field = descriptor->field(fieldIndex); - const QString fieldName = QString::fromStdString(field->name()); - if (field->is_repeated()) { - const int count = reflection->FieldSize(*message, field); - if (count == 0) { - auto *empty = new QTreeWidgetItem(parent); - empty->setText(0, fieldName + QStringLiteral(" []")); - empty->setText(1, QStringLiteral("<空>")); - empty->setText(2, fieldTypeName(field)); - empty->setFlags(empty->flags() & ~Qt::ItemIsEditable); - continue; - } - for (int index = 0; index < count; ++index) { - auto *item = new QTreeWidgetItem(parent); - item->setText(0, fieldName + QStringLiteral("[%1]").arg(index)); - item->setText(2, fieldTypeName(field)); - if (field->cpp_type() == Field::CPPTYPE_MESSAGE) { - item->setText(1, QStringLiteral("message")); - appendMessageFields(item, - reflection->MutableRepeatedMessage(message, field, index)); - item->setExpanded(true); - } else { - const QString value = scalarValue(message, field, index); - item->setText(1, value); - setItemMetadata(item, message, field, index, value); - } - } - continue; - } - - auto *item = new QTreeWidgetItem(parent); - item->setText(0, fieldName); - item->setText(2, fieldTypeName(field)); - if (field->cpp_type() == Field::CPPTYPE_MESSAGE) { - if (reflection->HasField(*message, field)) { - item->setText(1, QStringLiteral("message")); - appendMessageFields(item, reflection->MutableMessage(message, field)); - item->setExpanded(true); - } else { - item->setText(1, QStringLiteral("<未设置>")); - item->setFlags(item->flags() & ~Qt::ItemIsEditable); - } - } else { - const QString value = scalarValue(message, field, -1); - item->setText(1, value); - setItemMetadata(item, message, field, -1, value); - } - } -} - -void ConfigEditorWidget::rebuildFieldTree() -{ - const QSignalBlocker blocker(m_fieldTree); - m_fieldTree->clear(); - if (!parseFieldDocument()) - return; - - auto *root = new QTreeWidgetItem(m_fieldTree); - root->setText(0, m_messageType); - root->setText(1, QStringLiteral("message")); - root->setText(2, QStringLiteral("message")); - root->setFlags(root->flags() & ~Qt::ItemIsEditable); - appendMessageFields(root, m_dynamicMessage.get()); - root->setExpanded(true); -} - -bool ConfigEditorWidget::applyFieldValue(QTreeWidgetItem *item, const QString &text) -{ - if (!item) - return false; - auto *message = reinterpret_cast( - pointerValue(item->data(1, kMessageRole))); - const auto *field = reinterpret_cast( - pointerValue(item->data(1, kFieldRole))); - if (!message || !field) - return false; - const int index = item->data(1, kIndexRole).toInt(); - const QString value = text.trimmed(); - const auto *reflection = message->GetReflection(); - using Field = google::protobuf::FieldDescriptor; - bool ok = true; - - auto setBool = [&](bool parsed) { - if (field->is_repeated()) reflection->SetRepeatedBool(message, field, index, parsed); - else reflection->SetBool(message, field, parsed); - }; - switch (field->cpp_type()) { - case Field::CPPTYPE_BOOL: - if (value.compare(QStringLiteral("true"), Qt::CaseInsensitive) == 0 || value == QStringLiteral("1")) - setBool(true); - else if (value.compare(QStringLiteral("false"), Qt::CaseInsensitive) == 0 || value == QStringLiteral("0")) - setBool(false); - else ok = false; - break; - case Field::CPPTYPE_INT32: { - const qlonglong number = value.toLongLong(&ok); - if (ok) field->is_repeated() ? reflection->SetRepeatedInt32(message, field, index, static_cast(number)) - : reflection->SetInt32(message, field, static_cast(number)); - break; - } - case Field::CPPTYPE_INT64: { - const qlonglong number = value.toLongLong(&ok); - if (ok) field->is_repeated() ? reflection->SetRepeatedInt64(message, field, index, number) - : reflection->SetInt64(message, field, number); - break; - } - case Field::CPPTYPE_UINT32: { - const qulonglong number = value.toULongLong(&ok); - if (ok) field->is_repeated() ? reflection->SetRepeatedUInt32(message, field, index, static_cast(number)) - : reflection->SetUInt32(message, field, static_cast(number)); - break; - } - case Field::CPPTYPE_UINT64: { - const qulonglong number = value.toULongLong(&ok); - if (ok) field->is_repeated() ? reflection->SetRepeatedUInt64(message, field, index, number) - : reflection->SetUInt64(message, field, number); - break; - } - case Field::CPPTYPE_FLOAT: { - const float number = value.toFloat(&ok); - if (ok) field->is_repeated() ? reflection->SetRepeatedFloat(message, field, index, number) - : reflection->SetFloat(message, field, number); - break; - } - case Field::CPPTYPE_DOUBLE: { - const double number = value.toDouble(&ok); - if (ok) field->is_repeated() ? reflection->SetRepeatedDouble(message, field, index, number) - : reflection->SetDouble(message, field, number); - break; - } - case Field::CPPTYPE_STRING: - if (field->is_repeated()) reflection->SetRepeatedString(message, field, index, text.toUtf8().toStdString()); - else reflection->SetString(message, field, text.toUtf8().toStdString()); - break; - case Field::CPPTYPE_ENUM: { - const auto *enumValue = field->enum_type()->FindValueByName(value.toStdString()); - if (!enumValue) { - int number = value.toInt(&ok); - enumValue = field->enum_type()->FindValueByNumber(number); - } - if (!enumValue) ok = false; - else if (field->is_repeated()) reflection->SetRepeatedEnum(message, field, index, enumValue); - else reflection->SetEnum(message, field, enumValue); - break; - } - case Field::CPPTYPE_MESSAGE: - ok = false; - break; - } - return ok; -} - -bool ConfigEditorWidget::syncFieldTreeToText() -{ - if (!m_dynamicMessage) - return false; - google::protobuf::TextFormat::Printer printer; - std::string text; - if (!printer.PrintToString(*m_dynamicMessage, &text)) - return false; - m_loading = true; - { - const QSignalBlocker blocker(m_textEditor); - m_textEditor->setPlainText(QString::fromStdString(text)); - m_textEditor->document()->setModified(true); - } - m_loading = false; - return true; -} - -void ConfigEditorWidget::handleFieldItemChanged(QTreeWidgetItem *item, int column) -{ - if (m_loading || column != 1 || !item || !item->data(1, kFieldRole).isValid()) - return; - const QString previous = item->data(1, kPreviousValueRole).toString(); - if (!applyFieldValue(item, item->text(1)) || !syncFieldTreeToText()) { - const QSignalBlocker blocker(m_fieldTree); - item->setText(1, previous); - setStatus(QStringLiteral("字段值格式无效,修改未应用"), true); - return; - } - item->setData(1, kPreviousValueRole, item->text(1)); - m_dirty = true; - updateActions(); - m_parseTimer->start(); -} - -void ConfigEditorWidget::rebuildEnableTable() -{ - rebuildFieldTree(); - m_enableTable->setRowCount(0); - const ManagerKind kind = managerKindForPath(m_currentPath); - m_editorTabs->setTabEnabled(2, kind != ManagerKind::None); - if (kind == ManagerKind::None) - return; - - const std::string text = m_textEditor->toPlainText().toStdString(); - QStringList ids; - QStringList types; - QStringList configFiles; - QList enabledValues; - bool parsed = false; - if (kind == ManagerKind::Device) { - cmvr::config::DeviceManagerRootConfig root; - parsed = google::protobuf::TextFormat::ParseFromString(text, &root); - if (parsed) { - for (const auto &entry : root.device_manager().devices()) { - ids.append(QString::fromStdString(entry.id())); - types.append(QString::fromStdString( - cmvr::config::DeviceConfigEntry::DeviceType_Name(entry.type()))); - configFiles.append(QString::fromStdString(entry.config_file())); - enabledValues.append(entry.enable()); - } - } - } else { - cmvr::config::TaskManagerRootConfig root; - parsed = google::protobuf::TextFormat::ParseFromString(text, &root); - if (parsed) { - for (const auto &entry : root.task_manager().tasks()) { - ids.append(QString::fromStdString(entry.id())); - types.append(QString::fromStdString( - cmvr::config::TaskConfigEntry::TaskType_Name(entry.type()))); - configFiles.append(QString::fromStdString(entry.config_file())); - enabledValues.append(entry.enable()); - } - } - } - if (!parsed) { - setStatus(QStringLiteral("原始配置存在语法错误,启用项暂不可编辑"), true); - return; - } - - m_enableTable->setRowCount(ids.size()); - for (int row = 0; row < ids.size(); ++row) { - m_enableTable->setItem(row, 0, readOnlyItem(ids.at(row))); - m_enableTable->setItem(row, 1, readOnlyItem(types.at(row))); - m_enableTable->setItem(row, 2, readOnlyItem(configFiles.at(row))); - auto *container = new QWidget(m_enableTable); - auto *switchLayout = new QHBoxLayout(container); - switchLayout->setContentsMargins(8, 0, 8, 0); - switchLayout->setAlignment(Qt::AlignCenter); - auto *toggle = new QCheckBox(container); - toggle->setObjectName(QStringLiteral("configEnableSwitch")); - toggle->setChecked(enabledValues.at(row)); - toggle->setToolTip(enabledValues.at(row) ? QStringLiteral("点击停用") - : QStringLiteral("点击启用")); - switchLayout->addWidget(toggle); - m_enableTable->setCellWidget(row, 3, container); - connect(toggle, &QCheckBox::toggled, this, [this, row, toggle](bool checked) { - if (!replaceEnableValue(row, checked)) { - const QSignalBlocker blocker(toggle); - toggle->setChecked(!checked); - setStatus(QStringLiteral("无法定位对应的 enable 字段"), true); - } - }); - } -} - -bool ConfigEditorWidget::confirmDiscardChanges() -{ - if (!m_dirty) - return true; - const auto answer = AppMessageBox::question( - this, QStringLiteral("未保存的修改"), - QStringLiteral("当前配置尚未保存,确定放弃修改吗?"), - AppMessageBox::Discard | AppMessageBox::Cancel, AppMessageBox::Cancel); - return answer == AppMessageBox::Discard; -} - -void ConfigEditorWidget::setBusy(bool busy) -{ - m_busy = busy; - updateActions(); -} - -void ConfigEditorWidget::setStatus(const QString &text, bool error) -{ - m_statusLabel->setText(text); - m_statusLabel->setStyleSheet(error ? QStringLiteral("color:#b42318;") : QString()); -} - -void ConfigEditorWidget::clearCurrentFile() -{ - m_loading = true; - m_currentPath.clear(); - m_revision.clear(); - m_dirty = false; - m_textEditor->clear(); - m_messageType.clear(); - m_dynamicFactory.reset(); - m_dynamicMessage.reset(); - m_fieldTree->clear(); - m_loading = false; - m_pathLabel->setText(QStringLiteral("未选择配置文件")); - m_typeLabel->setText(QStringLiteral("--")); - m_enableTable->setRowCount(0); - m_editorTabs->setTabEnabled(2, false); - updateActions(); -} - -void ConfigEditorWidget::updateActions() -{ - const bool hasFile = !m_currentPath.isEmpty(); - m_refreshButton->setEnabled(m_connected && !m_busy); - m_fileList->setEnabled(m_connected && !m_busy); - m_textEditor->setEnabled(hasFile && m_connected && !m_busy); - m_fieldTree->setEnabled(hasFile && m_connected && !m_busy); - m_enableTable->setEnabled(hasFile && m_connected && !m_busy); - m_reloadButton->setEnabled(hasFile && m_connected && !m_busy); - m_validateButton->setEnabled(hasFile && m_connected && !m_busy); - m_saveButton->setEnabled(hasFile && m_connected && m_dirty && !m_busy); - m_connectButton->setEnabled(!m_busy); -} - -bool ConfigEditorWidget::replaceEnableValue(int index, bool enabled) -{ - QString text = m_textEditor->toPlainText(); - const QRegularExpression expression(QStringLiteral("\\benable\\s*:\\s*(true|false)")); - auto matches = expression.globalMatch(text); - QRegularExpressionMatch target; - int current = 0; - for (; current <= index && matches.hasNext(); ++current) - target = matches.next(); - if (!target.hasMatch() || current <= index) - return false; - QTextCursor cursor(m_textEditor->document()); - cursor.setPosition(target.capturedStart(1)); - cursor.setPosition(target.capturedEnd(1), QTextCursor::KeepAnchor); - m_loading = true; - cursor.insertText(enabled ? QStringLiteral("true") : QStringLiteral("false")); - m_loading = false; - m_dirty = true; - m_textEditor->document()->setModified(true); - updateActions(); - return true; -} - -ConfigEditorWidget::ManagerKind ConfigEditorWidget::managerKindForPath( - const QString &path) const -{ - const QString normalized = path.toLower(); - if (normalized == QStringLiteral("manager/device_manager.pb.txt")) - return ManagerKind::Device; - if (normalized == QStringLiteral("manager/task_manager.pb.txt")) - return ManagerKind::Task; - return ManagerKind::None; -} diff --git a/src/configeditorwidget.h b/src/configeditorwidget.h deleted file mode 100644 index 344e555..0000000 --- a/src/configeditorwidget.h +++ /dev/null @@ -1,163 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#include - -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 m_overviewContents; - QHash m_overviewRevisions; - QHash m_overviewMessageTypes; - QStringList m_overviewReadQueue; - QString m_overviewCurrentRead; - QStringList m_overviewSaveQueue; - QString m_overviewCurrentSave; - QHash m_overviewSaveContents; - QHash 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 m_dynamicFactory; - std::unique_ptr m_dynamicMessage; -}; diff --git a/src/demosimulator.h b/src/demosimulator.h index 282a3f4..83bbcf6 100644 --- a/src/demosimulator.h +++ b/src/demosimulator.h @@ -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(); diff --git a/src/freescaninterop.cpp b/src/freescaninterop.cpp index 1ce2935..6d15e04 100644 --- a/src/freescaninterop.cpp +++ b/src/freescaninterop.cpp @@ -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 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 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 deviceSlots,roleNames;QHash 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 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 restoreRobots=[&](QJsonArray& list){for(int i=0;isetPen(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(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 &selection) { QSet 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(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 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=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 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(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(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(m_view)->refreshHistoryButtons();} +} +void JointFlowEditor::recordHistory() { + if(m_restoringHistory||!m_view->isInteractive())return; + m_editHistory.push(historyState());static_cast(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 guard(m_restoringHistory,true); + m_graph=state.value("graph").toObject(); + fromJson(state.value("nodes").toArray(),false); + emit changed();m_editHistory.replaceCurrent(historyState());static_cast(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(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 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 selectedIds;for(auto* item:m_scene->selectedItems())selectedIds.insert(item->data(7010).toString()); m_scene->clear(); QHash 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 ¢er){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 ¢er){QTimer::singleShot(0,this,[this,id,center]{if(m_view->isInteractive()){QHash 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); diff --git a/src/jointfloweditor.h b/src/jointfloweditor.h index af5cb32..952545a 100644 --- a/src/jointfloweditor.h +++ b/src/jointfloweditor.h @@ -8,6 +8,7 @@ #include #include #include +#include "workflowhistory.h" class QGraphicsScene; class QGraphicsView; @@ -34,7 +35,7 @@ public: QList 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); }; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index f8b56bb..db78584 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -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(m_pages->widget(pageIndex))) - rpcPage->setDeviceId(deviceId); - if (auto *headPage = qobject_cast(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) { diff --git a/src/mainwindow.h b/src/mainwindow.h index 86fc0cb..d0b7cd5 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -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; diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index cb7a43c..2cf1e57 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -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); diff --git a/src/motordebugwidget.cpp b/src/motordebugwidget.cpp index 920f21b..b509fdb 100644 --- a/src/motordebugwidget.cpp +++ b/src/motordebugwidget.cpp @@ -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;icount();++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);} diff --git a/src/robotclient.cpp b/src/robotclient.cpp index fded31b..73ba878 100644 --- a/src/robotclient.cpp +++ b/src/robotclient.cpp @@ -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 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> &cancel) - : m_thread([this, &context, cancel]() { - std::unique_lock 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 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> &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(statusPort); - connection.controlPort = static_cast(controlPort); - connection.configPort = static_cast(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 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 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(file.size_bytes())); - item.insert(QStringLiteral("modifiedUnixMs"), QVariant::fromValue(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;icall("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 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(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(underscorecall("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(underscoresample(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(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(frame.source_sequence())}, {QStringLiteral("sourceFrameNumber"), static_cast(frame.source_frame_number())}, {QStringLiteral("sourceTimestamp"), static_cast(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::max()/1000000000-1 - ||stamp.nanos()<0||stamp.nanos()>=1000000000||receivedNs1500000000) { - 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<(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 audioStreamStatistics; std::function audioFrameReceived; - std::function configurationConnectionChanged; - std::function - configurationFilesReceived; - std::function configurationFileReceived; - std::function - configurationValidationFinished; - std::function - configurationSaveFinished; std::function commandFinished; std::function torqueFinished; std::function @@ -4071,24 +3704,8 @@ public: std::function logMessage; private: + std::shared_ptr 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 prepareArmMotionSession(const QString &command) { std::shared_ptr 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((now % 1000) * 1000000)); - header->set_command_id( - QUuid::createUuid().toString(QUuid::WithoutBraces).toStdString()); - header->set_valid_for_ms(static_cast(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(frame.capture_utc_ns())}, {QStringLiteral("sourceSequence"), static_cast(frame.source_sequence())}, @@ -5487,7 +5102,6 @@ private: } std::shared_ptr m_channel; - std::shared_ptr m_configChannel; std::unique_ptr m_arm; std::unique_ptr m_camera; std::unique_ptr m_dexHand; @@ -5495,7 +5109,6 @@ private: std::unique_ptr m_agv; std::unique_ptr m_microphone; std::unique_ptr m_generic; - std::unique_ptr m_configuration; bool m_jointTelemetryOnly = false; QHash m_legacyArmDiscovery; QHash> 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 m_armMotionSession; @@ -5563,8 +5175,8 @@ private: QVector m_demoTargets; }; -RobotClient::RobotClient(QObject *parent) - : QObject(parent), m_worker(new BackendWorker) +RobotClient::RobotClient(QObject *parent,std::shared_ptr simulator) + : QObject(parent), m_simulator(simulator?std::move(simulator):std::shared_ptr(&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); -} diff --git a/src/robotclient.h b/src/robotclient.h index 2873a15..cc181fa 100644 --- a/src/robotclient.h +++ b/src/robotclient.h @@ -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 simulator={}); + std::shared_ptr 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> m_agvMapDirectCancel; @@ -361,6 +334,7 @@ private: QString m_agvMapDirectRequestDevice; QString m_agvMapDirectRequestMap; QThread m_thread; + std::shared_ptr m_simulator; BackendWorker *m_worker = nullptr; std::atomic m_agvMapStreamGeneration{0}; QMutex m_videoFrameMutex; diff --git a/src/rpcservicewidget.cpp b/src/rpcservicewidget.cpp index df1812d..4a832ca 100644 --- a/src/rpcservicewidget.cpp +++ b/src/rpcservicewidget.cpp @@ -4,6 +4,7 @@ #include "ui_rpcservicewidget.h" #include +#include #include #include #include @@ -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); diff --git a/src/rpcservicewidget.h b/src/rpcservicewidget.h index 7139914..73fa4d2 100644 --- a/src/rpcservicewidget.h +++ b/src/rpcservicewidget.h @@ -33,4 +33,5 @@ private: RobotClient *m_client = nullptr; QString m_serviceName; QString m_pendingMethod; + bool m_methodAvailable = false; }; diff --git a/src/taskdeviceoptions.cpp b/src/taskdeviceoptions.cpp index b0ea076..a0d85df 100644 --- a/src/taskdeviceoptions.cpp +++ b/src/taskdeviceoptions.cpp @@ -6,8 +6,8 @@ #include #include -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(); }); diff --git a/src/taskdeviceoptions.h b/src/taskdeviceoptions.h index d99dd8a..e1c61dd 100644 --- a/src/taskdeviceoptions.h +++ b/src/taskdeviceoptions.h @@ -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 m_pending; bool m_busy=false; quint64 m_epoch=0; + QString m_robotId; }; diff --git a/src/taskjointeditor.h b/src/taskjointeditor.h index 3a72a8e..d0bb917 100644 --- a/src/taskjointeditor.h +++ b/src/taskjointeditor.h @@ -3,6 +3,11 @@ #include #include #include +#include +#include +#include +#include +#include #include #include #include @@ -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;isetText(QStringLiteral("原目标数量与设备关节数不一致,请按当前关节列表重新填写。")); for(int i=0;isetFlags(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&&isetText(QString::number(qRadiansToDegrees(values[i].toDouble()),'g',12)); - m_table->setCellWidget(i,1,edit);m_edits<setRowHeight(i,44); + rowLayout->addWidget(edit,0,1);m_edits<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 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 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;irowCount();++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 m_layoutChanged; + QLabel* m_hint=nullptr;QTableWidget* m_table=nullptr;QStringList m_names;QList m_edits;QVariantMap m_info;bool m_checkLimits=true; }; diff --git a/src/taskorchestrationwidget.cpp b/src/taskorchestrationwidget.cpp index e7c285b..bf24b1a 100644 --- a/src/taskorchestrationwidget.cpp +++ b/src/taskorchestrationwidget.cpp @@ -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(m_flowView)->componentDropped = createComponent; auto *taskCanvas=static_cast(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 &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(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<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&¶ms.contains("service")&¶ms.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()) { + 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::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::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(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 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 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 &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 &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(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(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 selectedIds;for(auto* graphic:m_flowScene->selectedItems())selectedIds.insert(graphic->data(7010).toString()); m_flowScene->clear(); QHash positions; QHash 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(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 ¢er){QTimer::singleShot(0,this,[this,id,center]{if(m_runSteps.isEmpty()){WorkflowGraph::position(m_graph,id,center);save();}});}; + terminal->moved=[this,id](const QPointF ¢er){QTimer::singleShot(0,this,[this,id,center]{if(m_runSteps.isEmpty()){QHash 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 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(m_flowView)->refreshHistoryButtons(); static_cast(m_flowView)->resetView(); QTimer::singleShot(0,this,[this]{static_cast(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(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 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(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;} diff --git a/src/taskorchestrationwidget.h b/src/taskorchestrationwidget.h index 3e16309..a2ff1a4 100644 --- a/src/taskorchestrationwidget.h +++ b/src/taskorchestrationwidget.h @@ -4,6 +4,7 @@ #include #include #include +#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 &executions,QString &error) const; WorkflowRuntime *m_runtime=nullptr; QHash 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> m_robotDeviceInfo; QVariantList m_availableDevices; QHash m_deviceInfo; QHash m_cameraCapabilities; diff --git a/src/taskprotoeditor.cpp b/src/taskprotoeditor.cpp index 9a3bfb0..4ea770f 100644 --- a/src/taskprotoeditor.cpp +++ b/src/taskprotoeditor.cpp @@ -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())if(auto* joints=dynamic_cast(widget))joints->setLayoutChangedHandler([this]{refreshContentSize();}); m_layout->activate();setFixedHeight(m_layout->sizeHint().height());updateGeometry(); for(auto* group:findChildren())if(group->isCheckable())connect(group,&QGroupBox::toggled,this,[this](bool){for(auto* tabs:findChildren())if(auto* parameterTabs=dynamic_cast(tabs))parameterTabs->fit();m_layout->invalidate();m_layout->activate();setFixedHeight(m_layout->sizeHint().height());updateGeometry();if(m_layoutChanged)m_layoutChanged();}); } diff --git a/src/taskrpcrunner.cpp b/src/taskrpcrunner.cpp index 9ef7d43..09b0862 100644 --- a/src/taskrpcrunner.cpp +++ b/src/taskrpcrunner.cpp @@ -15,13 +15,13 @@ #include #include #include -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::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 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::function1800000){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 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=timeoutm_demoDevice); + const bool expired=timeoutm_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::functionFindFieldByName("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; diff --git a/src/taskrpcrunner.h b/src/taskrpcrunner.h index 05fe859..fb0ea25 100644 --- a/src/taskrpcrunner.h +++ b/src/taskrpcrunner.h @@ -4,7 +4,7 @@ #include #include #include -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 m_demoCompletion; + std::shared_ptr m_simulator; RobotClient* m_client=nullptr; QString m_endpoint;bool m_connected=false,m_demo=false,m_busy=false; QThread* m_thread=nullptr; diff --git a/src/usercoordinatewidget.cpp b/src/usercoordinatewidget.cpp index 7fb0be2..5c46a1e 100644 --- a/src/usercoordinatewidget.cpp +++ b/src/usercoordinatewidget.cpp @@ -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){ diff --git a/src/workflowcanvas.h b/src/workflowcanvas.h index ecb802b..8e16161 100644 --- a/src/workflowcanvas.h +++ b/src/workflowcanvas.h @@ -23,6 +23,17 @@ inline void workflowVectorIcon(QPainter *p,const QRectF &rect,const QString &nam renderers.insert(name,QSharedPointer::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()<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 connectionRemoved; std::function &)> copyNodes; std::function pasteNodes; + std::function undoRequested,redoRequested,nodeDeletionRequested; + std::function 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(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 inputs,outputs;QList 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(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(focus)){if(redo)line->redo();else line->undo();return;} + if(auto *text=qobject_cast(focus)){if(redo)text->redo();else text->undo();return;} + if(auto *text=qobject_cast(focus)){if(redo)text->redo();else text->undo();return;} + if(auto *spin=qobject_cast(focus)) { + if(auto *line=spin->findChild()){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 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)&©Nodes) { QSet 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 m_undoButton,m_redoButton; + QHash 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; diff --git a/src/workflowgraph.h b/src/workflowgraph.h index d3b32c7..d1dfe98 100644 --- a/src/workflowgraph.h +++ b/src/workflowgraph.h @@ -56,6 +56,12 @@ inline void position(QJsonObject &graph,const QString &id,const QPointF ¢er) } graph.insert("nodes",nodes); } +// Move containers first so a selected child is positioned once in scene space. +inline void positions(QJsonObject& graph,const QHash& 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 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) 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); diff --git a/src/workflowhistory.h b/src/workflowhistory.h new file mode 100644 index 0000000..cc9904a --- /dev/null +++ b/src/workflowhistory.h @@ -0,0 +1,34 @@ +#pragma once +#include +#include +#include + +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; + int m_index=-1; + qint64 m_bytes=0; +}; diff --git a/src/workflowrobotmanager.h b/src/workflowrobotmanager.h new file mode 100644 index 0000000..4cfd05e --- /dev/null +++ b/src/workflowrobotmanager.h @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// 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->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();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());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 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<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::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& 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<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 m_target;QString m_path;bool m_closing=false;QHash> m_entries; +}; diff --git a/tests/agvpage_smoke.cpp b/tests/agvpage_smoke.cpp index 4a10bc1..580372a 100644 --- a/tests/agvpage_smoke.cpp +++ b/tests/agvpage_smoke.cpp @@ -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); diff --git a/tests/application_shell_test.cpp b/tests/application_shell_test.cpp index 85877bf..495422e 100644 --- a/tests/application_shell_test.cpp +++ b/tests/application_shell_test.cpp @@ -701,7 +701,7 @@ int main(int argc, char **argv) const auto viewers = window.findChildren(); 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()) { diff --git a/tests/bioheadjointclient_test.cpp b/tests/bioheadjointclient_test.cpp index a8fd9b5..057c654 100644 --- a/tests/bioheadjointclient_test.cpp +++ b/tests/bioheadjointclient_test.cpp @@ -68,7 +68,7 @@ public: ++states; { std::lock_guard guard(mutex); stateDevices.push_back(request->header().device_id()); statePeers.push_back(context->peer()); } - stateValidityMs.store(static_cast(request->header().valid_for_ms())); + stateValidityMs.store(static_cast(0)); stateDeadlineMs.store(static_cast(std::chrono::duration_cast( 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); diff --git a/tests/bioheadlocalexpressions_test.cpp b/tests/bioheadlocalexpressions_test.cpp index adbf0ec..802d8e8 100644 --- a/tests/bioheadlocalexpressions_test.cpp +++ b/tests/bioheadlocalexpressions_test.cpp @@ -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(); diff --git a/tests/bioheadwidget_test.cpp b/tests/bioheadwidget_test.cpp index 71e44c7..0c7ae79 100644 --- a/tests/bioheadwidget_test.cpp +++ b/tests/bioheadwidget_test.cpp @@ -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) { diff --git a/tests/canvas_selection_test.cpp b/tests/canvas_selection_test.cpp new file mode 100644 index 0000000..d8f13f1 --- /dev/null +++ b/tests/canvas_selection_test.cpp @@ -0,0 +1,24 @@ +#include "workflowcanvas.h" +#include "workflowgraph.h" +#include +#include +#include +#include +#include +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: "<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 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: "< +#include "freescaninterop.h" +#include "workflowgraph.h" +#include "jointpointdata.h" +#include +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 +#include +#include +#include +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())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())if(auto* candidate=dynamic_cast(widget)){editor=candidate;break;}check(editor,"inspector editor exists"); + auto* tabs=editor->findChild();check(tabs&&tabs->count()>=2,"motion tabs exist"); + int motion=-1;for(int i=0;icount();++i)if(tabs->tabText(i)==QStringLiteral("运动设置"))motion=i; + check(motion>=0,"motion tab exists");tabs->setCurrentIndex(motion); + auto* table=editor->findChild("taskJointTable");check(table,"joint editor exists"); + auto* angle=editor->findChild("jointTarget_0");check(angle,"joint input exists");angle->setText("12."); + QPointer 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();table=editor->findChild("taskJointTable"); + check(tabs&&tabs->tabText(tabs->currentIndex())==QStringLiteral("运动设置"),"metadata rebuild restores active tab"); + check(editor->findChild("jointTarget_0")->text()=="12.","metadata rebuild preserves unfinished input"); + auto* second=makeNode("second-node",.5);tree->setCurrentItem(second); + table=editor->findChild("taskJointTable"); + check(editor->findChild("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(); + if(currentTabs&¤tTabs->count()>1)currentTabs->setCurrentIndex(currentTabs->count()-1); + const auto edits=editor->findChildren(); + 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: "< +#include +#include +#include +#include +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("taskJointTable");check(table&&table->rowCount()==7,"all joints visible"); + for(int i=0;irowCount();++i){ + auto* row=table->cellWidget(i,0);auto* edit=row->findChild();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="<height()>=edit->minimumSizeHint().height(),"input fits theme minimum height"); + for(auto* label:row->findChildren())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: "< +#include +#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; +} diff --git a/tests/jointflow_canvas_test.cpp b/tests/jointflow_canvas_test.cpp new file mode 100644 index 0000000..2b59640 --- /dev/null +++ b/tests/jointflow_canvas_test.cpp @@ -0,0 +1,67 @@ +#include +#include "jointfloweditor.h" +#include "applicationstyle.h" +#include "workflowcanvas.h" +#include +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(); + 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(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(); + 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; } +} diff --git a/tests/robotclient_agvmanualvelocity_test.cpp b/tests/robotclient_agvmanualvelocity_test.cpp index e4f5324..aea1429 100644 --- a/tests/robotclient_agvmanualvelocity_test.cpp +++ b/tests/robotclient_agvmanualvelocity_test.cpp @@ -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); diff --git a/tests/robotclient_seer_map_integration_test.cpp b/tests/robotclient_seer_map_integration_test.cpp index 6a84527..d8c0760 100644 --- a/tests/robotclient_seer_map_integration_test.cpp +++ b/tests/robotclient_seer_map_integration_test.cpp @@ -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 @@ -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 lists{0}; - std::atomic 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 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 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; } diff --git a/tests/run_taskapi_test.py b/tests/run_taskapi_test.py index db58017..08c8409 100644 --- a/tests/run_taskapi_test.py +++ b/tests/run_taskapi_test.py @@ -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)) diff --git a/tests/seeragvmapclient_fake.h b/tests/seeragvmapclient_fake.h index 501a1ca..53a7a6a 100644 --- a/tests/seeragvmapclient_fake.h +++ b/tests/seeragvmapclient_fake.h @@ -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 m_stop{false}; std::atomic m_failed{false}; + quint16 m_listenPort = 0; std::atomic 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(); diff --git a/tests/startup_test.cpp b/tests/startup_test.cpp new file mode 100644 index 0000000..b9c3ff5 --- /dev/null +++ b/tests/startup_test.cpp @@ -0,0 +1,34 @@ +#include "mainwindow.h" +#include "robotclient.h" +#include "applicationstyle.h" +#include +#include +#include +#include +#include +#include +#include +#include +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())client->disconnectFromServer(); + auto* pages=window.findChild("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 "<("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; +} diff --git a/tests/task_device_ui_test.cpp b/tests/task_device_ui_test.cpp index 92807d8..4b4f88e 100644 --- a/tests/task_device_ui_test.cpp +++ b/tests/task_device_ui_test.cpp @@ -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;} } diff --git a/tests/taskapi_test.cpp b/tests/taskapi_test.cpp index 69aa64a..56d6b52 100644 --- a/tests/taskapi_test.cpp +++ b/tests/taskapi_test.cpp @@ -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>{{"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: "<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: "< +#include +#include +#include +#include +#include +#include +static void check(bool ok,const char* reason){if(!ok)throw std::runtime_error(reason);} +static void waitFor(std::function predicate,const char* reason,int limit=6000){QElapsedTimer t;t.start();while(!predicate()&&t.elapsed()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 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;iadd_joint_names("joint_"+std::to_string(i));return grpc::Status::OK;} +}; +struct FakeRobot{ + FakeSystem system;FakeArm arm;int port=0;std::unique_ptr 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(¤t); + const QString path=files.filePath("robots.json");QString a,b; + { + WorkflowRobotManager manager(¤t,¤tRunner,&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())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("workflowNodeRobot");auto* deviceChoice=target.findChild("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())if(auto* e=dynamic_cast(w)){if(auto* t=e->findChild("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())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())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("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=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(¤t,¤tRunner,&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: "< +#include +#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(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())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; +} diff --git a/ui/mainwindow.ui b/ui/mainwindow.ui index 280aad7..7a5527a 100644 --- a/ui/mainwindow.ui +++ b/ui/mainwindow.ui @@ -84,7 +84,6 @@ HLC 控制true1818navButton 接口调试true1818navButton QUIC Servertrue1818navButton - 项目配置true1818navButton 运行日志true1818navButton Qt::Vertical2040 服务端连接sidebarLabel