feat: export executable task flows and simulate devices with Release runtime fixes

This commit is contained in:
linbo 2026-11-18 09:22:04 +08:00
parent ee733021ad
commit 10285f8cea
52 changed files with 34332 additions and 222 deletions

View File

@ -179,6 +179,15 @@ set(CMVR_SOURCES
src/mainwindow_ui.cpp
src/mainwindow.h
src/taskorchestrationwidget.cpp
src/taskapi.cpp
src/taskjointeditor.h
src/taskuilabels.h
src/taskprotoeditor.cpp
src/demosimulator.cpp
src/demosimulator.h
src/taskdeviceoptions.cpp
src/taskdeviceoptions.h
src/taskrpcrunner.cpp
src/taskorchestrationwidget.h
src/quictestserver.cpp
src/quictestserver.h
@ -195,6 +204,8 @@ set(CMVR_SOURCES
src/urdfviewerwidget.h
src/videodecoder.cpp
src/videodecoder.h
src/camerasnapshotdecoder.h
src/snapshotimageview.h
src/videoframe.h
src/videorenderwidget.cpp
src/videorenderwidget.h
@ -234,6 +245,9 @@ list(APPEND CMVR_SOURCES
src/tcptoolstore.cpp src/tcptoolstore.h
src/tcpcalibrationwidget.cpp src/tcpcalibrationwidget.h)
add_executable(CmvrControlStation ${CMVR_SOURCES})
if(MINGW)
target_compile_options(CmvrControlStation PRIVATE -Wa,-mbig-obj)
endif()
if(WIN32)
target_sources(CmvrControlStation PRIVATE resources/application.rc)
set_target_properties(CmvrControlStation PROPERTIES WIN32_EXECUTABLE TRUE)
@ -438,3 +452,11 @@ install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/models/"
DESTINATION bin/models)
install(PROGRAMS "${CMVR_ASSIMP_SCENE_PARSER}"
DESTINATION bin/sceneparsers)
if(WIN32 AND MINGW)
add_custom_command(TARGET CmvrControlStation POST_BUILD
COMMAND powershell.exe -NoProfile -ExecutionPolicy RemoteSigned
-File "${CMAKE_CURRENT_SOURCE_DIR}/scripts/repair_qt3d_release.ps1"
-RuntimeDirectory "$<TARGET_FILE_DIR:CmvrControlStation>" -IfPresent
VERBATIM)
endif()

View File

@ -1,6 +1,7 @@
QT += core gui widgets network multimedia 3dcore 3drender 3dextras 3dinput 3danimation
CONFIG += c++17 warn_on debug_and_release
win32-g++: QMAKE_CXXFLAGS += -Wa,-mbig-obj
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS _WIN32_WINNT=0x0600
@ -316,6 +317,8 @@ HEADERS += \
src/uiicons.h \
src/urdfviewerwidget.h \
src/videodecoder.h \
src/camerasnapshotdecoder.h \
src/snapshotimageview.h \
src/videoframe.h \
src/videorenderwidget.h \
ui/handeyecalibrationwidget.h
@ -392,3 +395,24 @@ HEADERS += src/usercoordinatewidget.h src/usercoordinatestore.h
SOURCES += src/actionqueuetestwidget.cpp
HEADERS += src/actionqueuetestwidget.h
SOURCES += src/taskapi.cpp src/taskprotoeditor.cpp src/taskrpcrunner.cpp
HEADERS += src/taskapi.h src/taskprotoeditor.h src/taskrpcrunner.h
HEADERS += src/taskjointeditor.h src/taskuilabels.h
SOURCES += src/taskdeviceoptions.cpp
HEADERS += src/taskdeviceoptions.h
SOURCES += src/demosimulator.cpp
HEADERS += src/demosimulator.h
# Release diagnostics retain optimization and source line information.
QMAKE_CXXFLAGS_RELEASE += -g1
QMAKE_LFLAGS_RELEASE -= -Wl,-s
win32: QMAKE_LFLAGS_RELEASE += -Wl,-Map,bin/release/CmvrControlStation.map
win32:CONFIG(release, debug|release) {
QMAKE_POST_LINK += $$escape_expand(\n\t) powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File $$shell_quote($$shell_path($$PWD/scripts/repair_qt3d_release.ps1)) -RuntimeDirectory $$shell_quote($$shell_path($$DESTDIR)) -IfPresent
}
DISTFILES += scripts/repair_qt3d_release.ps1

View File

@ -111,6 +111,14 @@ CMake 是 Windows 和 Linux 的统一构建入口。`CmvrControlStation.pro` 继
## Linux 编译
麒麟 Linux x86 可先使用一键安装脚本(采用当前系统已配置的软件源):
```bash
bash scripts/setup_kylin.sh --source "$PWD"
```
仅安装 Qt 与依赖时去掉 `--source "$PWD"`;仅检查时使用 `--check`。如需 Qt Creator,追加 `--with-qtcreator`。脚本支持 APT、DNF/YUM,安装后会验证 Qt5、CMake、gRPC/Protobuf、音视频、模型插件及共享库;缺少必需包会明确失败。它不添加外部仓库,不启动上位机或控制设备。详见 [麒麟脚本使用说明](scripts/setup_kylin_使用说明.txt)。
### 1. 安装依赖
Debian/Ubuntu 示例:

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,118 @@
{
"executionPolicy": {
"automaticRetry": false,
"onError": "stop",
"order": "sequential",
"stopBehavior": "stop_scheduling_and_cancel_active_unary",
"waitStartsAfter": "operation_success"
},
"format": "cmvr.task-flow",
"groups": [
{
"id": "example-group",
"name": "offline example",
"nodes": [
{
"action": "接口 · ApplyUserCoordinateSystem",
"deviceId": "aubo_arm",
"deviceType": "机械臂",
"execution": {
"completion": "rpc_response",
"kind": "grpc_unary",
"method": "ApplyUserCoordinateSystem",
"request": {
"expected_revision": "0",
"header": {
"device_id": "aubo_arm"
},
"name": "测试坐标系"
},
"service": "cmvr.api.ArmService",
"timeoutMs": 180000
},
"id": "example-apply",
"kind": "task",
"name": "接口 · ApplyUserCoordinateSystem",
"operationId": "cmvr.api.ArmService.ApplyUserCoordinateSystem",
"parameters": {
"method": "ApplyUserCoordinateSystem",
"request": {
"expected_revision": "0",
"name": "测试坐标系"
},
"service": "cmvr.api.ArmService",
"timeoutMs": 180000
},
"waitMs": 3000,
"waitUnit": "s"
},
{
"children": [
{
"action": "接口 · moveJPose",
"deviceId": "aubo_arm",
"deviceType": "机械臂",
"execution": {
"completion": "rpc_response",
"kind": "grpc_unary",
"method": "moveJPose",
"request": {
"header": {
"device_id": "aubo_arm"
},
"options": {
"acceleration": 0.5,
"velocity": 0.1
},
"target": {
"rx": 0,
"ry": 0,
"rz": 0,
"x": 0.1,
"y": 0.2,
"z": 0.3
},
"user_coordinate_name": "测试坐标系",
"user_coordinate_revision": "0"
},
"service": "cmvr.api.ArmService",
"timeoutMs": 180000
},
"id": "example-movej-pose",
"kind": "task",
"name": "接口 · moveJPose",
"operationId": "cmvr.api.ArmService.moveJPose",
"parameters": {
"method": "moveJPose",
"request": {
"options": {
"acceleration": 0.5,
"velocity": 0.1
},
"target": {
"rx": 0,
"ry": 0,
"rz": 0,
"x": 0.1,
"y": 0.2,
"z": 0.3
},
"user_coordinate_name": "测试坐标系",
"user_coordinate_revision": "0"
},
"service": "cmvr.api.ArmService",
"timeoutMs": 180000
},
"waitMs": 3000,
"waitUnit": "s"
}
],
"count": 2,
"id": "example-loop",
"kind": "loop",
"name": "repeat"
}
]
}
]
}

View File

@ -0,0 +1,140 @@
// Transport-independent reference. No connection or device command is made on import.
export const executionPolicy = Object.freeze({order:'sequential',onError:'stop',automaticRetry:false,
waitStartsAfter:'operation_success',stopBehavior:'stop_scheduling_and_cancel_active_unary'});
const equal=(a,b)=>canonical(a)===canonical(b);
function canonical(v){return JSON.stringify(Array.isArray(v)?v.map(sort):sort(v));}
function sort(v){if(Array.isArray(v))return v.map(sort);if(v&&typeof v==='object')return Object.fromEntries(Object.keys(v).sort().map(k=>[k,sort(v[k])]));return v;}
const object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
function check(ok,message){if(!ok)throw new Error(message);}
function integer(v,min,max){return Number.isInteger(v)&&v>=min&&v<=max;}
export function validateMessage(value,type,catalog,depth=0){
check(depth<=32,'Message nesting exceeds 32');
if(type==='google.protobuf.Timestamp'){check(typeof value==='string'&&!Number.isNaN(Date.parse(value)),'Invalid Timestamp');return;}
if(type==='google.protobuf.Duration'){check(typeof value==='string'&&/^-?\d+(\.\d{1,9})?s$/.test(value),'Invalid Duration');return;}
check(object(value),`Expected message ${type}`);const message=catalog.messages[type];check(message,`Unknown message ${type}`);
const seen=new Set(),oneofs=new Set();
function scalar(v,f){
if(f.messageType){validateMessage(v,f.messageType,catalog,depth+1);return;}
if(f.enumType){check((catalog.enums[f.enumType]||[]).some(e=>e.name===v||e.number===v),`Invalid enum ${f.name}`);return;}
if(f.type==='string'){check(typeof v==='string',`Invalid string ${f.name}`);return;}
if(f.type==='bytes'){check(typeof v==='string'&&/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(v),`Invalid Base64 ${f.name}`);return;}
if(f.type==='bool'){check(typeof v==='boolean',`Invalid boolean ${f.name}`);return;}
if(['int64','sint64','sfixed64','uint64','fixed64'].includes(f.type)){
check(typeof v==='string'&&/^-?\d+$/.test(v),`Use a decimal string for ${f.name}`);
const number=BigInt(v),unsigned=f.type==='uint64'||f.type==='fixed64';
check(number>=(unsigned?0n:-(1n<<63n))&&number<=(unsigned?(1n<<64n)-1n:(1n<<63n)-1n),`64-bit overflow ${f.name}`);return;
}
check(typeof v==='number'&&Number.isFinite(v),`Invalid number ${f.name}`);
if(!['float','double'].includes(f.type)){const unsigned=f.type==='uint32'||f.type==='fixed32';check(integer(v,unsigned?0:-2147483648,unsigned?4294967295:2147483647),`32-bit overflow ${f.name}`);}
}
for(const [key,v] of Object.entries(value)){
const f=message.fields.find(f=>f.name===key||f.jsonName===key);check(f,`Unknown field ${type}.${key}`);
check(!seen.has(f.name),`Duplicate field alias ${key}`);seen.add(f.name);
if(f.oneof){check(!oneofs.has(f.oneof),`Mutually exclusive fields in ${f.oneof}`);oneofs.add(f.oneof);}
if(f.map){
check(object(v),`Map must be an object: ${key}`);const fields=catalog.messages[f.messageType].fields,keyField=fields.find(f=>f.name==='key'),entry=fields.find(f=>f.name==='value');
for(const [k,item] of Object.entries(v)){
const mapKey=keyField.type==='bool'?(k==='true'?true:k==='false'?false:k):keyField.type==='string'||keyField.type.includes('64')?k:Number(k);
scalar(mapKey,keyField);scalar(item,entry);
}
}else if(f.repeated){check(Array.isArray(v),`List required ${key}`);for(const item of v)scalar(item,f);}
else scalar(v,f);
}
}
// Validate the entire plan before executing the first node. Returned order is authoritative.
export function flatten(document,catalog,groupId){
check(document.format==='cmvr.task-flow'&&!Object.hasOwn(document,'version'),'Expected cmvr.task-flow without version; normalize legacy files using Qt');
check(equal(document.executionPolicy,executionPolicy),'Unsupported execution policy');
check(Array.isArray(document.groups),'groups must be an array');const ids=new Set(),result=new Map();
const methods=new Map(catalog.services.flatMap(s=>s.methods.map(m=>[m.id,{...m,deviceType:s.deviceType}])));
const adapters=new Map(catalog.clientAdapters.map(a=>[a.id,a]));
const identify=n=>{check(typeof n.id==='string'&&n.id&&!ids.has(n.id),'Missing or duplicate id');ids.add(n.id);};
function visit(nodes,depth){
check(depth<=32&&Array.isArray(nodes),'Invalid children or excessive nesting');const steps=[];
for(const node of nodes){
check(object(node),'Node must be an object');identify(node);
if(node.kind==='loop'){
check(integer(node.count,1,100000)&&Array.isArray(node.children)&&node.children.length>0,'Invalid repeat count or empty loop');const children=visit(node.children,depth+1);
check(steps.length+children.length*node.count<=100000,'Expanded plan exceeds 100000 steps');
for(let iteration=0;iteration<node.count;iteration++)for(const entry of children)steps.push({node:entry.node,iterationPath:[{loopId:node.id,iteration},...entry.iterationPath]});
}else{
check(node.kind==='task'&&typeof node.deviceId==='string'&&node.deviceId,'Invalid task or deviceId');
check(integer(node.waitMs,0,2147483647)&&['ms','s'].includes(node.waitUnit),'Invalid post-completion delay');
const ex=node.execution,p=node.parameters;check(object(ex)&&object(p),'Missing execution or parameters');
if(ex.kind==='grpc_unary'){
const m=methods.get(node.operationId);check(m&&!m.clientStreaming&&!m.serverStreaming,'Unknown or streaming operation');
check(m.service===ex.service&&m.method===ex.method&&p.service===m.service&&p.method===m.method,'Conflicting RPC identity');
check(node.deviceType==='通用RPC'||(node.deviceType===m.deviceType&&node.action===`接口 · ${m.method}`),'Conflicting display action/device type');
check(integer(ex.timeoutMs,100,1800000)&&ex.timeoutMs===(p.timeoutMs??180000),'Invalid RPC timeout');
const expected=structuredClone(p.request||{}),fields=catalog.messages[m.requestType].fields;
if(fields.some(f=>f.name==='header')){expected.header={...expected.header,device_id:node.deviceId};delete expected.header.deviceId;}
else if(fields.some(f=>f.name==='device_id')){delete expected.deviceId;expected.device_id=node.deviceId;}
check(ex.completion==='rpc_response'&&equal(expected,ex.request),'Conflicting RPC payload');validateMessage(ex.request,m.requestType,catalog);
}else{
const a=adapters.get(node.operationId);check(ex.kind==='client_adapter'&&a&&ex.adapter===a.id,'Unknown client adapter');
check(a.deviceType===node.deviceType&&a.action===node.action&&ex.deviceId===node.deviceId&&equal(p,ex.parameters)&&ex.completion==='adapter_callback','Conflicting adapter payload');
}
steps.push({node,iterationPath:[]});check(steps.length<=100000,'Expanded plan exceeds 100000 steps');
}
}return steps;
}
for(const group of document.groups){identify(group);result.set(group.id,visit(group.nodes,0));}
check(result.has(groupId),'Group not found');check(result.get(groupId).length>0,'No executable tasks');return result.get(groupId);
}
function succeeded(response){
const header=response?.header??response;
check(header?.success===true,header?.error_message||header?.errorMessage||'Missing/false business success');
return response;
}
function delay(ms,signal){return new Promise((resolve,reject)=>{
if(signal?.aborted){reject(new Error('Canceled'));return;}
const abort=()=>{clearTimeout(timer);reject(new Error('Canceled'));};
const timer=setTimeout(()=>{signal?.removeEventListener('abort',abort);resolve();},ms);
signal?.addEventListener('abort',abort,{once:true});
});}
// Inject transport/adapters. The reference has no built-in gRPC-Web connection.
// rpc(service,method,request,{signal,timeoutMs}) => Promise<decoded Protobuf-JSON response>
// adapters[id](parameters,{deviceId,signal}) => Promise<{success:true,...}>
export async function execute(document,catalog,groupId,{rpc,adapters={},signal,onEvent=()=>{}}){
const steps=flatten(document,catalog,groupId);
for(const {node} of steps)if(node.execution.kind==='client_adapter')check(typeof adapters[node.execution.adapter]==='function',`Missing adapter ${node.execution.adapter}`);
for(let index=0;index<steps.length;index++){
const {node,iterationPath}=steps[index],context={nodeId:node.id,index,iterationPath};let timer,detach=()=>{};
try{
check(!signal?.aborted,'Canceled');onEvent({...context,state:'running'});const ex=node.execution;let response;
if(ex.kind==='grpc_unary'){
check(typeof rpc==='function','RPC transport required');const controller=new AbortController();
const canceled=()=>controller.abort();signal?.addEventListener('abort',canceled,{once:true});detach=()=>signal?.removeEventListener('abort',canceled);
const request=structuredClone(ex.request),m=catalog.services.flatMap(s=>s.methods).find(m=>m.id===node.operationId);
const nested=catalog.messages[m.requestType].fields.some(f=>f.name==='header');const h=nested?(request.header??={}):request;
delete h.commandId;h.command_id=globalThis.crypto.randomUUID();h.timestamp=new Date().toISOString();
const interrupted=new Promise((_,reject)=>controller.signal.addEventListener('abort',()=>reject(new Error('Canceled or deadline exceeded; physical stop not confirmed')),{once:true}));
timer=setTimeout(()=>controller.abort(),ex.timeoutMs);
if(ex.service==='cmvr.api.ArmService'&&ex.method==='moveL'&&
(request.user_coordinate_name||request.userCoordinateName||'user_frame_pose' in request||'userFramePose' in request||'tcp_offset' in request||'tcpOffset' in request)){
let probeTimer;
try{
const probe=await Promise.race([rpc(ex.service,'ExecuteJsonCommand',{header:{device_id:node.deviceId},request_json:'{"command":"get_active_tcp_offset"}'},{signal:controller.signal,timeoutMs:3000}),interrupted,
new Promise((_,reject)=>{probeTimer=setTimeout(()=>reject(new Error('Coordinate capability probe timed out; no motion sent')),3000);})]);
succeeded(probe);const capability=JSON.parse(probe.response_json??probe.responseJson??'{}');
check(capability.coordinate_api_version>=4&&capability.movel_target_mode==='absolute_selected_frame','Absolute selected-frame MoveL unsupported; no motion sent');
}finally{clearTimeout(probeTimer);}
}
response=await Promise.race([Promise.resolve().then(()=>rpc(ex.service,ex.method,request,{signal:controller.signal,timeoutMs:ex.timeoutMs})),interrupted]);
}else {
const interrupted=new Promise((_,reject)=>{
const abort=()=>reject(new Error('Canceled; adapter/device stop not confirmed'));
signal?.addEventListener('abort',abort,{once:true});detach=()=>signal?.removeEventListener('abort',abort);
});
response=await Promise.race([Promise.resolve().then(()=>adapters[ex.adapter](structuredClone(ex.parameters),{deviceId:node.deviceId,signal})),interrupted]);
}
clearTimeout(timer);detach();succeeded(response);check(!signal?.aborted,'Canceled');
onEvent({...context,state:'succeeded',response});
if(node.waitMs){onEvent({...context,state:'waiting',waitMs:node.waitMs});await delay(node.waitMs,signal);}
}catch(error){clearTimeout(timer);detach();onEvent({...context,state:signal?.aborted?'canceled':'failed',error:String(error)});throw error;}
}
onEvent({state:'completed',completedSteps:steps.length});return {success:true,completedSteps:steps.length};
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,158 @@
CMVR 任务编排 JSON —— 外部解析与执行协议
2026-11-10
一、交付范围
本包定义一份可由Qt上位机和外部程序共同理解的任务文件。它不是网页项目,不包含云端同步服务或gRPC-Web网关。外部可导入同一文件,绘制节点、生成参数表单、按本协议实现执行器。
当前界面入口:任务编排 -> 添加任务 -> 选择已连接设备 -> 选择操作。
保留原有友好操作,额外提供“接口 · 方法名”。本次构建按Proto覆盖8类设备服务的120个Unary接口,完整清单见task_operations.json。
原有接口是否真正支持某型号、是否需要上电/使能及相关参数限制,以服务端驱动和反馈为准。目录列出接口不代表每台设备都支持全部功能,不自动启用设备,也不自动使能。
文件说明:
- example.task.json:Qt核心格式代码生成的完整示例,含坐标系应用和循环内末端位姿MoveJ。目标只是示例值,不能作为现场运动目标。
- task-flow.schema.json:JSON Schema Draft 2020-12;涵盖节点、执行字段及120个Unary接口的请求消息类型。
- task_operations.json:操作目录、请求/反馈消息、枚举及38个客户端适配节点的参数规则与实现说明。
- verify-example.mjs:用Node运行的离线自检:node verify-example.mjs;仅模拟传输,不连接设备。
- task-flow.mjs:无连接代码的JavaScript参考解析/执行器,运行时由外部注入rpc和媒体等适配函数。
- protos/:原始Proto及递归依赖,字段含义和单位以对应注释为准。相同数值字段在不同接口中可能单位不同。
- rpc_catalog.txt:按设备划分的清单,区分Unary/流式。
二、上位机现已实现的行为
新增的Unary操作使用按Proto生成的参数表单:支持数字、字符串、Base64二进制、布尔、枚举、嵌套消息、列表、Map和oneof互斥字段。
部分接口共用同一Request类型,editorFields标明当前方法实际使用的输入字段。电机设置模式、六种运动模式及限位设置分别只显示对应字段;Apply/Get/Delete坐标系不显示无关的完整coordinate记录。外部可使用editorFields渲染相同表单,完整消息字段仍在messages中保留。
消息参数通过复选框控制是否发送;列表逐项增删;oneof只能选一个分支;可选标量可控制是否发送。64位整数按十进制字符串保存,避免JS精度损失。表单最多展开12层参数嵌套。
通用请求头由上位机填写:device_id来自节点设备,command_id为每次调用的新UUID,timestamp为当前UTC时间;不用用户重复输入。
新增接口在未连接或演示模式下不会发送。新增接口在独立线程执行,每节点可设置100~1800000ms的RPC超时,默认180000ms,不阻塞界面线程。
反馈检查传输状态和业务success;失败终止后续节点,不自动重试。执行历史可双击查看/复制反馈。历史保留最近200条,单条详细反馈超过1MiB会明确截断;原始图像展示应使用专用抓图/预览节点。
同时修正了旧AGV停止/暂停/继续的命令映射;导航站点通过独立RPC线程等待结果。任务中的AGV新调用复用手动控制与地图操作的检查,并等待已排队控制命令结束,避免先前的停止速度命令晚于导航请求到达。外部若也有手动控制通道,应实现同样的协调。
原有方案、循环、拖动排序、节点间插入、执行后等待、图像结果窗口和音频播放等保留。录制、媒体流启动与停止依然由专用状态回调推进。
相机专用深度抓图以及新增GetDepthImage/GetRGBDImages操作会按已获取的深度能力过滤;未获取能力时按不支持处理。外部客户端应同样检查能力,并处理服务端“不支持”反馈。
三、根对象
format 固定为 cmvr.task-flow;任务文件不包含 version。Qt 兼容读取旧版 version=1/2 文件,规范化后移除 version。
groups 是方案数组。每个方案包含:id(稳定标识)、name(显示名)、nodes(根节点有序数组)。
executionPolicy 固定为:
order: sequential
onError: stop
automaticRetry: false
waitStartsAfter: operation_success
stopBehavior: stop_scheduling_and_cancel_active_unary
未知版本和不支持的策略必须拒绝,不能猜测后执行。
文件不保存服务器IP、凭据、robot_id和真实运行状态。外部必须单独绑定目标机器人/连接,确认deviceId属于该连接;不能仅凭同名deviceId跨机器人发送指令。
同一任务文件中的方案和节点id必须唯一。绘图和运行日志用id关联,不能用中文名称作为主键。
四、节点与顺序
kind=task:普通任务;kind=loop:循环。
普通节点包含 id、name、deviceType、deviceId、action、operationId、parameters、execution、waitMs、waitUnit。
deviceType/action保留上位机显示和兼容用途;operationId为稳定、机器可读的操作标识,不能只根据中文标题猜接口。
相邻节点的执行顺序由所在nodes/children数组顺序决定;无需另存edges。上一个完整子树执行完成后再执行下一个同级节点。
循环包含count与children:将整个children序列按count次数重复,允许嵌套。collapsed只是显示状态,折叠不跳过执行。
最多32层嵌套、每方案展开最多100000个任务。count为1~100000整数。空循环可作为编辑草稿保存,但执行时必须拒绝;空方案不可执行。
节点id在循环每次迭代中不改变。日志需要另外记录迭代路径和执行序号,例:[{loopId:"example-loop",iteration:0}],iteration从0开始。
waitMs为实际等待毫秒数,0~2147483647整数。waitUnit只影响显示,可为ms或s;例如waitMs=3000且waitUnit=s显示3s。执行器绝不能再把3000乘1000。
等待从本节点成功条件成立后开始;等待结束才进入下一任务。不能把“完成后等待”当作接口超时或动画时长。
五、直接gRPC节点(新增接口)
operationId示例:cmvr.api.ArmService.moveJPose。
action为“接口 · moveJPose”,deviceType对应目录服务的设备类型。
parameters包含service、method、request、timeoutMs。request为Proto-JSON;允许Proto原字段名或jsonName别名,但不能重复提供同一字段的两种写法。
execution包含:
kind: grpc_unary
service: 完整服务名,如cmvr.api.ArmService
method: 原方法名,大小写敏感
request: 根据parameters.request生成并绑定节点deviceId的请求
timeoutMs: RPC截止时间,默认180000ms
completion: rpc_response
对普通Request消息,目标设备写入request.header.device_id;对直接使用CommandHeader.Request的接口(如torqueOn),目标设备写在request.device_id,不能再包一层header。
request中的device_id以节点deviceId为准。发送前每次重新生成command_id和timestamp,不能将之前已执行的command_id作为自动重试标识。
parameters与execution是同一意图的编辑视图和执行视图。修改request时必须同步重建execution;action/operationId、service/method和request若互相矛盾,必须拒绝,不允许任选其一执行。
上位机导入会校验Proto字段、类型、互斥关系、有限数值和上述一致性;不能用NaN或Infinity,也不接受未知字段。
JSON Schema做结构验证,跨字段一致性、id全局唯一、循环展开数量以及64位范围等仍需语义校验;task-flow.mjs提供此部分参考。
消息字段规则:
- int32/uint32等为JSON整数,遵守32位范围;int64/uint64等用十进制字符串并校验64位范围。
- double/float为有限JSON数字;bool是true/false;string为字符串;bytes是Base64。
- enum使用目录中的枚举名称或已知整数值。
- repeated为数组,Map为JSON对象。
- 嵌套消息为对象。缺省消息字段可以不发送;不要把缺省和全部字段填0混为一谈。
- google.protobuf.Timestamp使用RFC3339 UTC时间字符串。
六、机械臂坐标系和运动示例的准确含义
先添加“接口 · ApplyUserCoordinateSystem”:填已保存name、expected_revision,不能把完整coordinate当应用请求;应用不运动。
再添加“接口 · moveL”或“接口 · moveJPose”,目标均为所选坐标系下的完整绝对TCP位姿,XYZ为m,RX/RY/RZ为rad,约定RzRyRx,不是增量。
MoveL:速度m/s,加速度m/s²;先应用坐标系,user_coordinate_name/revision校验对应当前应用,不混用base_frame/tcp_frame、显式坐标位姿或增量模式。
末端位姿MoveJ:速度rad/s,加速度rad/s²,name必填,blend_radius=0;服务端坐标变换、SDK逆解后调用moveJoint,路径不保证直线。逆解失败不运动。
user_coordinate_revision、expected_revision可填字符串"0"表示使用最新记录,但当前已应用版本也必须匹配。需要防止中途记录变更时,应填写查到的具体版本。
普通关节角MoveJ传target.position,不受工件坐标系改变影响。
新接口路径的自定义坐标系MoveL在运动前调用ArmService.ExecuteJsonCommand做能力确认,请求request_json为 {"command":"get_active_tcp_offset"};响应response_json解析后要求coordinate_api_version>=4且movel_target_mode=absolute_selected_frame。否则拒绝运动,不能依赖旧服务端忽略未知字段后的行为。task-flow.mjs也演示此检查。
Qt任务编排依次调用各个接口,不会将这些节点自动转换成SystemService.ExecuteActionQueue请求;“动作队列测试”仍是另一个页面和另一条服务端执行路径。
当前205服务端运动完成等待上限是120秒。任务节点的RPC超时调大不会延长这个驱动内部上限。
七、旧友好节点/媒体节点
旧节点operationId以client.开头,例如client.camera.preview_start、client.arm.move_j。
execution.kind=client_adapter,包含adapter、deviceId、parameters,completion=adapter_callback。
不能把adapter名字当RPC方法名调用。完整参数schema、所用RPC及成功含义在task_operations.json的clientAdapters中。
其中部分只是已有Unary接口的友好包装;图像预览、声音采集和播放需要客户端会话、编解码及结果展示逻辑。
预览/音频流启动节点确认流建立后就完成该节点,后续waitMs开始计时;流继续存在,直到专门的停止节点或显式关闭。不会一直等到整段流结束才执行下一节点。
相机预览需GetStatus查询编码器再建RGB视频流。开始录像/录音不意味着录制已经结束。播放服务端文件的path是服务端路径,不是自动上传本地文件。
本机麦克风流播放需先建立扬声器流,再采集本机PCM音频发送;浏览器端必须申请麦克风权限并提供对应媒体适配,Qt设备名不能直接当浏览器设备ID使用。
成功回调格式为{success:true,...};失败应reject或返回success:false。适配器必须保证反馈对应当前节点和设备,而不是复用别的会话事件。
目录还列出8个原始流式RPC。当前专用节点覆盖RGB预览、麦克风和扬声器流;深度/RGBD视频流、AGV地图流、灵巧手传感器流、仿生头表情流目前未作为新通用节点直接开放。它们不应被当作一次性Unary调用,也不能承诺都已适配。
八、成功、失败、取消和结果
直接RPC节点:传输成功且反馈header.success(或直接反馈对象success)为true才成功。缺少业务成功标志、gRPC错误或false均停止后续节点,不自动重试。
completion=rpc_response只代表这个服务接口的返回条件。某些接口等待运动完成,某些仅表示驱动接受;重定位可能未收敛,灵巧手可能未到位,不能从Unary一词推导物理完成。
目录中MotorRequest.mode的suggestedChoices给出轮廓位置/速度/力矩、周期位置/速度/力矩的常用数值,外部可据此渲染下拉框;支持范围仍由电机驱动决定。
导出的目录响应消息说明返回数据结构。结果、错误和运行进度单独保存,不写回计划参数,不用结果修改已定义节点目标。当前没有跨节点变量绑定、条件分支、并发节点或失败自动恢复。
点击停止或连接断开时,停止安排后续节点。新通用Unary的ClientContext会被取消;旧客户端适配节点只停止流程调度,不保证主动停止所有设备/媒体会话。需要结束流、录制或设备运动,应使用相应停止节点或专门的设备停止/急停操作。
RPC取消、客户端超时、网络断开不等于物理停止已经确认;服务端可能已经接受动作。结果不明时不能自动重发运动。
独立执行器应预检所有节点与适配器后再发第一个动作。执行中遇到错误即结束,已经完成的动作和坐标系应用不回滚;不要因重载网页自动重跑任务。
九、外部实现建议流程
1. 读取文件,检查format及JSON Schema。
2. 加载相同版本task_operations.json,按id解析接口及请求/反馈类型;用Proto或目录构造参数表单。
3. 做语义校验:id、循环限制、operationId与参数一致、设备归属、服务能力、适配器是否全部可用。
4. 将目标方案深度优先展开;每次迭代保持完整子序列顺序。
5. 新建运行上下文,按节点execution调用。rpc由外部注入连接/鉴权/gRPC-Web适配,client_adapter由外部注入媒体等逻辑。
6. 等待对应成功条件,记录返回结果,等待waitMs,再进入下一节点。
7. 失败/取消/超时停止,不重试、不自动恢复后续节点;由用户确认后决定下一步。
参考JavaScript(ES2022,浏览器或较新Node,需crypto.randomUUID/structuredClone/AbortController):
import {execute} from './task-flow.mjs';
const abort = new AbortController();
await execute(plan, catalog, plan.groups[0].id, {
rpc: async (service, method, request, {signal, timeoutMs}) => {
// 通过你自己的gRPC/gRPC-Web客户端调用,返回解码后的Proto-JSON对象。
// 传递取消和deadline;若使用SDK消息对象,先转成JSON,保留false的success。
return yourTransport(service, method, request, {signal, timeoutMs});
},
adapters: yourClientAdapters,
signal: abort.signal,
onEvent: event => console.log(event)
});
// abort.abort()停止执行器等待/后续调度;不代表现场机械臂已停稳。
不要将包中的示例rpc替换成真正网络传输后直接运行示例目标,先在离线/模拟环境验证解析和结果判断。
十、文件保存、导入导出与兼容
Qt仍保存到程序目录data/task_orchestration.json,使用原子写入,不使用注册表。
导出按钮生成选定文件名的整份任务文件,以及同目录task_operations.json。请将操作目录与任务文件一起交给外部开发者。
导入会追加方案,重新生成导入方案/节点id以避免与本地冲突,不删除已有方案,不执行任何节点。
v1旧文件会迁移到当前无 version 格式,迁移前先生成task_orchestration.json.v1.bak;同名备份已存在时生成独立UUID备份,不覆盖旧备份。
解析失败、未知版本、无效接口参数或执行描述冲突时保留原文件、禁用自动覆盖。重新导入有效文件前会先备份原文件。
当前协议只约定上述字段。外部自己的机器人连接绑定、云端版本、用户权限等放在外部系统中管理;不要依赖Qt保留额外的未知根字段。
十一、验证范围
已完成Release编译及纯离线校验:旧格式迁移、稳定id、请求头放置、参数类型、NaN拒绝、循环数量、歧义拒绝、业务错误和外部参考执行器。
测试仅使用本机回环模拟gRPC服务和模拟传输,没有发送任何现场设备控制指令。当前无头Qt初始化环境存在限制,未完成自动化真实窗口操作测试,也未逐个实机验证120个接口。
十二、网页服务端直接调用 cmvr-es 的导出约定(2026-11-16)
导出时将普通友好动作转换为真实 Unary RPC 节点;本地编辑方案不变。operationId 使用完整服务名.方法名,parameters 保留 service、method、request、timeoutMs,execution.request 为绑定设备后的 Proto-JSON 请求。MoveJ 的 positions 转为 target.position,AGV 的 stationId/maxSpeed 转为 station_id/options.max_speed,灵巧手 values 转为 [{id:0,value:...},...],录像 path 转为 video_path,录音 path 转为 file_path,播放 path 转为 audio_path。
预览、音频流仍保留编辑所需 client_adapter 字段,但每个节点额外导出 serverCalls。网页服务端按 serverCalls 顺序实现真实服务调用及会话控制,无需调用 Qt。每项含 service、method、rpcPath、requestType、responseType、clientStreaming、serverStreaming、mode、request。mode=unary 为一次调用,open_stream 为建立流,close_stream 为关闭 sessionKey 指定的既有流,关闭流不是再发一次同名 RPC。相机预览开始依次 GetStatus、StartCamera、GetRGBImageStream,状态响应 codec 用于解码。
runtimeRequestFields 列出运行时才有的请求字段,如扬声器流每帧 audio;具体 AudioData 类型参见 task_operations.json/protos。客户端采集设备、sampleRate、channels 等原始配置保留在 parameters,网页端需要自己的采集源绑定。request 是请求模板,发送时重新生成 command_id 和 timestamp,不把缺少音频帧的模板当成完整播放请求。
example.server-export.json 展示全部38个友好节点转换结果,仅用于离线解析,不可直接执行示例设备与路径。普通节点与循环的顺序、waitMs、失败停止策略不变。已有通用 RPC 节点的预检(如自定义坐标系 MoveL 能力确认)仍按本说明执行,不能只看到 service/method 就跳过预检。

View File

@ -1,6 +1,8 @@
<RCC>
<qresource prefix="/">
<file>styles.qss</file>
<file>resources/task_adapters.json</file>
<file>resources/task_ui.json</file>
<file>assets/agv/demo_scan.smap</file>
<file>icons/cmvr-app.ico</file>
<file>icons/cmvr-app.svg</file>

View File

@ -0,0 +1,652 @@
{
"client.arm.move_j": {
"rpc": {
"service": "cmvr.api.ArmService",
"method": "moveJ"
},
"parametersSchema": {
"type": "object",
"properties": {
"positions": {
"type": "array",
"items": {
"type": "number"
},
"description": "关节角数组 rad,长度为设备DOF"
},
"velocity": {
"type": "number",
"exclusiveMinimum": 0,
"description": "rad/s"
},
"acceleration": {
"type": "number",
"exclusiveMinimum": 0,
"description": "rad/s²"
}
},
"required": [
"positions",
"velocity",
"acceleration"
],
"additionalProperties": false
},
"successMeaning": "driver_motion_result",
"implementation": "positions -> target.position;速度/加速度 -> options;当前遨博等待运动完成,其他驱动以其返回语义为准。"
},
"client.arm.enable": {
"rpc": {
"service": "cmvr.api.ArmService",
"method": "torqueOn"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "选中deviceId写入通用请求头,不传运动目标。"
},
"client.arm.disable": {
"rpc": {
"service": "cmvr.api.ArmService",
"method": "torqueOff"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "选中deviceId写入通用请求头,不传运动目标。"
},
"client.arm.stop": {
"rpc": {
"service": "cmvr.api.ArmService",
"method": "stopMotion"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "选中deviceId写入通用请求头,不传运动目标。"
},
"client.arm.clear_fault": {
"rpc": {
"service": "cmvr.api.ArmService",
"method": "clearFault"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "选中deviceId写入通用请求头,不传运动目标。"
},
"client.camera.snapshot_rgb": {
"rpc": {
"service": "cmvr.api.CameraService",
"method": "GetRGBImage"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "image_callback",
"implementation": "获取图像并在客户端解码、展示;深度抓图需先查询设备能力,不支持时失败。"
},
"client.camera.snapshot_depth": {
"rpc": {
"service": "cmvr.api.CameraService",
"method": "GetDepthImage"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "image_callback",
"implementation": "获取图像并在客户端解码、展示;深度抓图需先查询设备能力,不支持时失败。"
},
"client.camera.preview_start": {
"rpc": {
"service": "cmvr.api.CameraService",
"method": "GetRGBImageStream"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "stream_started",
"implementation": "先GetStatus获取设备编码器,建立RGB视频流并展示结果;确认流已启动后本节点完成,流继续存在。"
},
"client.camera.preview_stop": {
"rpc": {
"service": "cmvr.api.CameraService",
"method": "GetRGBImageStream"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "stream_stopped",
"implementation": "取消/关闭该设备预览会话,确认流停止;不是重复提交Unary RPC。"
},
"client.camera.record_start": {
"rpc": {
"service": "cmvr.api.CameraService",
"method": "StartRecording"
},
"parametersSchema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"minLength": 1,
"description": "服务端录像路径"
}
},
"required": [
"path"
],
"additionalProperties": false
},
"successMeaning": "recording_started",
"implementation": "path由客户端映射到录制请求,记录状态确认启动后完成,不等待整段录像结束。"
},
"client.camera.record_stop": {
"rpc": {
"service": "cmvr.api.CameraService",
"method": "StopRecording"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "recording_stopped",
"implementation": "确认录制结束后继续。"
},
"client.agv.navigate_station": {
"rpc": {
"service": "cmvr.api.AgvService",
"method": "navigateToStation"
},
"parametersSchema": {
"type": "object",
"properties": {
"stationId": {
"type": "string",
"minLength": 1
},
"maxSpeed": {
"type": "number",
"exclusiveMinimum": 0,
"description": "m/s"
}
},
"required": [
"stationId",
"maxSpeed"
],
"additionalProperties": false
},
"successMeaning": "driver_navigation_result",
"implementation": "stationId -> station_id,maxSpeed -> options.max_speed;是否已到站以驱动同步/异步语义为准。"
},
"client.agv.stop": {
"rpc": {
"service": "cmvr.api.AgvService",
"method": "cancelNavigation"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "调用对应底盘操作。"
},
"client.agv.pause": {
"rpc": {
"service": "cmvr.api.AgvService",
"method": "pauseNavigation"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "调用对应底盘操作。"
},
"client.agv.resume": {
"rpc": {
"service": "cmvr.api.AgvService",
"method": "resumeNavigation"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "调用对应底盘操作。"
},
"client.dexhand.angle": {
"rpc": {
"service": "cmvr.api.DexHandService",
"method": "SetDexHandAngle"
},
"parametersSchema": {
"type": "object",
"properties": {
"values": {
"type": "array",
"items": {
"type": "number"
},
"description": "数值/数量由型号和对应Proto字段决定,不能假定是SI单位"
}
},
"required": [
"values"
],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "values通过已有DexHand客户端映射到对应请求;接口确认不等同于手指已到位。"
},
"client.dexhand.position": {
"rpc": {
"service": "cmvr.api.DexHandService",
"method": "SetDexHandPos"
},
"parametersSchema": {
"type": "object",
"properties": {
"values": {
"type": "array",
"items": {
"type": "number"
},
"description": "数值/数量由型号和对应Proto字段决定,不能假定是SI单位"
}
},
"required": [
"values"
],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "values通过已有DexHand客户端映射到对应请求;接口确认不等同于手指已到位。"
},
"client.dexhand.speed": {
"rpc": {
"service": "cmvr.api.DexHandService",
"method": "SetDexHandSpeed"
},
"parametersSchema": {
"type": "object",
"properties": {
"values": {
"type": "array",
"items": {
"type": "number"
},
"description": "数值/数量由型号和对应Proto字段决定,不能假定是SI单位"
}
},
"required": [
"values"
],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "values通过已有DexHand客户端映射到对应请求;接口确认不等同于手指已到位。"
},
"client.dexhand.force": {
"rpc": {
"service": "cmvr.api.DexHandService",
"method": "SetDexHandForce"
},
"parametersSchema": {
"type": "object",
"properties": {
"values": {
"type": "array",
"items": {
"type": "number"
},
"description": "数值/数量由型号和对应Proto字段决定,不能假定是SI单位"
}
},
"required": [
"values"
],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "values通过已有DexHand客户端映射到对应请求;接口确认不等同于手指已到位。"
},
"client.microphone.record_start": {
"rpc": {
"service": "cmvr.api.MicPhoneService",
"method": "StartRecord"
},
"parametersSchema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"minLength": 1,
"description": "服务端录音路径"
}
},
"required": [
"path"
],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "开始录音时 path -> file_path;停止节点结束录音。"
},
"client.microphone.record_stop": {
"rpc": {
"service": "cmvr.api.MicPhoneService",
"method": "StopRecord"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "开始录音时 path -> file_path;停止节点结束录音。"
},
"client.microphone.stream_start": {
"rpc": {
"service": "cmvr.api.MicPhoneService",
"method": "StreamAudio"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "stream_started",
"implementation": "维护服务端麦克风音频接收会话并在客户端播放;启动/停止状态确认后继续流程。"
},
"client.microphone.stream_stop": {
"rpc": {
"service": "cmvr.api.MicPhoneService",
"method": "StreamAudio"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "stream_stopped",
"implementation": "维护服务端麦克风音频接收会话并在客户端播放;启动/停止状态确认后继续流程。"
},
"client.speaker.file_play": {
"rpc": {
"service": "cmvr.api.SpeakerService",
"method": "PlayAudio"
},
"parametersSchema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"minLength": 1,
"description": "服务端音频文件路径"
}
},
"required": [
"path"
],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "path -> audio_path;不是上传本机文件。"
},
"client.speaker.file_stop": {
"rpc": {
"service": "cmvr.api.SpeakerService",
"method": "StopPlayback"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "停止服务端文件播放。"
},
"client.speaker.capture_stream_start": {
"rpc": {
"service": "cmvr.api.SpeakerService",
"method": "StreamAudio"
},
"parametersSchema": {
"type": "object",
"properties": {
"inputDevice": {
"type": "string",
"minLength": 1
},
"sampleRate": {
"type": "integer",
"minimum": 8000,
"maximum": 192000
},
"channels": {
"type": "integer",
"minimum": 1,
"maximum": 8
}
},
"required": [
"inputDevice",
"sampleRate",
"channels"
],
"additionalProperties": false
},
"successMeaning": "stream_started",
"implementation": "先建立扬声器发送流,再打开当前客户端本机麦克风采集PCM并编码为Proto音频帧传输;设备名属于当前客户端,网页端需由用户授权浏览器麦克风并提供对应适配,不能直接使用Qt音频设备名。"
},
"client.speaker.stream_start": {
"rpc": {
"service": "cmvr.api.SpeakerService",
"method": "StreamAudio"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "stream_started",
"implementation": "开始仅建立发送会话,不自动产生音频;停止会停止本地音源并结束发送会话。"
},
"client.speaker.stream_stop": {
"rpc": {
"service": "cmvr.api.SpeakerService",
"method": "StreamAudio"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "stream_stopped",
"implementation": "开始仅建立发送会话,不自动产生音频;停止会停止本地音源并结束发送会话。"
},
"client.biohead.happy": {
"rpc": {
"service": "cmvr.api.BioHeadService",
"method": "Happy"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "调用服务端预设操作;说话动作不等于音频播放,状态查询不保证包含真实舵机状态,成功不保证物理动作已到位。"
},
"client.biohead.surprise": {
"rpc": {
"service": "cmvr.api.BioHeadService",
"method": "Surprise"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "调用服务端预设操作;说话动作不等于音频播放,状态查询不保证包含真实舵机状态,成功不保证物理动作已到位。"
},
"client.biohead.tired": {
"rpc": {
"service": "cmvr.api.BioHeadService",
"method": "ExpressionTired"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "调用服务端预设操作;说话动作不等于音频播放,状态查询不保证包含真实舵机状态,成功不保证物理动作已到位。"
},
"client.biohead.angry": {
"rpc": {
"service": "cmvr.api.BioHeadService",
"method": "ExpressionAngry"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "调用服务端预设操作;说话动作不等于音频播放,状态查询不保证包含真实舵机状态,成功不保证物理动作已到位。"
},
"client.biohead.sad": {
"rpc": {
"service": "cmvr.api.BioHeadService",
"method": "ExpressionSadness"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "调用服务端预设操作;说话动作不等于音频播放,状态查询不保证包含真实舵机状态,成功不保证物理动作已到位。"
},
"client.biohead.yawn": {
"rpc": {
"service": "cmvr.api.BioHeadService",
"method": "ExpressionYawn"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "调用服务端预设操作;说话动作不等于音频播放,状态查询不保证包含真实舵机状态,成功不保证物理动作已到位。"
},
"client.biohead.speak_start": {
"rpc": {
"service": "cmvr.api.BioHeadService",
"method": "SpeakStart"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "调用服务端预设操作;说话动作不等于音频播放,状态查询不保证包含真实舵机状态,成功不保证物理动作已到位。"
},
"client.biohead.speak_stop": {
"rpc": {
"service": "cmvr.api.BioHeadService",
"method": "SpeakStop"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "调用服务端预设操作;说话动作不等于音频播放,状态查询不保证包含真实舵机状态,成功不保证物理动作已到位。"
},
"client.biohead.emergency_stop": {
"rpc": {
"service": "cmvr.api.BioHeadService",
"method": "EmergencyStop"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "调用服务端预设操作;说话动作不等于音频播放,状态查询不保证包含真实舵机状态,成功不保证物理动作已到位。"
},
"client.biohead.check": {
"rpc": {
"service": "cmvr.api.BioHeadService",
"method": "GetSystemStatus"
},
"parametersSchema": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
},
"successMeaning": "rpc_response",
"implementation": "调用服务端预设操作;说话动作不等于音频播放,状态查询不保证包含真实舵机状态,成功不保证物理动作已到位。"
}
}

315
resources/task_ui.json Normal file
View File

@ -0,0 +1,315 @@
{
"operations": {
"ControlHeadJoints": "控制头部关节",
"GetHeadJointState": "查询头部关节状态",
"SetHeadExpression": "设置头部关节表情",
"PlayHeadExpression": "播放头部预设表情",
"torqueOff": "去使能",
"torqueOn": "使能",
"clearFault": "清除故障",
"moveJPose": "末端位姿关节运动",
"moveJ": "关节角度运动",
"moveL": "末端直线运动",
"ListBaseFrame": "查询参考坐标系",
"ListTCPFrame": "查询工具坐标系",
"speedJ": "关节速度控制",
"speedL": "末端速度控制",
"servoJ": "关节伺服控制",
"stopMotion": "停止运动",
"GetArmInfo": "查询机械臂信息",
"getJointState": "查询关节状态",
"getRobotState": "查询机器人状态",
"getPose": "查询末端位姿",
"calibrateZeroQ": "校准零位",
"getPoseMatrix": "查询位姿矩阵",
"computeForwardKinematics": "计算正运动学",
"ExecuteJsonCommand": "设备扩展指令",
"EnterTeachingMode": "进入拖动示教",
"StartTrajectoryRecording": "开始录制轨迹",
"CompleteTeaching": "完成示教",
"StopTrajectoryRecording": "停止录制轨迹",
"ExitTeachingMode": "退出拖动示教",
"ListRecordedTrajectories": "查询已录制轨迹",
"MoveToTrajectoryStart": "移动到轨迹起点",
"ReplayRecordedTrajectory": "回放轨迹",
"CalibrateUserCoordinateSystem": "标定工件坐标系",
"CreateUserCoordinateSystem": "创建工件坐标系",
"GetUserCoordinateSystem": "查询工件坐标系",
"ListUserCoordinateSystems": "查询全部工件坐标系",
"UpdateUserCoordinateSystem": "修改工件坐标系",
"DeleteUserCoordinateSystem": "删除工件坐标系",
"ApplyUserCoordinateSystem": "应用工件坐标系",
"GetStatus": "查询设备状态",
"StartCamera": "启动相机",
"StopCamera": "关闭相机",
"GetRGBImage": "采集彩色图像",
"GetDepthImage": "采集深度图像",
"GetRGBDImages": "采集彩色与深度图像",
"StartRecording": "开始录像",
"StopRecording": "停止录像",
"ControlPtz": "云台控制",
"getRuntimeState": "查询底盘运行状态",
"getNavigationStatus": "查询导航状态",
"emergencyStop": "紧急停止",
"relocalize": "重新定位",
"navigateToPose": "导航到目标位姿",
"navigateToStation": "导航到站点",
"followPath": "沿路径导航",
"pauseNavigation": "暂停导航",
"resumeNavigation": "继续导航",
"cancelNavigation": "取消导航",
"setVelocity": "底盘速度控制",
"stopVelocityControl": "停止速度控制",
"listMaps": "查询地图",
"listStations": "查询站点",
"switchMap": "切换地图",
"uploadMap": "上传地图",
"downloadMap": "下载地图",
"startMapping": "开始建图",
"stopMapping": "停止建图",
"translate": "底盘平移",
"SetDexHandPos": "设置手指位置",
"SetDexHandAngle": "设置手指角度",
"SetDexHandForce": "设置手指力度",
"SetDexHandSpeed": "设置手指速度",
"SetDexHandPresetAct": "执行手部预设动作",
"GetSensorData": "读取触觉传感器",
"StartRecord": "开始录音",
"StopRecord": "停止录音",
"PauseRecord": "暂停录音",
"ResumeRecord": "继续录音",
"SetVolume": "设置音量",
"GetVolume": "查询音量",
"PlayAudio": "播放服务端音频",
"StopPlayback": "停止播放",
"PausePlayback": "暂停播放",
"ResumePlayback": "继续播放",
"SetExpression": "设置面部表情",
"GetSystemStatus": "查询仿生头状态",
"EmergencyStop": "紧急停止",
"SpeakStart": "开始说话动作",
"SpeakStop": "停止说话动作",
"Happy": "高兴表情",
"Surprise": "惊讶表情",
"ExpressionTired": "疲惫表情",
"ExpressionAngry": "愤怒表情",
"ExpressionSadness": "悲伤表情",
"ExpressionYawn": "打哈欠表情",
"ListMotors": "查询电机列表",
"GetInfo": "查询电机信息",
"GetState": "查询电机状态",
"getMode": "查询控制模式",
"getQ": "查询位置",
"getQd": "查询速度",
"getTau": "查询力矩",
"reachedTargetQ": "查询是否到位",
"setMode": "设置控制模式",
"brakeRelease": "松开抱闸",
"quickStop": "快速停止",
"commandProfilePosition": "轮廓位置控制",
"commandProfileVelocity": "轮廓速度控制",
"commandProfileTorque": "轮廓力矩控制",
"commandCyclicPosition": "周期位置控制",
"commandCyclicVelocity": "周期速度控制",
"commandCyclicTorque": "周期力矩控制",
"setLimitQ": "设置位置限位",
"setLimitQd": "设置速度限值",
"setLimitQdd": "设置加速度限值"
},
"fields": {
"cancel_expression": "取消后续表情帧",
"constraints": "关节运动约束",
"expression_id": "表情编号",
"expression_name": "表情名称",
"gain": "位置增益",
"home": "移动到初始位置",
"max_acceleration_rad_s2": "最大加速度(rad/s²)",
"max_jerk_rad_s3": "最大加加速度(rad/s³)",
"max_velocity_rad_s": "最大速度(rad/s)",
"move": "关节目标运动",
"period_ms": "更新周期(毫秒)",
"position_gain": "关节位置增益",
"position_rad": "目标角度(rad)",
"reconnect": "重新连接并探测设备",
"targets": "关节目标列表",
"transition_duration_s": "表情过渡时长(秒)",
"update_period": "设备更新周期",
"acceleration": "加速度",
"action": "动作",
"adapter_params": "驱动专用选项",
"asynchronous": "发送后立即返回",
"audio": "音频帧",
"audio_path": "服务端音频路径",
"base_frame": "参考坐标系",
"base_link": "参考坐标系",
"base_tcp_pose": "基座下的工具位姿",
"blend_radius": "轨迹衔接半径",
"blocked_timeout_ms": "阻塞超时(毫秒)",
"calibration_points": "标定采样点",
"calibration_version": "标定记录版本",
"channels": "声道数",
"codec": "编码格式",
"command": "控制指令",
"command_id": "本次调用标识",
"content": "地图文件内容",
"coordinate": "工件坐标系记录",
"coordinate_relative_translation": "沿工件坐标系增量平移",
"corner_x": "嘴角左右",
"corner_y": "嘴角上下",
"data": "二进制数据",
"device_id": "目标设备",
"dimension": "地图维度",
"distance": "移动距离(米)",
"duration": "持续时间(秒)",
"ee_link": "末端坐标系",
"eof": "结束数据流",
"expected_device_generation": "预期设备实例编号",
"expected_revision": "预期记录版本(0 为最新)",
"expected_service_instance_id": "预期服务实例标识",
"expr": "表情名称",
"expression": "表情参数",
"eyeball": "眼球",
"eyebrow": "眉毛",
"eyelid": "眼睑",
"file_name": "轨迹文件名",
"file_path": "服务端录音路径",
"format": "音频格式",
"frame": "参考坐标系",
"header": "调用信息",
"id": "通道编号",
"incremental": "使用增量目标",
"jaw": "下颌",
"jerk": "加加速度",
"joint_name": "关节名称",
"joint_velocity_limits": "各关节速度限制",
"joints": "关节目标",
"key": "选项名称",
"left_inside_y": "左侧内缘上下",
"left_lip": "左唇",
"left_lower_y": "左侧下缘上下",
"left_outside_y": "左侧外缘上下",
"left_upper_y": "左侧上缘上下",
"left_x": "左侧左右",
"left_y": "左侧上下",
"lower": "下限",
"lower_lip_y": "下唇上下",
"lower_lip_z": "下唇前后",
"lower_x": "下缘左右",
"lower_y": "下缘上下",
"map_name": "地图名称",
"max_acceleration": "最大线加速度(米/秒²)",
"max_angular_acceleration": "最大角加速度(弧度/秒²)",
"max_angular_speed": "最大角速度(弧度/秒)",
"max_chunk_bytes": "单块大小上限(字节)",
"max_jerk": "最大加加速度",
"max_speed": "最大移动速度(米/秒)",
"max_velocity": "最大速度",
"mode": "控制模式",
"mouth": "嘴部",
"name": "名称",
"nanos": "纳秒部分",
"nb_samples": "每帧采样数",
"node_id": "电机节点编号",
"nose": "鼻部",
"options": "运动设置",
"path": "导航路径点",
"poll_interval_ms": "状态检查间隔(毫秒)",
"pose": "目标位姿",
"position": "关节位置",
"presetActId": "预设动作编号",
"pts": "帧时间戳",
"q": "目标位置(弧度)",
"qd": "目标速度(弧度/秒)",
"qdd": "目标加速度(弧度/秒²)",
"reach_angle": "到位角度容差(弧度)",
"reach_distance": "到位距离容差(米)",
"real_time": "实时模式",
"request_json": "驱动扩展指令内容(JSON)",
"require_metric_depth": "要求以米标定的深度数据",
"resume_token": "断点续传标识",
"revision": "记录版本",
"right_inside_y": "右侧内缘上下",
"right_lip": "右唇",
"right_lower_y": "右侧下缘上下",
"right_outside_y": "右侧外缘上下",
"right_upper_y": "右侧上缘上下",
"right_x": "右侧左右",
"right_y": "右侧上下",
"rx": "绕 X 轴旋转(弧度)",
"ry": "绕 Y 轴旋转(弧度)",
"rz": "绕 Z 轴旋转(弧度)",
"sample_rate": "采样率(赫兹)",
"sampling_frequency_hz": "轨迹采样频率(赫兹)",
"seconds": "秒",
"snapshot": "地图快照",
"source_station": "起始站点",
"target": "运动目标",
"target_station": "目标站点",
"tau": "目标力矩(额定力矩千分比)",
"tcp_frame": "工具坐标系",
"tcp_offset": "工具偏移量",
"theta": "平面朝向(弧度)",
"timestamp": "调用时间",
"torque_slope": "力矩变化率",
"translation": "位移量",
"upper": "上限",
"upper_lip_y": "上唇上下",
"upper_lip_z": "上唇前后",
"upper_x": "上缘左右",
"upper_y": "上缘上下",
"user_coordinate_name": "已应用工件坐标系名称",
"user_coordinate_revision": "工件坐标系版本(0 为最新)",
"user_frame_pose": "工件坐标系位姿",
"user_pose": "工件坐标系内的目标位姿",
"valid_for_ms": "指令有效期(毫秒)",
"value": "目标值",
"values": "各通道目标值",
"velocity": "速度",
"video_path": "服务端录像路径",
"volume": "音量",
"vx": "X 方向线速度(米/秒)",
"vy": "Y 方向线速度(米/秒)",
"vz": "Z 方向线速度(米/秒)",
"wait_timeout_ms": "等待完成超时(毫秒)",
"wx": "绕 X 轴角速度(弧度/秒)",
"wy": "绕 Y 轴角速度(弧度/秒)",
"wz": "绕 Z 轴角速度(弧度/秒)",
"x": "X 位置(米)",
"y": "Y 位置(米)",
"z": "Z 位置(米)",
"speed_ratio": "轨迹回放速度倍率",
"speed": "速度(设备单位)",
"station_id": "目标站点编号"
},
"enums": {
"START": "开始",
"STOP": "停止",
"COMMAND_UNSPECIFIED": "未指定",
"TILT_UP": "向上",
"TILT_DOWN": "向下",
"PAN_LEFT": "向左",
"PAN_RIGHT": "向右",
"UP_LEFT": "左上",
"UP_RIGHT": "右上",
"DOWN_LEFT": "左下",
"DOWN_RIGHT": "右下",
"ZOOM_IN": "放大",
"ZOOM_OUT": "缩小",
"PAN_AUTO": "自动巡航",
"AGV_MAP_DIMENSION_UNSPECIFIED": "使用默认地图维度",
"AGV_MAP_2D": "二维地图",
"AGV_MAP_3D": "三维地图",
"AGV_MAP_2D_AND_3D": "二维及三维地图",
"AGV_TRANSLATION_MODE_ODOMETRY": "按里程计平移",
"AGV_TRANSLATION_MODE_LOCALIZATION": "按定位坐标平移",
"ARM_FRAME_BASE": "基座坐标系",
"ARM_FRAME_TOOL": "工具坐标系",
"ARM_FRAME_WORLD": "世界坐标系",
"ARM_FRAME_USER": "用户坐标系",
"PCM": "原始 PCM 音频",
"MP3": "MP3 音频",
"WAV": "WAV 音频",
"AAC": "AAC 音频",
"OPUS": "Opus 音频"
}
}

View File

@ -0,0 +1,65 @@
"""Generate the external JSON Schema from the catalog exported by taskapi_test or the Qt app."""
import json
from pathlib import Path
root=Path("docs/task-flow")
catalog=json.loads((root/"task_operations.json").read_text(encoding="utf-8"))
ref=lambda name:{"$ref":"#/$defs/"+name}
msgref=lambda name:{"$ref":"#/$defs/message."+name}
def scalar(f):
if "messageType" in f:return msgref(f["messageType"])
if "enumType" in f:return {"enum":[x["name"] for x in catalog["enums"][f["enumType"]]]+[x["number"] for x in catalog["enums"][f["enumType"]]]}
t=f["type"]
if t in ["string","bytes"]:return {"type":"string",**({"contentEncoding":"base64"} if t=="bytes" else {})}
if t=="bool":return {"type":"boolean"}
if t in ["int64","sint64","sfixed64"]:return {"type":"string","pattern":"^-?[0-9]+$"}
if t in ["uint64","fixed64"]:return {"type":"string","pattern":"^[0-9]+$"}
if t in ["float","double"]:return {"type":"number"}
unsigned=t in ["uint32","fixed32"]
return {"type":"integer","minimum":0 if unsigned else -2147483648,"maximum":4294967295 if unsigned else 2147483647}
messages={}
for name,m in catalog["messages"].items():
if name=="google.protobuf.Timestamp":messages[name]={"type":"string","format":"date-time"};continue
props={};rules=[];unions={}
for f in m["fields"]:
if f["map"]:
entry=catalog["messages"][f["messageType"]]["fields"]
field={"type":"object","additionalProperties":scalar(next(x for x in entry if x["name"]=="value"))}
elif f["repeated"]:field={"type":"array","items":scalar(f)}
else:field=scalar(f)
props[f["name"]]=field
if f["name"]!=f["jsonName"]:
props[f["jsonName"]]=field;rules.append({"not":{"required":[f["name"],f["jsonName"]]}})
if f.get("oneof"):unions.setdefault(f["oneof"],[]).append(f)
for union in unions.values():
for i,a in enumerate(union):
for b in union[i+1:]:
for ak in set([a["name"],a["jsonName"]]):
for bk in set([b["name"],b["jsonName"]]):rules.append({"not":{"required":[ak,bk]}})
messages[name]={"type":"object","properties":props,"additionalProperties":False,**({"allOf":rules} if rules else {})}
policy={"order":"sequential","onError":"stop","automaticRetry":False,"waitStartsAfter":"operation_success","stopBehavior":"stop_scheduling_and_cancel_active_unary"}
methods=[m for s in catalog["services"] for m in s["methods"] if not m["clientStreaming"] and not m["serverStreaming"]]
common={"id":{"type":"string","minLength":1},"name":{"type":"string"}}
task={"type":"object","required":["id","name","kind","deviceType","deviceId","action","parameters","operationId","execution","waitMs","waitUnit"],"properties":{
**common,"kind":{"const":"task"},"deviceType":{"type":"string"},"deviceId":{"type":"string","minLength":1},"action":{"type":"string","minLength":1},
"parameters":{"type":"object"},"operationId":{"type":"string"},"waitMs":{"type":"integer","minimum":0,"maximum":2147483647},"waitUnit":{"enum":["ms","s"]},
"execution":{"oneOf":[ref("rpc"),ref("adapter")]}},"allOf":[]}
for m in methods:
request=msgref(m["requestType"])
task["allOf"].append({"if":{"properties":{"operationId":{"const":m["id"]}}},"then":{"properties":{
"parameters":{"type":"object","required":["service","method","request"],"properties":{"service":{"const":m["service"]},"method":{"const":m["method"]},"request":request,"timeoutMs":{"type":"integer","minimum":100,"maximum":1800000}}},
"execution":{"properties":{"kind":{"const":"grpc_unary"},"service":{"const":m["service"]},"method":{"const":m["method"]},"request":request}}}}})
for a in catalog["clientAdapters"]:
task["allOf"].append({"if":{"properties":{"operationId":{"const":a["id"]}}},"then":{"properties":{
"deviceType":{"const":a["deviceType"]},"action":{"const":a["action"]},"parameters":a["parametersSchema"],
"execution":{"properties":{"kind":{"const":"client_adapter"},"adapter":{"const":a["id"]},"parameters":a["parametersSchema"]}}}}})
task["properties"]["operationId"]={"enum":[m["id"] for m in methods]+[a["id"] for a in catalog["clientAdapters"]]}
schema={"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"urn:cmvr:task-flow","title":"CMVR portable task flow","type":"object","required":["format","executionPolicy","groups"],"properties":{
"format":{"const":"cmvr.task-flow"},"executionPolicy":{"const":policy},"groups":{"type":"array","items":ref("group")}},"$defs":{
**{"message."+name:value for name,value in messages.items()},"node":{"oneOf":[ref("task"),ref("loop")]},"task":task,
"group":{"type":"object","required":["id","name","nodes"],"properties":{**common,"nodes":{"type":"array","items":ref("node")}}},
"loop":{"type":"object","required":["id","name","kind","count","children"],"properties":{**common,"kind":{"const":"loop"},"count":{"type":"integer","minimum":1,"maximum":100000},"collapsed":{"type":"boolean"},"children":{"type":"array","items":ref("node")}}},
"rpc":{"type":"object","required":["kind","service","method","request","timeoutMs","completion"],"properties":{"kind":{"const":"grpc_unary"},"service":{"type":"string"},"method":{"type":"string"},"request":{"type":"object"},"timeoutMs":{"type":"integer","minimum":100,"maximum":1800000},"completion":{"const":"rpc_response"}}},
"adapter":{"type":"object","required":["kind","adapter","deviceId","parameters","completion"],"properties":{"kind":{"const":"client_adapter"},"adapter":{"type":"string"},"deviceId":{"type":"string"},"parameters":{"type":"object"},"completion":{"const":"adapter_callback"}}}}}
task["properties"]["serverCalls"]={"type":"array","minItems":1,"items":{"type":"object","required":["service","method","rpcPath","requestType","responseType","clientStreaming","serverStreaming","mode","request"],"properties":{"service":{"type":"string"},"method":{"type":"string"},"rpcPath":{"type":"string"},"requestType":{"type":"string"},"responseType":{"type":"string"},"clientStreaming":{"type":"boolean"},"serverStreaming":{"type":"boolean"},"mode":{"enum":["unary","open_stream","close_stream"]},"request":{"type":"object"},"sessionKey":{"type":"string"},"runtimeRequestFields":{"type":"array","items":{"type":"string"}},"runtimeHeaderFields":{"type":"array","items":{"type":"string"}}}}}
(root/"task-flow.schema.json").write_text(json.dumps(schema,ensure_ascii=False,indent=2)+"\n",encoding="utf-8")
print("Generated schema for",len(methods),"unary methods and",len(catalog["clientAdapters"]),"client adapters")

View File

@ -0,0 +1,49 @@
"""Package the task JSON contract, schemas, catalog, reference parser and Proto closure."""
from pathlib import Path
import json, re, zipfile, os, subprocess, shutil, hashlib
root=Path.cwd(); docs=root/"docs/task-flow"; staging=root/"artifacts/TaskFlow_20261110"
staging.mkdir(parents=True,exist_ok=True)
files=[]
for p in sorted(docs.iterdir()):
if p.is_file():
dst=staging/p.name;shutil.copyfile(p,dst);files.append(dst)
verify=staging/"verify-example.mjs"
test=(root/"tests/task_flow_reference_test.mjs").read_text(encoding="utf-8").replace("../docs/task-flow/", "./")
verify.write_text(test,encoding="utf-8");files.append(verify)
catalog=json.loads((docs/"task_operations.json").read_text(encoding="utf-8"))
seen=set()
def copy_proto(name):
if name in seen:return
seen.add(name);source=root/"protos"/name
if not source.is_file():source=root/"include"/name
if not source.is_file():raise FileNotFoundError(name)
text=source.read_text(encoding="utf-8");dst=staging/"protos"/name;dst.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(source,dst);files.append(dst)
for dependency in re.findall(r'^import\s+(?:public\s+|weak\s+)?"([^"]+)"',text,re.M):copy_proto(dependency)
services=[]
for service in catalog["services"]:
name=service["service"].split(".")[-1]
candidates=[]
for p in (root/"protos/cmvr/api").glob("*service.proto"):
if re.search(r'\bservice\s+'+name+r'\s*\{',p.read_text(encoding="utf-8")):candidates.append(p)
assert len(candidates)==1,name
filename=candidates[0].relative_to(root/"protos").as_posix();services.append(filename);copy_proto(filename)
lines=["CMVR device RPC catalog / 2026-11-10",""]
for service in catalog["services"]:
lines.append(service["deviceType"]+" / "+service["service"])
for m in service["methods"]:
kind="Streaming: dedicated adapter required" if m["clientStreaming"] or m["serverStreaming"] else "Unary: structured task editor"
lines.append(" "+m["method"]+" | "+kind+" | "+m["requestType"]+" -> "+m["responseType"])
lines.append("")
listing=staging/"rpc_catalog.txt";listing.write_text("\n".join(lines),encoding="utf-8-sig");files.append(listing)
env=os.environ.copy();env["PATH"]=str(root/"lib")+os.pathsep+env.get("PATH","")
descriptor=staging/"api_descriptor.pb"
subprocess.run([str(root/"tools/protoc.exe"),"--experimental_allow_proto3_optional","--proto_path="+str(staging/"protos"),"--include_imports","--include_source_info","--descriptor_set_out="+str(descriptor),*services],env=env,check=True)
files.append(descriptor)
manifest={str(p.relative_to(staging)).replace("\\","/"):hashlib.sha256(p.read_bytes()).hexdigest() for p in files}
manifest_path=staging/"SHA256.json";manifest_path.write_text(json.dumps(manifest,ensure_ascii=False,indent=2),encoding="utf-8");files.append(manifest_path)
out=root/"artifacts/TaskFlow_JSON_Protocol_20261110.zip"
with zipfile.ZipFile(out,"w",zipfile.ZIP_DEFLATED) as z:
for p in files:z.write(p,p.relative_to(staging))
with zipfile.ZipFile(out) as z:assert z.testzip() is None
print("ZIP:",out,"files:",len(files),"bytes:",out.stat().st_size)
print("SHA256:",hashlib.sha256(out.read_bytes()).hexdigest())

View File

@ -0,0 +1,151 @@
"""Stage the already-built Windows x64 Release with its redistributable runtime."""
import argparse
import hashlib
import json
import os
import shutil
import struct
import subprocess
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
NAME = 'CmvrControlStation-Windows-x64-Release'
def pe_imports(file):
data = file.read_bytes()
if data[:2] != b'MZ':
raise ValueError(f'Not a Windows executable: {file}')
pe = struct.unpack_from('<I', data, 0x3c)[0]
if data[pe:pe + 4] != b'PE\0\0':
raise ValueError(f'Invalid PE header: {file}')
machine, count = struct.unpack_from('<HH', data, pe + 4)
optional_size = struct.unpack_from('<H', data, pe + 20)[0]
optional = pe + 24
magic = struct.unpack_from('<H', data, optional)[0]
directory = optional + (112 if magic == 0x20b else 96)
import_rva = struct.unpack_from('<I', data, directory + 8)[0]
section_start = optional + optional_size
sections = [struct.unpack_from('<8sIIII', data, section_start + i * 40)
for i in range(count)]
def offset(rva):
for _, virtual_size, virtual_address, raw_size, raw_start in sections:
if virtual_address <= rva < virtual_address + max(virtual_size, raw_size):
return raw_start + rva - virtual_address
if rva < section_start:
return rva
raise ValueError(f'Unmapped import RVA in {file}')
imports = []
if import_rva:
cursor = offset(import_rva)
while True:
descriptor = struct.unpack_from('<IIIII', data, cursor)
if not any(descriptor):
break
start = offset(descriptor[3])
imports.append(data[start:data.index(b'\0', start)].decode('ascii'))
cursor += 20
return machine, imports
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--qt', default='C:/Qt/Qt5.12.4/5.12.4/mingw73_64')
parser.add_argument('--compiler', default='C:/Qt/Qt5.12.4/Tools/mingw730_64/bin')
args = parser.parse_args()
qt, compiler = Path(args.qt), Path(args.compiler)
built = ROOT / 'bin/release/CmvrControlStation.exe'
deploy = qt / 'bin/windeployqt.exe'
if not built.is_file() or not deploy.is_file():
raise RuntimeError('Build the Release application and provide its matching Qt kit first')
stage = ROOT / 'dist' / NAME
if stage.parent.resolve() != (ROOT / 'dist').resolve() or stage.name != NAME:
raise RuntimeError('Unexpected staging path')
if stage.exists():
shutil.rmtree(stage)
stage.mkdir(parents=True)
shutil.copy2(built, stage / built.name)
for dll in (ROOT / 'lib').glob('*.dll'):
shutil.copy2(dll, stage / dll.name)
for name in ['libgcc_s_seh-1.dll', 'libstdc++-6.dll', 'libwinpthread-1.dll']:
shutil.copy2(compiler / name, stage / name)
env = dict(os.environ)
env['PATH'] = str(qt / 'bin') + os.pathsep + str(compiler) + os.pathsep + env.get('PATH', '')
print('Deploying Qt Release runtime...', flush=True)
subprocess.run([str(deploy), '--release', '--compiler-runtime', '--no-translations',
str(stage / built.name)], env=env, check=True)
subprocess.run(['powershell.exe', '-NoProfile', '-ExecutionPolicy', 'RemoteSigned',
'-File', str(ROOT / 'scripts/repair_qt3d_release.ps1'),
'-RuntimeDirectory', str(stage)], check=True)
scene = stage / 'sceneparsers'
scene.mkdir(exist_ok=True)
shutil.copy2(qt / 'plugins/sceneparsers/assimpsceneimport.dll', scene / 'assimpsceneimport.dll')
shutil.copytree(ROOT / 'models', stage / 'models')
shutil.copytree(ROOT / 'third_party/handeye-runtime', stage / 'runtime/handeye',
ignore=shutil.ignore_patterns('__pycache__', '*.pyc'))
algorithms = stage / 'scripts'
algorithms.mkdir()
for name in ['handeye_worker.py', 'handeye_math.py', 'handeye_refinement.py']:
shutil.copy2(ROOT / 'scripts' / name, algorithms / name)
(stage / 'data').mkdir()
shutil.copy2(ROOT / 'resources/application_settings.json', stage / 'data/application_settings.json')
for name in ['quic-test-server.pfx', 'quic-test-ca.crt']:
shutil.copy2(ROOT / 'certs' / name, stage / name)
(stage / 'qt.conf').write_text('[Paths]\nPlugins=.\n', encoding='utf-8')
(stage / '使用说明.txt').write_text(
'CMVR 控制台 Windows x64 Release 免安装包\n\n'
'完整解压到可写目录,双击 CmvrControlStation.exe。不要只复制 exe。\n'
'已包含 Qt 5.12.4、MinGW运行库、音视频DLL、Qt插件、模型与手眼标定Python环境。\n'
'普通界面使用不需要另行安装Qt;手眼标定使用随包运行环境。\n'
'无实物演示:勾选“演示模式”,地址填127.0.0.1,再连接。确认提示“演示数据源”。\n'
'使用真实设备时取消演示模式,核实服务地址和设备状态后再操作。\n'
'图形驱动有问题时可尝试“启动_兼容模式.cmd”,使用软件OpenGL。\n'
'本包为Windows 64位程序,不适用于麒麟Linux;未在其他电脑上实机验证。\n'
'quic-test-server.pfx为工程开发测试证书,仅供QUIC测试。\n', encoding='utf-8-sig')
(stage / '启动_兼容模式.cmd').write_bytes(
b'@echo off\r\ncd /d "%~dp0"\r\nset "QT_OPENGL=software"\r\n'
b'"%~dp0CmvrControlStation.exe"\r\n')
# Check imports of the executable, redistributable root DLLs and Qt plugins.
# Windows API-set names are virtual OS modules, not redistributable files.
system = Path(os.environ.get('SystemRoot', 'C:/Windows')) / 'System32'
binaries = [stage / built.name] + list(stage.glob('*.dll'))
binaries += [p for p in stage.glob('*/*.dll') if p.parent.name not in ['runtime']]
missing = []
for binary in binaries:
machine, imports = pe_imports(binary)
if machine != 0x8664:
raise RuntimeError(f'Not x64: {binary}')
for name in imports:
if name.lower().startswith(('api-ms-', 'ext-ms-')):
continue
if not any((folder / name).exists() for folder in [binary.parent, stage, system]):
missing.append((str(binary.relative_to(stage)), name))
if missing:
raise RuntimeError(f'Missing DLL dependencies: {missing}')
# Qt's debug configuration is recorded in its plugin metadata.
if any((stage / name).exists() for name in ['Qt5Cored.dll', 'Qt5Guid.dll', 'Qt5Widgetsd.dll', 'platforms/qwindowsd.dll']):
raise RuntimeError('Debug Qt DLL detected in Release package')
manifest = {}
for file in sorted(stage.rglob('*')):
if file.is_file():
manifest[file.relative_to(stage).as_posix()] = hashlib.sha256(file.read_bytes()).hexdigest()
(stage / 'SHA256.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
archive = stage.with_suffix('.zip')
print(f'Writing archive ({len(manifest)} files)...', flush=True)
with zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED, compresslevel=5) as output:
for file in sorted(stage.rglob('*')):
if file.is_file():
output.write(file, NAME + '/' + file.relative_to(stage).as_posix())
with zipfile.ZipFile(archive) as output:
if output.testzip() is not None:
raise RuntimeError('ZIP integrity validation failed')
print(json.dumps({'archive': str(archive), 'size_bytes': archive.stat().st_size,
'pe_files_checked': len(binaries), 'files': len(manifest) + 1}, ensure_ascii=False))
if __name__ == '__main__':
main()

View File

@ -0,0 +1,66 @@
param([string]$RuntimeDirectory = (Join-Path $PSScriptRoot '..\bin\release'), [switch]$IfPresent)
$ErrorActionPreference = 'Stop'
function FileHash([string]$path) { $algorithm = [Security.Cryptography.SHA256]::Create(); try { return [BitConverter]::ToString($algorithm.ComputeHash([IO.File]::ReadAllBytes($path))).Replace('-', '') } finally { $algorithm.Dispose() } }
$dll = Join-Path ([IO.Path]::GetFullPath($RuntimeDirectory)) 'Qt53DRender.dll'
if (!(Test-Path -LiteralPath $dll)) { if ($IfPresent) { Write-Output "Qt3D runtime not deployed yet; repair will run during packaging."; exit 0 }; throw "Qt3D runtime not found: $dll" }
$originalHash = '40FD189F1E233FCDCC07A8BC7E226DB7FBF86DBC4A6480C70E31FE1A185936F7'
$repairedHash = 'AABB4931C7F7145205F3DEA5DAA1F096600EDD16258FC0A67A5C4F203C5A5DE0'
$actual = (FileHash $dll)
if ($actual -eq $repairedHash) { Write-Output 'Qt3D Release register-preservation repair already installed.'; exit 0 }
if ($actual -ne $originalHash) { throw "Unrecognized Qt3D runtime; refusing a version-specific repair: $actual" }
# This exact Qt 5.12.4 MinGW x64 build's QVector<QNodeId>::contains helper calls
# a find helper that clobbers R11. Other optimized callers retain their container
# pointer in R11 across contains(), subsequently passing null to QVector::append.
# Preserve R11 in this function's own first parameter home slot. Stack allocation
# and nonvolatile saves stay unchanged; extend its x64 runtime-function extent.
[byte[]]$bytes = [IO.File]::ReadAllBytes($dll)
$pe = [BitConverter]::ToInt32($bytes, 0x3c)
$optional = $pe + 24
if ([BitConverter]::ToUInt16($bytes, $optional) -ne 0x20b) { throw 'Expected PE32+ image' }
$sections = $optional + [BitConverter]::ToUInt16($bytes, $pe + 20)
function Offset([int]$rva) {
for ($i = 0; $i -lt [BitConverter]::ToUInt16($bytes, $pe + 6); $i++) {
$s = $sections + $i * 40
$va = [BitConverter]::ToInt32($bytes, $s + 12)
$size = [BitConverter]::ToInt32($bytes, $s + 16)
if ($rva -ge $va -and $rva -lt ($va + $size)) { return [BitConverter]::ToInt32($bytes, $s + 20) + $rva - $va }
}
throw ('Unmapped RVA: 0x{0:x}' -f $rva)
}
$rva = 0x1c2690
$start = Offset $rva
$code = [Array]::CreateInstance([byte], 62)
[Array]::Copy($bytes, $start, $code, 0, 5)
[Array]::Copy([byte[]](0x4c,0x89,0x5c,0x24,0x30), 0, $code, 5, 5) # save R11
[Array]::Copy($bytes, $start + 5, $code, 10, 41)
[Array]::Copy([byte[]](0x4c,0x8b,0x5c,0x24,0x30), 0, $code, 51, 5) # restore R11
[Array]::Copy($bytes, $start + 46, $code, 56, 6)
[BitConverter]::GetBytes([int](0x1c3bc0 - ($rva + 45))).CopyTo($code, 41)
$code.CopyTo($bytes, $start)
$bytes[$start + 62] = 0x90
$bytes[$start + 63] = 0x90
$directory = $optional + 112 + 3 * 8
$pdata = [BitConverter]::ToInt32($bytes, $directory)
$size = [BitConverter]::ToInt32($bytes, $directory + 4)
$found = $false
for ($i = 0; $i -lt $size; $i += 12) {
$entry = Offset ($pdata + $i)
if ([BitConverter]::ToInt32($bytes, $entry) -eq $rva) {
if ([BitConverter]::ToInt32($bytes, $entry + 4) -ne ($rva + 52)) { throw 'Unexpected unwind extent' }
[BitConverter]::GetBytes([int]($rva + 62)).CopyTo($bytes, $entry + 4)
$found = $true
break
}
}
if (!$found) { throw 'Missing x64 runtime-function entry' }
$sha = [Security.Cryptography.SHA256]::Create()
try { $after = [BitConverter]::ToString($sha.ComputeHash($bytes)).Replace('-', '') } finally { $sha.Dispose() }
if ($after -ne $repairedHash) { throw "Unexpected repaired image hash: $after" }
$backupDir = Join-Path $RuntimeDirectory 'crash_dumps\dependency_backups'
New-Item -ItemType Directory -Path $backupDir -Force | Out-Null
$backup = Join-Path $backupDir 'Qt53DRender.original.dll'
if (!(Test-Path -LiteralPath $backup)) { Copy-Item -LiteralPath $dll -Destination $backup }
elseif ((FileHash $backup) -ne $originalHash) { throw 'Backup differs from the expected original; preserving it' }
[IO.File]::WriteAllBytes($dll, $bytes)
Write-Output "Repaired Qt3D Release runtime: $dll; original preserved at $backup"

343
scripts/setup_kylin.sh Normal file
View File

@ -0,0 +1,343 @@
#!/usr/bin/env bash
# Qt 5 / CMVR setup using the target machine's configured distribution repositories.
set -euo pipefail
export LC_ALL=C
log() { printf '\n[CMVR] %s\n' "$*"; }
fail() { printf '\n[ERROR] %s\n' "$*" >&2; return 1; }
have() { command -v "$1" >/dev/null 2>&1; }
usage() {
cat <<'HELP'
CMVR setup for Kylin Linux x86 (Qt 5.12+, CMake 3.16+).
bash setup_kylin.sh Install Qt and development/runtime dependencies
bash setup_kylin.sh --source /path/qt_client Install, configure and build Release
bash setup_kylin.sh --app /path/CmvrControlStation
Install and check an existing Linux application
bash setup_kylin.sh --check Check installed tools/dependencies only
bash setup_kylin.sh --dry-run Print repository package plan without installing
Options:
--source DIR Full qt_client source tree, not the Windows ZIP
--app FILE Existing native Linux ELF application
--jobs N Parallel build jobs (default: 4)
--with-qtcreator Also install the optional Qt Creator IDE
--no-update Use current package metadata (e.g. prepared offline repositories)
--check Do not install, build, or generate a launcher
--dry-run Do not refresh repositories, install, build, or generate files
-h, --help Show this help
Run as the desktop user; the script invokes sudo only for package management.
No robot connections, motor commands or service restarts are performed.
HELP
}
detect_platform() {
[[ $(uname -s) == Linux ]] || { fail 'Run this script on the Kylin Linux computer.'; return 1; }
ARCH=$(uname -m)
case "$ARCH" in x86_64|i386|i486|i586|i686) ;; *) fail "Expected Linux x86, detected $ARCH"; return 1 ;; esac
OS_NAME=Linux
if [[ -r /etc/os-release ]]; then
# Standard distribution-owned identification file.
OS_NAME=$(. /etc/os-release; printf '%s' "${PRETTY_NAME:-Linux}")
fi
if have apt-get && have dpkg; then PM=apt
elif have dnf; then PM=dnf
elif have yum; then PM=yum
else fail 'No supported package manager: apt-get, dnf or yum.'; return 1
fi
log "System: $OS_NAME; architecture: $ARCH; package manager: $PM"
}
package_available() {
local pkg=$1 candidate
if [[ $PM == apt ]]; then
candidate=$(apt-cache policy "$pkg" 2>/dev/null | awk '/Candidate:/ {print $2; exit}')
[[ -n $candidate && $candidate != '(none)' ]]
else
# rpm -q handles packages already installed but absent from current repository metadata.
rpm -q "$pkg" >/dev/null 2>&1 || "$PM" -q list "$pkg" >/dev/null 2>&1
fi
}
select_package() {
local required=$1 label=$2 pkg
shift 2
for pkg in "$@"; do
if package_available "$pkg"; then
PACKAGES+=("$pkg")
return 0
fi
done
if [[ $required == required ]]; then
MISSING+=("$label: $*")
else
log "Optional package unavailable ($label): $*"
fi
}
resolve_packages() {
PACKAGES=(); MISSING=()
if [[ $PM == apt ]]; then
select_package required 'C/C++ compiler' build-essential
select_package required CMake cmake
select_package required 'build tool' ninja-build make
select_package required pkg-config pkg-config pkgconf
select_package required 'Qt5 base development' qtbase5-dev
select_package required 'Qt5 development tools' qtbase5-dev-tools
select_package required 'Qt5 qmake' qt5-qmake
select_package required 'Qt5 multimedia' qtmultimedia5-dev
select_package required 'Qt5 3D modules' qt3d5-dev
select_package required 'Qt3D mesh plugin' qt3d-assimpsceneimport-plugin
select_package required 'Protobuf development' libprotobuf-dev
select_package required protoc protobuf-compiler
select_package required 'gRPC C++ development' libgrpc++-dev
select_package required 'gRPC code generator' protobuf-compiler-grpc
select_package required 'FFmpeg codec' libavcodec-dev
select_package required 'FFmpeg utility' libavutil-dev
select_package required 'FFmpeg scaling' libswscale-dev
select_package required urdfdom liburdfdom-dev
select_package required TinyXML libtinyxml-dev
select_package required Assimp libassimp-dev
select_package required OpenGL libgl1-mesa-dev libgl-dev
select_package required 'XCB integration' libxcb-xinerama0
select_package optional 'XCB cursor' libxcb-cursor0
select_package optional 'Qt Wayland integration' qtwayland5
select_package optional 'Qt multimedia backend' libqt5multimedia5-plugins
select_package optional 'GStreamer base codecs' gstreamer1.0-plugins-base
select_package optional 'GStreamer additional codecs' gstreamer1.0-plugins-good
select_package optional 'Mesa diagnostics' mesa-utils
select_package optional 'Chinese fonts' fonts-noto-cjk fonts-wqy-microhei
select_package required 'ELF inspection' file
select_package required 'Python examples' python3
if (( WITH_CREATOR )); then select_package required QtCreator qtcreator; fi
else
select_package required 'C compiler' gcc
select_package required 'C++ compiler' gcc-c++
select_package required CMake cmake cmake3
select_package required 'build tool' ninja-build make
select_package required pkg-config pkgconf-pkg-config pkgconfig
select_package required 'Qt5 base development' qt5-qtbase-devel
select_package required 'Qt5 multimedia' qt5-qtmultimedia-devel
select_package required 'Qt5 3D modules' qt5-qt3d-devel
select_package required 'Qt3D runtime/plugins' qt5-qt3d
select_package required 'Protobuf development' protobuf-devel
select_package required protoc protobuf-compiler
select_package required 'gRPC development' grpc-devel
select_package optional 'gRPC C++ split package' grpc-c++-devel grpc-c++
select_package required 'gRPC code generator' grpc-plugins
select_package required FFmpeg ffmpeg-devel
select_package required urdfdom urdfdom-devel
select_package required TinyXML tinyxml-devel
select_package required Assimp assimp-devel
select_package required OpenGL mesa-libGL-devel libglvnd-devel
select_package required 'XCB integration' xcb-util-wm
select_package optional 'XCB image support' xcb-util-image
select_package optional 'XCB key support' xcb-util-keysyms
select_package optional 'XCB render support' xcb-util-renderutil
select_package optional 'XCB cursor' xcb-util-cursor
select_package optional 'Qt5 graphics integration' qt5-qtbase-gui
select_package optional 'Qt Wayland integration' qt5-qtwayland
select_package optional 'GStreamer base codecs' gstreamer1-plugins-base
select_package optional 'GStreamer additional codecs' gstreamer1-plugins-good
select_package optional 'Mesa diagnostics' glx-utils
select_package optional 'Chinese fonts' google-noto-sans-cjk-fonts wqy-microhei-fonts
select_package required 'ELF inspection' file
select_package required 'Python examples' python3
if (( WITH_CREATOR )); then select_package required QtCreator qt-creator qtcreator; fi
fi
if ((${#MISSING[@]})); then
printf '\nRequired packages unavailable in this system\047s repositories:\n' >&2
printf ' %s\n' "${MISSING[@]}" >&2
fail 'Ask the system administrator to enable the matching Kylin development/media repositories, then rerun. No foreign repositories were added.'
return 1
fi
}
install_packages() {
local -a privilege=()
if (( EUID != 0 )); then
have sudo || { fail 'Package installation requires root or sudo.'; return 1; }
privilege=(sudo)
fi
if (( UPDATE_METADATA )); then
log 'Refreshing configured repository metadata...'
if [[ $PM == apt ]]; then "${privilege[@]}" apt-get update
else "${privilege[@]}" "$PM" makecache
fi
fi
resolve_packages
log 'Installing Qt5 and CMVR dependencies...'
if [[ $PM == apt ]]; then
"${privilege[@]}" apt-get install -y --no-install-recommends "${PACKAGES[@]}"
else
"${privilege[@]}" "$PM" install -y "${PACKAGES[@]}"
fi
}
version_at_least() {
[[ $(printf '%s\n%s\n' "$2" "$1" | sort -V | head -n 1) == "$2" ]]
}
probe_dependencies() {
local tool qt_version cmake_version tmp status
CMAKE_TOOL=''
for tool in cmake cmake3; do
if have "$tool"; then
cmake_version=$("$tool" --version | awk 'NR==1 {print $3}')
if version_at_least "$cmake_version" 3.16; then CMAKE_TOOL=$(command -v "$tool"); break; fi
fi
done
[[ -n $CMAKE_TOOL ]] || { fail 'CMake >= 3.16 is required; repository package is too old or missing.'; return 1; }
QMAKE_TOOL=''
for tool in qmake-qt5 qmake /usr/lib64/qt5/bin/qmake /usr/lib/qt5/bin/qmake; do
if have "$tool"; then
qt_version=$("$tool" -query QT_VERSION 2>/dev/null) || continue
if [[ $qt_version == 5.* ]] && version_at_least "$qt_version" 5.12; then
QMAKE_TOOL=$(command -v "$tool"); break
fi
fi
done
[[ -n $QMAKE_TOOL ]] || { fail 'Qt 5.12+ qmake is required. Qt6 alone cannot build this Qt5 project.'; return 1; }
log "Using Qt $qt_version ($QMAKE_TOOL); CMake $cmake_version"
for tool in c++ pkg-config protoc grpc_cpp_plugin file python3; do
have "$tool" || { fail "Missing executable: $tool"; return 1; }
done
if ! python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3,9) else 1)'; then
log 'Python is older than 3.9: Qt UI builds can continue, but the classroom example requires Python 3.9+.'
fi
tmp=$(mktemp -d "${TMPDIR:-/tmp}/cmvr-dependency-probe.XXXXXXXX")
cat > "$tmp/CMakeLists.txt" <<'CMAKE'
cmake_minimum_required(VERSION 3.16)
project(CmvrDependencyProbe LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
find_package(Qt5 5.12 REQUIRED COMPONENTS Core Gui Widgets Network Multimedia 3DCore 3DRender 3DExtras 3DInput 3DAnimation)
find_package(Protobuf CONFIG QUIET)
if(NOT Protobuf_FOUND)
find_package(Protobuf REQUIRED)
endif()
find_package(gRPC CONFIG REQUIRED)
if(NOT TARGET protobuf::protoc OR NOT TARGET gRPC::grpc_cpp_plugin)
message(FATAL_ERROR "Protobuf/gRPC compiler CMake targets are missing")
endif()
find_package(PkgConfig REQUIRED)
pkg_check_modules(FFMPEG REQUIRED libavcodec libavutil libswscale)
find_path(URDF_INCLUDE urdf_parser/urdf_parser.h PATH_SUFFIXES include include/urdfdom)
find_path(TINYXML_INCLUDE tinyxml.h PATH_SUFFIXES include)
find_library(URDF_LIBRARY urdfdom_model)
if(NOT URDF_INCLUDE OR NOT TINYXML_INCLUDE OR NOT URDF_LIBRARY)
message(FATAL_ERROR "urdfdom or TinyXML development files are missing")
endif()
execute_process(COMMAND "${PROBE_QMAKE}" -query QT_INSTALL_PLUGINS OUTPUT_VARIABLE PLUGINS OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT EXISTS "${PLUGINS}/platforms/libqxcb.so")
message(FATAL_ERROR "Qt xcb platform plugin is missing")
endif()
if(NOT EXISTS "${PLUGINS}/sceneparsers/libassimpsceneimport.so")
message(FATAL_ERROR "Qt3D Assimp scene parser is missing; install the distribution's matching Qt3D mesh plugin")
endif()
message(STATUS "CMVR dependency probe passed")
CMAKE
status=0
"$CMAKE_TOOL" -S "$tmp" -B "$tmp/build" "-DPROBE_QMAKE=$QMAKE_TOOL" || status=$?
# Remove only the private directory just created by mktemp.
if [[ $tmp == "${TMPDIR:-/tmp}"/cmvr-dependency-probe.* ]]; then rm -rf -- "$tmp"; fi
(( status == 0 )) || { fail 'Dependency probe failed; review the CMake error above. Installation is not declared complete.'; return 1; }
check_plugin "$($QMAKE_TOOL -query QT_INSTALL_PLUGINS)/platforms/libqxcb.so"
check_plugin "$($QMAKE_TOOL -query QT_INSTALL_PLUGINS)/sceneparsers/libassimpsceneimport.so"
}
check_plugin() {
local file=$1 output
[[ -f $file ]] || { fail "File not found: $file"; return 1; }
if ! output=$(ldd "$file" 2>&1); then
printf '%s\n' "$output" >&2; fail "Cannot resolve ELF dependencies: $file"; return 1
fi
if [[ $output == *'not found'* ]]; then
printf '%s\n' "$output" >&2; fail "Missing shared libraries: $file"; return 1
fi
}
check_app() {
local app=$1 description
[[ -f $app ]] || { fail "Application not found: $app"; return 1; }
description=$(file -Lb -- "$app")
[[ $description == ELF* ]] || { fail 'Provide a native Linux ELF application, not the Windows .exe.'; return 1; }
if [[ $ARCH != x86_64 && $description == *64-bit* ]]; then fail 'A 64-bit application cannot run on this 32-bit OS.'; return 1; fi
check_plugin "$app"
log "ELF loader dependencies resolved: $app"
log 'If symbol/GLIBC/Qt ABI errors remain, rebuild from source on this machine. File presence alone does not prove ABI compatibility.'
}
build_source() {
local source=$1 output_dir build_dir
[[ -f $source/CMakeLists.txt && -f $source/src/main.cpp && -d $source/protos/cmvr ]] || {
fail '--source must point to the complete qt_client source tree.'; return 1;
}
build_dir=$source/build/kylin-release
log "Configuring Release in $build_dir"
"$CMAKE_TOOL" -S "$source" -B "$build_dir" -DCMAKE_BUILD_TYPE=Release -DCMVR_WITH_MSQUIC=OFF
"$CMAKE_TOOL" --build "$build_dir" --parallel "$JOBS"
APP=$source/bin/release/CmvrControlStation
check_app "$APP"
output_dir=$(dirname -- "$APP")
cat > "$output_dir/run_cmvr.sh" <<'LAUNCHER'
#!/usr/bin/env bash
set -euo pipefail
cd -- "$(dirname -- "$0")"
if [[ ${CMVR_SOFTWARE_OPENGL:-0} == 1 ]]; then
export QT_OPENGL=software LIBGL_ALWAYS_SOFTWARE=1
fi
exec ./CmvrControlStation "$@"
LAUNCHER
chmod u+x -- "$output_dir/run_cmvr.sh"
log "Ready: bash \"$output_dir/run_cmvr.sh\""
log 'For offline class: select Demo mode before connecting. This script does not launch the GUI or connect to devices.'
}
main() {
local source='' arg
APP=''; JOBS=4; WITH_CREATOR=0; UPDATE_METADATA=1; CHECK_ONLY=0; DRY_RUN=0
while (($#)); do
arg=$1; shift
case "$arg" in
--source|--app|--jobs)
(($#)) || { fail "Missing value for $arg"; return 2; }
case "$arg" in --source) source=$1 ;; --app) APP=$1 ;; --jobs) JOBS=$1 ;; esac
shift ;;
--with-qtcreator) WITH_CREATOR=1 ;;
--no-update) UPDATE_METADATA=0 ;;
--check) CHECK_ONLY=1 ;;
--dry-run) DRY_RUN=1 ;;
-h|--help) usage; return 0 ;;
*) fail "Unknown option: $arg"; usage; return 2 ;;
esac
done
[[ $JOBS =~ ^[1-9][0-9]*$ ]] || { fail '--jobs must be a positive integer.'; return 2; }
(( !(CHECK_ONLY && DRY_RUN) )) || { fail 'Choose either --check or --dry-run.'; return 2; }
if [[ -n $source ]]; then
[[ -d $source ]] || { fail "Source directory does not exist: $source"; return 2; }
source=$(cd -- "$source" && pwd -P)
[[ -f $source/CMakeLists.txt && -f $source/src/main.cpp ]] || { fail 'Source tree is incomplete.'; return 2; }
fi
if [[ -n $APP ]]; then
[[ -f $APP ]] || { fail "Application does not exist: $APP"; return 2; }
APP=$(cd -- "$(dirname -- "$APP")" && printf '%s/%s' "$PWD" "$(basename -- "$APP")")
fi
detect_platform
if (( DRY_RUN )); then
resolve_packages
log 'Dry run: required/available package plan (current metadata only)'
printf ' %s\n' "${PACKAGES[@]}"
log 'No sudo, installation, build or GUI launch was performed.'
return 0
fi
if (( ! CHECK_ONLY )); then install_packages; fi
probe_dependencies
if [[ -n $APP ]]; then check_app "$APP"; fi
if [[ -n $source ]] && (( ! CHECK_ONLY )); then build_source "$source"; fi
log 'Dependency checks passed. No devices were controlled.'
if [[ -z $source && -z $APP ]]; then
log 'To build: bash setup_kylin.sh --source /path/to/qt_client'
log 'To check a Linux release: bash setup_kylin.sh --check --app /path/to/CmvrControlStation'
fi
}
if [[ ${BASH_SOURCE[0]} == "$0" ]]; then main "$@"; fi

View File

@ -0,0 +1,63 @@
麒麟 Linux:一键安装 Qt 与 CMVR 上位机依赖
1. 把 setup_kylin.sh 复制到麒麟电脑,在该目录打开终端。
安装依赖(安装 Qt 库和开发工具,不默认安装 Qt Creator):
bash setup_kylin.sh
需要 Qt Creator IDE 时:
bash setup_kylin.sh --with-qtcreator
2. 如果电脑已有完整的 Linux 上位机源码,安装后直接构建 Release:
bash setup_kylin.sh --source /你的路径/qt_client
把路径替换为包含 CMakeLists.txt、src 和 protos 的工程目录。
默认4个编译任务,内存较小时可用 --jobs 2。
成功后输出为:qt_client/bin/release/CmvrControlStation。
启动:
bash /你的路径/qt_client/bin/release/run_cmvr.sh
3. 如果已有 Linux 版程序,只安装依赖并检查它:
bash setup_kylin.sh --app /你的路径/CmvrControlStation
该模式不编译,也不修改这个程序。安装的依赖来自当前系统仓库。
若它来自其他 Linux 版本,Qt/GLIBC/编译器 ABI 仍可能不兼容,需在本机重新构建。
4. 已安装过时可以仅检查:
bash setup_kylin.sh --check
bash setup_kylin.sh --check --app /你的路径/CmvrControlStation
仅查看当前仓库的安装计划:
bash setup_kylin.sh --dry-run
使用已准备好的离线/本地软件源,不刷新元数据:
bash setup_kylin.sh --no-update
--no-update 不代表随脚本附带了安装包;缺少包文件时仍需可访问的软件源。
脚本内容
自动识别 Linux x86 架构、系统名称及 APT / DNF / YUM。
按本机仓库中可用的包名安装 Qt5、Multimedia、Qt3D、Assimp网格插件、
Protobuf/gRPC、FFmpeg、urdfdom、TinyXML、OpenGL/XCB、CMake和编译工具。
安装后检查 Qt>=5.12、CMake>=3.16、CMake依赖、Qt平台与网格插件、ELF缺失库。
源码构建默认关闭 MsQuic/QUIC,不影响普通界面和演示模式。
普通上位机运行和课堂Python示例不依赖pip。手眼标定算法的Python扩展环境需另外准备。
课堂示例还要求Python>=3.9,版本不足时脚本会提示。
使用条件
需要已有正确的麒麟软件源和管理员安装权限,按提示输入sudo密码。
无需以root启动整个脚本;编译和生成启动器使用当前桌面用户。
本脚本不修改软件源、不禁用签名校验、不删除软件锁、不关闭防火墙。
仓库缺少必需包时会列出包名并停止;需管理员配置同版本开发/媒体仓库后重跑。
安装包、依赖或编译失败时不会显示“全部安装成功”。
发行版仓库内的版本可能不足,脚本会在实际检查中报告;不能保证所有麒麟版本无需调整。
没有把未经验证的 Ubuntu/Fedora 外部仓库强行加入麒麟系统。
注意
先前 Windows Release 压缩包中的 .exe 不能用这个脚本变成 Linux 程序。
本脚本包不含完整上位机源码或预编译 Linux 程序。
已有对应的 Linux 上位机后,勾选“演示模式”,地址填127.0.0.1,再连接即可用于无实物讲课。
脚本不会启动GUI、连接机器人、控制电机或重启cmvr-es。
图形驱动异常时,可尝试启动脚本的兼容选项:
CMVR_SOFTWARE_OPENGL=1 bash /你的路径/qt_client/bin/release/run_cmvr.sh
验证范围
已在开发机进行 Bash 语法检查与模拟包管理器测试,尚未在目标麒麟电脑上安装验证。
包名参考与项目要求:
项目 CMakeLists.txt 与 README.md
https://www.kylinos.cn/upload/1/kycms/20250617/1934877956515139584.pdf
https://packages.ubuntu.com/jammy/qt3d-assimpsceneimport-plugin
https://packages.fedoraproject.org/pkgs/qt5-qt3d/qt5-qt3d-devel/index.html

View File

@ -0,0 +1,59 @@
#pragma once
#include "cmvr/api/camera_command.pb.h"
#include <QImage>
#include <QString>
#include <cstring>
#include <limits>
inline QImage decodeCameraSnapshot(const cmvr::api::FrameData &frame, QString &error)
{
error.clear();
if (frame.data().size() > 64 * 1024 * 1024) {
error = QStringLiteral("RGB 图像数据超过 64 MiB");
return {};
}
const QString codec = QString::fromStdString(frame.codec()).trimmed().toLower();
const bool raw = codec.isEmpty() || codec == QStringLiteral("none");
if (!raw) {
const QImage image = QImage::fromData(
reinterpret_cast<const uchar *>(frame.data().data()),
static_cast<int>(qMin<size_t>(frame.data().size(), std::numeric_limits<int>::max())));
if (image.isNull()) error = QStringLiteral("不支持的抓图编码:%1").arg(codec);
return image;
}
const int channels = frame.type() == cmvr::api::FrameData::U8C1 ? 1 : 3;
const bool sixteen = frame.type() == cmvr::api::FrameData::U16C3;
const bool validSize = frame.width() > 0 && frame.height() > 0
&& frame.width() <= 16384 && frame.height() <= 16384;
const qint64 size = validSize
? qint64(frame.width()) * frame.height() * channels * (sixteen ? 2 : 1) : 0;
if (frame.width() <= 0 || frame.height() <= 0 || frame.width() > 16384 || frame.height() > 16384
|| (frame.type() != cmvr::api::FrameData::U8C1
&& frame.type() != cmvr::api::FrameData::U8C3 && !sixteen)
|| size > 64 * 1024 * 1024 || quint64(size) != frame.data().size()) {
error = QStringLiteral("RGB 图像数据无效:%1×%2,类型=%3,字节数=%4")
.arg(frame.width()).arg(frame.height()).arg(frame.type()).arg(qulonglong(frame.data().size()));
return {};
}
const auto *data = reinterpret_cast<const uchar *>(frame.data().data());
if (!sixteen) {
const QImage borrowed(data, frame.width(), frame.height(), frame.width() * channels,
channels == 1 ? QImage::Format_Grayscale8 : QImage::Format_RGB888);
return channels == 1 ? borrowed.copy() : borrowed.rgbSwapped();
}
QImage image(frame.width(), frame.height(), QImage::Format_RGB888);
if (image.isNull()) { error = QStringLiteral("RGB 图像内存分配失败"); return {}; }
// Server serializes native OpenCV BGR16. Map the full 16-bit range to display RGB8.
for (int y = 0; y < frame.height(); ++y) {
uchar *out = image.scanLine(y);
for (int x = 0; x < frame.width(); ++x) {
for (int c = 0; c < 3; ++c) {
quint16 value;
std::memcpy(&value, data + (qint64(y) * frame.width() * 3 + x * 3 + (2 - c)) * 2, 2);
out[x * 3 + c] = uchar(value >> 8);
}
}
}
return image;
}

140
src/demosimulator.cpp Normal file
View File

@ -0,0 +1,140 @@
#include "demosimulator.h"
#include <QMutexLocker>
#include <QDateTime>
#include <QJsonDocument>
#include <QImage>
#include <QtCore/QBuffer>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/util/json_util.h>
#include <cmath>
#include <memory>
#include <QColor>
namespace {
QJsonObject protoJson(const google::protobuf::Message& message);
QJsonValue protoValue(const google::protobuf::Message& m,const google::protobuf::FieldDescriptor* f,int index=-1){
using F=google::protobuf::FieldDescriptor;const auto* r=m.GetReflection();const bool repeated=index>=0;
switch(f->cpp_type()){
case F::CPPTYPE_MESSAGE:return protoJson(repeated?r->GetRepeatedMessage(m,f,index):r->GetMessage(m,f));
case F::CPPTYPE_BOOL:return repeated?r->GetRepeatedBool(m,f,index):r->GetBool(m,f);
case F::CPPTYPE_DOUBLE:return repeated?r->GetRepeatedDouble(m,f,index):r->GetDouble(m,f);
case F::CPPTYPE_FLOAT:return double(repeated?r->GetRepeatedFloat(m,f,index):r->GetFloat(m,f));
case F::CPPTYPE_INT32:return repeated?r->GetRepeatedInt32(m,f,index):r->GetInt32(m,f);
case F::CPPTYPE_UINT32:return double(repeated?r->GetRepeatedUInt32(m,f,index):r->GetUInt32(m,f));
case F::CPPTYPE_INT64:return QString::number(repeated?r->GetRepeatedInt64(m,f,index):r->GetInt64(m,f));
case F::CPPTYPE_UINT64:return QString::number(repeated?r->GetRepeatedUInt64(m,f,index):r->GetUInt64(m,f));
case F::CPPTYPE_ENUM:return QString::fromStdString((repeated?r->GetRepeatedEnum(m,f,index):r->GetEnum(m,f))->name());
case F::CPPTYPE_STRING:{const auto value=repeated?r->GetRepeatedString(m,f,index):r->GetString(m,f);return f->type()==F::TYPE_BYTES?QString::fromLatin1(QByteArray::fromStdString(value).toBase64()):QString::fromStdString(value);}
}return QJsonValue();
}
QJsonObject protoJson(const google::protobuf::Message& m){
QJsonObject result;const auto* d=m.GetDescriptor();const auto* r=m.GetReflection();
for(int i=0;i<d->field_count();++i){const auto* f=d->field(i);const QString name=QString::fromStdString(f->name());
if(f->is_map()){QJsonObject map;for(int j=0;j<r->FieldSize(m,f);++j){const auto& entry=r->GetRepeatedMessage(m,f,j);const auto* key=entry.GetDescriptor()->FindFieldByName("key");const auto* value=entry.GetDescriptor()->FindFieldByName("value");map.insert(protoValue(entry,key).toVariant().toString(),protoValue(entry,value));}result.insert(name,map);}
else if(f->is_repeated()){QJsonArray values;for(int j=0;j<r->FieldSize(m,f);++j)values.append(protoValue(m,f,j));result.insert(name,values);}
else if(f->has_presence()&&!r->HasField(m,f))continue;
else if(f->cpp_type()==google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE&&f->message_type()->full_name()=="google.protobuf.Timestamp"){
const auto& stamp=r->GetMessage(m,f);const auto* sr=stamp.GetReflection();const auto* sd=stamp.GetDescriptor();const qint64 seconds=sr->GetInt64(stamp,sd->FindFieldByName("seconds"));const auto nanos=sr->GetInt32(stamp,sd->FindFieldByName("nanos"));result.insert(name,QDateTime::fromMSecsSinceEpoch(seconds*1000+nanos/1000000,Qt::UTC).toString(Qt::ISODateWithMs));
}else result.insert(name,protoValue(m,f));
}return result;
}
QJsonValue item(const QJsonArray& a,int i){return i>=0&&i<a.size()?a[i]:QJsonValue();}
QJsonValue field(const QJsonObject& q,const char* snake,const char* camel){return q.contains(snake)?q.value(snake):q.value(camel);}
QJsonArray names(const QString& id){QJsonArray a;const QString prefix=id.contains("left")?"L_":"R_";for(const auto& n:QStringList{"SHOULDER_P","SHOULDER_R","SHOULDER_Y","ELBOW_R","WRIST_P","WRIST_Y","WRIST_R"})a.append(prefix+n);return a;}
}
DemoSimulator& DemoSimulator::instance(){static DemoSimulator value;return value;}
void DemoSimulator::reset(){QMutexLocker lock(&m_mutex);m_devices.clear();}
QJsonObject DemoSimulator::sampleLocked(Device& d){
if(d.target.isEmpty()){for(int i=0;i<7;++i)d.target.append(0.0);d.from=d.target;}
const double t=d.duration? qBound(0.0,double(QDateTime::currentMSecsSinceEpoch()-d.started)/d.duration,1.0):1.0;
const double smooth=t*t*(3-2*t);QJsonArray position;
for(int i=0;i<d.target.size();++i)position.append(item(d.from,i).toDouble()+(d.target[i].toDouble()-item(d.from,i).toDouble())*smooth);
if(d.pose.isEmpty())d.pose={{"x",.42},{"y",-.18},{"z",.73},{"rx",0},{"ry",0},{"rz",0}};
auto pose=d.pose;if(!d.poseFrom.isEmpty())for(auto it=pose.begin();it!=pose.end();++it)if(it.value().isDouble())it.value()=d.poseFrom.value(it.key()).toDouble()+(it.value().toDouble()-d.poseFrom.value(it.key()).toDouble())*smooth;
return {{"position",position},{"pose",pose},{"moving",t<1},{"progress",t},{"map",d.settings.value("map").toString("demo_factory")},{"station",d.settings.value("station").toString("station_a")},{"enabled",d.settings.value("enabled").toBool(true)}};
}
QJsonObject DemoSimulator::sample(const QString& id){QMutexLocker lock(&m_mutex);return sampleLocked(m_devices[id]);}
void DemoSimulator::stop(const QString& id){QMutexLocker lock(&m_mutex);auto& d=m_devices[id];auto snapshot=sampleLocked(d);d.target=snapshot.value("position").toArray();d.pose=snapshot.value("pose").toObject();d.poseFrom={};d.from=d.target;d.duration=0;}
DemoSimulator::Reply DemoSimulator::call(const QString& service,const QString& method,const QJsonObject& request){
QMutexLocker lock(&m_mutex);Reply reply;
const auto* s=google::protobuf::DescriptorPool::generated_pool()->FindServiceByName(service.toStdString());
const auto* rpc=s?s->FindMethodByName(method.toStdString()):nullptr;
if(!rpc){reply.response={{"success",false},{"error_message","Unknown simulated interface"}};return reply;}
google::protobuf::DynamicMessageFactory factory;
std::unique_ptr<google::protobuf::Message> input(factory.GetPrototype(rpc->input_type())->New()),output(factory.GetPrototype(rpc->output_type())->New());
const auto parsed=google::protobuf::util::JsonStringToMessage(QJsonDocument(request).toJson(QJsonDocument::Compact).toStdString(),input.get());
if(!parsed.ok()){reply.response={{"success",false},{"error_message",QString::fromStdString(parsed.ToString())}};return reply;}
const auto header=request.contains("header")?request.value("header").toObject():request;
QString id=field(header,"device_id","deviceId").toString();if(id.isEmpty())id="demo-device";
auto& d=m_devices[id];auto state=sampleLocked(d);
QJsonObject result;const QJsonObject feedback{{"success",true},{"error_message",QStringLiteral("演示模拟反馈:未连接真实设备")},{"command_id",field(header,"command_id","commandId")},{"timestamp",QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs)}};
if(rpc->output_type()->FindFieldByName("header"))result.insert("header",feedback);else result=feedback;
if(d.coordinates.isEmpty())d.coordinates.append(QJsonObject{{"name",QStringLiteral("演示工件坐标系")},{"revision","1"},{"user_pose",QJsonArray{0,0,0,0,0,0}},{"tcp_offset",QJsonArray{0,0,0,0,0,0}}});
if(service.endsWith("ArmService")){
if(method=="moveJ"||method=="servoJ"||method=="moveJPose"||method=="moveL"||method=="speedJ"||method=="speedL"){
d.from=state.value("position").toArray();auto target=request.value("target").toObject().value("position").toArray();
if(method=="speedJ"){
target={};const auto speeds=request.value("velocity").toObject().value("velocity").toArray();for(int i=0;i<d.from.size();++i)target.append(d.from[i].toDouble()+item(speeds,i).toDouble()*request.value("duration").toDouble(1));
}
if(target.isEmpty()){
// Visual demonstration only: this is not a physical inverse-kinematics solver.
d.poseFrom=state.value("pose").toObject();d.pose=request.value("target").toObject();if(d.pose.isEmpty())d.pose=state.value("pose").toObject();
for(int i=0;i<d.from.size();++i)target.append(d.from[i].toDouble()+.15*(i%2?1:-1));
}
d.target=target;d.started=QDateTime::currentMSecsSinceEpoch();d.duration=1200;reply.delayMs=1200;
}
if(method=="stopMotion"||method=="ExitTeachingMode"){d.target=state.value("position").toArray();d.from=d.target;d.duration=0;}
if(method=="torqueOn"||method=="torqueOff")d.settings.insert("enabled",method=="torqueOn");
if(method=="calibrateZeroQ"){d.from=state.value("position").toArray();d.target=d.from;const int index=names(id).toVariantList().indexOf(request.value("joint_name").toString());if(index>=0)d.target[index]=0;d.duration=0;}
if(method=="GetArmInfo")result={{"header",feedback},{"device_id",id},{"manufacturer","CMVR Demo"},{"model","Simulated 7-axis arm"},{"dof",7},{"joint_names",names(id)},{"default_base_frame","base"},{"default_tcp_frame","tool0"},{"description_id","demo"}};
if(method=="getJointState")result.insert("state",QJsonObject{{"name",names(id)},{"position",state.value("position")},{"velocity",QJsonArray{0,0,0,0,0,0,0}}});
if(method=="getRobotState")result.insert("state",QJsonObject{{"is_connected",true},{"is_powered_on",true},{"is_moving",state.value("moving")}});
if(method=="getPose"||method=="computeForwardKinematics")result.insert("pose",state.value("pose"));
if(method=="ListBaseFrame"||method=="ListTCPFrame")result.insert("frame_names",method=="ListBaseFrame"?QJsonArray{"base","world"}:QJsonArray{"tool0","tcp"});
if(method=="CreateUserCoordinateSystem"||method=="UpdateUserCoordinateSystem"||method=="CalibrateUserCoordinateSystem"){
auto c=request.value("coordinate").toObject();if(c.isEmpty())c={{"name",request.value("name")},{"user_pose",QJsonArray{0,0,0,0,0,0}}};if(c.value("name").toString().isEmpty())c.insert("name",QStringLiteral("演示坐标系"));c.insert("revision","1");d.coordinates.append(c);result.insert("coordinate",c);
}
if(method=="ApplyUserCoordinateSystem")d.activeCoordinate=request.value("name").toString();
if(method=="DeleteUserCoordinateSystem")for(int i=d.coordinates.size()-1;i>=0;--i)if(d.coordinates[i].toObject().value("name")==request.value("name"))d.coordinates.removeAt(i);
if(method=="GetUserCoordinateSystem"||method=="ApplyUserCoordinateSystem")for(const auto& c:d.coordinates)if(c.toObject().value("name")==request.value("name"))result.insert("coordinate",c);
if(method=="ListUserCoordinateSystems")result.insert("coordinates",d.coordinates);
if(method=="ExecuteJsonCommand")result.insert("response_json",QString::fromUtf8(QJsonDocument(QJsonObject{{"simulation",true},{"coordinate_api_version",4},{"movel_target_mode","absolute_selected_frame"},{"active_coordinate",d.activeCoordinate}}).toJson(QJsonDocument::Compact)));
}
if(service.endsWith("AgvService")){
if(method=="listMaps")result.insert("maps",QJsonArray{"demo_factory","demo_lab"});
if(method=="listStations")result.insert("stations",QJsonArray{QJsonObject{{"id","station_a"},{"description",QStringLiteral("演示工作站 A")}},QJsonObject{{"id","station_b"},{"description",QStringLiteral("演示工作站 B")}}});
if(method=="switchMap")d.settings.insert("map",field(request,"map_name","mapName"));
if(method.startsWith("navigate")||method=="followPath"||method=="translate"){d.settings.insert("station",field(request,"station_id","stationId"));d.poseFrom=state.value("pose").toObject();d.pose=request.value("pose").toObject();if(d.pose.isEmpty())d.pose={{"x",d.settings.value("station")=="station_b"?3.0:1.0},{"y",2.0},{"theta",0.0}};d.started=QDateTime::currentMSecsSinceEpoch();d.duration=1200;reply.delayMs=1200;}
const auto now=sampleLocked(d);result.insert("state",QJsonObject{{"connected",true},{"localized",true},{"moving",now.value("moving")},{"current_map",now.value("map")},{"current_station",now.value("station")},{"battery",QJsonObject{{"percentage",.9},{"voltage",48.0}}},{"pose",now.value("pose")}});
}
if(service.endsWith("MotorService")){
const int node=field(request,"node_id","nodeId").toInt(1);auto info=QJsonObject{{"manager_id",id},{"node_id",node},{"joint_name",QString("demo_joint_%1").arg(node)},{"driver","DemoMotor"},{"limit_q_lb",-3.14},{"limit_q_ub",3.14},{"limit_qd",2},{"limit_qdd",5}};
if(method=="ListMotors"){QJsonArray motors;for(int i=1;i<=7;++i){auto m=info;m.insert("node_id",i);m.insert("joint_name",QString("demo_joint_%1").arg(i));motors.append(m);}result.insert("motors",motors);}
const QString key=QString::number(node);auto motor=d.settings.value(key).toObject();
for(const auto& name:QStringList{"q","qd","qdd","tau","mode"})if(request.contains(name)&&!(method.startsWith("get")||method.startsWith("Get")))motor.insert(name,request.value(name));
if(method=="torqueOn"||method=="torqueOff")motor.insert("enabled",method=="torqueOn");d.settings.insert(key,motor);auto feedbackState=motor;feedbackState.insert("position",motor.value("q").toDouble());feedbackState.insert("velocity",motor.value("qd").toDouble());feedbackState.insert("torque",motor.value("tau").toDouble());feedbackState.insert("feedback_valid",true);feedbackState.insert("status_valid",true);feedbackState.insert("sampled_at_s",QDateTime::currentMSecsSinceEpoch()/1000.0);result.insert("info",info);result.insert("state",feedbackState);result.insert("reached_target",true);result.insert("driver_acknowledged",true);
}
if(method=="StartRecording"||method=="StartRecord")d.settings.insert("is_recording",true);
if(method=="StopRecording"||method=="StopRecord")d.settings.insert("is_recording",false);
if(method=="PlayAudio")d.settings.insert("is_playing",true);
if(method=="StopPlayback")d.settings.insert("is_playing",false);
if(method=="GetStatus"&&!service.endsWith("CameraService")&&!service.endsWith("DexHandService")){auto status=d.settings;status.insert("is_initialized",true);status.insert("is_opened",true);result.insert("state",status);}
if(method=="SetVolume")d.settings.insert("volume",request.value("volume"));
if(method=="GetVolume")result.insert("volume",d.settings.value("volume").toInt(50));
if(method.startsWith("SetDexHand"))d.settings.insert("values",request.value("values"));
if(service.endsWith("DexHandService")&&method=="GetStatus"){
QJsonArray freedoms;for(int i=0;i<6;++i)freedoms.append(QJsonObject{{"dof_id",i},{"angle",item(d.settings.value("values").toArray(),i).toObject().value("value").toInt()}});
result.insert("state",QJsonObject{{"is_initialized",true},{"model","Demo Hand"},{"hands",freedoms}});
}
if(method=="GetStatus"&&service.endsWith("CameraService"))result.insert("state",QJsonObject{{"is_initialized",true},{"is_opened",true},{"is_recording",d.settings.value("is_recording").toBool()},{"width",640},{"height",480},{"fps",30},{"codec","h264"},{"capabilities",QJsonObject{{"depth_image",true},{"depth_stream",true},{"metric_aligned_depth",true}}}});
if(service.endsWith("CameraService")&&(method=="GetRGBImage"||method=="GetDepthImage"||method=="GetRGBDImages")){
QImage image(320,240,QImage::Format_RGB888);image.fill(QColor("#1b6ef3"));QByteArray bytes;QBuffer buffer(&bytes);buffer.open(QIODevice::WriteOnly);image.save(&buffer,"PNG");
const QJsonObject frame{{"width",320},{"height",240},{"codec","png"},{"data",QString::fromLatin1(bytes.toBase64())}};result.insert("color_frame",frame);result.insert("depth_frame",frame);
}
// A typed default feedback exists for every reflected unary/streaming method.
// Specialized handlers above provide visible state for common device operations.
google::protobuf::util::JsonParseOptions options;options.ignore_unknown_fields=true;
auto converted=google::protobuf::util::JsonStringToMessage(QJsonDocument(result).toJson(QJsonDocument::Compact).toStdString(),output.get(),options);
if(!converted.ok()){reply.response={{"success",false},{"error_message",QString::fromStdString(converted.ToString())}};return reply;}
reply.response=protoJson(*output);reply.ok=true;return reply;
}

21
src/demosimulator.h Normal file
View File

@ -0,0 +1,21 @@
#pragma once
#include <QJsonObject>
#include <QJsonArray>
#include <QVariantList>
#include <QMutex>
#include <QHash>
// Shared by the UI RPC runner and the legacy worker; never opens a connection.
class DemoSimulator {
public:
struct Reply {bool ok=false;QJsonObject response;int delayMs=30;};
static DemoSimulator& instance();
void reset();
Reply call(const QString& service,const QString& method,const QJsonObject& request);
QJsonObject sample(const QString& id);
void stop(const QString& id);
private:
struct Device {QJsonArray from,target;QJsonObject pose,poseFrom;QJsonObject settings;QJsonArray coordinates;QString activeCoordinate;qint64 started=0;int duration=0;};
QJsonObject sampleLocked(Device&);
QMutex m_mutex;
QHash<QString,Device> m_devices;
};

View File

@ -3,6 +3,9 @@
#include "videorenderwidget.h"
#include "applicationsettings.h"
#include "applicationstyle.h"
#include "urdfviewerwidget.h"
#include <QDateTime>
#include <QDebug>
#include <QApplication>
#include <QCheckBox>
@ -19,6 +22,20 @@
#include <dbghelp.h>
namespace {
HANDLE diagnosticLog=INVALID_HANDLE_VALUE;
QtMessageHandler previousMessageHandler=nullptr;
void diagnosticMessage(QtMsgType type,const QMessageLogContext& context,const QString& message){
const auto line=(QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs)+QString(" [tid=%1 type=%2 %3] ").arg(GetCurrentThreadId()).arg(int(type)).arg(QString::fromLatin1(context.category?context.category:"default"))+message+"\r\n").toUtf8();
if(diagnosticLog!=INVALID_HANDLE_VALUE){DWORD written;WriteFile(diagnosticLog,line.constData(),DWORD(line.size()),&written,nullptr);FlushFileBuffers(diagnosticLog);}
if(previousMessageHandler)previousMessageHandler(type,context,message);
}
void installDiagnosticLog(){
wchar_t path[MAX_PATH]={};GetModuleFileNameW(nullptr,path,MAX_PATH);if(auto* slash=wcsrchr(path,L'\\'))*slash=0;
wchar_t directory[MAX_PATH]={};_snwprintf(directory,MAX_PATH-1,L"%ls\\crash_dumps",path);CreateDirectoryW(directory,nullptr);
wchar_t logPath[MAX_PATH]={};_snwprintf(logPath,MAX_PATH-1,L"%ls\\runtime_%lu.log",directory,GetCurrentProcessId());
diagnosticLog=CreateFileW(logPath,FILE_APPEND_DATA,FILE_SHARE_READ|FILE_SHARE_WRITE,nullptr,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,nullptr);
previousMessageHandler=qInstallMessageHandler(diagnosticMessage);
}
LONG WINAPI writeCrashDump(EXCEPTION_POINTERS *exceptionPointers)
{
@ -49,6 +66,7 @@ LONG WINAPI writeCrashDump(EXCEPTION_POINTERS *exceptionPointers)
_snwprintf(dumpPath, MAX_PATH - 1, L"%ls\\%ls.dmp", dumpDirectory, baseName);
HANDLE dumpFile = CreateFileW(dumpPath, GENERIC_WRITE, FILE_SHARE_READ, nullptr,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
BOOL dumpWritten=FALSE;DWORD dumpError=0;
if (dumpFile != INVALID_HANDLE_VALUE) {
MINIDUMP_EXCEPTION_INFORMATION exceptionInfo = {};
exceptionInfo.ThreadId = GetCurrentThreadId();
@ -57,12 +75,14 @@ LONG WINAPI writeCrashDump(EXCEPTION_POINTERS *exceptionPointers)
const MINIDUMP_TYPE dumpType = static_cast<MINIDUMP_TYPE>(
MiniDumpWithDataSegs | MiniDumpWithHandleData |
MiniDumpWithThreadInfo | MiniDumpWithIndirectlyReferencedMemory);
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), dumpFile,
dumpWritten=MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), dumpFile,
dumpType, &exceptionInfo, nullptr, nullptr);
if(!dumpWritten)dumpError=GetLastError();
FlushFileBuffers(dumpFile);
CloseHandle(dumpFile);
}
else dumpError=GetLastError();
wchar_t summaryPath[MAX_PATH] = {};
_snwprintf(summaryPath, MAX_PATH - 1, L"%ls\\%ls.txt", dumpDirectory, baseName);
HANDLE summaryFile = CreateFileW(summaryPath, GENERIC_WRITE, FILE_SHARE_READ, nullptr,
@ -72,21 +92,24 @@ LONG WINAPI writeCrashDump(EXCEPTION_POINTERS *exceptionPointers)
? exceptionPointers->ExceptionRecord->ExceptionCode : 0;
const void *exceptionAddress = exceptionPointers && exceptionPointers->ExceptionRecord
? exceptionPointers->ExceptionRecord->ExceptionAddress : nullptr;
char summary[512] = {};
HMODULE faultModule=nullptr;wchar_t modulePath[MAX_PATH]={};
GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,reinterpret_cast<LPCWSTR>(exceptionAddress),&faultModule);
if(faultModule)GetModuleFileNameW(faultModule,modulePath,MAX_PATH);
char summary[2048] = {};
const int length = _snprintf(summary, sizeof(summary) - 1,
"Application: CmvrControlStation.exe\r\n"
"Timestamp: %04u-%02u-%02u %02u:%02u:%02u\r\n"
"Exception code: 0x%08lX\r\n"
"Exception address: %p\r\n"
"Process ID: %lu\r\nThread ID: %lu\r\n"
"Dump: %ls\r\n",
"Dump: %ls\r\nDumpWritten: %d Win32Error: %lu\r\nFaultModule: %ls\r\nModuleOffset: 0x%llx\r\nRuntimeLog: runtime_%lu.log\r\n",
time.wYear, time.wMonth, time.wDay,
time.wHour, time.wMinute, time.wSecond,
exceptionCode, exceptionAddress,
GetCurrentProcessId(), GetCurrentThreadId(), dumpPath);
GetCurrentProcessId(), GetCurrentThreadId(), dumpPath,int(dumpWritten),dumpError,modulePath,static_cast<unsigned long long>(reinterpret_cast<ULONG_PTR>(exceptionAddress)-reinterpret_cast<ULONG_PTR>(faultModule)),GetCurrentProcessId());
DWORD written = 0;
if (length > 0)
WriteFile(summaryFile, summary, static_cast<DWORD>(length), &written, nullptr);
WriteFile(summaryFile, summary, static_cast<DWORD>(qMin(length,int(sizeof(summary)-1))), &written, nullptr);
FlushFileBuffers(summaryFile);
CloseHandle(summaryFile);
}
@ -101,6 +124,9 @@ int main(int argc, char *argv[])
{
#ifdef Q_OS_WIN
SetUnhandledExceptionFilter(writeCrashDump);
SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
installDiagnosticLog();
for(int i=1;i<argc;++i)if(QString::fromLocal8Bit(argv[i])=="--crash-dump-self-test")RaiseException(0xE0434D56,EXCEPTION_NONCONTINUABLE,0,nullptr);
#endif
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
@ -111,7 +137,16 @@ int main(int argc, char *argv[])
app.setApplicationVersion(QStringLiteral("1.0.0"));
ApplicationStyle::install(app);
qInfo().noquote()<<"[STARTUP] Qt="<<qVersion()<<"app="<<QCoreApplication::applicationFilePath()<<"plugins="<<QCoreApplication::libraryPaths()<<"platform="<<QGuiApplication::platformName();
const QStringList args = app.arguments();
const int urdfSmoke=args.indexOf("--urdf-smoke");
if(urdfSmoke>=0&&urdfSmoke+1<args.size()){
UrdfViewerWidget viewer;viewer.resize(1000,760);viewer.show();const auto file=args[urdfSmoke+1];bool accepted=false;
QTimer::singleShot(100,&viewer,[&viewer,file,&accepted]{qInfo()<<"[SMOKE] load"<<file;accepted=viewer.loadUrdf(file);});
if(args.contains("--urdf-reload-smoke")){for(int delay:{1800,3600})QTimer::singleShot(delay,&viewer,[&viewer,file,&accepted]{qInfo()<<"[SMOKE] reload"<<file;accepted=viewer.loadUrdf(file)&&accepted;});}
QTimer::singleShot(6000,&app,[&viewer,&accepted]{qInfo()<<"[SMOKE] survived 6 seconds";viewer.saveDiagnosticViewport(QDir(QCoreApplication::applicationDirPath()).filePath("crash_dumps/urdf-viewport.png"));viewer.grab().save(QDir(QCoreApplication::applicationDirPath()).filePath("crash_dumps/urdf-smoke.png"));qApp->exit(accepted?0:2);});
return app.exec();
}
if (args.contains(QStringLiteral("--quic-smoke-test"))) {
QFile logFile(QDir(QCoreApplication::applicationDirPath())
.filePath(QStringLiteral("quic-smoke.log")));

View File

@ -1,3 +1,7 @@
#include "snapshotimageview.h"
#include "taskapi.h"
#include "taskrpcrunner.h"
#include "taskdeviceoptions.h"
#include "mainwindow.h"
#include "applicationsettings.h"
#include "applicationstyle.h"
@ -681,9 +685,24 @@ MainWindow::MainWindow(QWidget *parent)
connect(motorDebugPage,&MotorDebugWidget::statusMessage,this,&MainWindow::appendLog);
connect(m_taskOrchestration, &TaskOrchestrationWidget::statusMessage,
this, &MainWindow::appendLog);
auto* taskRpcRunner=new TaskRpcRunner(m_client,this);
connect(m_taskOrchestration,&TaskOrchestrationWidget::executionStopped,taskRpcRunner,&TaskRpcRunner::cancel);
connect(m_taskOrchestration, &TaskOrchestrationWidget::taskRequested, this,
[this](const QString &deviceType, const QString &deviceId,
[this,taskRpcRunner](const QString &deviceType, const QString &deviceId,
const QString &action, const QJsonObject &parameters) {
const auto api=TaskApi::operation(deviceType,action);
if(!api.isEmpty()){
const quint64 generation=m_taskOrchestration->executionGeneration();
taskRpcRunner->run(TaskApi::execution(deviceType,action,deviceId,parameters),
[this,generation,api,deviceId](bool ok,const QString& response){
if(api.value("service")=="cmvr.api.ArmService"&&(api.value("method")=="torqueOn"||api.value("method")=="torqueOff")){
QString detail;const bool accepted=TaskApi::responseSucceeded(ok,response,detail);
emit m_client->torqueFinished(deviceId,api.value("method")=="torqueOn",accepted,detail);
}
if(generation==m_taskOrchestration->executionGeneration())m_taskOrchestration->completeRpcTask(api.value("service").toString(),api.value("method").toString(),ok,response);
});
return;
}
bool dispatched = false;
if (deviceType == QStringLiteral("机械臂")) {
if (action == QStringLiteral("MoveJ")) {
@ -750,17 +769,20 @@ MainWindow::MainWindow(QWidget *parent)
} else if (deviceType == QStringLiteral("AGV")) {
if (action == QStringLiteral("导航站点")) {
dispatched = true;
m_client->requestAgvNavigateStation(deviceId,
parameters.value(QStringLiteral("stationId")).toString(),
parameters.value(QStringLiteral("maxSpeed")).toDouble(0.5));
const quint64 generation=m_taskOrchestration->executionGeneration();
const QJsonObject ex{{"service","cmvr.api.AgvService"},{"method","navigateToStation"},{"timeoutMs",180000},{"request",QJsonObject{{"header",QJsonObject{{"device_id",deviceId}}},{"station_id",parameters.value("stationId")},{"options",QJsonObject{{"max_speed",parameters.value("maxSpeed").toDouble(.5)}}}}}};
taskRpcRunner->run(ex,[this,generation,deviceId,action](bool ok,const QString& response){
if(generation!=m_taskOrchestration->executionGeneration())return;QString detail;const bool success=TaskApi::responseSucceeded(ok,response,detail);
m_taskOrchestration->completeActionTask(QStringLiteral("AGV"),deviceId,action,success,detail);
});
} else if (action == QStringLiteral("停止")
|| action == QStringLiteral("暂停")
|| action == QStringLiteral("继续")) {
dispatched = true;
const QHash<QString, QString> commands = {
{QStringLiteral("停止"), QStringLiteral("stop")},
{QStringLiteral("暂停"), QStringLiteral("pause")},
{QStringLiteral("继续"), QStringLiteral("resume")}};
{QStringLiteral("停止"), QStringLiteral("Cancel")},
{QStringLiteral("暂停"), QStringLiteral("Pause")},
{QStringLiteral("继续"), QStringLiteral("Resume")}};
m_client->requestAgvAction(deviceId, commands.value(action));
}
} else if (deviceType == QStringLiteral("灵巧手")) {
@ -925,6 +947,19 @@ MainWindow::MainWindow(QWidget *parent)
connect(m_client, &RobotClient::connectionChanged, this, &MainWindow::updateConnection);
connect(m_client, &RobotClient::armInfoReceived, this, &MainWindow::updateArmInfo);
connect(m_client,&RobotClient::armInfoReceived,m_taskOrchestration,&TaskOrchestrationWidget::setDeviceInfo);
connect(m_client,&RobotClient::connectionChanged,this,[this](bool connected,int,const QString&){if(!connected)m_taskOrchestration->clearDeviceInfo();});
auto* taskOptions=new TaskDeviceOptions(m_client,m_taskOrchestration,this);
connect(m_taskOrchestration,&TaskOrchestrationWidget::deviceInfoRequested,taskOptions,&TaskDeviceOptions::load);
connect(m_taskOrchestration,&TaskOrchestrationWidget::deviceInfoRequested,this,[this](const QString& id,const QString& type){
if(type==QStringLiteral("机械臂"))m_client->requestArmInfo(id);
else if(type==QStringLiteral("灵巧手"))m_client->requestDexHandStatus(id);
});
connect(m_client,&RobotClient::dexHandStatusReceived,this,[this](const QString& id,bool,bool,const QString&,const QVariantList& freedoms){
QStringList names;QVariantList ids;for(const auto& item:freedoms){const auto f=item.toMap();const int channel=f.value("id").toInt();ids<<channel;names<<QStringLiteral("关节 / 通道 %1").arg(channel);}
if(!names.isEmpty())m_taskOrchestration->setDeviceInfo(id,{{"jointNames",names},{"channelIds",ids},{"dof",names.size()}});
});
connect(m_client, &RobotClient::telemetryReceived, this, &MainWindow::updateTelemetry);
connect(m_client, &RobotClient::armTelemetryHealthChanged,
this, &MainWindow::updateArmTelemetryHealth);
@ -966,7 +1001,7 @@ MainWindow::MainWindow(QWidget *parent)
m_client->requestCameraCapabilities(m_activeCameraId,++m_cameraCapabilitiesToken);
}); capabilityTimer->start();
connect(m_client, &RobotClient::systemInfoReceived, this, &MainWindow::updateSystemInfo);
connect(m_client, &RobotClient::imageReceived, this, &MainWindow::updateImage);
connect(m_client, &RobotClient::snapshotImageReceived, this, &MainWindow::updateImage);
connect(m_client, &RobotClient::cameraStatusReceived, this,
[this](const QString &cameraId, const QVariantMap &state) {
const QString codec = state.value(QStringLiteral("codec")).toString().toLower();
@ -2063,6 +2098,7 @@ void MainWindow::updateConnection(bool connected, int latencyMs, const QString &
{
m_connected = connected;
if (!connected) {
m_cameraSnapshotPending = false;
++m_jointPointCaptureToken;
m_jointPointCapturePending=false;
stopJointPointLoop(QStringLiteral("连接已断开"));
@ -2888,7 +2924,7 @@ void MainWindow::updateTelemetry(const QString &deviceId, const QVariantList &jo
}
if (state.contains(QStringLiteral("robotStateAvailable"))
&& !state.value(QStringLiteral("robotStateAvailable")).toBool()) {
for (QLabel *label : {m_servoStatusValue, m_faultStatusValue}) {
for (QLabel *label : {m_faultStatusValue}) {
if (!label) continue;
label->setText(QStringLiteral("服务端未提供"));
label->setProperty("state", QStringLiteral("unknown"));
@ -2897,13 +2933,8 @@ void MainWindow::updateTelemetry(const QString &deviceId, const QVariantList &jo
label->style()->polish(label);
}
} else if (!state.isEmpty()) {
if (m_servoStatusValue) m_servoStatusValue->setToolTip(QString());
if (m_faultStatusValue) m_faultStatusValue->setToolTip(QString());
const bool connected = state.value(QStringLiteral("connected")).toBool();
const bool powered = state.value(QStringLiteral("poweredOn")).toBool();
const bool enabled = powered && (!state.contains(QStringLiteral("brakeReleased"))
|| state.value(QStringLiteral("brakeReleased")).toBool());
const bool moving = state.value(QStringLiteral("moving")).toBool();
const bool fault = state.value(QStringLiteral("fault")).toBool();
const bool emergency = state.value(QStringLiteral("emergencyStopped")).toBool();
const bool protective = state.value(QStringLiteral("protectiveStopped")).toBool();
@ -2925,16 +2956,6 @@ void MainWindow::updateTelemetry(const QString &deviceId, const QVariantList &jo
label->style()->unpolish(label);
label->style()->polish(label);
};
setStateLabel(
m_servoStatusValue,
isDisconnected ? QStringLiteral("已断开")
: freedrive ? QStringLiteral("拖动示教")
: enabled ? (moving ? QStringLiteral("已使能 · 运动中")
: QStringLiteral("已使能 · 空闲"))
: powered ? QStringLiteral("已上电 · 未使能")
: QStringLiteral("未使能"),
(isDisconnected || isEmergency || isFault || isProtective)
? QStringLiteral("error") : QStringLiteral("good"));
setStateLabel(
m_faultStatusValue,
isDisconnected ? QStringLiteral("通信断开")
@ -2999,7 +3020,6 @@ void MainWindow::updateArmTelemetryHealth(const QString &deviceId, bool availabl
label->style()->unpolish(label);
label->style()->polish(label);
};
markError(m_servoStatusValue, QStringLiteral("遥测中断"));
markError(m_faultStatusValue, QStringLiteral("通信异常"));
updateArmAlert(deviceId, QStringLiteral("communication"),
QStringLiteral("ERROR"), QStringLiteral("机械臂遥测通信异常"), detail);
@ -3068,7 +3088,6 @@ void MainWindow::updateSystemStatus(double cpu, double memory, double disk,
m_activeCameraId=selected; m_activeCameraCapabilities.clear();
if(m_handEye) m_handEye->setCameraCapabilities(selected,{});
if(m_touchOperation) m_touchOperation->setCameraCapabilities(selected,{});
if(!selected.isEmpty()) rebuildCameraPreviewGrid({selected});
}
if(!selected.isEmpty()&&!m_cameraCapabilityInFlight) {
m_cameraCapabilityInFlight=true; m_client->requestCameraCapabilities(selected,++m_cameraCapabilitiesToken);
@ -3120,8 +3139,7 @@ void MainWindow::updateSystemStatus(double cpu, double memory, double disk,
}
if (m_cameraDeviceCombo) {
const QString previousCameraId = m_activeCameraId.isEmpty()
? m_cameraDeviceCombo->currentData().toString() : m_activeCameraId;
const QString previousCameraId = m_cameraDeviceCombo->currentData().toString();
{
const QSignalBlocker blocker(m_cameraDeviceCombo);
m_cameraDeviceCombo->clear();
@ -3148,8 +3166,7 @@ void MainWindow::updateSystemStatus(double cpu, double memory, double disk,
}
m_cameraDeviceCombo->setEnabled(!m_cameraStreaming && !m_cameraRecording
&& m_cameraDeviceCombo->count() > 0);
if (!m_cameraStreaming
&& previousCameraId != m_cameraDeviceCombo->currentData().toString())
if (!m_cameraStreaming)
rebuildCameraPreviewGrid(configuredCameraIds());
const QString cameraId = m_cameraDeviceCombo->currentData().toString();
refreshCameraDepthControls();
@ -3502,7 +3519,11 @@ void MainWindow::showTaskCameraResult(const QString &cameraId, const QString &ti
result.render->setMinimumSize(520, 320);
result.status = new QLabel(QStringLiteral("等待媒体数据…"), dialog);
result.status->setObjectName(QStringLiteral("mutedLabel"));
dialog->contentLayout()->addWidget(result.render, 1);
result.display = new QStackedWidget(dialog);
result.display->addWidget(result.render);
result.snapshot = new SnapshotImageView(dialog);
result.display->addWidget(result.snapshot);
dialog->contentLayout()->addWidget(result.display, 1);
dialog->contentLayout()->addWidget(result.status);
}
result.window->show();
@ -3515,7 +3536,8 @@ void MainWindow::updateTaskCameraImage(const QString &cameraId, const QImage &im
{
if (cameraId.isEmpty() || !m_taskCameraResults.contains(cameraId)) return;
TaskCameraResult &result = m_taskCameraResults[cameraId];
result.render->setImage(image);
result.snapshot->setImage(image);
result.display->setCurrentWidget(result.snapshot);
result.status->setText(detail);
if (m_taskOrchestration)
m_taskOrchestration->reportTaskFeedback(cameraId, detail, !image.isNull());
@ -3527,19 +3549,30 @@ void MainWindow::updateTaskCameraFrame(const QString &cameraId, const VideoFrame
if (cameraId.isEmpty() || !m_taskCameraResults.contains(cameraId)) return;
TaskCameraResult &result = m_taskCameraResults[cameraId];
result.render->setFrame(frame);
result.display->setCurrentWidget(result.render);
result.status->setText(detail);
}
void MainWindow::updateImage(const QImage &image, const QString &detail)
void MainWindow::updateImage(const QString &cameraId, const QImage &image, const QString &detail)
{
m_lastImage = image;
m_lastImageIsDepth = detail.startsWith(QStringLiteral("深度"));
if (m_videoRender)
m_videoRender->setImage(image);
m_imageMetaLabel->setText(detail);
m_saveImageButton->setEnabled(true);
if (!m_taskSnapshotCameraId.isEmpty()) {
updateTaskCameraImage(m_taskSnapshotCameraId, image, detail);
if (image.isNull()) return;
// A capture may finish after the selection changes. Never display it as another camera.
if (configuredCameraIds().contains(cameraId)) {
rebuildCameraPreviewGrid(configuredCameraIds());
auto it = m_cameraPreviewTiles.find(cameraId);
if (it != m_cameraPreviewTiles.end()) {
it->snapshot->setImage(image);
it->display->setCurrentWidget(it->snapshot);
it->status->setText(QStringLiteral("已抓图"));
it->meta->setText(detail);
}
m_lastImage = image;
m_lastImageIsDepth = detail.startsWith(QStringLiteral("深度"));
m_imageMetaLabel->setText(detail);
m_saveImageButton->setEnabled(true);
}
if (m_taskSnapshotCameraId == cameraId) {
updateTaskCameraImage(cameraId, image, detail);
m_taskSnapshotCameraId.clear();
}
}
@ -3558,6 +3591,7 @@ void MainWindow::updateVideoFrame(const QString &cameraId, const VideoFrame &fra
if (it == m_cameraPreviewTiles.end())
return;
it->render->setFrame(frame);
it->display->setCurrentWidget(it->render);
it->meta->setText(detail);
m_imageMetaLabel->setText(QStringLiteral("%1 | %2").arg(resolvedId, detail));
m_saveImageButton->setEnabled(true);
@ -3616,6 +3650,12 @@ void MainWindow::updateCameraRecordingState(bool recording, const QString &detai
void MainWindow::handleCommand(const QString &command, bool success, const QString &detail)
{
if (command == QStringLiteral("Snapshot") || command == QStringLiteral("Depth Snapshot")) {
m_cameraSnapshotPending = false;
refreshCameraStreamControls();
if (!success)
m_imageMetaLabel->setText(QStringLiteral("获取图像失败:%1").arg(detail));
}
if (!success) {
if (command == QStringLiteral("Snapshot")
|| command == QStringLiteral("Depth Snapshot"))
@ -3636,13 +3676,7 @@ void MainWindow::handleCommand(const QString &command, bool success, const QStri
m_taskOrchestration->completeCommandTask(command, success, detail);
QLabel *stateLabel = nullptr;
QString stateText;
if (command == QStringLiteral("Torque On")) {
stateLabel = m_servoStatusValue;
stateText = success ? QStringLiteral("已使能") : QStringLiteral("使能失败");
} else if (command == QStringLiteral("Torque Off")) {
stateLabel = m_servoStatusValue;
stateText = success ? QStringLiteral("已去使能") : QStringLiteral("操作失败");
} else if (command == QStringLiteral("Clear Fault")) {
if (command == QStringLiteral("Clear Fault")) {
stateLabel = m_faultStatusValue;
stateText = success ? QStringLiteral("正常") : QStringLiteral("清除失败");
} else if (command == QStringLiteral("Enter Teaching Mode")) {

View File

@ -47,6 +47,7 @@ class QuicTestServer;
class UrdfViewerWidget;
class AudioStreamManager;
class VideoRenderWidget;
class SnapshotImageView;
class TcpCalibrationWidget;
class TouchOperationWidget;
class TcpJogController;
@ -85,7 +86,7 @@ private slots:
void updateSystemStatus(double cpu, double memory, double disk,
const QVariantList &devices);
void updateSystemInfo(const QVariantMap &info);
void updateImage(const QImage &image, const QString &detail);
void updateImage(const QString &cameraId, const QImage &image, const QString &detail);
void updateVideoFrame(const QString &cameraId, const VideoFrame &frame,
const QString &detail);
void updateCameraStreamState(const QString &cameraId, bool running,
@ -390,6 +391,8 @@ private:
struct CameraPreviewTile {
QWidget *container = nullptr;
VideoRenderWidget *render = nullptr;
QStackedWidget *display = nullptr;
SnapshotImageView *snapshot = nullptr;
QLabel *status = nullptr;
QLabel *meta = nullptr;
};
@ -400,6 +403,8 @@ private:
struct TaskCameraResult {
QDialog *window = nullptr;
VideoRenderWidget *render = nullptr;
QStackedWidget *display = nullptr;
SnapshotImageView *snapshot = nullptr;
QLabel *status = nullptr;
};
QHash<QString, TaskCameraResult> m_taskCameraResults;
@ -415,6 +420,7 @@ private:
QImage m_lastImage;
bool m_lastImageIsDepth = false;
bool m_cameraStreaming = false;
bool m_cameraSnapshotPending = false;
bool m_cameraRecording = false;
QComboBox *m_dexHandDeviceCombo = nullptr;

View File

@ -1,3 +1,4 @@
#include "snapshotimageview.h"
#include "actionqueuetestwidget.h"
#include "mainwindow.h"
@ -1471,6 +1472,21 @@ QWidget *MainWindow::createArmPage()
}
setArmTelemetryEnabled(enabled);
});
const auto torqueResults=std::make_shared<QHash<QString,bool>>();
const auto showTorqueResult=[this,torqueResults]{
const QString device=m_armIdEdit->text().trimmed();
m_servoStatusValue->setText(torqueResults->contains(device)?(torqueResults->value(device)?QStringLiteral("已使能"):QStringLiteral("未使能")):QStringLiteral("未知"));
m_servoStatusValue->setProperty("state",torqueResults->contains(device)?QStringLiteral("good"):QStringLiteral("muted"));
m_servoStatusValue->setToolTip(QStringLiteral("按使能/去使能接口成功结果显示"));
m_servoStatusValue->style()->unpolish(m_servoStatusValue);m_servoStatusValue->style()->polish(m_servoStatusValue);
};
connect(m_client,&RobotClient::torqueFinished,this,[this,torqueResults,showTorqueResult](const QString& device,bool enabled,bool success,const QString&){
if(!success)return;torqueResults->insert(device,enabled);if(device==m_armIdEdit->text().trimmed())showTorqueResult();
});
connect(m_armIdEdit,&QLineEdit::textChanged,this,[showTorqueResult](const QString&){showTorqueResult();});
connect(m_client,&RobotClient::connectRequested,this,[torqueResults,showTorqueResult](const QString&,int,bool){torqueResults->clear();showTorqueResult();});
connect(m_client,&RobotClient::connectionChanged,this,[torqueResults,showTorqueResult](bool connected,int,const QString&){if(!connected){torqueResults->clear();showTorqueResult();}});
showTorqueResult();
connect(m_torqueOnButton, &QPushButton::clicked, this, [this]() {
m_client->requestTorque(m_armIdEdit->text().trimmed(), true);
});
@ -1739,7 +1755,11 @@ void MainWindow::rebuildCameraPreviewGrid(const QStringList &cameraIds)
meta->setTextInteractionFlags(Qt::TextSelectableByMouse);
layout->addLayout(header);
layout->addWidget(render, 1);
tile.display = new QStackedWidget(container);
tile.display->addWidget(render);
tile.snapshot = new SnapshotImageView(container);
tile.display->addWidget(tile.snapshot);
layout->addWidget(tile.display, 1);
layout->addWidget(meta);
tile.container = container;
tile.render = render;
@ -1802,9 +1822,9 @@ void MainWindow::refreshCameraStreamControls()
&& m_cameraDeviceCombo->count() > 0);
m_cameraCodecCombo->setEnabled(false);
m_cameraStreamModeCombo->setEnabled(!m_cameraStreaming);
m_snapshotButton->setEnabled(m_connected && !m_cameraStreaming);
m_snapshotButton->setEnabled(m_connected && !m_cameraStreaming && !m_cameraSnapshotPending);
if (m_depthSnapshotButton)
m_depthSnapshotButton->setEnabled(m_connected && !m_cameraStreaming);
m_depthSnapshotButton->setEnabled(m_connected && !m_cameraStreaming && !m_cameraSnapshotPending);
m_cameraStreamStateLabel->setText(m_cameraStreaming
? QStringLiteral("%1 路播放中").arg(m_runningCameraIds.size())
: QStringLiteral("已停止"));
@ -1857,14 +1877,28 @@ QWidget *MainWindow::createCameraPage()
connect(m_saveImageButton, &QPushButton::clicked, this, &MainWindow::saveSnapshot);
connect(m_snapshotButton, &QPushButton::clicked, this, [this]() {
const QStringList cameraIds = configuredCameraIds();
if (!cameraIds.isEmpty())
m_client->requestSnapshot(cameraIds.first());
if (cameraIds.isEmpty()) {
const QString error = QStringLiteral("未选择可用相机,请刷新系统设备列表并选择相机");
m_imageMetaLabel->setText(error);
appendLog(QStringLiteral("ERROR"), error);
return;
}
m_cameraSnapshotPending = true;
m_imageMetaLabel->setText(QStringLiteral("%1 · 正在打开相机并获取 RGB 图像…").arg(cameraIds.first()));
refreshCameraStreamControls();
m_client->requestSnapshot(cameraIds.first());
});
connect(m_depthSnapshotButton, &QPushButton::clicked, this, [this]() {
const QStringList cameraIds = configuredCameraIds();
if (!cameraIds.isEmpty() && CameraCapabilities::depthImage(
m_cameraCapabilitiesById.value(cameraIds.first())))
m_client->requestDepthSnapshot(cameraIds.first());
if (cameraIds.isEmpty()) {
m_imageMetaLabel->setText(QStringLiteral("未选择可用相机"));
appendLog(QStringLiteral("ERROR"), QStringLiteral("未选择可用相机"));
return;
}
m_cameraSnapshotPending = true;
m_imageMetaLabel->setText(QStringLiteral("%1 · 正在打开相机并获取深度图像…").arg(cameraIds.first()));
refreshCameraStreamControls();
m_client->requestDepthSnapshot(cameraIds.first());
});
connect(m_cameraCodecCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, [this](int index) {

View File

@ -1,3 +1,4 @@
#include "demosimulator.h"
#include "robotclient.h"
#include "agvmaprasterizer.h"
#include "seeragvmapclient.h"
@ -45,6 +46,7 @@
#include "cmvr/api/arm_service.grpc.pb.h"
#include "cmvr/api/motor_service.grpc.pb.h"
#include "cmvr/api/camera_command.pb.h"
#include "camerasnapshotdecoder.h"
#include "cmvr/api/camera_service.grpc.pb.h"
#include "cmvr/api/dexhand_command.pb.h"
#include "cmvr/api/dexhand_service.grpc.pb.h"
@ -286,6 +288,8 @@ QVariantList demoDeviceList()
{
QVariantList devices;
const QList<QVariantMap> definitions = {
{{"deviceId","bio_head"},{"type",8},{"driverType","DemoBioHead"},{"vendor","CMVR Demo"}},
{{"deviceId","motor_manager"},{"type",9},{"driverType","DemoMotor"},{"vendor","CMVR Demo"}},
{{QStringLiteral("deviceId"), QStringLiteral("right_arm")},
{QStringLiteral("type"), 6}, {QStringLiteral("deviceKind"), 2},
{QStringLiteral("driverType"), QStringLiteral("AuboARM")},
@ -460,8 +464,11 @@ public:
}
public:
void finishDemoAfter(int delay,std::function<void()> done){const auto session=m_demoSession;QTimer::singleShot(delay,this,[this,session,done]{if(m_connected&&m_demoMode&&session==m_demoSession)done();});}
void connectToServer(const QString &host, int port, bool demoMode)
{
++m_demoSession;
// A failed gRPC channel can leave stubs and stream threads alive even
// though the server has disappeared. Always rebuild from a clean
// transport before accepting a new connection request.
@ -482,12 +489,13 @@ public:
m_armFrameDefaults.clear();
#endif
if (m_host.isEmpty()) {
if (m_host.isEmpty()&&!m_demoMode) {
emit connectionChanged(false, 0, QStringLiteral("主机地址不能为空"));
return;
}
if (m_demoMode) {
DemoSimulator::instance().reset();
m_connected = true;
m_pollTimer->start();
emit connectionChanged(true, 8, QStringLiteral("演示数据源"));
@ -530,6 +538,7 @@ public:
void disconnectFromServer()
{
++m_demoSession;
m_pollTimer->stop();
stopArmMotionInternal();
stopCameraStreamInternal();
@ -813,7 +822,17 @@ public:
else if (rpcFinished) rpcFinished(service,QString::number(token),false,why);
};
if (!ensureConnected(service) || !ensureDeviceId(service,deviceId)) { fail(QStringLiteral("设备未连接")); return; }
if (m_demoMode) { fail(QStringLiteral("演示模式不应用坐标系或运动")); return; }
if (m_demoMode) {
const QString op=parameters.value("operation").toString();
QJsonObject q{{"header",QJsonObject{{"device_id",deviceId}}},{"name",parameters.value("name").toString()}};
if(move){QJsonObject pose;const auto values=parameters.value("target").toList();const QStringList fields={"x","y","z","rx","ry","rz"};for(int i=0;i<qMin(values.size(),fields.size());++i)pose.insert(fields[i],values[i].toDouble());q.remove("name");q.insert("target",pose);const auto reply=DemoSimulator::instance().call("cmvr.api.ArmService",jointMove?"moveJPose":"moveL",q);finishDemoAfter(reply.delayMs,[this,command,reply]{if(m_connected&&m_demoMode)emit commandFinished(command,reply.ok,QStringLiteral("演示坐标系运动完成"));});return;}
const QMap<QString,QString> methods={{"list","ListUserCoordinateSystems"},{"get","GetUserCoordinateSystem"},{"create","CreateUserCoordinateSystem"},{"update","UpdateUserCoordinateSystem"},{"delete","DeleteUserCoordinateSystem"},{"apply","ApplyUserCoordinateSystem"},{"calibrate","CalibrateUserCoordinateSystem"}};
QString method=methods.value(op,"getPose");
if(op=="create"||op=="update"||op=="calibrate")q.insert("coordinate",QJsonObject{{"name",q.value("name")},{"user_pose",QJsonArray::fromVariantList(parameters.value("user_pose").toList())},{"tcp_offset",QJsonArray::fromVariantList(parameters.value("tcp_offset").toList())}});
if(method=="getPose")q.remove("name");const auto reply=DemoSimulator::instance().call("cmvr.api.ArmService",method,q);auto data=reply.response;data.insert("success",reply.ok);data.insert("operation",op);data.insert("device_id",deviceId);data.insert("simulation",true);
if(op=="pose"||op=="selected_pose"){QJsonArray p;const auto pose=DemoSimulator::instance().sample(deviceId).value("pose").toObject();for(const auto& name:QStringList{"x","y","z","rx","ry","rz"})p.append(pose.value(name));data.insert("pose",p);data.insert("reference",op=="selected_pose"?parameters.value("name").toString():QString("base"));data.insert("end_frame","tcp");data.insert("source","Demo");}
if(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;
@ -1439,7 +1458,9 @@ public:
{
const auto fail=[&](const QString &error) { motorRpcFinished(token,method,false,{},error); };
if (!m_connected || manager.isEmpty()) { fail(QStringLiteral("服务未连接或电机系统为空")); return; }
if (m_demoMode) { fail(QStringLiteral("电机调试需要连接支持 MotorService 的真实服务端")); return; }
if (m_demoMode) {auto request=QJsonObject::fromVariantMap(params);request.insert("header",QJsonObject{{"device_id",manager}});request.insert("node_id",node);const auto reply=DemoSimulator::instance().call("cmvr.api.MotorService",method,request);const auto convert=[](const QJsonObject& data){QVariantMap out;for(auto i=data.begin();i!=data.end();++i){QString key=i.key();int underscore;while((underscore=key.indexOf('_'))>=0){key.remove(underscore,1);if(underscore<key.size())key[underscore]=key[underscore].toUpper();}out.insert(key,i.value().toVariant());}return out;};QVariantMap payload;
if(method=="ListMotors"){QVariantList motors;for(const auto& m:reply.response.value("motors").toArray())motors<<convert(m.toObject());payload.insert("motors",motors);}else{payload.insert("info",convert(reply.response.value("info").toObject()));payload.insert("state",convert(reply.response.value("state").toObject()));payload.insert("reachedTarget",true);payload.insert("driverAcknowledged",true);}
motorRpcFinished(token,method,reply.ok,payload,QStringLiteral("演示电机反馈"));return;}
#ifdef CMVR_WITH_GRPC
try {
cmvr::api::MotorRequest request;
@ -1513,11 +1534,7 @@ public:
if (error.isEmpty() && m_demoMode) {
for (const auto &id : devices) {
const auto names=armJointNamesForDevice(id);
QVariantList values;
for (int i=0;i<names.size();++i) {
const double phase=m_tick*0.035+i*0.46;
values.append(i<m_demoTargets.size() ? m_demoTargets[i]+0.025*qSin(phase*1.7) : 0.36*qSin(phase));
}
const auto values=DemoSimulator::instance().sample(id).value("position").toArray().toVariantList();
targets.append(QVariantMap{{"deviceId",id},{"jointNames",names},{"positions",values}});
}
emit jointPointCaptured(token,targets,true,QStringLiteral("演示点位"));
@ -1587,15 +1604,8 @@ public:
}
}
if (m_demoMode) {
for (const auto &value : targets) {
const auto t=value.toMap();
if (t.value("deviceId").toString()==m_armDeviceId || targets.size()==1) {
m_demoTargets.clear();
for (const auto &p : t.value("positions").toList()) m_demoTargets.append(p.toDouble());
}
}
emit jointPointMoveFinished(token,true,QStringLiteral("演示点位已执行(未控制真实设备)"));
return;
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())}}}});}
finishDemoAfter(1200,[this,token]{if(m_connected&&m_demoMode)emit jointPointMoveFinished(token,true,QStringLiteral("演示点位运动完成"));});return;
}
#ifdef CMVR_WITH_GRPC
// Keep the existing global motion gate; one group owns one session.
@ -1738,13 +1748,8 @@ public:
return;
}
if (m_demoMode) {
m_demoTargets.clear();
for (const QVariant &value : positions)
m_demoTargets.append(value.toDouble());
emit commandFinished(QStringLiteral("MoveJ"), true,
QStringLiteral("已发送 %1 个目标,v=%2,a=%3,j=%4")
.arg(positions.size()).arg(velocity, 0, 'f', 2).arg(acceleration, 0, 'f', 2).arg(jerk, 0, 'f', 2));
return;
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}}}});
finishDemoAfter(reply.delayMs,[this,reply]{if(m_connected&&m_demoMode)emit commandFinished(QStringLiteral("MoveJ"),reply.ok,QStringLiteral("演示关节运动完成"));});return;
}
#ifdef CMVR_WITH_GRPC
cmvr::api::MoveJ::Request request;
@ -1789,12 +1794,8 @@ public:
if (!ensureDeviceId(command, deviceId))
return;
if (m_demoMode) {
emit commandFinished(command, true,
QStringLiteral("已发送末端位姿 MoveL,%1 → %2,v=%3,a=%4")
.arg(baseLink, eeLink)
.arg(velocity, 0, 'f', 2)
.arg(acceleration, 0, 'f', 2));
return;
const auto reply=DemoSimulator::instance().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
cmvr::api::MoveL::Request request;
@ -1831,6 +1832,8 @@ public:
if (!ensureDeviceId(command, deviceId))
return;
if (m_demoMode) {
DemoSimulator::instance().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;
}
@ -1844,6 +1847,7 @@ public:
const grpc::Status status = enabled
? m_arm->torqueOn(&context, request, &response)
: m_arm->torqueOff(&context, request, &response);
if(torqueFinished)torqueFinished(deviceId,enabled,status.ok()&&response.success(),QString::fromStdString(status.ok()?response.error_message():status.error_message()));
finish(command, status, response.success(), QString::fromStdString(response.error_message()));
#endif
}
@ -1856,7 +1860,7 @@ public:
if (!ensureDeviceId(QStringLiteral("Stop Motion"), deviceId))
return;
if (m_demoMode) {
m_demoTargets.clear();
DemoSimulator::instance().stop(deviceId);m_demoTargets.clear();
emit commandFinished(QStringLiteral("Stop Motion"), true, QStringLiteral("运动已停止"));
return;
}
@ -2031,6 +2035,39 @@ public:
teachingCommand(QStringLiteral("Exit Teaching Mode"), deviceId, 3);
}
#ifdef CMVR_WITH_GRPC
bool prepareCameraSnapshot(const QString &cameraId, const QString &command)
{
cmvr::api::GetCameraStateCommand::Request stateRequest;
fillHeader(stateRequest.mutable_header(), cameraId);
cmvr::api::GetCameraStateCommand::Feedback state;
grpc::ClientContext stateContext;
setDeadline(stateContext, 3000);
const auto status = m_camera->GetStatus(&stateContext, stateRequest, &state);
if (!status.ok() || !state.header().success()) {
finish(command, status, state.header().success(),
QString::fromStdString(state.header().error_message()));
return false;
}
if (state.state().is_opened()) return true;
// Opening the camera is part of an explicit capture request, never page entry.
cmvr::api::StartCameraCommand::Request startRequest;
fillHeader(startRequest.mutable_header(), cameraId);
cmvr::api::StartCameraCommand::Feedback started;
grpc::ClientContext startContext;
setDeadline(startContext, 20000);
const auto startStatus = m_camera->StartCamera(&startContext, startRequest, &started);
if (!startStatus.ok() || !started.header().success()) {
finish(command, startStatus, started.header().success(),
QStringLiteral("启动相机失败:%1")
.arg(QString::fromStdString(started.header().error_message())));
return false;
}
return true;
}
#endif
void snapshot(const QString &cameraId)
{
if (!ensureConnected(QStringLiteral("Snapshot")))
@ -2055,11 +2092,12 @@ public:
painter.drawText(image.rect().adjusted(0, 48, 0, 0), Qt::AlignCenter,
QStringLiteral("%1 · DEMO · %2")
.arg(cameraId, QDateTime::currentDateTime().toString("HH:mm:ss")));
emit imageReceived(image, QStringLiteral("1280 x 720 · 演示帧"));
emit imageReceived(cameraId, image, QStringLiteral("1280 x 720 · 演示帧"));
emit commandFinished(QStringLiteral("Snapshot"), true, QStringLiteral("已获取演示图像"));
return;
}
#ifdef CMVR_WITH_GRPC
if (!prepareCameraSnapshot(cameraId, QStringLiteral("Snapshot"))) return;
cmvr::api::GetRGBImageCommand::Request request;
fillHeader(request.mutable_header(), cameraId);
cmvr::api::GetRGBImageCommand::Feedback response;
@ -2072,25 +2110,14 @@ public:
return;
}
const auto &frame = response.color_frame();
const QByteArray bytes(frame.data().data(), static_cast<int>(frame.data().size()));
QImage image;
if (frame.type() == cmvr::api::FrameData::U8C3 &&
frame.width() > 0 && frame.height() > 0 && bytes.size() == frame.width() * frame.height() * 3) {
image = QImage(reinterpret_cast<const uchar *>(bytes.constData()), frame.width(), frame.height(),
frame.width() * 3, QImage::Format_RGB888).rgbSwapped();
} else if (frame.type() == cmvr::api::FrameData::U8C1 &&
frame.width() > 0 && frame.height() > 0 && bytes.size() == frame.width() * frame.height()) {
image = QImage(reinterpret_cast<const uchar *>(bytes.constData()), frame.width(), frame.height(),
frame.width(), QImage::Format_Grayscale8).copy();
} else {
image = QImage::fromData(bytes);
}
QString decodeError;
const QImage image = decodeCameraSnapshot(frame, decodeError);
if (image.isNull()) {
emit commandFinished(QStringLiteral("Snapshot"), false,
QStringLiteral("暂不支持图像编码:%1").arg(QString::fromStdString(frame.codec())));
decodeError.isEmpty() ? QStringLiteral("RGB 图像解码失败") : decodeError);
return;
}
emit imageReceived(image, QStringLiteral("%1 x %2 · %3")
emit imageReceived(cameraId, image, QStringLiteral("%1 x %2 · %3")
.arg(image.width()).arg(image.height()).arg(QString::fromStdString(frame.codec())));
emit commandFinished(QStringLiteral("Snapshot"), true, QStringLiteral("图像获取成功"));
#endif
@ -2223,6 +2250,7 @@ public:
void getCameraCapabilities(const QString &cameraId, quint64 token) {
QVariantMap result; bool success=false; QString detail;
if(m_demoMode&&m_connected){cameraCapabilitiesReceived(token,cameraId,{{"version",1},{"driver","DemoCamera"},{"depthImage",true},{"depthStream",true},{"rawImage",true},{"metricAlignedDepth",false},{"width",640},{"height",480}},true,QStringLiteral("演示相机能力"));return;}
#ifdef CMVR_WITH_GRPC
if(m_connected && !m_demoMode && m_camera && !cameraId.isEmpty()) {
cmvr::api::GetCameraStateCommand::Request request; fillHeader(request.mutable_header(),cameraId);
@ -2336,12 +2364,13 @@ public:
line[x * 3 + 2] = static_cast<uchar>(color.blue());
}
}
emit imageReceived(image, QStringLiteral("深度 · 640 x 480 · DEMO · 0–5 m"));
emit imageReceived(cameraId, image, QStringLiteral("深度 · 640 x 480 · DEMO · 0–5 m"));
emit commandFinished(QStringLiteral("Depth Snapshot"), true,
QStringLiteral("深度图像获取成功"));
return;
}
#ifdef CMVR_WITH_GRPC
if (!prepareCameraSnapshot(cameraId, QStringLiteral("Depth Snapshot"))) return;
cmvr::api::GetDepthImageCommand::Request request;
fillHeader(request.mutable_header(), cameraId);
cmvr::api::GetDepthImageCommand::Feedback response;
@ -2361,7 +2390,7 @@ public:
.arg(frame.type()).arg(QString::fromStdString(frame.codec())));
return;
}
emit imageReceived(image, QStringLiteral("深度 · %1 x %2 · %3 · 0–5 m")
emit imageReceived(cameraId, image, QStringLiteral("深度 · %1 x %2 · %3 · 0–5 m")
.arg(frame.width()).arg(frame.height())
.arg(QString::fromStdString(frame.codec())));
emit commandFinished(QStringLiteral("Depth Snapshot"), true,
@ -2869,29 +2898,30 @@ public:
return;
}
if (m_demoMode) {
const auto simulated=DemoSimulator::instance().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);
state.insert(QStringLiteral("mode"), 2);
state.insert(QStringLiteral("localized"), true);
state.insert(QStringLiteral("moving"), false);
state.insert(QStringLiteral("moving"), simulated.value("moving").toBool());
state.insert(QStringLiteral("fault"), false);
state.insert(QStringLiteral("emergency"), false);
state.insert(QStringLiteral("map"), demoAgvCurrentMap(deviceId));
state.insert(QStringLiteral("station"), QStringLiteral("HOME"));
state.insert(QStringLiteral("station"), simulated.value("station").toString());
state.insert(QStringLiteral("battery"), 0.82);
state.insert(QStringLiteral("voltage"), 49.2);
state.insert(QStringLiteral("current"), -2.9);
state.insert(QStringLiteral("temperature"), 28.0);
state.insert(QStringLiteral("charging"), false);
state.insert(QStringLiteral("x"), 1.24);
state.insert(QStringLiteral("y"), -0.36);
state.insert(QStringLiteral("x"), pose.value("x").toDouble());
state.insert(QStringLiteral("y"), pose.value("y").toDouble());
state.insert(QStringLiteral("theta"), 0.12);
QVariantMap navigation;
navigation.insert(QStringLiteral("state"), 0);
navigation.insert(QStringLiteral("type"), 0);
navigation.insert(QStringLiteral("progress"), 0.0);
navigation.insert(QStringLiteral("message"), QStringLiteral("空闲"));
navigation.insert(QStringLiteral("progress"), simulated.value("progress").toDouble());
navigation.insert(QStringLiteral("message"), simulated.value("moving").toBool()?QStringLiteral("演示导航中"):QStringLiteral("演示导航已完成 / 空闲"));
emit agvStateReceived(state, navigation);
emit commandFinished(QStringLiteral("AGV Refresh"), true, QStringLiteral("AGV 状态已刷新"));
return;
@ -3811,16 +3841,15 @@ public:
return;
}
if (m_demoMode) {
QJsonObject result;
result.insert(QStringLiteral("demo"), true);
result.insert(QStringLiteral("header"), QJsonObject{{QStringLiteral("success"), true}});
result.insert(QStringLiteral("service"), serviceName);
result.insert(QStringLiteral("method"), methodName);
result.insert(QStringLiteral("deviceId"), deviceId);
result.insert(QStringLiteral("message"), QStringLiteral("演示模式调用成功"));
emit rpcFinished(serviceName, methodName, true,
QString::fromUtf8(QJsonDocument(result).toJson(QJsonDocument::Indented)));
emit commandFinished(command, true, QStringLiteral("演示模式 RPC 调用完成"));
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);}
else if(!deviceId.isEmpty()){request.insert("device_id",deviceId);request.remove("deviceId");}
const auto reply=DemoSimulator::instance().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("演示接口模拟完成,未发送网络请求"));});
return;
}
#ifdef CMVR_WITH_GRPC
@ -3963,6 +3992,10 @@ public:
error.insert(QStringLiteral("error"), QString::fromStdString(grpcStatus.error_message()));
result = QString::fromUtf8(QJsonDocument(error).toJson(QJsonDocument::Indented));
}
if(serviceName==QStringLiteral("cmvr.api.ArmService")&&(methodName=="torqueOn"||methodName=="torqueOff")){
const auto root=QJsonDocument::fromJson(result.toUtf8()).object();const auto feedback=root.value("header").isObject()?root.value("header").toObject():root;
if(torqueFinished)torqueFinished(deviceId,methodName=="torqueOn",transportOk&&feedback.value("success").toBool(),result);
}
emit rpcFinished(serviceName, methodName, transportOk, result);
emit commandFinished(command, transportOk,
transportOk ? QStringLiteral("RPC 调用完成")
@ -3987,7 +4020,7 @@ public:
armTelemetryHealthChanged;
std::function<void(double, double, double, const QVariantList &)> systemStatusReceived;
std::function<void(const QVariantMap &)> systemInfoReceived;
std::function<void(const QImage &, const QString &)> imageReceived;
std::function<void(const QString &, const QImage &, const QString &)> imageReceived;
std::function<void(quint64, const QString &, const QImage &, const QVariantMap &,
const QVariantMap &, bool, const QString &)> handEyeImageReceived;
std::function<void(quint64, const QString &, const QImage &, const QVariantMap &,
@ -4029,6 +4062,7 @@ public:
std::function<void(const QString &, const QString &, bool, const QString &)>
configurationSaveFinished;
std::function<void(const QString &, bool, const QString &)> commandFinished;
std::function<void(const QString&,bool,bool,const QString&)> torqueFinished;
std::function<void(const QString &, const QVariantList &, const QVariantMap &, bool, const QString &)>
recordedTrajectoriesReceived;
std::function<void(quint64, const QVariantList &, bool, const QString &)> jointPointCaptured;
@ -4492,11 +4526,11 @@ private:
if (m_armPollingEnabled) {
QVariantList joints;
const QStringList jointNames = armJointNamesForDevice(m_armDeviceId);
const auto simulated=DemoSimulator::instance().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;
double position = 0.36 * qSin(phase);
if (i < m_demoTargets.size())
position = m_demoTargets.at(i) + 0.025 * qSin(phase * 1.7);
const double position=i<positions.size()?positions[i].toDouble():0;
QVariantMap joint;
joint.insert(QStringLiteral("name"), jointNames.at(i));
joint.insert(QStringLiteral("position"), position);
@ -4516,7 +4550,8 @@ private:
state.insert(QStringLiteral("connected"), true);
state.insert(QStringLiteral("poweredOn"), true);
state.insert(QStringLiteral("fault"), false);
state.insert(QStringLiteral("moving"), !m_demoTargets.isEmpty());
state.insert(QStringLiteral("moving"), simulated.value("moving").toBool());
pose=simulated.value("pose").toObject().toVariantMap();
emit telemetryReceived(m_armDeviceId, joints, pose, state);
}
if (m_tick % 10 == 0) {
@ -5489,6 +5524,7 @@ private:
QString m_armTcpFrame;
int m_port = 50052;
int m_tick = 0;
quint64 m_demoSession=0;
int m_consecutivePollErrors = 0;
int m_channelFailureTicks = 0;
bool m_connected = false;
@ -5599,9 +5635,10 @@ RobotClient::RobotClient(QObject *parent)
emit systemInfoReceived(info);
}, Qt::QueuedConnection);
};
m_worker->imageReceived = [this](const QImage &image, const QString &detail) {
QMetaObject::invokeMethod(this, [this, image, detail]() {
m_worker->imageReceived = [this](const QString &cameraId, const QImage &image, const QString &detail) {
QMetaObject::invokeMethod(this, [this, cameraId, image, detail]() {
emit imageReceived(image, detail);
emit snapshotImageReceived(cameraId, image, detail);
}, Qt::QueuedConnection);
};
m_worker->cameraCapabilitiesReceived=[this](quint64 token,const QString& camera,const QVariantMap& c,bool ok,const QString& detail) {
@ -5799,6 +5836,9 @@ RobotClient::RobotClient(QObject *parent)
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);
};
m_worker->commandFinished = [this](const QString &command, bool success, const QString &detail) {
QMetaObject::invokeMethod(this, [this, command, success, detail]() {
emit commandFinished(command, success, detail);
@ -6568,8 +6608,15 @@ void RobotClient::requestUserCoordinates(const QString &deviceId, const QVariant
emit userCoordinatesRequested(deviceId,parameters,token);
}
void RobotClient::requestRpc(const QString &serviceName, const QString &methodName,
const QString &requestJson, const QString &deviceId)
void RobotClient::afterPendingCommands(std::function<void()> callback)
{
QMetaObject::invokeMethod(m_worker,[this,callback](){
QMetaObject::invokeMethod(this,callback,Qt::QueuedConnection);
},Qt::QueuedConnection);
}
bool RobotClient::prepareRpcDispatch(const QString& serviceName,const QString& methodName,
const QString& requestJson,const QString& deviceId,QString& error)
{
const QString method = methodName.toLower();
if (serviceName.contains(QStringLiteral("ArmService"), Qt::CaseInsensitive)
@ -6610,15 +6657,22 @@ void RobotClient::requestRpc(const QString &serviceName, const QString &methodNa
if (stop || zeroVelocity)
cancelAgvMapDirect();
else if (!read && m_agvMapDirectBusy) {
const QString error = QStringLiteral("地图直连操作进行中,该 AGV 命令未发送;停止和急停仍可使用");
emit rpcFinished(serviceName, methodName, false,
QString::fromUtf8(QJsonDocument(QJsonObject{{QStringLiteral("error"), error}})
.toJson(QJsonDocument::Compact)));
emit commandFinished(QStringLiteral("%1.%2").arg(serviceName, methodName), false, error);
return;
error = QStringLiteral("地图直连操作进行中,该 AGV 命令未发送;停止和急停仍可使用");
return false;
}
}
emit rpcRequested(serviceName, methodName, requestJson, deviceId);
return true;
}
void RobotClient::requestRpc(const QString &serviceName, const QString &methodName,
const QString &requestJson, const QString &deviceId)
{
QString error;
if(!prepareRpcDispatch(serviceName,methodName,requestJson,deviceId,error)){
emit rpcFinished(serviceName,methodName,false,QString::fromUtf8(QJsonDocument(QJsonObject{{"error",error}}).toJson(QJsonDocument::Compact)));
emit commandFinished(serviceName+"."+methodName,false,error);return;
}
emit rpcRequested(serviceName,methodName,requestJson,deviceId);
}
void RobotClient::startSpeakerAudioStream(const QString &deviceId)

View File

@ -10,6 +10,7 @@
#include <QThread>
#include <QVariantList>
#include <QVariantMap>
#include <functional>
#include <atomic>
#include <memory>
@ -27,6 +28,8 @@ public:
~RobotClient() override;
bool grpcAvailable() const;
bool prepareRpcDispatch(const QString&,const QString&,const QString&,const QString&,QString&);
void afterPendingCommands(std::function<void()> callback);
quint64 agvMapStreamGeneration() const;
public slots:
@ -134,6 +137,7 @@ public slots:
const QString &expectedRevision);
signals:
void torqueFinished(const QString& deviceId,bool enabled,bool success,const QString& detail);
void userCoordinatesRequested(const QString &deviceId, const QVariantMap &parameters, quint64 token);
void motorRpcRequested(const QString &method, const QString &managerId, int nodeId,
const QVariantMap &parameters, quint64 token);
@ -266,6 +270,7 @@ signals:
const QVariantList &devices);
void systemInfoReceived(const QVariantMap &info);
void imageReceived(const QImage &image, const QString &detail);
void snapshotImageReceived(const QString &cameraId, const QImage &image, const QString &detail);
// success validates image/intrinsics only. Pairing must additionally check
// metadata.captureTimestampAvailable and its captureUtcNs against robot poses.
void handEyeImageReceived(quint64 token, const QString &cameraId,

27
src/snapshotimageview.h Normal file
View File

@ -0,0 +1,27 @@
#pragma once
#include <QImage>
#include <QPainter>
#include <QWidget>
// Still images use the raster painter, independently of the video GL context.
class SnapshotImageView : public QWidget
{
public:
explicit SnapshotImageView(QWidget *parent = nullptr) : QWidget(parent) {}
void setImage(const QImage &image) { m_image = image; update(); }
protected:
void paintEvent(QPaintEvent *) override
{
QPainter painter(this);
painter.fillRect(rect(), QColor(QStringLiteral("#0e1115")));
if (m_image.isNull()) return;
QSize target = m_image.size();
target.scale(size(), Qt::KeepAspectRatio);
painter.drawImage(QRect((width() - target.width()) / 2,
(height() - target.height()) / 2,
target.width(), target.height()), m_image);
}
private:
QImage m_image;
};

258
src/taskapi.cpp Normal file
View File

@ -0,0 +1,258 @@
#include "taskapi.h"
#include <google/protobuf/descriptor.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/util/json_util.h>
#include <QJsonDocument>
#include <QSet>
#include <QFile>
#include <QMap>
#include <memory>
#include <QUuid>
#include <cmath>
#include <functional>
namespace {
using google::protobuf::Descriptor;
using google::protobuf::FieldDescriptor;
QString id(){return QUuid::createUuid().toString(QUuid::WithoutBraces);}
const google::protobuf::MethodDescriptor* method(const QString& service,const QString& name){
auto* s=google::protobuf::DescriptorPool::generated_pool()->FindServiceByName(service.toStdString());
return s?s->FindMethodByName(name.toStdString()):nullptr;
}
QJsonObject methodInfo(const google::protobuf::MethodDescriptor* m){
if(!m)return {};
QJsonObject result{{"id",QString::fromStdString(m->full_name())},{"service",QString::fromStdString(m->service()->full_name())},
{"method",QString::fromStdString(m->name())},{"requestType",QString::fromStdString(m->input_type()->full_name())},
{"responseType",QString::fromStdString(m->output_type()->full_name())},
{"clientStreaming",m->client_streaming()},{"serverStreaming",m->server_streaming()},
{"completion","rpc_response"},{"defaultTimeoutMs",180000}};
const QString name=QString::fromStdString(m->name());QStringList fields;
if(m->service()->full_name()=="cmvr.api.MotorService"){
fields=QStringList{"header","node_id","joint_name"};
const QMap<QString,QStringList> extra={{"setMode",{"mode"}},{"commandProfilePosition",{"q","qd","qdd"}},
{"commandProfileVelocity",{"qd","qdd"}},{"commandProfileTorque",{"tau","torque_slope"}},
{"commandCyclicPosition",{"q","qd"}},{"commandCyclicVelocity",{"qd"}},{"commandCyclicTorque",{"tau"}},
{"setLimitQ",{"upper","lower"}},{"setLimitQd",{"qd"}},{"setLimitQdd",{"upper","lower"}}};
fields+=extra.value(name);if(name=="ListMotors")fields=QStringList{"header"};
}
if(m->input_type()->full_name()=="cmvr.api.UserCoordinateSystemCommand.Request"){
if(name=="ListUserCoordinateSystems")fields=QStringList{"header"};
if(name=="GetUserCoordinateSystem"||name=="DeleteUserCoordinateSystem"||name=="ApplyUserCoordinateSystem")fields=QStringList{"header","name","expected_revision"};
}
if(!fields.isEmpty()){QJsonArray array;for(const auto& f:fields)array.append(f);result.insert("editorFields",array);}
return result;
}
const QMap<QString,QStringList>& adapters(){
static const QMap<QString,QStringList> a={
{QStringLiteral("机械臂"),{"MoveJ","使能","去使能","停止","清除故障"}},
{QStringLiteral("相机"),{"RGB抓图","深度抓图","开始预览","停止预览","开始录像","停止录像"}},
{QStringLiteral("AGV"),{"导航站点","停止","暂停","继续"}},
{QStringLiteral("灵巧手"),{"设置角度","设置位置","设置速度","设置力"}},
{QStringLiteral("麦克风"),{"开始录音","停止录音","开始音频流","停止音频流"}},
{QStringLiteral("扬声器"),{"播放服务端文件","停止文件播放","本机麦克风流播放","停止音频流","开始音频流"}},
{QStringLiteral("仿生头"),{"高兴","惊讶","疲惫","愤怒","悲伤","打哈欠","开始说话","停止说话","紧急停止","检查设备"}}};return a;
}
QString adapterId(const QString& type,const QString& action){
const QStringList types={"机械臂","相机","AGV","灵巧手","麦克风","扬声器","仿生头"};
const QStringList kinds={"arm","camera","agv","dexhand","microphone","speaker","biohead"};
const QMap<QString,QStringList> ids={
{"机械臂",{"move_j","enable","disable","stop","clear_fault"}},
{"相机",{"snapshot_rgb","snapshot_depth","preview_start","preview_stop","record_start","record_stop"}},
{"AGV",{"navigate_station","stop","pause","resume"}},
{"灵巧手",{"angle","position","speed","force"}},
{"麦克风",{"record_start","record_stop","stream_start","stream_stop"}},
{"扬声器",{"file_play","file_stop","capture_stream_start","stream_stop","stream_start"}},
{"仿生头",{"happy","surprise","tired","angry","sad","yawn","speak_start","speak_stop","emergency_stop","check"}}};
const int t=types.indexOf(type),n=adapters().value(type).indexOf(action);
return t>=0&&n>=0?"client."+kinds[t]+"."+ids.value(type)[n]:QString();
}
}
namespace TaskApi {
QString serviceForType(const QString& t){
const QMap<QString,QString> map={{"机械臂","ArmService"},{"相机","CameraService"},{"AGV","AgvService"},
{"灵巧手","DexHandService"},{"麦克风","MicPhoneService"},{"扬声器","SpeakerService"},{"仿生头","BioHeadService"},{"电机","MotorService"}};
return map.contains(t)?"cmvr.api."+map.value(t):QString();
}
QStringList actions(const QString& type){
QStringList result;auto* s=google::protobuf::DescriptorPool::generated_pool()->FindServiceByName(serviceForType(type).toStdString());
if(s)for(int i=0;i<s->method_count();++i){auto* m=s->method(i);if(!m->client_streaming()&&!m->server_streaming())result<<QStringLiteral("接口 · ")+QString::fromStdString(m->name());}
return result;
}
QJsonObject operation(const QString& type,const QString& action){
const QString prefix=QStringLiteral("接口 · ");
return action.startsWith(prefix)?methodInfo(method(serviceForType(type),action.mid(prefix.size()))):QJsonObject();
}
QJsonObject definition(const QString& service,const QString& name){return methodInfo(method(service,name));}
const Descriptor* requestDescriptor(const QString& s,const QString& n){auto* m=method(s,n);return m?m->input_type():nullptr;}
bool validateRequest(const QString& service,const QString& name,const QJsonObject& request,QString& error){
auto* m=method(service,name);
if(!m||m->client_streaming()||m->server_streaming()){error=QStringLiteral("接口不存在或需要专用流式节点");return false;}
google::protobuf::DynamicMessageFactory factory;std::unique_ptr<google::protobuf::Message> message(factory.GetPrototype(m->input_type())->New());
const auto status=google::protobuf::util::JsonStringToMessage(QJsonDocument(request).toJson(QJsonDocument::Compact).toStdString(),message.get());
if(!status.ok()){error=QString::fromStdString(status.ToString());return false;}
std::function<bool(const google::protobuf::Message&)> finite=[&](const google::protobuf::Message& value){
const auto* reflection=value.GetReflection();std::vector<const FieldDescriptor*> fields;reflection->ListFields(value,&fields);
for(const auto* field:fields){
const int count=field->is_repeated()?reflection->FieldSize(value,field):1;
for(int i=0;i<count;++i){
if(field->cpp_type()==FieldDescriptor::CPPTYPE_DOUBLE){const double n=field->is_repeated()?reflection->GetRepeatedDouble(value,field,i):reflection->GetDouble(value,field);if(!std::isfinite(n))return false;}
if(field->cpp_type()==FieldDescriptor::CPPTYPE_FLOAT){const float n=field->is_repeated()?reflection->GetRepeatedFloat(value,field,i):reflection->GetFloat(value,field);if(!std::isfinite(n))return false;}
if(field->cpp_type()==FieldDescriptor::CPPTYPE_MESSAGE&&!finite(field->is_repeated()?reflection->GetRepeatedMessage(value,field,i):reflection->GetMessage(value,field)))return false;
}
}return true;
};
if(!finite(*message)){error=QStringLiteral("接口参数不能包含 NaN 或 Infinity");return false;}return true;
}
QJsonObject catalog(){
QJsonArray services,legacy;QJsonObject messages,enums;
std::function<void(const Descriptor*)> describe=[&](const Descriptor* d){
const QString name=QString::fromStdString(d->full_name());if(messages.contains(name))return;messages.insert(name,QJsonObject());QJsonArray fields;
for(int i=0;i<d->field_count();++i){auto* f=d->field(i);
QJsonObject item{{"name",QString::fromStdString(f->name())},{"jsonName",QString::fromStdString(f->json_name())},{"number",f->number()},
{"type",QString::fromLatin1(f->type_name())},{"repeated",f->is_repeated()},{"map",f->is_map()},
{"presence",f->has_presence()}};
if(d->full_name()=="cmvr.api.MotorRequest"&&f->name()=="mode"){
const QStringList labels={QStringLiteral("轮廓位置"),QStringLiteral("轮廓速度"),QStringLiteral("轮廓力矩"),QStringLiteral("周期位置"),QStringLiteral("周期速度"),QStringLiteral("周期力矩")};
const int values[]={1,3,4,8,9,10};QJsonArray choices;for(int j=0;j<6;++j)choices.append(QJsonObject{{"label",labels[j]},{"value",values[j]}});item.insert("suggestedChoices",choices);
}
if(f->real_containing_oneof())item.insert("oneof",QString::fromStdString(f->real_containing_oneof()->name()));
if(f->message_type()){item.insert("messageType",QString::fromStdString(f->message_type()->full_name()));describe(f->message_type());}
if(f->enum_type()){
const QString en=QString::fromStdString(f->enum_type()->full_name());item.insert("enumType",en);QJsonArray values;
for(int j=0;j<f->enum_type()->value_count();++j){auto* v=f->enum_type()->value(j);values.append(QJsonObject{{"name",QString::fromStdString(v->name())},{"number",v->number()}});}enums.insert(en,values);
}
fields.append(item);
}
messages.insert(name,QJsonObject{{"fields",fields}});
};
for(const auto& type:QStringList{"机械臂","相机","AGV","灵巧手","麦克风","扬声器","仿生头","电机"}){
auto* s=google::protobuf::DescriptorPool::generated_pool()->FindServiceByName(serviceForType(type).toStdString());if(!s)continue;QJsonArray methods;
for(int i=0;i<s->method_count();++i){auto* m=s->method(i);methods.append(methodInfo(m));describe(m->input_type());describe(m->output_type());}
services.append(QJsonObject{{"deviceType",type},{"service",serviceForType(type)},{"methods",methods}});
}
QFile definitions(":/resources/task_adapters.json");QJsonObject adapterDefinitions;
if(definitions.open(QIODevice::ReadOnly))adapterDefinitions=QJsonDocument::fromJson(definitions.readAll()).object();
for(auto i=adapters().begin();i!=adapters().end();++i)for(const auto& label:i.value()){
const auto key=adapterId(i.key(),label);auto entry=adapterDefinitions.value(key).toObject();entry.insert("id",key);entry.insert("deviceType",i.key());entry.insert("action",label);entry.insert("kind","client_adapter");legacy.append(entry);
}
return {{"format","cmvr.task-operation-catalog"},{"version",1},{"services",services},{"messages",messages},{"enums",enums},{"clientAdapters",legacy}};
}
QJsonObject execution(const QString& type,const QString& action,const QString& device,const QJsonObject& p){
auto op=operation(type,action);
const bool generic=type==QStringLiteral("通用RPC");
if(!op.isEmpty()||generic){
QJsonObject request=p.value("request").toObject();const auto* d=requestDescriptor(generic?p.value("service").toString():op.value("service").toString(),generic?p.value("method").toString():op.value("method").toString());
if(d&&d->FindFieldByName("header")){auto h=request.value("header").toObject();h.remove("deviceId");h.insert("device_id",device);request.insert("header",h);}
else if(d&&d->FindFieldByName("device_id")){request.remove("deviceId");request.insert("device_id",device);}
return {{"kind","grpc_unary"},{"service",generic?p.value("service"):op.value("service")},{"method",generic?p.value("method"):op.value("method")},
{"request",request},{"timeoutMs",p.value("timeoutMs").toInt(180000)},{"completion","rpc_response"}};
}
return {{"kind","client_adapter"},{"adapter",adapterId(type,action)},{"deviceId",device},{"parameters",p},{"completion","adapter_callback"}};
}
// Export a transport-ready copy; leave the local editor's friendly nodes unchanged.
bool serverDocument(QJsonObject& document,QString& error){
if(!normalize(document,error))return false;
const auto definitions=catalog();QMap<QString,QJsonObject> legacy;
for(const auto& value:definitions.value("clientAdapters").toArray()){auto a=value.toObject();legacy.insert(a.value("id").toString(),a);}
std::function<bool(QJsonArray&)> visit=[&](QJsonArray& nodes){
for(int i=0;i<nodes.size();++i){auto n=nodes[i].toObject();
if(n.value("kind")=="loop"){auto children=n.value("children").toArray();if(!visit(children))return false;n.insert("children",children);}
else {
auto ex=n.value("execution").toObject();
if(ex.value("kind")=="client_adapter"){
const auto a=legacy.value(n.value("operationId").toString());const auto rpc=a.value("rpc").toObject();
const QString service=rpc.value("service").toString(),name=rpc.value("method").toString(),key=a.value("id").toString();
const auto info=definition(service,name);if(info.isEmpty()){error="Missing server RPC mapping: "+key;return false;}
const auto p=n.value("parameters").toObject();QJsonObject request;
const auto* d=requestDescriptor(service,name);const QJsonObject header{{"device_id",n.value("deviceId")}};
if(d->FindFieldByName("header"))request.insert("header",header);else request=header;
if(key=="client.arm.move_j"){
request.insert("target",QJsonObject{{"position",p.value("positions")}});
request.insert("options",QJsonObject{{"velocity",p.value("velocity").toDouble(.1)},{"acceleration",p.value("acceleration").toDouble(.1)},{"jerk",0}});
}else if(key=="client.agv.navigate_station"){
request.insert("station_id",p.value("stationId"));request.insert("options",QJsonObject{{"max_speed",p.value("maxSpeed").toDouble(.5)}});
}else if(key.startsWith("client.dexhand.")){
QJsonArray values;int index=0;for(const auto& value:p.value("values").toArray())values.append(QJsonObject{{"id",index++},{"value",double(float(value.toDouble()))}});request.insert("values",values);
}else if(key=="client.camera.record_start")request.insert("video_path",p.value("path").toString().trimmed());
else if(key=="client.microphone.record_start")request.insert("file_path",p.value("path"));
else if(key=="client.speaker.file_play")request.insert("audio_path",p.value("path"));
if(!info.value("clientStreaming").toBool()&&!info.value("serverStreaming").toBool()){
if(!validateRequest(service,name,request,error))return false;
n.insert("action",QStringLiteral("接口 · ")+name);
n.insert("operationId",service+"."+name);
const QJsonObject parameters{{"service",service},{"method",name},{"request",request},{"timeoutMs",180000}};
n.insert("parameters",parameters);n.insert("execution",execution(n.value("deviceType").toString(),n.value("action").toString(),n.value("deviceId").toString(),parameters));
}else {
const bool stop=a.value("successMeaning")=="stream_stopped";
auto call=info;call.remove("id");call.insert("rpcPath","/"+service+"/"+name);
call.insert("mode",stop?"close_stream":"open_stream");call.insert("request",request);
call.insert("sessionKey",service+"."+name+":"+n.value("deviceId").toString());
call.insert("completion",a.value("successMeaning"));call.insert("notes",a.value("implementation"));
call.insert("runtimeHeaderFields",QJsonArray{"command_id","timestamp"});
if(info.value("clientStreaming").toBool()&&!stop)call.insert("runtimeRequestFields",QJsonArray{"audio"});
QJsonArray calls;
if(key=="client.camera.preview_start"){
for(const auto& pre:QStringList{"GetStatus","StartCamera"}){auto c=definition(service,pre);c.insert("rpcPath","/"+service+"/"+pre);c.insert("mode","unary");c.insert("request",QJsonObject{{"header",header}});calls.append(c);}
}
calls.append(call);n.insert("serverCalls",calls);
}
}
}nodes[i]=n;
}return true;
};
auto groups=document.value("groups").toArray();for(int i=0;i<groups.size();++i){auto g=groups[i].toObject();auto nodes=g.value("nodes").toArray();if(!visit(nodes))return false;g.insert("nodes",nodes);groups[i]=g;}
document.insert("groups",groups);return normalize(document,error);
}
bool responseSucceeded(bool ok,const QString& text,QString& detail){
detail=text;if(!ok)return false;
QJsonParseError error;const auto doc=QJsonDocument::fromJson(text.toUtf8(),&error);
if(error.error!=QJsonParseError::NoError||!doc.isObject()){detail=QStringLiteral("接口未返回有效对象反馈:")+text;return false;}
const auto root=doc.object();const auto h=root.value("header").isObject()?root.value("header").toObject():root;
if(!h.value("success").isBool()){detail=QStringLiteral("反馈缺少业务 success 标志:")+text;return false;}
if(!h.value("success").toBool()){detail=h.value("error_message").toString(h.value("errorMessage").toString(text));if(detail.isEmpty())detail=QStringLiteral("服务端返回 success=false");return false;}return true;
}
bool normalize(QJsonObject& root,QString& error){
const int version=root.value("version").toInt(1);
if((version!=1&&version!=2)||!root.value("groups").isArray()){error=QStringLiteral("不支持的任务版本或 groups 格式");return false;}
if((version==2 || root.contains("format")) && root.value("format").toString()!="cmvr.task-flow"){error=QStringLiteral("任务格式标识不匹配");return false;}
const QJsonObject policy{{"order","sequential"},{"onError","stop"},{"automaticRetry",false},{"waitStartsAfter","operation_success"},{"stopBehavior","stop_scheduling_and_cancel_active_unary"}};
if(root.contains("executionPolicy")&&root.value("executionPolicy").toObject()!=policy){error=QStringLiteral("不支持的执行策略,未导入");return false;}
QSet<QString> ids;
auto ensureId=[&](QJsonObject& obj){QString value=obj.value("id").toString();if(value.isEmpty())value=id();if(ids.contains(value))return false;ids.insert(value);obj.insert("id",value);return true;};
std::function<bool(QJsonArray&,int,qint64&)> nodes=[&](QJsonArray& array,int depth,qint64& expanded){
if(depth>32){error=QStringLiteral("循环嵌套超过32层");return false;}
expanded=0;
for(int i=0;i<array.size();++i){
if(!array[i].isObject()){error=QStringLiteral("节点必须是对象");return false;}auto n=array[i].toObject();
if(!ensureId(n)){error=QStringLiteral("节点/方案 id 重复");return false;}
const QString kind=n.value("kind").toString("task");n.insert("kind",kind);
if(kind=="loop"){
const double count=n.value("count").toDouble(-1);if(count<1||count>100000||std::floor(count)!=count||!n.value("children").isArray()){error=QStringLiteral("循环次数或子节点格式无效");return false;}
auto children=n.value("children").toArray();qint64 size=0;if(!nodes(children,depth+1,size))return false;
expanded+=size*qint64(count);n.insert("children",children);
}else if(kind=="task"){
if(n.value("deviceId").toString().isEmpty()){error=QStringLiteral("节点设备不能为空");return false;}
const auto p=n.value("parameters").toObject();
const auto op=operation(n.value("deviceType").toString(),n.value("action").toString());
if(!op.isEmpty()&&(p.value("service")!=op.value("service")||p.value("method")!=op.value("method"))){error=QStringLiteral("接口操作与参数中的服务/方法不一致");return false;}
const auto ex=execution(n.value("deviceType").toString(),n.value("action").toString(),n.value("deviceId").toString(),p);
if(ex.value("kind")=="client_adapter"&&ex.value("adapter").toString().isEmpty()){error=QStringLiteral("未知任务操作,未执行或保存:")+n.value("action").toString();return false;}
if(ex.value("kind")=="grpc_unary"){
if(!validateRequest(ex.value("service").toString(),ex.value("method").toString(),ex.value("request").toObject(),error))return false;
const int timeout=ex.value("timeoutMs").toInt();if(timeout<100||timeout>1800000){error=QStringLiteral("接口超时必须在100~1800000ms之间");return false;}
}
const double wait=n.value("waitMs").toDouble(0);if(wait<0||wait>2147483647||std::floor(wait)!=wait){error=QStringLiteral("等待时间无效");return false;}
if(n.contains("execution") && n.value("execution").toObject()!=ex){error=QStringLiteral("execution 与节点参数不一致,拒绝歧义任务");return false;}
const QString opid=ex.value("kind")=="grpc_unary"?ex.value("service").toString()+"."+ex.value("method").toString():ex.value("adapter").toString();
if(n.contains("operationId")&&n.value("operationId").toString()!=opid){error=QStringLiteral("operationId 与执行操作不一致");return false;}
n.insert("execution",ex);n.insert("operationId",ex.value("kind")=="grpc_unary"?ex.value("service").toString()+"."+ex.value("method").toString():ex.value("adapter").toString());
n.insert("waitMs",int(wait));n.insert("waitUnit",n.value("waitUnit").toString()=="s"?"s":"ms");++expanded;
}else{error=QStringLiteral("未知节点类型");return false;}
if(expanded>100000){error=QStringLiteral("流程展开超过100000步");return false;}array[i]=n;
}return true;
};
auto groups=root.value("groups").toArray();for(int i=0;i<groups.size();++i){if(!groups[i].isObject()){error="Invalid group";return false;}auto g=groups[i].toObject();if(!ensureId(g)){error="Duplicate group id";return false;}if(!g.value("nodes").isArray()){error="Invalid nodes";return false;}auto list=g.value("nodes").toArray();qint64 size;if(!nodes(list,0,size))return false;g.insert("nodes",list);groups[i]=g;}
root.insert("format","cmvr.task-flow");root.remove("version");root.insert("groups",groups);
root.insert("executionPolicy",QJsonObject{{"order","sequential"},{"onError","stop"},{"automaticRetry",false},{"waitStartsAfter","operation_success"},{"stopBehavior","stop_scheduling_and_cancel_active_unary"}});
return true;
}
}

18
src/taskapi.h Normal file
View File

@ -0,0 +1,18 @@
#pragma once
#include <QJsonObject>
#include <QJsonArray>
#include <QStringList>
namespace google { namespace protobuf { class Descriptor; } }
namespace TaskApi {
QString serviceForType(const QString& type);
QStringList actions(const QString& type);
QJsonObject operation(const QString& type,const QString& action);
QJsonObject definition(const QString& service,const QString& method);
const google::protobuf::Descriptor* requestDescriptor(const QString& service,const QString& method);
bool validateRequest(const QString& service,const QString& method,const QJsonObject& request,QString& error);
QJsonObject catalog();
QJsonObject execution(const QString& type,const QString& action,const QString& device,const QJsonObject& parameters);
bool serverDocument(QJsonObject& document,QString& error);
bool normalize(QJsonObject& document,QString& error);
bool responseSucceeded(bool transportOk,const QString& response,QString& detail);
}

62
src/taskdeviceoptions.cpp Normal file
View File

@ -0,0 +1,62 @@
#include "taskdeviceoptions.h"
#include "taskapi.h"
#include "taskrpcrunner.h"
#include "taskorchestrationwidget.h"
#include "robotclient.h"
#include <QJsonDocument>
#include <QJsonArray>
TaskDeviceOptions::TaskDeviceOptions(RobotClient* client,TaskOrchestrationWidget* target,QObject* parent)
:QObject(parent),m_runner(new TaskRpcRunner(client,this)),m_target(target){
connect(client,&RobotClient::connectionChanged,this,[this](bool connected,int,const QString&){
if(!connected){++m_epoch;m_queue.clear();m_pending.clear();m_runner->cancel();}
});
}
QVariantMap TaskDeviceOptions::decode(const QString& method,const QJsonObject& response){
if(method=="ListUserCoordinateSystems")return {{"coordinates",response.value("coordinates").toArray().toVariantList()}};
if(method=="ListBaseFrame"||method=="ListTCPFrame"){
const auto frames=response.contains("frame_names")?response.value("frame_names"):response.value("frameNames");
return {{method=="ListBaseFrame"?"baseFrames":"tcpFrames",frames.toArray().toVariantList()}};
}
if(method=="listMaps")return {{"maps",response.value("maps").toArray().toVariantList()}};
if(method=="listStations")return {{"stations",response.value("stations").toArray().toVariantList()}};
if(method=="ListMotors"){
QVariantList motors;
for(const auto& value:response.value("motors").toArray()){
auto m=value.toObject();
if(!m.contains("node_id"))m.insert("node_id",m.value("nodeId"));
if(!m.contains("joint_name"))m.insert("joint_name",m.value("jointName"));
motors<<m.toVariantMap();
}
return {{"motors",motors}};
}
return {};
}
void TaskDeviceOptions::load(const QString& id,const QString& type){
QStringList methods;
if(type==QStringLiteral("机械臂"))methods=QStringList{"ListUserCoordinateSystems","ListBaseFrame","ListTCPFrame"};
else if(type==QStringLiteral("AGV"))methods=QStringList{"listMaps","listStations"};
else if(type==QStringLiteral("电机"))methods=QStringList{"ListMotors"};
for(const auto& method:methods){const auto key=id+":"+method;if(m_pending.contains(key))continue;
m_pending.insert(key);m_queue.append({id,type,method,m_epoch});}
next();
}
void TaskDeviceOptions::next(){
if(m_busy||m_queue.isEmpty()||!m_target)return;
const auto q=m_queue.takeFirst();m_busy=true;
const QString service=TaskApi::serviceForType(q.type);
const auto execution=TaskApi::execution(q.type,QStringLiteral("接口 · ")+q.method,q.id,
{{"service",service},{"method",q.method},{"request",QJsonObject()},{"timeoutMs",3000}});
const QPointer<TaskDeviceOptions> guard(this);
m_runner->run(execution,[guard,q](bool ok,const QString& response){
if(!guard)return;
guard->m_busy=false;
if(q.epoch==guard->m_epoch){
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->next();
});
}

26
src/taskdeviceoptions.h Normal file
View File

@ -0,0 +1,26 @@
#pragma once
#include <QObject>
#include <QPointer>
#include <QVariantMap>
#include <QJsonObject>
#include <QSet>
class RobotClient;
class TaskRpcRunner;
class TaskOrchestrationWidget;
// Read-only discovery, separate from the task execution runner.
class TaskDeviceOptions final : public QObject {
public:
TaskDeviceOptions(RobotClient*,TaskOrchestrationWidget*,QObject* parent=nullptr);
void load(const QString& deviceId,const QString& type);
static QVariantMap decode(const QString& method,const QJsonObject& response);
private:
struct Query {QString id,type,method;quint64 epoch;};
void next();
TaskRpcRunner* m_runner;
QPointer<TaskOrchestrationWidget> m_target;
QList<Query> m_queue;
QSet<QString> m_pending;
bool m_busy=false;
quint64 m_epoch=0;
};

63
src/taskjointeditor.h Normal file
View File

@ -0,0 +1,63 @@
#pragma once
#include <QWidget>
#include <QTableWidget>
#include <QHeaderView>
#include <QVBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QDoubleValidator>
#include <QJsonArray>
#include <QVariantMap>
#include <QtMath>
#include <cmath>
// Every joint stays visible. Values on the wire remain in radians.
class TaskJointEditor final : public QWidget {
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->verticalHeader()->hide();m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
m_table->setMinimumHeight(150);m_table->setMaximumHeight(400);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_info=info;m_names=info.value("jointNames").toStringList();
// A server DOF is valid metadata; never guess six or seven axes.
if(m_names.isEmpty())for(int i=0;i<info.value("dof").toInt();++i)m_names<<QStringLiteral("关节 %1").arg(i+1);
const bool mismatched=!values.isEmpty()&&values.size()!=m_names.size();
m_table->setRowCount(m_names.size());m_edits.clear();
m_hint->setText(m_names.isEmpty()?QStringLiteral("尚未获取该设备的关节信息,请连接设备后点击“刷新设备参数”。"):
(checkLimits?QStringLiteral("逐关节填写目标角度;保存时换算为弧度。空值不会自动设为零。"):
QStringLiteral("逐关节填写角速度;保存时换算为弧度/秒。")));
if(mismatched)m_hint->setText(QStringLiteral("原目标数量与设备关节数不一致,请按当前关节列表重新填写。"));
for(int i=0;i<m_names.size();++i){
auto* name=new QTableWidgetItem(m_names[i]);name->setFlags(Qt::ItemIsEnabled);m_table->setItem(i,0,name);
auto* edit=new QLineEdit(m_table);edit->setObjectName(QString("jointTarget_%1").arg(i));
edit->setProperty("taskJointName",m_names[i]);
edit->setValidator(new QDoubleValidator(-1e12,1e12,9,edit));edit->setPlaceholderText(QStringLiteral("输入角度"));
if(!mismatched&&i<values.size()&&values[i].isDouble())edit->setText(QString::number(qRadiansToDegrees(values[i].toDouble()),'g',12));
m_table->setCellWidget(i,1,edit);m_edits<<edit;m_table->setRowHeight(i,44);
const auto limit=info.value("jointLimits").toMap().value(m_names[i]).toMap();
auto* range=new QTableWidgetItem(limit.isEmpty()?QStringLiteral("设备未提供"):
QStringLiteral("%1 ~ %2").arg(qRadiansToDegrees(limit.value("lower").toDouble()),0,'f',2).arg(qRadiansToDegrees(limit.value("upper").toDouble()),0,'f',2));
range->setFlags(Qt::ItemIsEnabled);if(!checkLimits)range->setText(QStringLiteral("角度/秒 → 弧度/秒"));m_table->setItem(i,2,range);
}
m_table->setMinimumHeight(qMin(400,qMax(150,44*m_names.size()+42)));
}
bool values(QJsonArray& result,QString& error) const {
result={};if(m_names.isEmpty()){error=QStringLiteral("请先获取所选设备的关节信息。");return false;}
for(int i=0;i<m_edits.size();++i){bool ok=false;const auto degrees=m_edits[i]->text().toDouble(&ok);const double radians=qDegreesToRadians(degrees);
if(!ok||!std::isfinite(radians)){error=QStringLiteral("请填写 %1 的有效目标角度。").arg(m_names[i]);return false;}
const auto limit=m_info.value("jointLimits").toMap().value(m_names[i]).toMap();
if(m_checkLimits&&!limit.isEmpty()&&(radians<limit.value("lower").toDouble()-1e-10||radians>limit.value("upper").toDouble()+1e-10)){
error=QStringLiteral("%1 的目标角度超出设备关节限位。").arg(m_names[i]);return false;}
result.append(radians);
}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;}
private:
QLabel* m_hint;QTableWidget* m_table;QStringList m_names;QList<QLineEdit*> m_edits;QVariantMap m_info;bool m_checkLimits=true;
};

View File

@ -4,6 +4,16 @@
#include "cameracapabilities.h"
#include "bioheadoperations.h"
#include "uiicons.h"
#include "taskapi.h"
#include "taskprotoeditor.h"
#include "taskjointeditor.h"
#include "taskuilabels.h"
#include <QScrollArea>
#include <QGuiApplication>
#include <QScreen>
#include <QFileDialog>
#include <QPlainTextEdit>
#include <QUuid>
#include <QApplication>
#include <QAbstractItemModel>
@ -47,7 +57,7 @@
namespace {
enum Roles { KindRole = Qt::UserRole, DeviceTypeRole, DeviceIdRole, ActionRole,
ParametersRole, WaitRole, WaitUnitRole, LoopCountRole, RunStateRole, CollapsedRole };
ParametersRole, WaitRole, WaitUnitRole, LoopCountRole, RunStateRole, CollapsedRole, NodeIdRole };
void restoreTaskExpansion(QTreeWidgetItem *item)
{
@ -211,6 +221,13 @@ private:
};
class TaskParameterScroll final:public QScrollArea {
public:
using QScrollArea::QScrollArea;
QSize sizeHint()const override{QSize hint=widget()?widget()->sizeHint():QSize(640,160);hint.setHeight(qBound(minimumHeight(),hint.height()+8,maximumHeight()));return hint;}
QSize minimumSizeHint()const override{return QSize(320,minimumHeight());}
};
class TaskNodeDialog final : public QDialog
{
public:
@ -313,7 +330,7 @@ void showTaskNotice(QWidget *parent, const QString &title, const QString &messag
dialog.exec();
}
QStringList actionsForType(const QString &type)
QStringList legacyActionsForType(const QString &type)
{
if (type == QStringLiteral("仿生头"))
return BioHeadOperations::actions();
@ -340,6 +357,8 @@ QStringList actionsForType(const QString &type)
return {QStringLiteral("调用RPC")};
}
QStringList actionsForType(const QString& type) { return (type==QStringLiteral("电机")?QStringList():legacyActionsForType(type))+TaskApi::actions(type); }
QString deviceTypeName(int type)
{
switch (type) {
@ -350,24 +369,11 @@ QString deviceTypeName(int type)
case 7: return QStringLiteral("扬声器");
case 5: return QStringLiteral("麦克风");
case 8: return QStringLiteral("仿生头");
case 9: case 10: return QStringLiteral("电机");
default: return QStringLiteral("通用RPC");
}
}
bool parseNumberList(const QString &text, QJsonArray &values)
{
values = QJsonArray();
const QStringList parts = text.split(',', QString::SkipEmptyParts);
if (parts.isEmpty()) return false;
for (const QString &part : parts) {
bool ok = false;
const double value = part.trimmed().toDouble(&ok);
if (!ok) return false;
values.append(value);
}
return true;
}
void configureComboPopup(QComboBox *combo)
{
ApplicationStyle::styleComboBox(combo);
@ -470,15 +476,18 @@ bool editTaskDialog(QWidget *parent, QString &name, QString &type, QString &devi
}
TaskNodeDialog dialog(QStringLiteral("任务节点参数"), parent);
dialog.setWindowModality(Qt::WindowModal);
dialog.setMinimumWidth(560);
const int availableWidth=QGuiApplication::primaryScreen()?QGuiApplication::primaryScreen()->availableGeometry().width():1200;
dialog.setMinimumWidth(qMin(980,qMax(640,availableWidth-60)));
const int availableHeight=QGuiApplication::primaryScreen()?QGuiApplication::primaryScreen()->availableGeometry().height():900;
dialog.setMaximumHeight(qMax(480,availableHeight-60));
QVBoxLayout *layout = dialog.contentLayout();
QFormLayout form;
QFormLayout form;QFormLayout headerForm;headerForm.setHorizontalSpacing(16);headerForm.setVerticalSpacing(10);headerForm.setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
form.setHorizontalSpacing(16);
form.setVerticalSpacing(12);
form.setLabelAlignment(Qt::AlignLeft | Qt::AlignVCenter);
form.setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
QLineEdit nameEdit(name, &dialog);
QComboBox deviceCombo(&dialog);
QComboBox deviceCombo(&dialog);deviceCombo.setObjectName("taskDeviceCombo");
configureComboPopup(&deviceCombo);
for (const QVariant &value : availableDevices) {
const QVariantMap device = value.toMap();
@ -493,7 +502,7 @@ bool editTaskDialog(QWidget *parent, QString &name, QString &type, QString &devi
if (deviceIndex >= 0) deviceCombo.setCurrentIndex(deviceIndex);
QLineEdit typeValue(&dialog);
typeValue.setReadOnly(true);
QComboBox actionCombo(&dialog);
QComboBox actionCombo(&dialog);actionCombo.setObjectName("taskActionCombo");
configureComboPopup(&actionCombo);
QWidget waitEditor(&dialog);
QHBoxLayout waitLayout(&waitEditor);
@ -533,15 +542,14 @@ bool editTaskDialog(QWidget *parent, QString &name, QString &type, QString &devi
noParameterLayout.addStretch();
QWidget moveJPage; QFormLayout moveJForm(&moveJPage);
QLineEdit positionsEdit(&moveJPage);
positionsEdit.setPlaceholderText(QStringLiteral("例如:0, 0, 0, 0, 0, 0, 0"));
TaskJointEditor jointEditor(&moveJPage);
QDoubleSpinBox velocitySpin(&moveJPage), accelerationSpin(&moveJPage);
for (QDoubleSpinBox *spin : {&velocitySpin, &accelerationSpin}) {
spin->setRange(0.001, 1000.0); spin->setDecimals(3); spin->setValue(0.1);
}
velocitySpin.setSuffix(QStringLiteral(" rad/s"));
accelerationSpin.setSuffix(QStringLiteral(" rad/s²"));
moveJForm.addRow(QStringLiteral("目标关节位置"), &positionsEdit);
velocitySpin.setSuffix(QStringLiteral(" °/s"));
accelerationSpin.setSuffix(QStringLiteral(" °/s²"));
moveJForm.addRow(&jointEditor);
moveJForm.addRow(QStringLiteral("速度"), &velocitySpin);
moveJForm.addRow(QStringLiteral("加速度"), &accelerationSpin);
@ -556,7 +564,7 @@ bool editTaskDialog(QWidget *parent, QString &name, QString &type, QString &devi
cameraForm.addRow(QStringLiteral("画面类型"), &modeCombo);
QWidget agvPage; QFormLayout agvForm(&agvPage);
QLineEdit stationEdit(&agvPage);
QComboBox stationEdit(&agvPage);stationEdit.setObjectName("taskAgvStationSelector");configureComboPopup(&stationEdit);
QDoubleSpinBox maxSpeedSpin(&agvPage);
maxSpeedSpin.setRange(0.01, 100.0); maxSpeedSpin.setDecimals(2);
maxSpeedSpin.setValue(0.5); maxSpeedSpin.setSuffix(QStringLiteral(" m/s"));
@ -564,9 +572,12 @@ bool editTaskDialog(QWidget *parent, QString &name, QString &type, QString &devi
agvForm.addRow(QStringLiteral("最大速度"), &maxSpeedSpin);
QWidget dexPage; QFormLayout dexForm(&dexPage);
QLineEdit dexValuesEdit(&dexPage);
dexValuesEdit.setPlaceholderText(QStringLiteral("例如:0, 0, 0, 0, 0, 0"));
dexForm.addRow(QStringLiteral("六指令值"), &dexValuesEdit);
auto* dexTable=new QTableWidget(0,2,&dexPage);dexTable->setHorizontalHeaderLabels({QStringLiteral("关节 / 通道"),QStringLiteral("目标值")});
dexTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);dexTable->verticalHeader()->hide();dexTable->setMinimumHeight(180);dexTable->setMaximumHeight(240);dexForm.addRow(dexTable);
auto* dexAdd=new QPushButton(QStringLiteral("添加设备通道"),&dexPage);dexForm.addRow(dexAdd);
auto addDex=[&](const QString& label,const QJsonValue& value){int row=dexTable->rowCount();dexTable->insertRow(row);auto* item=new QTableWidgetItem(label);item->setFlags(Qt::ItemIsEnabled);dexTable->setItem(row,0,item);auto* edit=new QLineEdit(dexTable);edit->setValidator(new QDoubleValidator(edit));edit->setPlaceholderText(QStringLiteral("输入该通道的目标值"));if(value.isDouble())edit->setText(QString::number(value.toDouble(),'g',12));dexTable->setCellWidget(row,1,edit);dexTable->setRowHeight(row,44);};
QObject::connect(dexAdd,&QPushButton::clicked,&dialog,[&]{addDex(QStringLiteral("通道 %1").arg(dexTable->rowCount()),{});});
auto* dexHint=new QLabel(QStringLiteral("数值单位与范围由该型号设备定义;通道按服务端顺序排列。"),&dexPage);dexHint->setWordWrap(true);dexForm.addRow(dexHint);
QWidget rpcPage; QFormLayout rpcForm(&rpcPage);
QLineEdit serviceEdit(&rpcPage), methodEdit(&rpcPage), requestEdit(&rpcPage);
@ -603,23 +614,26 @@ bool editTaskDialog(QWidget *parent, QString &name, QString &type, QString &devi
parameterPages.addWidget(&rpcPage);
parameterPages.addWidget(&pathPage);
parameterPages.addWidget(&localCapturePage);
QWidget apiPage;QVBoxLayout apiLayout(&apiPage);apiLayout.setContentsMargins(0,0,0,0);apiLayout.setAlignment(Qt::AlignTop);
TaskProtoEditor apiEditor(&apiPage);apiLayout.addWidget(&apiEditor);
QSpinBox rpcTimeout(&apiPage);rpcTimeout.setRange(100,1800000);rpcTimeout.setValue(parameters.value("timeoutMs").toInt(180000));rpcTimeout.setSuffix(" ms");
auto* rpcHint=new QLabel(QStringLiteral("按所选设备填写目标和运动设置。操作完成条件以设备返回结果为准。"),&apiPage);
rpcHint->setWordWrap(true);apiLayout.addWidget(rpcHint);parameterPages.addWidget(&apiPage);
QString currentApi;QHash<QString,QJsonObject> apiDrafts;QHash<QString,QVariantMap> apiInputDrafts;
QString displayedDevice;QHash<QString,QJsonArray> jointDrafts;QHash<QString,QString> stationDrafts;
parameterPages.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
const QJsonArray existingPositions = parameters.value(QStringLiteral("positions")).toArray();
QStringList positionTexts;
for (const QJsonValue &value : existingPositions) positionTexts << QString::number(value.toDouble(), 'f', 6);
positionsEdit.setText(positionTexts.join(QStringLiteral(", ")));
velocitySpin.setValue(parameters.value(QStringLiteral("velocity")).toDouble(0.1));
accelerationSpin.setValue(parameters.value(QStringLiteral("acceleration")).toDouble(0.1));
velocitySpin.setValue(qRadiansToDegrees(parameters.value(QStringLiteral("velocity")).toDouble(0.1)));
accelerationSpin.setValue(qRadiansToDegrees(parameters.value(QStringLiteral("acceleration")).toDouble(0.1)));
codecCombo.setCurrentText(parameters.value(QStringLiteral("codec")).toString(QStringLiteral("H264")));
const int modeIndex = modeCombo.findData(parameters.value(QStringLiteral("mode")).toString(QStringLiteral("rgb")));
if (modeIndex >= 0) modeCombo.setCurrentIndex(modeIndex);
stationEdit.setText(parameters.value(QStringLiteral("stationId")).toString());
maxSpeedSpin.setValue(parameters.value(QStringLiteral("maxSpeed")).toDouble(0.5));
QStringList dexTexts;
for (const QJsonValue &value : parameters.value(QStringLiteral("values")).toArray())
dexTexts << QString::number(value.toDouble(), 'f', 3);
dexValuesEdit.setText(dexTexts.join(QStringLiteral(", ")));
serviceEdit.setText(parameters.value(QStringLiteral("service")).toString());
methodEdit.setText(parameters.value(QStringLiteral("method")).toString());
requestEdit.setText(QString::fromUtf8(QJsonDocument(parameters.value(QStringLiteral("request")).toObject()).toJson(QJsonDocument::Compact)));
@ -629,21 +643,27 @@ bool editTaskDialog(QWidget *parent, QString &name, QString &type, QString &devi
if (inputIndex >= 0) inputDeviceCombo.setCurrentIndex(inputIndex);
QLabel parameterLabel(QStringLiteral("操作参数"), &dialog);
form.addRow(QStringLiteral("节点名称"), &nameEdit);
form.addRow(QStringLiteral("选择设备"), &deviceCombo);
form.addRow(QStringLiteral("设备类型"), &typeValue);
form.addRow(QStringLiteral("执行操作"), &actionCombo);
headerForm.addRow(QStringLiteral("节点名称"), &nameEdit);
auto* deviceRow=new QWidget(&dialog);auto* deviceRowLayout=new QHBoxLayout(deviceRow);deviceRowLayout->setContentsMargins(0,0,0,0);deviceRowLayout->addWidget(&deviceCombo,1);
QPushButton refreshInfo(QStringLiteral("刷新设备参数"),deviceRow);refreshInfo.setObjectName("secondaryButton");deviceRowLayout->addWidget(&refreshInfo);
headerForm.addRow(QStringLiteral("选择设备"), deviceRow);
typeValue.hide();
headerForm.addRow(QStringLiteral("执行操作"), &actionCombo);
QLabel bioheadHint(&dialog);
bioheadHint.setWordWrap(true);
bioheadHint.setObjectName(QStringLiteral("mutedLabel"));
form.addRow(&bioheadHint);
headerForm.addRow(&bioheadHint);
form.addRow(&parameterLabel, &parameterPages);
form.addRow(QStringLiteral("完成后等待"), &waitEditor);
layout->addLayout(&form);
layout->addLayout(&headerForm);
auto* formBody=new QWidget(&dialog);formBody->setLayout(&form);
auto* formScroll=new TaskParameterScroll(&dialog);formScroll->setObjectName("taskParameterScroll");formScroll->setFrameShape(QFrame::NoFrame);formScroll->setWidgetResizable(true);formScroll->setWidget(formBody);formScroll->setMinimumHeight(160);formScroll->setMaximumHeight(qMax(160,availableHeight-540));layout->addWidget(formScroll,1);
auto* waitForm=new QFormLayout;waitForm->setHorizontalSpacing(16);waitForm->addRow(QStringLiteral("完成后等待"),&waitEditor);layout->addLayout(waitForm);
auto* timeoutSegment=new QWidget(&waitEditor);auto* timeoutLayout=new QHBoxLayout(timeoutSegment);timeoutLayout->setContentsMargins(8,0,0,0);timeoutLayout->addWidget(new QLabel(QStringLiteral("操作超时"),timeoutSegment));timeoutLayout->addWidget(&rpcTimeout);rpcTimeout.setMaximumWidth(180);waitLayout.addWidget(timeoutSegment);
auto refreshParameterPage = [&]() {
const QString selectedType = typeValue.text();
const QString selectedAction = actionCombo.currentText();
const QString selectedAction = actionCombo.currentData().toString();
bioheadHint.setVisible(selectedType == QStringLiteral("仿生头"));
bioheadHint.setText(BioHeadOperations::hint(selectedAction));
int page = 0;
@ -672,29 +692,78 @@ bool editTaskDialog(QWidget *parent, QString &name, QString &type, QString &devi
&& selectedAction == QStringLiteral("本机麦克风流播放")) {
page = 7;
}
if(!currentApi.isEmpty()){apiInputDrafts.insert(currentApi,apiEditor.inputState());QJsonObject request;QString error;if(apiEditor.request(request,error))apiDrafts.insert(currentApi,request);}
const auto op=TaskApi::operation(selectedType,selectedAction);
if(!op.isEmpty()){
page=8;const QString key=deviceCombo.currentData().toMap().value("deviceId").toString()+":"+op.value("id").toString();
QJsonObject request=apiDrafts.value(key);
if(request.isEmpty() && deviceCombo.currentData().toMap().value("deviceId").toString()==deviceId && parameters.value("service")==op.value("service") && parameters.value("method")==op.value("method"))request=parameters.value("request").toObject();
auto* owner=qobject_cast<TaskOrchestrationWidget*>(parent);
const QString id=deviceCombo.currentData().toMap().value("deviceId").toString();
apiEditor.setDeviceContext(owner?owner->deviceInfo(id):QVariantMap());
apiEditor.setOperation(op.value("service").toString(),op.value("method").toString(),request);
if(apiInputDrafts.contains(key))apiEditor.restoreInputState(apiInputDrafts.value(key));currentApi=key;
QString note=QStringLiteral("按设备填写操作参数;服务端不支持的操作会返回错误。成功只代表该接口定义的完成条件,并非所有设备都已运动到位。");
const QString method=op.value("method").toString();
if(method=="moveL")note+=QStringLiteral(" 直线运动:请先应用工件坐标系,再填写该坐标系内的绝对目标位姿。位置单位为米,旋转单位为弧度。");
if(method=="moveJPose")note+=QStringLiteral(" 末端位姿MoveJ:目标为所选坐标系下的绝对TCP位姿m/rad,速度rad/s,加速度rad/s²;先应用同名同版本坐标系,SDK逆解后执行关节运动,路径不是直线。");
if(method=="ApplyUserCoordinateSystem")note+=QStringLiteral(" 填写已保存的坐标系名称和预期记录版本。应用坐标系本身不会产生运动。");
if(method=="getPose")note+=QStringLiteral(" 参考坐标系填写 base 或已保存的坐标系名称;末端坐标系填写 tcp 读取工具中心,tool0 读取法兰。");
rpcHint->setToolTip(note);
rpcHint->setText(method=="moveL"?QStringLiteral("直线运动请先应用工件坐标系;填写绝对目标位姿。更多说明可将鼠标停留在此处查看。"):QStringLiteral("填写所需参数即可;悬停此处查看操作说明。"));
}else currentApi.clear();
timeoutSegment->setVisible(page==8);
parameterPages.setCurrentIndex(page);
const bool hasParameters = page != 0;
parameterLabel.setVisible(hasParameters);
parameterPages.setVisible(hasParameters);
if (hasParameters)
if (hasParameters){
if(parameterPages.currentWidget()->layout()){parameterPages.currentWidget()->layout()->invalidate();parameterPages.currentWidget()->layout()->activate();}
parameterPages.setFixedHeight(parameterPages.currentWidget()->sizeHint().height());
}
else
parameterPages.setFixedHeight(0);
formScroll->setMinimumHeight(qMin(qMax(160,formBody->sizeHint().height()+12),qMax(160,availableHeight-560)));
dialog.adjustSize();
};
apiEditor.setLayoutChangedHandler([&]{
if(parameterPages.currentWidget()!=&apiPage)return;
apiPage.layout()->invalidate();apiPage.layout()->activate();parameterPages.setFixedHeight(apiPage.sizeHint().height());
formBody->layout()->activate();formBody->updateGeometry();
formScroll->setMinimumHeight(qMin(qMax(160,formBody->sizeHint().height()+12),qMax(160,availableHeight-560)));dialog.adjustSize();
});
auto refreshActions = [&]() {
const QVariantMap device = deviceCombo.currentData().toMap();
const QString selectedType = deviceTypeName(device.value(QStringLiteral("type")).toInt());
typeValue.setText(selectedType);
const QString previous = actionCombo.currentText().isEmpty() ? action : actionCombo.currentText();
const QString id=device.value("deviceId").toString();auto* owner=qobject_cast<TaskOrchestrationWidget*>(parent);
if(!displayedDevice.isEmpty()&&!jointEditor.draft().isEmpty())jointDrafts.insert(displayedDevice,jointEditor.draft());
const auto info=owner?owner->deviceInfo(id):QVariantMap();
jointEditor.setDevice(info,jointDrafts.contains(id)?jointDrafts.value(id):(id==deviceId?existingPositions:QJsonArray()));
const auto deviceNames=info.value("jointNames").toStringList();
if(displayedDevice!=id||(!deviceNames.isEmpty()&&deviceNames.size()!=dexTable->rowCount())){QJsonArray draft;
if(displayedDevice==id)for(int row=0;row<dexTable->rowCount();++row){bool ok;double n=qobject_cast<QLineEdit*>(dexTable->cellWidget(row,1))->text().toDouble(&ok);draft.append(ok?QJsonValue(n):QJsonValue());}
dexTable->setRowCount(0);const auto values=!draft.isEmpty()?draft:(id==deviceId?parameters.value("values").toArray():QJsonArray());const auto names=deviceNames;
for(int i=0;i<qMax(names.size(),values.size());++i)addDex(i<names.size()?names[i]:QStringLiteral("通道 %1").arg(i),i<values.size()?values[i]:QJsonValue());}
if(!displayedDevice.isEmpty())stationDrafts.insert(displayedDevice,stationEdit.currentData().toString());
const QString oldStation=stationDrafts.contains(id)?stationDrafts.value(id):(id==deviceId?parameters.value("stationId").toString():QString());
stationEdit.clear();stationEdit.addItem(QStringLiteral("请选择站点(无选项时刷新设备参数)"),QString());
for(const auto& entry:info.value("stations").toList()){const auto station=entry.toMap();const auto stationId=station.value("id").toString();const auto description=station.value("description").toString();if(!stationId.isEmpty())stationEdit.addItem(description.isEmpty()?stationId:stationId+" · "+description,stationId);}
int stationIndex=stationEdit.findData(oldStation);
if(stationIndex<0&&!oldStation.isEmpty()){stationEdit.addItem(oldStation+QStringLiteral("(待设备确认)"),oldStation);stationIndex=stationEdit.count()-1;}
if(stationIndex>=0)stationEdit.setCurrentIndex(stationIndex);
displayedDevice=id;
const QString previous = actionCombo.currentData().toString().isEmpty() ? action : actionCombo.currentData().toString();
const QSignalBlocker actionBlocker(&actionCombo);
actionCombo.clear();
QStringList actions = actionsForType(selectedType);
if (selectedType == QStringLiteral("相机")
&& !CameraCapabilities::depthImage(cameraCapabilities.value(
device.value(QStringLiteral("deviceId")).toString())))
actions.removeAll(QStringLiteral("深度抓图"));
actionCombo.addItems(actions);
if (actionCombo.findText(previous) >= 0) actionCombo.setCurrentText(previous);
{actions.removeAll(QStringLiteral("深度抓图"));actions.removeAll(QStringLiteral("接口 · GetDepthImage"));actions.removeAll(QStringLiteral("接口 · GetRGBDImages"));}
for(const auto& value:actions)actionCombo.addItem(TaskUi::operationTitle(selectedType,value),value);
if (actionCombo.findData(previous) >= 0) actionCombo.setCurrentIndex(actionCombo.findData(previous));
refreshParameterPage();
};
QObject::connect(&deviceCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), &dialog,
@ -704,16 +773,19 @@ bool editTaskDialog(QWidget *parent, QString &name, QString &type, QString &devi
if (auto *orchestration = qobject_cast<TaskOrchestrationWidget *>(parent))
QObject::connect(orchestration, &TaskOrchestrationWidget::cameraCapabilitiesChanged,
&dialog, [&]() { refreshActions(); });
refreshActions();
auto requestInfo=[&]{if(auto* owner=qobject_cast<TaskOrchestrationWidget*>(parent)){const auto device=deviceCombo.currentData().toMap();emit owner->deviceInfoRequested(device.value("deviceId").toString(),deviceTypeName(device.value("type").toInt()));}};
QObject::connect(&refreshInfo,&QPushButton::clicked,&dialog,requestInfo);
QObject::connect(&deviceCombo,QOverload<int>::of(&QComboBox::currentIndexChanged),&dialog,[&](int){requestInfo();});
if(auto* owner=qobject_cast<TaskOrchestrationWidget*>(parent))QObject::connect(owner,&TaskOrchestrationWidget::deviceInfoChanged,&dialog,[&](const QString& id){if(id==displayedDevice)refreshActions();});
refreshActions();QTimer::singleShot(0,&dialog,requestInfo);
QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);
buttons.button(QDialogButtonBox::Ok)->setText(QStringLiteral("确定"));
buttons.button(QDialogButtonBox::Cancel)->setText(QStringLiteral("取消"));
QObject::connect(&buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
QObject::connect(&buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
buttons.button(QDialogButtonBox::Ok)->setObjectName(QStringLiteral("primaryButton"));
buttons.button(QDialogButtonBox::Cancel)->setObjectName(QStringLiteral("secondaryButton"));
layout->addWidget(&buttons);
if (dialog.exec() != QDialog::Accepted) return false;
auto collectParameters=[&]()->bool {
if (nameEdit.text().trimmed().isEmpty() || deviceCombo.currentIndex() < 0) {
showTaskNotice(parent, QStringLiteral("参数错误"),
QStringLiteral("节点名称和设备不能为空。"));
@ -721,37 +793,44 @@ bool editTaskDialog(QWidget *parent, QString &name, QString &type, QString &devi
}
const QVariantMap selectedDevice = deviceCombo.currentData().toMap();
name = nameEdit.text().trimmed(); type = deviceTypeName(selectedDevice.value(QStringLiteral("type")).toInt());
deviceId = selectedDevice.value(QStringLiteral("deviceId")).toString(); action = actionCombo.currentText();
deviceId = selectedDevice.value(QStringLiteral("deviceId")).toString(); action = actionCombo.currentData().toString();
parameters = QJsonObject();
if (parameterPages.currentIndex() == 1) {
QJsonArray values;
if (!parseNumberList(positionsEdit.text(), values)) {
QString jointError;
if (!jointEditor.values(values,jointError)) {
showTaskNotice(parent, QStringLiteral("参数错误"),
QStringLiteral("请填写有效的关节位置,数值之间使用逗号分隔。"));
jointError);
return false;
}
parameters.insert(QStringLiteral("positions"), values);
parameters.insert(QStringLiteral("velocity"), velocitySpin.value());
parameters.insert(QStringLiteral("acceleration"), accelerationSpin.value());
parameters.insert(QStringLiteral("velocity"), qDegreesToRadians(velocitySpin.value()));
parameters.insert(QStringLiteral("acceleration"), qDegreesToRadians(accelerationSpin.value()));
} else if (parameterPages.currentIndex() == 2) {
parameters.insert(QStringLiteral("codec"), codecCombo.currentText());
parameters.insert(QStringLiteral("mode"), modeCombo.currentData().toString());
} else if (parameterPages.currentIndex() == 3) {
if (stationEdit.text().trimmed().isEmpty()) {
if (stationEdit.currentData().toString().trimmed().isEmpty()) {
showTaskNotice(parent, QStringLiteral("参数错误"),
QStringLiteral("站点 ID 不能为空。"));
return false;
}
parameters.insert(QStringLiteral("stationId"), stationEdit.text().trimmed());
parameters.insert(QStringLiteral("stationId"), stationEdit.currentData().toString().trimmed());
parameters.insert(QStringLiteral("maxSpeed"), maxSpeedSpin.value());
} else if (parameterPages.currentIndex() == 4) {
QJsonArray values;
if (!parseNumberList(dexValuesEdit.text(), values)) {
bool valid=dexTable->rowCount()>0;
for(int row=0;row<dexTable->rowCount();++row){bool ok;double value=qobject_cast<QLineEdit*>(dexTable->cellWidget(row,1))->text().toDouble(&ok);valid=valid&&ok&&std::isfinite(value);values.append(value);}
if (!valid) {
showTaskNotice(parent, QStringLiteral("参数错误"),
QStringLiteral("请填写有效的指令值,数值之间使用逗号分隔。"));
QStringLiteral("请逐项填写设备通道的有效目标值。"));
return false;
}
parameters.insert(QStringLiteral("values"), values);
const auto info=qobject_cast<TaskOrchestrationWidget*>(parent)->deviceInfo(deviceId);const auto ids=info.value("channelIds").toList();
QJsonArray targets;for(int i=0;i<values.size();++i)targets.append(QJsonObject{{"id",i<ids.size()?ids[i].toInt():i},{"value",values[i]}});
const QMap<QString,QString> methods={{QStringLiteral("设置角度"),"SetDexHandAngle"},{QStringLiteral("设置位置"),"SetDexHandPos"},{QStringLiteral("设置速度"),"SetDexHandSpeed"},{QStringLiteral("设置力"),"SetDexHandForce"}};
const QString method=methods.value(action);action=QStringLiteral("接口 · ")+method;
parameters={{"service","cmvr.api.DexHandService"},{"method",method},{"request",QJsonObject{{"values",targets}}},{"timeoutMs",180000}};
} else if (parameterPages.currentIndex() == 5) {
QJsonParseError error;
const QJsonDocument request = QJsonDocument::fromJson(requestEdit.text().trimmed().toUtf8(), &error);
@ -781,9 +860,18 @@ bool editTaskDialog(QWidget *parent, QString &name, QString &type, QString &devi
parameters.insert(QStringLiteral("sampleRate"), sampleRateSpin.value());
parameters.insert(QStringLiteral("channels"), channelSpin.value());
}
if(parameterPages.currentIndex()==8){
QJsonObject request;QString error;
if(!apiEditor.request(request,error)){showTaskNotice(parent,QStringLiteral("接口参数错误"),error);return false;}
const auto op=TaskApi::operation(type,action);
parameters={{"service",op.value("service")},{"method",op.value("method")},{"request",request},{"timeoutMs",rpcTimeout.value()}};
}
waitUnit = normalizedWaitUnit(waitUnitCombo.currentData().toString());
waitMs = qRound(waitSpin.value() * (waitUnit == QStringLiteral("s") ? 1000.0 : 1.0));
return true;
};
QObject::connect(&buttons,&QDialogButtonBox::accepted,&dialog,[&]{if(collectParameters())dialog.accept();});
return dialog.exec()==QDialog::Accepted;
}
}
@ -802,6 +890,13 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare
title->setObjectName(QStringLiteral("sectionTitle"));
m_groupCombo = new QComboBox(panel);
m_groupCombo->setMinimumWidth(240);
auto* importButton=new QPushButton(QStringLiteral("导入 JSON"),panel);
auto* exportButton=new QPushButton(QStringLiteral("导出 JSON / 接口清单"),panel);
groups->addWidget(importButton);groups->addWidget(exportButton);
connect(importButton,&QPushButton::clicked,this,&TaskOrchestrationWidget::importDocument);
connect(exportButton,&QPushButton::clicked,this,&TaskOrchestrationWidget::exportDocument);
m_editControls<<importButton<<exportButton;
QPushButton *newGroup = new QPushButton(QStringLiteral("新建方案"), panel);
QPushButton *renameGroup = new QPushButton(QStringLiteral("重命名"), panel);
newGroup->setObjectName(QStringLiteral("primaryButton"));
@ -840,7 +935,7 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare
m_insertionHint->setToolTip(QStringLiteral("与点位规划相同:选中节点后在同层后方插入,进入循环需点击“添加到选中循环”。"));
insertionToolbar->addWidget(m_insertionHint);
m_editControls = {newGroup, renameGroup, m_groupCombo, addTaskButton, addLoopButton,
editButton, removeButton, upButton, downButton, rootInsertion, loopInsertion};
editButton, removeButton, upButton, downButton, rootInsertion, loopInsertion, importButton, exportButton};
layout->addLayout(insertionToolbar);
connect(rootInsertion, &QPushButton::clicked, this, &TaskOrchestrationWidget::setInsertionAtRoot);
connect(loopInsertion, &QPushButton::clicked, this, [this]() {
@ -875,6 +970,14 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare
m_history->setMaximumHeight(128);
m_history->setMinimumHeight(82);
m_history->addItem(QStringLiteral("尚未执行任务"));
connect(m_history->model(),&QAbstractItemModel::rowsInserted,this,[this]{while(m_history->count()>200)delete m_history->takeItem(0);});
connect(m_history,&QListWidget::itemDoubleClicked,this,[this](QListWidgetItem* item){
const QString detail=item->data(Qt::UserRole).toString();if(detail.isEmpty())return;
TaskNodeDialog dialog(QStringLiteral("节点执行反馈"),this);dialog.setWindowModality(Qt::WindowModal);dialog.resize(780,540);
auto* text=new QPlainTextEdit(&dialog);text->setReadOnly(true);text->setPlainText(detail);dialog.contentLayout()->addWidget(text);
auto* close=new QPushButton(QStringLiteral("关闭"),&dialog);connect(close,&QPushButton::clicked,&dialog,&QDialog::accept);dialog.contentLayout()->addWidget(close);dialog.exec();
});
layout->addWidget(m_history);
QHBoxLayout *actions = new QHBoxLayout;
m_status = new QLabel(QStringLiteral("未运行"), panel);
@ -893,7 +996,7 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare
QString name = QStringLiteral("新任务方案");
if (!editNameDialog(this, QStringLiteral("新建任务方案"), QStringLiteral("方案名称"), name)) return;
storeCurrentGroup();
QJsonObject group; group.insert(QStringLiteral("name"), name); group.insert(QStringLiteral("nodes"), QJsonArray());
QJsonObject group; group.insert("id",QUuid::createUuid().toString(QUuid::WithoutBraces)); group.insert(QStringLiteral("name"), name); group.insert(QStringLiteral("nodes"), QJsonArray());
m_groups.append(group); m_groupCombo->addItem(name); m_groupCombo->setCurrentIndex(m_groups.size() - 1);
});
connect(renameGroup, &QPushButton::clicked, this, [this]() {
@ -927,6 +1030,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();
if(!m_storageWritable)m_status->setText(QStringLiteral("任务文件读取/校验失败,原文件已保留,自动保存已禁用;可导出当前编辑内容或导入有效文件。"));
}
TaskOrchestrationWidget::~TaskOrchestrationWidget()
@ -1096,6 +1200,7 @@ bool TaskOrchestrationWidget::appendRunSteps(QTreeWidgetItem *item, QList<RunSte
void TaskOrchestrationWidget::startRun()
{
if (!m_runSteps.isEmpty()) return;
++m_executionGeneration;
m_runSteps.clear();
QString error;
for (int i = 0; i < m_tree->topLevelItemCount(); ++i)
@ -1132,7 +1237,7 @@ void TaskOrchestrationWidget::runNext()
m_waitingForResult = true;
m_currentWaitMs = step.waitMs;
m_currentWaitUnit = step.waitUnit;
if (step.deviceType == QStringLiteral("相机") && step.action == QStringLiteral("深度抓图")
if (step.deviceType == QStringLiteral("相机") && (step.action == QStringLiteral("深度抓图")||step.action==QStringLiteral("接口 · GetDepthImage")||step.action==QStringLiteral("接口 · GetRGBDImages"))
&& !CameraCapabilities::depthImage(m_cameraCapabilities.value(step.deviceId))) {
completeCurrentTask(false, QStringLiteral("相机 %1 不支持深度图像或尚未获取深度能力")
.arg(step.deviceId));
@ -1154,6 +1259,9 @@ void TaskOrchestrationWidget::completeCurrentTask(bool success, const QString &d
m_history->addItem(QStringLiteral("%1 %2 · %3")
.arg(success ? QStringLiteral("✓") : QStringLiteral("✕"), step->name,
detail.isEmpty() ? QStringLiteral("已完成") : detail));
const QString feedback=detail.size()>1048576?detail.left(1048576)+QStringLiteral("\n[反馈超过1MiB,界面已截断;图像请使用专用抓图/预览节点]"):detail;
m_history->item(m_history->count()-1)->setData(Qt::UserRole,feedback);
m_history->item(m_history->count()-1)->setToolTip(QStringLiteral("双击查看并复制接口反馈"));
m_history->scrollToBottom();
}
rebuildFlowScene();
@ -1198,9 +1306,9 @@ void TaskOrchestrationWidget::completeCommandTask(const QString &command, bool s
}
} else if (step.deviceType == QStringLiteral("AGV")) {
if (step.action == QStringLiteral("导航站点")) expected = QStringLiteral("AGV NavigateToStation");
else if (step.action == QStringLiteral("停止")) expected = QStringLiteral("AGV stop");
else if (step.action == QStringLiteral("暂停")) expected = QStringLiteral("AGV pause");
else if (step.action == QStringLiteral("继续")) expected = QStringLiteral("AGV resume");
else if (step.action == QStringLiteral("停止")) expected = QStringLiteral("AGV Cancel");
else if (step.action == QStringLiteral("暂停")) expected = QStringLiteral("AGV Pause");
else if (step.action == QStringLiteral("继续")) expected = QStringLiteral("AGV Resume");
} else if (step.deviceType == QStringLiteral("灵巧手")) {
const QHash<QString, QString> commands = {
{QStringLiteral("设置角度"), QStringLiteral("DexHand angle")},
@ -1239,9 +1347,10 @@ void TaskOrchestrationWidget::completeRpcTask(const QString &service,
const RunStep &step = m_runSteps.at(m_runIndex - 1);
QString expectedService;
QString expectedMethod;
if (step.deviceType == QStringLiteral("通用RPC")) {
if (!TaskApi::operation(step.deviceType,step.action).isEmpty() || step.deviceType == QStringLiteral("通用RPC")) {
expectedService = step.parameters.value(QStringLiteral("service")).toString();
expectedMethod = step.parameters.value(QStringLiteral("method")).toString();
const auto api=TaskApi::operation(step.deviceType,step.action);if(!api.isEmpty()){expectedService=api.value("service").toString();expectedMethod=api.value("method").toString();}
} else if (step.deviceType == QStringLiteral("仿生头")) {
expectedService = QStringLiteral("cmvr.api.BioHeadService");
expectedMethod = BioHeadOperations::method(step.action);
@ -1268,7 +1377,8 @@ void TaskOrchestrationWidget::completeRpcTask(const QString &service,
completeCurrentTask(accepted, feedback);
return;
}
completeCurrentTask(success, detail);
QString feedback;const bool accepted=TaskApi::responseSucceeded(success,detail,feedback);
completeCurrentTask(accepted, feedback);
}
void TaskOrchestrationWidget::failActiveTask(const QString &detail)
@ -1330,6 +1440,7 @@ void TaskOrchestrationWidget::completeActionTask(const QString &deviceType,
void TaskOrchestrationWidget::stopRun(const QString &reason)
{
++m_executionGeneration;emit executionStopped();
m_runTimer->stop(); m_runSteps.clear(); m_runIndex = 0; m_waitingForResult = false;
for (auto *control : m_editControls) control->setEnabled(true);
m_flowView->setInteractive(true);
@ -1343,6 +1454,8 @@ QString TaskOrchestrationWidget::storagePath() const
QJsonObject TaskOrchestrationWidget::itemToJson(QTreeWidgetItem *item) const
{
QJsonObject object; const QString kind = item->data(0, KindRole).toString();
if(item->data(0,NodeIdRole).toString().isEmpty())item->setData(0,NodeIdRole,QUuid::createUuid().toString(QUuid::WithoutBraces));
object.insert("id",item->data(0,NodeIdRole).toString());
object.insert(QStringLiteral("kind"), kind); object.insert(QStringLiteral("name"), item->text(0));
if (kind == QStringLiteral("loop")) {
object.insert(QStringLiteral("collapsed"), !item->isExpanded());
@ -1357,12 +1470,15 @@ QJsonObject TaskOrchestrationWidget::itemToJson(QTreeWidgetItem *item) const
object.insert(QStringLiteral("parameters"), QJsonDocument::fromJson(item->data(0, ParametersRole).toString().toUtf8()).object());
object.insert(QStringLiteral("waitMs"), item->data(0, WaitRole).toInt());
object.insert(QStringLiteral("waitUnit"), normalizedWaitUnit(item->data(0, WaitUnitRole).toString()));
const auto ex=TaskApi::execution(object.value("deviceType").toString(),object.value("action").toString(),object.value("deviceId").toString(),object.value("parameters").toObject());
object.insert("execution",ex);object.insert("operationId",ex.value("kind")=="grpc_unary"?ex.value("service").toString()+"."+ex.value("method").toString():ex.value("adapter").toString());
} return object;
}
QTreeWidgetItem *TaskOrchestrationWidget::itemFromJson(const QJsonObject &object) const
{
QTreeWidgetItem *item = new QTreeWidgetItem; const QString kind = object.value(QStringLiteral("kind")).toString(QStringLiteral("task"));
item->setData(0,NodeIdRole,object.value("id").toString(QUuid::createUuid().toString(QUuid::WithoutBraces)));
item->setData(0, KindRole, kind); item->setText(0, object.value(QStringLiteral("name")).toString());
if (kind == QStringLiteral("loop")) {
const int count = qMax(1, object.value(QStringLiteral("count")).toInt(1)); item->setData(0, LoopCountRole, count);
@ -1505,6 +1621,14 @@ void TaskOrchestrationWidget::storeCurrentGroup()
m_groups[m_activeGroup].insert(QStringLiteral("nodes"), nodes);
}
void TaskOrchestrationWidget::clearDeviceInfo(){const auto ids=m_deviceInfo.keys();m_deviceInfo.clear();for(const auto& id:ids)emit deviceInfoChanged(id);}
void TaskOrchestrationWidget::setDeviceInfo(const QString& id,const QVariantMap& info)
{
auto merged=m_deviceInfo.value(id);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_deviceInfo.value(id))return;m_deviceInfo.insert(id,merged);emit deviceInfoChanged(id);
}
void TaskOrchestrationWidget::setAvailableDevices(const QVariantList &devices)
{
m_availableDevices = devices;
@ -1537,11 +1661,22 @@ void TaskOrchestrationWidget::activateGroup(int index)
void TaskOrchestrationWidget::load()
{
QFile file(storagePath()); if (file.open(QIODevice::ReadOnly)) {
const QJsonArray groups = QJsonDocument::fromJson(file.readAll()).object().value(QStringLiteral("groups")).toArray();
for (const QJsonValue &group : groups) m_groups.append(group.toObject());
QFile file(storagePath());
if(file.exists()){
if(!file.open(QIODevice::ReadOnly)){m_storageWritable=false;emit statusMessage("ERROR",QStringLiteral("无法读取任务文件,禁止自动覆盖"));}
else {QJsonParseError parse;const auto doc=QJsonDocument::fromJson(file.readAll(),&parse);auto data=doc.object();QString error;
if(parse.error!=QJsonParseError::NoError||!doc.isObject()||!TaskApi::normalize(data,error)){
m_storageWritable=false;emit statusMessage("ERROR",QStringLiteral("任务文件无效,原文件保留并禁止覆盖:")+error);
}else{
if(doc.object().value("version").toInt()==1 || !doc.object().contains("format")){
const QString backup=QFile::exists(storagePath()+".v1.bak")?storagePath()+".v1."+QUuid::createUuid().toString(QUuid::WithoutBraces)+".bak":storagePath()+".v1.bak";
if(!QFile::copy(storagePath(),backup)){m_storageWritable=false;emit statusMessage("ERROR",QStringLiteral("旧任务备份失败,禁止覆盖原文件"));}
}
for(const auto& g:data.value("groups").toArray())m_groups.append(g.toObject());
}
}
}
if (m_groups.isEmpty()) { QJsonObject group; group.insert(QStringLiteral("name"), QStringLiteral("默认任务")); group.insert(QStringLiteral("nodes"), QJsonArray()); m_groups.append(group); }
if (m_groups.isEmpty()) { QJsonObject group; group.insert("id",QUuid::createUuid().toString(QUuid::WithoutBraces)); group.insert(QStringLiteral("name"), QStringLiteral("默认任务")); group.insert(QStringLiteral("nodes"), QJsonArray()); m_groups.append(group); }
m_switchingGroup = true; for (const QJsonObject &group : m_groups) m_groupCombo->addItem(group.value(QStringLiteral("name")).toString());
m_groupCombo->setCurrentIndex(0); m_switchingGroup = false; m_activeGroup = 0;
for (const QJsonValue &node : m_groups.first().value(QStringLiteral("nodes")).toArray()) m_tree->addTopLevelItem(itemFromJson(node.toObject()));
@ -1551,10 +1686,46 @@ void TaskOrchestrationWidget::load()
void TaskOrchestrationWidget::save()
{
if(!m_storageWritable)return;
storeCurrentGroup(); QJsonArray groups; for (const QJsonObject &group : m_groups) groups.append(group);
QJsonObject root; root.insert(QStringLiteral("version"), 1); root.insert(QStringLiteral("groups"), groups);
QJsonObject root; root.insert(QStringLiteral("groups"), groups);
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());
QDir().mkpath(QFileInfo(storagePath()).absolutePath()); QSaveFile file(storagePath());
if (!file.open(QIODevice::WriteOnly) || file.write(QJsonDocument(root).toJson(QJsonDocument::Indented)) < 0 || !file.commit())
emit statusMessage(QStringLiteral("ERROR"), QStringLiteral("任务编排 JSON 保存失败:%1").arg(storagePath()));
rebuildFlowScene();
}
void TaskOrchestrationWidget::exportDocument(){
storeCurrentGroup();QJsonArray groups;for(const auto& g:m_groups)groups.append(g);
QJsonObject document{{"groups",groups}};QString error;
if(!TaskApi::serverDocument(document,error)){showTaskNotice(this,QStringLiteral("无法导出"),error);return;}
const QString path=QFileDialog::getSaveFileName(this,QStringLiteral("导出任务"),"task_flow.json",QStringLiteral("JSON (*.json)"));if(path.isEmpty())return;
QSaveFile output(path);const auto bytes=QJsonDocument(document).toJson(QJsonDocument::Indented);
if(!output.open(QIODevice::WriteOnly)||output.write(bytes)!=bytes.size()||!output.commit()){showTaskNotice(this,QStringLiteral("导出失败"),output.errorString());return;}
QSaveFile catalog(QFileInfo(path).absolutePath()+"/task_operations.json");const auto definitions=QJsonDocument(TaskApi::catalog()).toJson(QJsonDocument::Indented);
if(!catalog.open(QIODevice::WriteOnly)||catalog.write(definitions)!=definitions.size()||!catalog.commit())showTaskNotice(this,QStringLiteral("接口清单导出失败"),catalog.errorString());
else emit statusMessage("OK",QStringLiteral("已导出任务和 task_operations.json;未发送任何设备操作"));
}
void TaskOrchestrationWidget::importDocument(){
if(!m_runSteps.isEmpty())return;
const QString path=QFileDialog::getOpenFileName(this,QStringLiteral("导入任务"),{},QStringLiteral("JSON (*.json)"));if(path.isEmpty())return;
QFile file(path);if(!file.open(QIODevice::ReadOnly)){showTaskNotice(this,QStringLiteral("导入失败"),file.errorString());return;}
if(file.size()>16*1024*1024){showTaskNotice(this,QStringLiteral("导入失败"),QStringLiteral("文件超过16MB"));return;}
QJsonParseError parse;const auto parsed=QJsonDocument::fromJson(file.readAll(),&parse);auto doc=parsed.object();QString error;
if(parse.error!=QJsonParseError::NoError||!parsed.isObject()||!TaskApi::normalize(doc,error)){showTaskNotice(this,QStringLiteral("导入失败"),error.isEmpty()?parse.errorString():error);return;}
// Imported plans are appended; existing plans and source files are preserved.
const auto regenerate=[](QJsonObject g){
std::function<void(QJsonObject&)> renew=[&](QJsonObject& n){n.insert("id",QUuid::createUuid().toString(QUuid::WithoutBraces));auto children=n.value("children").toArray();for(int i=0;i<children.size();++i){auto child=children[i].toObject();renew(child);children[i]=child;}if(n.value("kind")=="loop")n.insert("children",children);};
g.insert("id",QUuid::createUuid().toString(QUuid::WithoutBraces));auto nodes=g.value("nodes").toArray();for(int i=0;i<nodes.size();++i){auto node=nodes[i].toObject();renew(node);nodes[i]=node;}g.insert("nodes",nodes);return g;
};
if(!m_storageWritable&&QFile::exists(storagePath())){
const QString backup=storagePath()+".before-import."+QUuid::createUuid().toString(QUuid::WithoutBraces)+".bak";
if(!QFile::copy(storagePath(),backup)){showTaskNotice(this,QStringLiteral("导入失败"),QStringLiteral("原任务备份失败,未修改原文件"));return;}
}
storeCurrentGroup();const int first=m_groups.size();m_switchingGroup=true;
for(const auto& value:doc.value("groups").toArray()){auto group=regenerate(value.toObject());m_groups.append(group);m_groupCombo->addItem(group.value("name").toString());}
m_switchingGroup=false;m_storageWritable=true;
if(m_groups.size()>first){m_groupCombo->setCurrentIndex(first);if(m_activeGroup!=first)activateGroup(first);}else save();
}

View File

@ -23,6 +23,9 @@ public:
explicit TaskOrchestrationWidget(QWidget *parent = nullptr);
~TaskOrchestrationWidget() override;
void setAvailableDevices(const QVariantList &devices);
void setDeviceInfo(const QString &deviceId, const QVariantMap &info);
void clearDeviceInfo();
QVariantMap deviceInfo(const QString &deviceId) const { return m_deviceInfo.value(deviceId); }
void setCameraCapabilities(const QString &deviceId, const QVariantMap &capabilities);
void completeCurrentTask(bool success, const QString &detail);
void completeCommandTask(const QString &command, bool success,
@ -38,8 +41,13 @@ public:
const QString &action, bool success,
const QString &detail);
quint64 executionGeneration() const { return m_executionGeneration; }
signals:
void executionStopped();
void cameraCapabilitiesChanged();
void deviceInfoChanged(const QString &deviceId);
void deviceInfoRequested(const QString &deviceId, const QString &deviceType);
void taskRequested(const QString &deviceType, const QString &deviceId,
const QString &action, const QJsonObject &parameters);
void statusMessage(const QString &level, const QString &message);
@ -57,6 +65,10 @@ private:
QTreeWidgetItem *source = nullptr;
};
void importDocument();
void exportDocument();
bool m_storageWritable=true;
quint64 m_executionGeneration=0;
void addTask(QTreeWidgetItem *parentItem = nullptr);
void addLoop(QTreeWidgetItem *parentItem = nullptr);
void editSelected();
@ -103,5 +115,6 @@ private:
int m_currentWaitMs = 0;
QString m_currentWaitUnit = QStringLiteral("ms");
QVariantList m_availableDevices;
QHash<QString,QVariantMap> m_deviceInfo;
QHash<QString, QVariantMap> m_cameraCapabilities;
};

318
src/taskprotoeditor.cpp Normal file
View File

@ -0,0 +1,318 @@
#include "taskprotoeditor.h"
#include "taskapi.h"
#include "applicationstyle.h"
#include "taskjointeditor.h"
#include "taskuilabels.h"
#include <QDoubleValidator>
#include <google/protobuf/descriptor.h>
#include <QFormLayout>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGroupBox>
#include <QScrollArea>
#include <QLineEdit>
#include <QPlainTextEdit>
#include <QDoubleSpinBox>
#include <QComboBox>
#include <QCheckBox>
#include <QPushButton>
#include <QLabel>
#include <QJsonArray>
#include <QMap>
#include <QTabWidget>
#include <QTabBar>
#include <QGridLayout>
#include <memory>
#include <cmath>
namespace {
using D=google::protobuf::Descriptor;using F=google::protobuf::FieldDescriptor;
using Read=std::function<QJsonValue(QString&)>;
struct Context {QString service,method;QVariantMap device;};
bool messageEnabled(const QGroupBox* group){const auto enabled=group->property("taskMessageEnabled");return enabled.isValid()?enabled.toBool():(!group->isCheckable()||group->isChecked());}
QString label(const F* f,const QString& method={}){
const QString n=QString::fromStdString(f->name());QString title=TaskUi::text("fields",n);
if(n=="velocity"||n=="acceleration"||n=="jerk"){
if(f->cpp_type()==F::CPPTYPE_MESSAGE)return title;
const bool linear=method=="moveL"||method=="speedL";
title+=linear?(n=="velocity"?QStringLiteral("(米/秒)"):n=="acceleration"?QStringLiteral("(米/秒²)"):QStringLiteral("(米/秒³)")):
(n=="velocity"?QStringLiteral("(弧度/秒)"):n=="acceleration"?QStringLiteral("(弧度/秒²)"):QStringLiteral("(弧度/秒³)"));
}
return title;
}
Read message(QWidget*,QFormLayout*,const D*,const QJsonObject&,int,bool,const Context&,const QStringList& = {});
Read value(QWidget* parent,QFormLayout* form,const F* f,const QJsonValue& initial,int depth,const Context& context){
const QString title=label(f,context.method);
const QString field=QString::fromStdString(f->name());
QString source;bool required=false;
if(context.service=="cmvr.api.AgvService"){
if(field=="station_id"||field=="source_station"||field=="target_station"){
source="stations";required=field=="station_id";
}
if(field=="map_name"&&(context.method=="switchMap"||context.method=="downloadMap")){
source="maps";required=true;
}
}
if(context.service=="cmvr.api.ArmService"){
if(field=="user_coordinate_name") {source="coordinates";required=context.method=="moveJPose";}
if(field=="name"&&f->containing_type()->full_name()=="cmvr.api.UserCoordinateSystemCommand.Request"&&
(context.method=="GetUserCoordinateSystem"||context.method=="DeleteUserCoordinateSystem"||context.method=="ApplyUserCoordinateSystem"||context.method=="UpdateUserCoordinateSystem")){
source="coordinates";required=true;
}
if(field=="base_link"||field=="base_frame")source="baseFrames";
if(field=="ee_link"||field=="tcp_frame")source="tcpFrames";
}
if(!source.isEmpty()){
auto* combo=new QComboBox(parent);combo->setObjectName("taskOption_"+field);ApplicationStyle::styleComboBox(combo);
combo->addItem(required?QStringLiteral("请选择(无选项时刷新设备参数)"):QStringLiteral("使用设备默认 / 不指定"),QString());
const auto entries=context.device.value(source).toList();
for(const auto& entry:entries){
const auto record=entry.toMap();QString name=entry.toString(),text=name;
if(source=="coordinates")name=text=record.value("name").toString();
if(source=="stations"){
name=record.value("id").toString();const auto description=record.value("description").toString();
text=description.isEmpty()?name:name+" · "+description;
}
if(!name.isEmpty()&&combo->findData(name)<0)combo->addItem(text,name);
}
const QString defaultFrame=context.device.value(source=="baseFrames"?"defaultBaseFrame":"defaultTcpFrame").toString();
if((source=="baseFrames"||source=="tcpFrames")&&!defaultFrame.isEmpty()&&combo->findData(defaultFrame)<0)combo->addItem(defaultFrame,defaultFrame);
const QString existing=initial.toString();int at=combo->findData(existing);
// Keep an imported value visible, but never silently replace it with another resource.
if(at<0&&!existing.isEmpty()){combo->addItem(existing+QStringLiteral("(待设备确认)"),existing);at=combo->count()-1;}
if(at>=0)combo->setCurrentIndex(at);
form->addRow(title,combo);
return [combo,required](QString& error){const auto name=combo->currentData().toString();if(required&&name.isEmpty())error=QStringLiteral("请选择设备返回的有效选项,没有选项时请刷新设备参数。");return QJsonValue(name);};
}
if(f->name()=="joint_name"&&context.service=="cmvr.api.ArmService"){
auto* edit=new QComboBox(parent);edit->setObjectName("taskJointSelector");
ApplicationStyle::styleComboBox(edit);edit->setEditable(false);
const auto names=context.device.value("jointNames").toStringList();
edit->addItem(names.isEmpty()?QStringLiteral("请先刷新设备参数"):QStringLiteral("请选择关节"),QString());
for(const auto& name:names)if(!name.isEmpty())edit->addItem(name,name);
const int selected=edit->findData(initial.toString());
if(selected>0)edit->setCurrentIndex(selected);
else if(!initial.toString().isEmpty())edit->setItemText(0,QStringLiteral("原关节不属于当前设备,请重新选择"));
edit->setEnabled(edit->count()>1);form->addRow(title,edit);
if(names.isEmpty()){
auto* hint=new QLabel(QStringLiteral("点击“刷新设备参数”获取当前设备的实际关节列表。"),parent);
hint->setWordWrap(true);form->addRow(hint);
}
return [edit](QString& error){
const QString name=edit->currentData().toString();
if(name.isEmpty())error=QStringLiteral("请选择当前设备中要操作的关节;没有选项时请先刷新设备参数。");
return QJsonValue(name);
};
}
if(f->name()=="mode"&&f->containing_type()->full_name()=="cmvr.api.MotorRequest"){
auto* edit=new QComboBox(parent);ApplicationStyle::styleComboBox(edit);
const QStringList names={QStringLiteral("轮廓位置"),QStringLiteral("轮廓速度"),QStringLiteral("轮廓力矩"),QStringLiteral("周期位置"),QStringLiteral("周期速度"),QStringLiteral("周期力矩")};
const int modes[]={1,3,4,8,9,10};for(int i=0;i<6;++i)edit->addItem(names[i]+QString(" (%1)").arg(modes[i]),modes[i]);
if(initial.isDouble()){const int at=edit->findData(initial.toInt());if(at>=0)edit->setCurrentIndex(at);else{edit->addItem(QString::number(initial.toInt()),initial.toInt());edit->setCurrentIndex(edit->count()-1);}}
form->addRow(title,edit);return [edit](QString&){return QJsonValue(edit->currentData().toInt());};
}
if(f->cpp_type()==F::CPPTYPE_MESSAGE){
const QString full=QString::fromStdString(f->message_type()->full_name());
if(full=="google.protobuf.Timestamp"||full=="google.protobuf.Duration"||full=="google.protobuf.FieldMask"){
auto* edit=new QLineEdit(initial.toString(),parent);edit->setPlaceholderText(full.endsWith("Timestamp")?"2026-11-10T00:00:00Z":full.endsWith("Duration")?"1.5s":"field_a,field_b");form->addRow(title,edit);
return [edit](QString&){return QJsonValue(edit->text());};
}
const bool required=QStringList{"target","options","joints","velocity","translation","pose","coordinate","base_tcp_pose","user_pose"}.contains(QString::fromStdString(f->name()));
auto* group=new QGroupBox(title,parent);group->setProperty("taskMessageEnabled",required||initial.isObject());
auto* groupLayout=new QVBoxLayout(group);auto* body=new QWidget(group);auto* children=new QFormLayout(body);
children->setContentsMargins(0,0,0,0);groupLayout->addWidget(body);body->setVisible(messageEnabled(group));
if(!required){auto* toggle=new QPushButton(messageEnabled(group)?QStringLiteral("移除此项设置"):QStringLiteral("添加此项设置"),group);toggle->setObjectName("taskMessageToggle");groupLayout->insertWidget(0,toggle,0,Qt::AlignLeft);
QObject::connect(toggle,&QPushButton::clicked,group,[group,body,toggle]{const bool enabled=!messageEnabled(group);group->setProperty("taskMessageEnabled",enabled);body->setVisible(enabled);toggle->setText(enabled?QStringLiteral("移除此项设置"):QStringLiteral("添加此项设置"));for(QWidget* at=group;at;at=at->parentWidget())if(auto* editor=dynamic_cast<TaskProtoEditor*>(at)){editor->refreshContentSize();break;}});
}
QObject::connect(group,&QGroupBox::toggled,body,&QWidget::setVisible);form->addRow(group);
if(f->message_type()->full_name()=="cmvr.api.CartesianPose"){
auto* grid=new QGridLayout;children->addRow(grid);auto entries=std::make_shared<QList<QPair<QString,QLineEdit*>>>();
for(int i=0;i<f->message_type()->field_count();++i){auto* part=f->message_type()->field(i);const QString key=QString::fromStdString(part->name());
auto* box=new QWidget(body);auto* cell=new QVBoxLayout(box);cell->setContentsMargins(0,0,0,0);cell->addWidget(new QLabel(label(part),box));
auto* edit=new QLineEdit(box);edit->setProperty("taskField",key);edit->setValidator(new QDoubleValidator(edit));edit->setPlaceholderText(QStringLiteral("填写目标值"));
const auto v=initial.toObject().value(key);if(v.isDouble())edit->setText(QString::number(v.toDouble(),'g',17));cell->addWidget(edit);grid->addWidget(box,i/2,i%2);entries->append(qMakePair(key,edit));}
return [group,entries](QString& error){if(!messageEnabled(group))return QJsonValue(QJsonValue::Undefined);QJsonObject result;
for(const auto& entry:*entries){bool ok;double n=entry.second->text().toDouble(&ok);if(!ok||!std::isfinite(n)){error=QStringLiteral("请完整填写目标位姿。");return QJsonValue();}result.insert(entry.first,n);}return QJsonValue(result);};
}
if(depth>=12){auto* hint=new QLabel(QStringLiteral("嵌套超过12层,当前表单不支持;请拆分节点。"),group);children->addRow(hint);return [group](QString& e){if(messageEnabled(group))e=QStringLiteral("参数嵌套超过12层");return QJsonValue();};}
auto read=message(group,children,f->message_type(),initial.toObject(),depth+1,false,context);
return [group,read](QString& error){return messageEnabled(group)?read(error):QJsonValue(QJsonValue::Undefined);};
}
if(f->cpp_type()==F::CPPTYPE_BOOL){auto* edit=new QCheckBox(parent);edit->setChecked(initial.toBool());form->addRow(title,edit);return [edit](QString&){return QJsonValue(edit->isChecked());};}
if(f->cpp_type()==F::CPPTYPE_ENUM){
auto* edit=new QComboBox(parent);ApplicationStyle::styleComboBox(edit);for(int i=0;i<f->enum_type()->value_count();++i){auto* v=f->enum_type()->value(i);edit->addItem(TaskUi::text("enums",QString::fromStdString(v->name())),QString::fromStdString(v->name()));}
int at=initial.isString()?edit->findData(initial.toString()):-1;
if(initial.isDouble())for(int i=0;i<f->enum_type()->value_count();++i)if(f->enum_type()->value(i)->number()==initial.toInt())at=i;
if(at>=0)edit->setCurrentIndex(at);form->addRow(title,edit);return [edit](QString&){return QJsonValue(edit->currentData().toString());};
}
auto* edit=new QLineEdit(parent);if(initial.isString())edit->setText(initial.toString());else if(initial.isDouble())edit->setText(QString::number(initial.toDouble(),'g',17));
const bool explicitPose=context.service=="cmvr.api.ArmService"&&f->containing_type()->name()=="CartesianPose";
if(edit->text().isEmpty()&&f->cpp_type()!=F::CPPTYPE_STRING&&!explicitPose)edit->setText("0");
if(explicitPose)edit->setPlaceholderText(QStringLiteral("填写目标值"));
if(f->type()==F::TYPE_BYTES)edit->setPlaceholderText(QStringLiteral("Base64 编码的二进制内容"));
edit->setToolTip(QStringLiteral("%1;按十进制输入数值。").arg(QString::fromLatin1(f->type_name())));edit->setToolTip(edit->toolTip()+QStringLiteral("\n接口字段:")+QString::fromStdString(f->name()));
if(f->cpp_type()!=F::CPPTYPE_STRING)edit->setValidator(new QDoubleValidator(edit));
form->addRow(title,edit);
return [edit,f](QString& error)->QJsonValue{
const QString text=edit->text();if(f->cpp_type()==F::CPPTYPE_STRING)return text;
if(f->cpp_type()==F::CPPTYPE_INT64){bool ok;text.toLongLong(&ok);if(!ok)error=label(f)+QStringLiteral(":请输入有效的64位整数");return text;}
if(f->cpp_type()==F::CPPTYPE_UINT64){bool ok;text.toULongLong(&ok);if(!ok||text.startsWith('-'))error=label(f)+QStringLiteral(":请输入有效的无符号64位整数");return text;}
bool ok=false;const double n=text.toDouble(&ok);if(!ok||!std::isfinite(n))error=label(f)+QStringLiteral(":数值无效");
if((f->cpp_type()==F::CPPTYPE_INT32||f->cpp_type()==F::CPPTYPE_UINT32)&&std::floor(n)!=n)error=label(f)+QStringLiteral(":必须为整数");return n;
};
}
Read message(QWidget* parent,QFormLayout* form,const D* descriptor,const QJsonObject& initial,int depth,bool root,const Context& context,const QStringList& allowed){
struct Field {QString name;Read read;const google::protobuf::OneofDescriptor* oneof;QCheckBox* present;};
auto fields=std::make_shared<QList<Field>>();QMap<const google::protobuf::OneofDescriptor*,QComboBox*> choices;
QComboBox* motor=nullptr;
if(root&&descriptor->full_name()=="cmvr.api.MotorRequest"&&(allowed.isEmpty()||allowed.contains("node_id"))){
motor=new QComboBox(parent);motor->setObjectName("taskMotorSelector");ApplicationStyle::styleComboBox(motor);
motor->addItem(QStringLiteral("请选择电机(无选项时刷新设备参数)"),QVariantMap());
const auto motors=context.device.value("motors").toList();
for(const auto& entry:motors){const auto m=entry.toMap();motor->addItem(QStringLiteral("%1 · 节点 %2").arg(m.value("joint_name").toString()).arg(m.value("node_id").toUInt()),m);}
for(int i=1;i<motor->count();++i){const auto m=motor->itemData(i).toMap();
const auto node=initial.contains("node_id")?initial.value("node_id"):initial.value("nodeId");
const auto name=initial.contains("joint_name")?initial.value("joint_name"):initial.value("jointName");
if((!node.isUndefined()&&m.value("node_id").toUInt()==node.toVariant().toUInt())||(!name.toString().isEmpty()&&m.value("joint_name").toString()==name.toString()))motor->setCurrentIndex(i);
}
form->addRow(QStringLiteral("目标电机"),motor);
}
for(int i=0;i<descriptor->oneof_decl_count();++i){auto* oneof=descriptor->oneof_decl(i);if(oneof->is_synthetic())continue;
auto* combo=new QComboBox(parent);ApplicationStyle::styleComboBox(combo);combo->addItem(QStringLiteral("不设置"),QString());
for(int j=0;j<oneof->field_count();++j){auto* f=oneof->field(j);combo->addItem(label(f),QString::fromStdString(f->name()));if(initial.contains(QString::fromStdString(f->name()))||initial.contains(QString::fromStdString(f->json_name())))combo->setCurrentIndex(j+1);}
form->addRow(QStringLiteral("选择输入方式"),combo);choices.insert(oneof,combo);
}
for(int i=0;i<descriptor->field_count();++i){auto* f=descriptor->field(i);const QString name=QString::fromStdString(f->name());if(root&&(name=="header"||name=="device_id"||name=="timestamp"||name=="command_id"))continue;
if(root&&!allowed.isEmpty()&&!allowed.contains(name))continue;
if(motor&&(name=="node_id"||name=="joint_name")){
Read read=[motor,name](QString& error){const auto selected=motor->currentData().toMap();
if(selected.isEmpty()){error=QStringLiteral("请选择设备实际提供的电机。");return QJsonValue();}
return QJsonValue::fromVariant(selected.value(name));};
fields->append({name,read,nullptr,nullptr});continue;
}
auto existing=initial.contains(name)?initial.value(name):initial.value(QString::fromStdString(f->json_name()));
auto* holder=new QWidget(parent);auto* layout=new QFormLayout(holder);layout->setContentsMargins(0,0,0,0);form->addRow(holder);Read read;
holder->setProperty("taskField",QString::fromStdString(descriptor->full_name())+"."+name);
if(f->is_repeated()&&f->cpp_type()!=F::CPPTYPE_MESSAGE&&
(name=="user_pose"||name=="user_frame_pose"||name=="tcp_offset")){
auto* group=new QGroupBox(label(f),holder);group->setCheckable(true);group->setChecked(!existing.toArray().isEmpty());
auto* grid=new QGridLayout(group);layout->addRow(group);auto edits=std::make_shared<QList<QLineEdit*>>();
const QStringList labels={QStringLiteral("X(米)"),QStringLiteral("Y(米)"),QStringLiteral("Z(米)"),QStringLiteral("RX(弧度)"),QStringLiteral("RY(弧度)"),QStringLiteral("RZ(弧度)")};
for(int i=0;i<6;++i){auto* box=new QWidget(group);auto* cell=new QVBoxLayout(box);cell->setContentsMargins(0,0,0,0);cell->addWidget(new QLabel(labels[i],box));
auto* edit=new QLineEdit(box);edit->setValidator(new QDoubleValidator(edit));const auto values=existing.toArray();if(i<values.size())edit->setText(QString::number(values[i].toDouble(),'g',17));cell->addWidget(edit);grid->addWidget(box,i/2,i%2);edits->append(edit);
box->setVisible(group->isChecked());QObject::connect(group,&QGroupBox::toggled,box,&QWidget::setVisible);}
read=[group,edits](QString& error){if(!group->isChecked())return QJsonValue(QJsonValue::Undefined);QJsonArray result;for(auto* edit:*edits){bool ok;double n=edit->text().toDouble(&ok);if(!ok||!std::isfinite(n)){error=QStringLiteral("请填写完整的六维坐标数据。");return QJsonValue();}result.append(n);}return QJsonValue(result);};
}else if(f->is_repeated()&&(f->name()=="position"||f->containing_type()->name()=="JointVelocityCommand")&&context.service=="cmvr.api.ArmService"){
auto* joints=new TaskJointEditor(holder);joints->setDevice(context.device,existing.toArray(),f->name()=="position");layout->addRow(joints);
read=[joints](QString& error){QJsonArray result;joints->values(result,error);return QJsonValue(result);};
}else if(f->is_repeated()&&f->name()=="values"&&context.service=="cmvr.api.DexHandService"&&!context.device.value("jointNames").toStringList().isEmpty()){
auto* table=new QTableWidget(0,2,holder);table->setHorizontalHeaderLabels({QStringLiteral("关节 / 通道"),QStringLiteral("目标值(设备单位)")});table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);table->verticalHeader()->hide();table->setMinimumHeight(200);layout->addRow(table);
const auto names=context.device.value("jointNames").toStringList();const auto ids=context.device.value("channelIds").toList();
auto edits=std::make_shared<QList<QPair<int,QLineEdit*>>>();const auto values=existing.toArray();
for(int i=0;i<names.size();++i){const int id=i<ids.size()?ids[i].toInt():i;table->insertRow(i);auto* item=new QTableWidgetItem(names[i]);item->setFlags(Qt::ItemIsEnabled);table->setItem(i,0,item);auto* edit=new QLineEdit(table);edit->setValidator(new QDoubleValidator(edit));edit->setPlaceholderText(QStringLiteral("输入目标值"));
for(const auto& value:values)if(value.toObject().value("id").toInt()==id)edit->setText(QString::number(value.toObject().value("value").toDouble(),'g',12));table->setCellWidget(i,1,edit);table->setRowHeight(i,44);edits->append(qMakePair(id,edit));}
read=[edits](QString& error){QJsonArray values;for(const auto& entry:*edits){bool ok;double n=entry.second->text().toDouble(&ok);if(!ok||!std::isfinite(n)){error=QStringLiteral("请填写每个通道的目标值。");return QJsonValue();}values.append(QJsonObject{{"id",entry.first},{"value",n}});}return QJsonValue(values);};
}else if(f->is_repeated()){
auto* group=new QGroupBox(label(f)+QStringLiteral(" · 列表"),holder);auto* rows=new QVBoxLayout(group);layout->addRow(group);
struct Entry{bool active=true;Read read;};auto entries=std::make_shared<QList<std::shared_ptr<Entry>>>();
const auto add=[group,rows,entries,f,depth,context](const QJsonValue& v){
auto* row=new QWidget(group);auto* form=new QFormLayout(row);auto entry=std::make_shared<Entry>();entry->read=value(row,form,f,v,depth,context);
auto* remove=new QPushButton(QStringLiteral("删除此项"),row);form->addRow(remove);QObject::connect(remove,&QPushButton::clicked,row,[row,entry]{entry->active=false;row->deleteLater();});rows->addWidget(row);entries->append(entry);
};
if(f->is_map()){
const auto map=existing.toObject();for(auto i=map.begin();i!=map.end();++i)add(QJsonObject{{"key",i.key()},{"value",i.value()}});
}else for(const auto& v:existing.toArray())add(v);
auto* addButton=new QPushButton(QStringLiteral("+ 添加一项"),group);layout->addRow(addButton);QObject::connect(addButton,&QPushButton::clicked,group,[add,f]{add(f->cpp_type()==F::CPPTYPE_MESSAGE?QJsonValue(QJsonObject()):QJsonValue());});
read=[entries,f](QString& error){QJsonArray result;for(const auto& entry:*entries)if(entry->active){auto v=entry->read(error);if(v.isUndefined()){error=QStringLiteral("列表项不能为空,请填写或删除此项");return QJsonValue();}result.append(v);}
if(f->is_map()){QJsonObject map;for(const auto& v:result){const auto entry=v.toObject();const QString key=entry.value("key").toVariant().toString();if(map.contains(key)){error=QStringLiteral("Map键重复:")+key;return QJsonValue();}map.insert(key,entry.value("value"));}return QJsonValue(map);}
return QJsonValue(result);};
}else read=value(holder,layout,f,existing,depth,context);
QCheckBox* present=nullptr;
if(f->has_optional_keyword()&&f->cpp_type()!=F::CPPTYPE_MESSAGE){present=new QCheckBox(QStringLiteral("设置此可选字段"),parent);form->addRow(present);present->setChecked(!existing.isUndefined());holder->setEnabled(present->isChecked());QObject::connect(present,&QCheckBox::toggled,holder,&QWidget::setEnabled);}
auto* oneof=f->real_containing_oneof();if(oneof){auto* combo=choices.value(oneof);const auto refresh=[holder,combo,name]{holder->setVisible(combo->currentData().toString()==name);};QObject::connect(combo,QOverload<int>::of(&QComboBox::currentIndexChanged),holder,[refresh](int){refresh();});refresh();}
fields->append({name,read,oneof,present});
}
return [fields,choices](QString& error){QJsonObject result;for(const auto& f:*fields){if(f.oneof&&choices.value(f.oneof)->currentData().toString()!=f.name)continue;if(f.present&&!f.present->isChecked())continue;const auto v=f.read(error);if(!error.isEmpty())return QJsonValue();if(!v.isUndefined())result.insert(f.name,v);}return QJsonValue(result);};
}
}
namespace {
class ParameterTabs final:public QTabWidget {
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());}
};
QString stateKey(const QWidget* widget,const QWidget* root){
QStringList path;for(auto* at=widget;at&&at!=root;at=at->parentWidget()){
const auto field=at->property("taskField").toString();if(!field.isEmpty())path.prepend(field);
const auto joint=at->property("taskJointName").toString();if(!joint.isEmpty())path.prepend(joint);
}return path.join("/")+":"+widget->metaObject()->className();
}
}
TaskProtoEditor::TaskProtoEditor(QWidget* p):QWidget(p),m_layout(new QVBoxLayout(this)){m_layout->setContentsMargins(0,0,0,0);m_layout->setAlignment(Qt::AlignTop);}
void TaskProtoEditor::setOperation(const QString& service,const QString& method,const QJsonObject& request){
m_service=service;m_method=method;m_read={};while(auto* item=m_layout->takeAt(0)){delete item->widget();delete item;}
auto* descriptor=TaskApi::requestDescriptor(service,method);if(!descriptor)return;
QStringList fields;for(const auto& f:TaskApi::definition(service,method).value("editorFields").toArray())fields.append(f.toString());
QJsonObject initial=request;
if(service=="cmvr.api.ArmService"&&(method=="moveJ"||method=="moveJPose"||method=="moveL")){
auto options=initial.value("options").toObject();if(!options.contains("velocity"))options.insert("velocity",.1);if(!options.contains("acceleration"))options.insert("acceleration",.1);initial.insert("options",options);
}
QStringList all;int nested=0;bool hasOneof=false;
for(int i=0;i<descriptor->field_count();++i){auto* f=descriptor->field(i);const QString name=QString::fromStdString(f->name());
if(name=="header"||name=="device_id"||name=="timestamp"||name=="command_id"||(!fields.isEmpty()&&!fields.contains(name)))continue;
all<<name;if(f->cpp_type()==F::CPPTYPE_MESSAGE)++nested;if(f->real_containing_oneof())hasOneof=true;
}
QStringList categories[4];
const QStringList motion={"options","acceleration","duration","velocity","max_speed","max_acceleration","max_angular_speed","max_angular_acceleration","speed_ratio","max_velocity","max_jerk"};
const QStringList coordinate={"user_coordinate_name","user_coordinate_revision","base_link","ee_link"};
const QStringList advanced={"frame","base_frame","tcp_frame","user_frame_pose","tcp_offset","coordinate_relative_translation","expected_device_generation","expected_service_instance_id","wait_timeout_ms","poll_interval_ms","asynchronous","adapter_params","max_chunk_bytes","resume_token"};
for(const auto& name:all)categories[coordinate.contains(name)?2:motion.contains(name)?1:advanced.contains(name)?3:0]<<name;
int sections=0;for(const auto& category:categories)if(!category.isEmpty())++sections;
const bool useTabs=!hasOneof&&sections>1&&(all.size()>6||nested>1||categories[2].size()>2);
auto reads=std::make_shared<QList<Read>>();
const auto build=[&](QWidget* body,const QStringList& allowed){auto* form=new QFormLayout(body);form->setContentsMargins(8,8,8,8);form->setVerticalSpacing(8);form->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
reads->append(message(body,form,descriptor,initial,0,true,Context{service,method,m_deviceInfo},allowed));
if(!form->rowCount())form->addRow(new QLabel(QStringLiteral("此操作无需额外参数。"),body));};
if(useTabs){
auto* tabs=new ParameterTabs(this);tabs->setObjectName("taskParameterTabs");
const QStringList titles={QStringLiteral("基本参数"),QStringLiteral("运动设置"),QStringLiteral("坐标设置"),QStringLiteral("高级参数")};
for(int i=0;i<4;++i)if(!categories[i].isEmpty()){auto* body=new QWidget(tabs);body->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Ignored);build(body,categories[i]);tabs->addTab(body,titles[i]);}
tabs->ensurePolished();m_layout->addWidget(tabs);tabs->show();tabs->fit();
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;};
m_layout->activate();setFixedHeight(m_layout->sizeHint().height());updateGeometry();
for(auto* group:findChildren<QGroupBox*>())if(group->isCheckable())connect(group,&QGroupBox::toggled,this,[this](bool){for(auto* tabs:findChildren<QTabWidget*>())if(auto* parameterTabs=dynamic_cast<ParameterTabs*>(tabs))parameterTabs->fit();m_layout->invalidate();m_layout->activate();setFixedHeight(m_layout->sizeHint().height());updateGeometry();if(m_layoutChanged)m_layoutChanged();});
}
void TaskProtoEditor::refreshContentSize(){for(auto* tabs:findChildren<QTabWidget*>())if(auto* pane=dynamic_cast<ParameterTabs*>(tabs))pane->fit();m_layout->invalidate();m_layout->activate();setFixedHeight(m_layout->sizeHint().height());updateGeometry();if(m_layoutChanged)m_layoutChanged();}
QVariantMap TaskProtoEditor::inputState()const{
QVariantMap result;QMap<QString,int> occurrences;
for(auto* widget:findChildren<QWidget*>()){
const auto key=stateKey(widget,this);QVariant value;
if(auto* tabs=qobject_cast<QTabWidget*>(widget))value=tabs->tabText(tabs->currentIndex());
else if(auto* edit=qobject_cast<QLineEdit*>(widget))value=edit->text();
else if(auto* combo=qobject_cast<QComboBox*>(widget))value=combo->currentData();
else if(auto* check=qobject_cast<QCheckBox*>(widget))value=check->isChecked();
else if(auto* group=qobject_cast<QGroupBox*>(widget)){if(group->property("taskMessageEnabled").isValid())value=messageEnabled(group);else if(group->isCheckable())value=group->isChecked();}
if(value.isValid())result.insert(key+"#"+QString::number(occurrences[key]++),value);
}return result;
}
void TaskProtoEditor::restoreInputState(const QVariantMap& state){
QMap<QString,int> occurrences;
for(auto* widget:findChildren<QWidget*>()){
const bool supported=qobject_cast<QTabWidget*>(widget)||qobject_cast<QLineEdit*>(widget)||qobject_cast<QComboBox*>(widget)||qobject_cast<QCheckBox*>(widget)||(qobject_cast<QGroupBox*>(widget)&&(qobject_cast<QGroupBox*>(widget)->isCheckable()||qobject_cast<QGroupBox*>(widget)->property("taskMessageEnabled").isValid()));
if(!supported)continue;const auto base=stateKey(widget,this);const auto key=base+"#"+QString::number(occurrences[base]++);if(!state.contains(key))continue;const auto value=state.value(key);
if(auto* tabs=qobject_cast<QTabWidget*>(widget)){for(int i=0;i<tabs->count();++i)if(tabs->tabText(i)==value.toString())tabs->setCurrentIndex(i);}
else if(auto* edit=qobject_cast<QLineEdit*>(widget))edit->setText(value.toString());
else if(auto* combo=qobject_cast<QComboBox*>(widget)){int at=combo->findData(value);
if(at<0&&combo->objectName()=="taskMotorSelector"&&value.toMap().contains("node_id"))for(int i=1;i<combo->count();++i)if(combo->itemData(i).toMap().value("node_id")==value.toMap().value("node_id")){at=i;break;}
if(at>=0)combo->setCurrentIndex(at);
}
else if(auto* check=qobject_cast<QCheckBox*>(widget))check->setChecked(value.toBool());
else if(auto* group=qobject_cast<QGroupBox*>(widget)){if(group->property("taskMessageEnabled").isValid()){if(messageEnabled(group)!=value.toBool())if(auto* toggle=group->findChild<QPushButton*>("taskMessageToggle",Qt::FindDirectChildrenOnly))toggle->click();}else group->setChecked(value.toBool());}
}
}
bool TaskProtoEditor::request(QJsonObject& result,QString& error)const{
if(!m_read){error=QStringLiteral("无有效接口表单");return false;}result=m_read(error);return error.isEmpty()&&TaskApi::validateRequest(m_service,m_method,result,error);
}

23
src/taskprotoeditor.h Normal file
View File

@ -0,0 +1,23 @@
#pragma once
#include <QWidget>
#include <QJsonObject>
#include <QVariantMap>
#include <functional>
class QVBoxLayout;
class TaskProtoEditor final:public QWidget {
public:
explicit TaskProtoEditor(QWidget* parent=nullptr);
void setOperation(const QString& service,const QString& method,const QJsonObject& request={});
void setDeviceContext(const QVariantMap& info) { m_deviceInfo=info; }
void refreshContentSize();
QVariantMap inputState() const;
void restoreInputState(const QVariantMap& state);
void setLayoutChangedHandler(std::function<void()> handler) { m_layoutChanged=std::move(handler); }
bool request(QJsonObject& result,QString& error) const;
private:
std::function<void()> m_layoutChanged;
QString m_service,m_method;
QVariantMap m_deviceInfo;
QVBoxLayout* m_layout;
std::function<QJsonObject(QString&)> m_read;
};

99
src/taskrpcrunner.cpp Normal file
View File

@ -0,0 +1,99 @@
#include "taskrpcrunner.h"
#include "taskapi.h"
#include "demosimulator.h"
#include <QTimer>
#include "robotclient.h"
#include "cmvr/api/arm_service.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <grpcpp/generic/generic_stub.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/util/json_util.h>
#include <QThread>
#include <QDateTime>
#include <QJsonDocument>
#include <QUuid>
#include <QPointer>
#include <chrono>
TaskRpcRunner::TaskRpcRunner(RobotClient* client,QObject* parent):QObject(parent),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(){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(){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("演示调用已取消"));}}
void TaskRpcRunner::run(const QJsonObject& ex,std::function<void(bool,const QString&)> done){
if(!m_connected||m_busy){done(false,QStringLiteral("接口未连接或上次调用仍未结束,未发送请求"));return;}
QString error;const QString service=ex.value("service").toString(),method=ex.value("method").toString();
if(!TaskApi::validateRequest(service,method,ex.value("request").toObject(),error)){done(false,error);return;}
const auto pending=ex.value("request").toObject();const auto* pendingDescriptor=TaskApi::requestDescriptor(service,method);
const QString target=pendingDescriptor->FindFieldByName("header")?pending.value("header").toObject().value("device_id").toString():pending.value("device_id").toString();
if(m_demo){
const int timeout=ex.value("timeoutMs").toInt(180000);
if(timeout<100||timeout>1800000){done(false,QStringLiteral("接口超时无效"));return;}
auto simulatedRequest=pending;auto h=pendingDescriptor->FindFieldByName("header")?pending.value("header").toObject():pending;h.remove("commandId");h.insert("command_id",QUuid::createUuid().toString(QUuid::WithoutBraces));h.insert("timestamp",QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs));if(pendingDescriptor->FindFieldByName("header"))simulatedRequest.insert("header",h);else simulatedRequest=h;
const auto reply=DemoSimulator::instance().call(service,method,simulatedRequest);
m_busy=true;m_demoDevice=target;m_demoCompletion=std::move(done);const quint64 generation=++m_demoGeneration;
const QPointer<TaskRpcRunner> guard(this);
QTimer::singleShot(qMin(timeout,reply.delayMs),this,[guard,generation,reply,timeout]{
if(!guard||generation!=guard->m_demoGeneration||!guard->m_demoCompletion)return;
const bool expired=timeout<reply.delayMs;if(expired)DemoSimulator::instance().stop(guard->m_demoDevice);
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;
}
if(m_client&&!m_client->prepareRpcDispatch(service,method,QString::fromUtf8(QJsonDocument(pending).toJson(QJsonDocument::Compact)),target,error)){done(false,error);return;}
auto request=ex.value("request").toObject();const auto* descriptor=TaskApi::requestDescriptor(service,method);
const bool nested=descriptor->FindFieldByName("header")!=nullptr;
auto header=nested?request.value("header").toObject():request;
header.remove("commandId");header.insert("command_id",QUuid::createUuid().toString(QUuid::WithoutBraces));header.insert("timestamp",QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs));
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;
m_context=std::make_shared<grpc::ClientContext>();m_context->set_deadline(std::chrono::system_clock::now()+std::chrono::milliseconds(timeout));
const auto context=m_context;const QString endpoint=m_endpoint;
m_thread=QThread::create([this,context,endpoint,service,method,request,done]{
bool ok=false;QString detail;
try{
google::protobuf::DynamicMessageFactory factory;
auto* svc=google::protobuf::DescriptorPool::generated_pool()->FindServiceByName(service.toStdString());auto* rpc=svc->FindMethodByName(method.toStdString());
std::unique_ptr<google::protobuf::Message> q(factory.GetPrototype(rpc->input_type())->New()),r(factory.GetPrototype(rpc->output_type())->New());
const auto parsed=google::protobuf::util::JsonStringToMessage(QJsonDocument(request).toJson(QJsonDocument::Compact).toStdString(),q.get());
if(!parsed.ok())detail=QString::fromStdString(parsed.ToString());
else {
auto channel=grpc::CreateChannel(endpoint.toStdString(),grpc::InsecureChannelCredentials());
// Old servers can silently ignore new protobuf coordinate fields.
if(service=="cmvr.api.ArmService"&&method=="moveL"&&
(!request.value("user_coordinate_name").toString().isEmpty()||!request.value("userCoordinateName").toString().isEmpty()||
request.contains("user_frame_pose")||request.contains("userFramePose")||request.contains("tcp_offset")||request.contains("tcpOffset"))){
auto arm=cmvr::api::ArmService::NewStub(channel);cmvr::api::JsonDeviceCommand::Request probe;
probe.mutable_header()->set_device_id(request.value("header").toObject().value("device_id").toString().toStdString());
probe.set_request_json("{\"command\":\"get_active_tcp_offset\"}");cmvr::api::JsonDeviceCommand::Feedback feedback;
grpc::ClientContext probeContext;probeContext.set_deadline(std::chrono::system_clock::now()+std::chrono::seconds(3));
const auto status=arm->ExecuteJsonCommand(&probeContext,probe,&feedback);
const auto capability=QJsonDocument::fromJson(QByteArray::fromStdString(feedback.response_json())).object();
if(!status.ok()||!feedback.header().success()||capability.value("coordinate_api_version").toInt()<4||capability.value("movel_target_mode").toString()!="absolute_selected_frame")
throw std::runtime_error("Server did not confirm absolute selected-frame MoveL support; no motion sent");
}
grpc::GenericStub stub(channel);grpc::CompletionQueue queue;
std::string binary;q->SerializeToString(&binary);grpc::Slice slice(binary);grpc::ByteBuffer input(&slice,1),output;grpc::Status status;
auto call=stub.PrepareUnaryCall(context.get(),("/"+service+"/"+method).toStdString(),input,&queue);
call->StartCall();call->Finish(&output,&status,reinterpret_cast<void*>(1));void* tag=nullptr;bool event=false;
const bool received=queue.Next(&tag,&event)&&event&&tag==reinterpret_cast<void*>(1);queue.Shutdown();
if(received&&status.ok()){
std::vector<grpc::Slice> slices;output.Dump(&slices);binary.clear();for(const auto& s:slices)binary.append(reinterpret_cast<const char*>(s.begin()),s.size());
if(r->ParseFromString(binary)){
google::protobuf::util::JsonPrintOptions options;options.always_print_primitive_fields=true;
binary.clear();const auto converted=google::protobuf::util::MessageToJsonString(*r,&binary,options);ok=converted.ok();detail=ok?QString::fromStdString(binary):QString::fromStdString(converted.ToString());
}else detail=QStringLiteral("无法解析接口反馈");
}else detail=QStringLiteral("gRPC %1:%2;结果未确认,不自动重试").arg(status.error_code()).arg(QString::fromStdString(status.error_message()));
}
}catch(const std::exception& e){detail=QString::fromLocal8Bit(e.what());}
QMetaObject::invokeMethod(this,[this,done,ok,detail]{m_busy=false;m_context.reset();done(ok,detail);},Qt::QueuedConnection);
});
// A queued manual-velocity stop must not overtake a new navigation RPC.
if(m_client&&service=="cmvr.api.AgvService"){
const QPointer<TaskRpcRunner> guard(this);
m_client->afterPendingCommands([guard]{if(guard&&guard->m_thread)guard->m_thread->start();});
}else m_thread->start();
}

23
src/taskrpcrunner.h Normal file
View File

@ -0,0 +1,23 @@
#pragma once
#include <QObject>
#include <QJsonObject>
#include <memory>
#include <functional>
class RobotClient;class QThread;
namespace grpc {class ClientContext;}
class TaskRpcRunner final:public QObject {
public:
explicit TaskRpcRunner(RobotClient*,QObject* parent=nullptr);
~TaskRpcRunner()override;
void run(const QJsonObject& execution,std::function<void(bool,const QString&)> done);
void cancel();
private:
friend struct TaskRpcTestAccess;
quint64 m_demoGeneration=0;
QString m_demoDevice;
std::function<void(bool,const QString&)> m_demoCompletion;
RobotClient* m_client=nullptr;
QString m_endpoint;bool m_connected=false,m_demo=false,m_busy=false;
QThread* m_thread=nullptr;
std::shared_ptr<grpc::ClientContext> m_context;
};

9
src/taskuilabels.h Normal file
View File

@ -0,0 +1,9 @@
#pragma once
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
namespace TaskUi {
inline QJsonObject metadata(){static const QJsonObject data=[] {QFile file(":/resources/task_ui.json");file.open(QIODevice::ReadOnly);return QJsonDocument::fromJson(file.readAll()).object();}();return data;}
inline QString text(const QString& section,const QString& key){return metadata().value(section).toObject().value(key).toString(key);}
inline QString operationTitle(const QString&,const QString& action){const QString prefix=QStringLiteral("接口 · ");if(!action.startsWith(prefix))return action=="MoveJ"?QStringLiteral("关节角度运动"):action;return text("operations",action.mid(prefix.size()))+QStringLiteral("(接口)");}
}

View File

@ -1,6 +1,9 @@
#include "urdfviewerwidget.h"
#include "applicationsettings.h"
#include "uiicons.h"
#include <QDebug>
#include <QScreen>
#include <QPixmap>
#include <Qt3DCore/QComponent>
#include <Qt3DCore/QEntity>
@ -280,7 +283,7 @@ const QStringList &motionDemoPoseNames()
UrdfViewerWidget::UrdfViewerWidget(QWidget *parent)
: QWidget(parent)
{
m_modelPreviewEnabled = ApplicationSettings::instance().options().armModelPreview;
m_modelPreviewEnabled = ApplicationSettings::instance().options().armModelPreview || QCoreApplication::arguments().contains("--urdf-smoke");
m_layout = new QVBoxLayout(this);
m_layout->setContentsMargins(0, 0, 0, 0);
m_layout->setSpacing(0);
@ -401,6 +404,7 @@ UrdfViewerWidget::UrdfViewerWidget(QWidget *parent)
void UrdfViewerWidget::ensureSceneInitialized()
{
qInfo()<<"[URDF] scene initialize"<<m_sceneInitialized;
if (m_sceneInitialized)
return;
@ -946,8 +950,11 @@ void UrdfViewerWidget::prepareLoad(const QString &filePath)
m_statusLabel->setText(QStringLiteral("正在初始化 3D 模型…"));
}
bool UrdfViewerWidget::saveDiagnosticViewport(const QString& path)const{if(!m_view||!m_view->screen())return false;qInfo()<<"[URDF] diagnostic viewport"<<m_view->isExposed()<<m_view->size();return m_view->screen()->grabWindow(m_view->winId()).save(path);}
bool UrdfViewerWidget::loadUrdf(const QString &filePath)
{
qInfo()<<"[URDF] begin load"<<filePath;
if (!m_modelPreviewEnabled) {
Q_UNUSED(filePath);
m_loadingTitle->setText(QStringLiteral("机械臂模型预览已关闭"));
@ -980,7 +987,9 @@ bool UrdfViewerWidget::loadUrdf(const QString &filePath)
}
const QByteArray xml = file.readAll();
qInfo()<<"[URDF] parse bytes"<<xml.size();
urdf::ModelInterfaceSharedPtr model = urdf::parseURDF(xml.toStdString());
qInfo()<<"[URDF] parsed"<<bool(model);
if (!model || !model->getRoot()) {
setLoading(false, QStringLiteral("URDF 文件解析失败"));
m_statusLabel->setText(QStringLiteral("URDF 解析失败"));
@ -1094,12 +1103,14 @@ bool UrdfViewerWidget::loadUrdf(const QString &filePath)
geometryTransform->setRotation(
QQuaternion::fromAxisAndAngle(1.0f, 0.0f, 0.0f, 90.0f));
}
qInfo()<<"[URDF] mesh submit"<<source<<QFileInfo(source).size();
Qt3DRender::QSceneLoader *loader = new Qt3DRender::QSceneLoader(geometryEntity);
const QPointer<Qt3DRender::QSceneLoader> guardedLoader(loader);
const QPointer<Qt3DCore::QEntity> guardedGeometry(geometryEntity);
connect(loader, &Qt3DRender::QSceneLoader::statusChanged, this,
[this, guardedLoader, source, guardedGeometry, teachingJointName]
(Qt3DRender::QSceneLoader::Status status) {
qInfo()<<"[URDF] mesh status"<<source<<int(status);
if (!guardedLoader || !guardedGeometry)
return;
if (status == Qt3DRender::QSceneLoader::Error) {
@ -1193,6 +1204,7 @@ bool UrdfViewerWidget::loadUrdf(const QString &filePath)
for (const QString &jointName : m_jointOrder)
m_jointPositions.insert(jointName, m_latestTelemetryPositions.value(jointName, 0.0));
applyJointPositions(m_jointPositions);
qInfo()<<"[URDF] publish model"<<model->links_.size()<<model->joints_.size();
m_modelRoot->setParent(m_rootEntity);
const int linkCount = static_cast<int>(model->links_.size());
const int jointCount = static_cast<int>(model->joints_.size());
@ -1634,6 +1646,7 @@ void UrdfViewerWidget::resetView()
void UrdfViewerWidget::clearModel()
{
qInfo()<<"[URDF] clear"<<m_currentFile<<m_modelRoot;
m_joints.clear();
m_jointOrder.clear();
m_jointPositions.clear();

View File

@ -44,6 +44,7 @@ public:
QString currentFile() const;
void prepareLoad(const QString &filePath);
bool saveDiagnosticViewport(const QString &path) const;
bool loadUrdf(const QString &filePath);
bool loadModelForIdentity(const QString &manufacturer, const QString &model,
const QString &subtype, const QString &descriptionId);

View File

@ -2012,3 +2012,25 @@ QWidget#bioheadPage QToolButton#bioheadHelp:hover {
QListWidget#bioheadHistory { border: none; background: transparent; outline: none; }
QListWidget#bioheadHistory::item { padding: 9px 10px; border-bottom: 1px solid #edf1f6; }
QLabel#bioheadStatus { color: #64748b; padding: 4px 0; }
/* Task parameter tables share the existing dialog palette and typography. */
QWidget#jointFlowChildContent QTableWidget {
background: #ffffff;
alternate-background-color: #f7f9fc;
border: 1px solid #dce3ed;
border-radius: 6px;
gridline-color: #edf1f6;
}
QWidget#jointFlowChildContent QTableWidget QLineEdit {
min-height: 28px;
margin: 4px 6px;
padding: 0 8px;
border: 1px solid #cbd5e1;
border-radius: 4px;
}
QScrollArea#taskParameterScroll { background: #ffffff; border: none; }
QTabWidget#taskParameterTabs::pane { border: 1px solid #dce3ed; border-radius: 6px; background: #ffffff; }
QTabWidget#taskParameterTabs QTabBar::tab { color: #52627a; background: #f2f5f9; border: 1px solid #dce3ed; border-bottom: none; padding: 8px 18px; margin-right: 4px; border-top-left-radius: 5px; border-top-right-radius: 5px; }
QTabWidget#taskParameterTabs QTabBar::tab:selected { color: #165dcc; background: #ffffff; border-top: 2px solid #1b6ef3; }
QTabWidget#taskParameterTabs QTabBar::tab:hover { color: #165dcc; background: #edf4ff; }

View File

@ -0,0 +1,83 @@
// Loopback fake camera: exercise the actual RobotClient worker and signals.
#include "../src/robotclient.h"
#include "cmvr/api/camera_service.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <QCoreApplication>
#include <QElapsedTimer>
#include <QThread>
#include <atomic>
#include <iostream>
#include <stdexcept>
class FakeCamera final : public cmvr::api::CameraService::Service {
public:
std::atomic<bool> opened{false}, failStart{false};
std::atomic<int> starts{0}, captures{0};
grpc::Status GetStatus(grpc::ServerContext *, const cmvr::api::GetCameraStateCommand::Request *,
cmvr::api::GetCameraStateCommand::Feedback *r) override {
r->mutable_header()->set_success(true); r->mutable_state()->set_is_opened(opened);
return grpc::Status::OK;
}
grpc::Status StartCamera(grpc::ServerContext *, const cmvr::api::StartCameraCommand::Request *,
cmvr::api::StartCameraCommand::Feedback *r) override {
++starts; r->mutable_header()->set_success(!failStart);
if (failStart) r->mutable_header()->set_error_message("test start failure");
else opened = true;
return grpc::Status::OK;
}
grpc::Status GetRGBImage(grpc::ServerContext *, const cmvr::api::GetRGBImageCommand::Request *,
cmvr::api::GetRGBImageCommand::Feedback *r) override {
++captures; r->mutable_header()->set_success(opened);
if (!opened) { r->mutable_header()->set_error_message("camera not opened"); return grpc::Status::OK; }
auto *f = r->mutable_color_frame(); f->set_width(1); f->set_height(1);
f->set_type(cmvr::api::FrameData::U8C3); f->set_codec("none");
f->set_data(std::string("\x00\x00\xff", 3)); return grpc::Status::OK;
}
};
template<class Predicate> void waitUntil(Predicate done) {
QElapsedTimer timer; timer.start();
while (!done() && timer.elapsed() < 5000) {
QCoreApplication::processEvents(); QThread::msleep(2);
}
if (!done()) throw std::runtime_error("worker callback timeout");
}
int main(int argc, char **argv) {
QCoreApplication app(argc, argv);
try {
FakeCamera service; int port = 0; grpc::ServerBuilder builder;
builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port);
builder.RegisterService(&service); auto server = builder.BuildAndStart();
if (!server || !port) throw std::runtime_error("fake server failed");
{
RobotClient client;
bool connected = false, done = false, success = false, imageReceived = false;
QString detail;
QObject::connect(&client, &RobotClient::connectionChanged,
[&](bool ok, int, const QString &) { connected = ok; });
QObject::connect(&client, &RobotClient::commandFinished,
[&](const QString &command, bool ok, const QString &message) {
if (command == "Snapshot") { done = true; success = ok; detail = message; }
});
QObject::connect(&client, &RobotClient::snapshotImageReceived,
[&](const QString &id, const QImage &image, const QString &) {
imageReceived = id == "fake-camera" && image.pixelColor(0, 0) == QColor(Qt::red);
});
client.connectToServer("127.0.0.1", port, false); waitUntil([&] { return connected; });
client.requestSnapshot("fake-camera"); waitUntil([&] { return done; });
if (!success || !imageReceived || service.starts != 1 || service.captures != 1)
throw std::runtime_error("closed camera must start before capture");
done = false; client.requestSnapshot("fake-camera"); waitUntil([&] { return done; });
if (!success || service.starts != 1 || service.captures != 2)
throw std::runtime_error("opened camera must not restart");
service.opened = false; service.failStart = true; done = false;
client.requestSnapshot("fake-camera"); waitUntil([&] { return done; });
if (success || service.captures != 2 || !detail.contains("test start failure"))
throw std::runtime_error("start failure must propagate without capture");
}
server->Shutdown();
std::cout << "Camera client tests passed: open/capture, image routing, no repeated start, error propagation\n";
return 0;
} catch (const std::exception &e) { std::cerr << e.what() << '\n'; return 1; }
}

View File

@ -0,0 +1,52 @@
#include "camerasnapshotdecoder.h"
#include <QtCore/QBuffer>
#include <QCoreApplication>
#include <iostream>
#include <stdexcept>
static void require(bool ok, const char *message)
{
if (!ok) throw std::runtime_error(message);
}
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
try {
cmvr::api::FrameData frame;
frame.set_codec("none");
frame.set_type(cmvr::api::FrameData::U8C3);
frame.set_width(1); frame.set_height(2); // Unaligned, tightly packed rows.
const char bgr[] = {0, 0, char(255), 0, char(255), 0};
frame.set_data(bgr, sizeof bgr);
QString error;
QImage image = decodeCameraSnapshot(frame, error);
require(error.isEmpty() && image.pixelColor(0, 0) == QColor(Qt::red)
&& image.pixelColor(0, 1) == QColor(Qt::green), "BGR8 rows/colors");
frame.clear_data();
require(image.pixelColor(0, 0) == QColor(Qt::red), "decoded image must own bytes");
require(decodeCameraSnapshot(frame, error).isNull() && !error.isEmpty(), "truncated raw data");
frame.set_type(cmvr::api::FrameData::U8C1);
frame.set_data(std::string("\x10\xf0", 2));
image = decodeCameraSnapshot(frame, error);
require(image.pixelColor(0, 0).red() == 16 && image.pixelColor(0, 1).red() == 240, "gray8");
frame.set_height(1); frame.set_type(cmvr::api::FrameData::U16C3);
const quint16 values[] = {0, 32768, 65535};
frame.set_data(values, sizeof values);
image = decodeCameraSnapshot(frame, error);
require(image.pixelColor(0, 0) == QColor(255, 128, 0), "BGR16 full-range display");
frame.set_width(std::numeric_limits<int>::max());
frame.set_height(std::numeric_limits<int>::max());
require(decodeCameraSnapshot(frame, error).isNull(), "invalid dimensions");
QByteArray png;
QBuffer buffer(&png); buffer.open(QIODevice::WriteOnly);
require(image.save(&buffer, "PNG"), "PNG encoding fixture");
frame.set_codec("png"); frame.set_data(png.constData(), png.size());
image = decodeCameraSnapshot(frame, error);
require(!image.isNull() && image.pixelColor(0, 0) == QColor(255, 128, 0), "encoded snapshot");
std::cout << "Camera snapshot tests passed: BGR8, gray8, BGR16, PNG, ownership, invalid input\n";
return 0;
} catch (const std::exception &e) {
std::cerr << e.what() << '\n'; return 1;
}
}

View File

@ -0,0 +1,64 @@
#include "../src/demosimulator.h"
#include "../src/taskapi.h"
#include "../src/taskrpcrunner.h"
#include "../src/robotclient.h"
#include <QCoreApplication>
#include <QElapsedTimer>
#include <QThread>
#include <QTimer>
#include <QJsonDocument>
#include <google/protobuf/descriptor.h>
#include <stdexcept>
#include <iostream>
#include <QSet>
#include <cmath>
#define CHECK(x) do{if(!(x))throw std::runtime_error(#x);}while(false)
static bool waitFor(std::function<bool()> ready,int ms=5000){QElapsedTimer t;t.start();while(!ready()&&t.elapsed()<ms){QCoreApplication::processEvents();QThread::msleep(2);}return ready();}
int main(int argc,char** argv){QCoreApplication app(argc,argv);try{
auto& sim=DemoSimulator::instance();sim.reset();int unary=0,stream=0;
const auto catalog=TaskApi::catalog();
for(const auto& value:catalog.value("services").toArray()){
const auto service=value.toObject();const auto name=service.value("service").toString();
for(const auto& value:service.value("methods").toArray()){
const auto method=value.toObject();const auto rpc=method.value("method").toString();
const auto* desc=TaskApi::requestDescriptor(name,rpc);QJsonObject request;
if(desc->FindFieldByName("header"))request.insert("header",QJsonObject{{"device_id",name}});
else if(desc->FindFieldByName("device_id"))request.insert("device_id",name);
const auto reply=sim.call(name,rpc,request);
if(!reply.ok)std::cerr<<qPrintable(name+"."+rpc)<<": "<<QJsonDocument(reply.response).toJson().constData();
CHECK(reply.ok);
QString detail;const bool streaming=method.value("clientStreaming").toBool()||method.value("serverStreaming").toBool();
if(streaming)++stream;else{++unary;const bool success=TaskApi::responseSucceeded(true,QString::fromUtf8(QJsonDocument(reply.response).toJson()),detail);if(!success)std::cerr<<qPrintable(name+"."+rpc)<<" output="<<google::protobuf::DescriptorPool::generated_pool()->FindServiceByName(name.toStdString())->FindMethodByName(rpc.toStdString())->output_type()->full_name()<<": "<<QJsonDocument(reply.response).toJson().constData();CHECK(success);}
}
}
CHECK(unary==124&&stream==8);
sim.reset();const QJsonObject movement{{"header",QJsonObject{{"device_id","right_arm"}}},{"target",QJsonObject{{"position",QJsonArray{1,0,0,0,0,0,0}}}}};
auto reply=sim.call("cmvr.api.ArmService","moveJ",movement);CHECK(reply.ok&&reply.delayMs>100);
QThread::msleep(150);auto snapshot=sim.sample("right_arm");const double mid=snapshot.value("position").toArray()[0].toDouble();CHECK(mid>0&&mid<1&&snapshot.value("moving").toBool());
sim.stop("right_arm");CHECK(!sim.sample("right_arm").value("moving").toBool());
RobotClient client;TaskRpcRunner runner(&client);bool connected=false;QVariantList devices;
QObject::connect(&client,&RobotClient::connectionChanged,[&](bool ok,int,const QString&){connected=ok;});
QObject::connect(&client,&RobotClient::systemStatusReceived,[&](double,double,double,const QVariantList& d){devices=d;});
client.connectToServer("",0,true);CHECK(waitFor([&]{return connected;}));client.requestSystemRefresh();
CHECK(waitFor([&]{return devices.size()>=8;}));QSet<int> types;for(const auto& value:devices)types.insert(value.toMap().value("type").toInt());
for(int type:{0,2,3,5,6,7,8,9})CHECK(types.contains(type));
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;
auto ex=TaskApi::execution(QStringLiteral("机械臂"),QStringLiteral("接口 · ")+method,"right_arm",{{"request",request},{"timeoutMs",timeout}});
runner.run(ex,[&](bool success,const QString& text){ok=success;response=text;done=true;});
if(cancel)QTimer::singleShot(50,&runner,&TaskRpcRunner::cancel);
CHECK(waitFor([&]{return done;}));return qMakePair(ok,response);
};
const auto target=movement.value("target").toObject();auto moved=run("moveJ",{{"target",target}});QString detail;CHECK(TaskApi::responseSucceeded(moved.first,moved.second,detail));
CHECK(telemetryCount>=2&&movingSeen);
CHECK(std::abs(sim.sample("right_arm").value("position").toArray()[0].toDouble()-1)<1e-9);
const auto info=run("GetArmInfo");CHECK(info.first&&QJsonDocument::fromJson(info.second.toUtf8()).object().value("dof").toInt()==7);
auto canceled=run("moveJ",{{"target",QJsonObject{{"position",QJsonArray{0,0,0,0,0,0,0}}}}},3000,true);CHECK(!canceled.first);
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"));
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;
}catch(const std::exception& e){std::cerr<<"FAIL: "<<e.what()<<"\n";return 1;}}

46
tests/run_taskapi_test.py Normal file
View File

@ -0,0 +1,46 @@
"""Run the core task format test using a completed qmake Release build.
Run from qt_client root: python tests/run_taskapi_test.py
No GUI, network, or device commands are issued.
"""
import os
import sys
from pathlib import Path
import shutil
import subprocess
makefile = Path("Makefile.JointLimits.Release")
variables = {}
for line in makefile.read_text().splitlines():
if " = " in line:
key, value = line.split("=", 1)
variables[key.strip()] = value.strip()
compiler = shutil.which("g++")
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",
"bioheadexpressionstore_test", "bioheadjointclient_test",
"bioheadwidget_test", "bioheadlocalexpressions_test"}:
raise SystemExit("Unknown test")
obj = "build/tests/" + test + ".o"
with Path("build/tests/taskapi-build.log").open("w") as log:
subprocess.run([compiler, "-c", "-O2", "-std=gnu++1z", "-mthreads", "-fexceptions",
*variables["DEFINES"].split(), *variables["INCPATH"].split(), "-Isrc",
"tests/" + test + ".cpp", "-o", obj], stdout=log, stderr=subprocess.STDOUT, check=True)
object_script = Path("object_script.CmvrControlStation.Release")
if not object_script.exists():
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":
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))
subprocess.run([compiler, "-mthreads", "-Wl,-subsystem,console", "-o", "build/tests/" + test + ".exe",
"@" + str(response_file), *variables["LIBS"].split()], stdout=log, stderr=subprocess.STDOUT, check=True)
env = os.environ.copy()
env["PATH"] = str(Path("bin/release").resolve()) + os.pathsep + env["PATH"]
env.setdefault("QT_QPA_PLATFORM", "windows")
env.setdefault("QT_QPA_PLATFORM_PLUGIN_PATH", str(Path("bin/release/platforms").resolve()))
raise SystemExit(subprocess.run(["build/tests/" + test + ".exe"], env=env, timeout=45).returncode)

63
tests/setup_kylin_test.sh Normal file
View File

@ -0,0 +1,63 @@
#!/usr/bin/env bash
set -euo pipefail
root=$(cd -- "$(dirname -- "$0")/.." && pwd)
script=$root/scripts/setup_kylin.sh
passed=0
check() {
local title=$1; shift
if "$@"; then printf 'PASS %s\n' "$title"; passed=$((passed+1))
else printf 'FAIL %s\n' "$title" >&2; exit 1
fi
}
check 'syntax' bash -n "$script"
check 'help works without Linux or privilege' bash "$script" --help
check 'version boundaries' bash -c 'source "$1"; version_at_least 5.15.8 5.12; ! version_at_least 5.9.9 5.12; version_at_least 3.16 3.16' _ "$script"
check 'required vs optional and alternate package choice' bash -c '
source "$1"; PACKAGES=(); MISSING=()
package_available() { [[ $1 == available ]]; }
select_package required label unavailable available
[[ ${PACKAGES[0]} == available ]]
select_package optional optional absent
[[ ${#MISSING[@]} == 0 ]]
select_package required required absent
[[ ${#MISSING[@]} == 1 ]]
' _ "$script"
check 'APT dry-run never installs, probes or requests sudo' bash -c '
source "$1"
detect_platform() { PM=apt; ARCH=x86_64; }
package_available() { return 0; }
sudo() { echo UNEXPECTED_SUDO >&2; exit 41; }
install_packages() { exit 42; }
probe_dependencies() { exit 43; }
main --dry-run
' _ "$script"
check 'RPM dry-run resolves repository aliases without install' bash -c '
source "$1"
detect_platform() { PM=dnf; ARCH=x86_64; }
package_available() { return 0; }
install_packages() { exit 42; }
main --dry-run
' _ "$script"
check 'missing gRPC stops before any installation' bash -c '
source "$1"; PM=apt; WITH_CREATOR=0; UPDATE_METADATA=0
package_available() { [[ $1 != libgrpc++-dev ]]; }
apt-get() { echo UNEXPECTED_INSTALL >&2; exit 44; }
# Resolve preflight must fail with an explicit missing capability.
if resolve_packages; then exit 45; fi
[[ ${MISSING[*]} == *gRPC* ]]
' _ "$script"
check 'check-only never installs or builds' bash -c '
source "$1"
detect_platform() { PM=apt; ARCH=x86_64; }
install_packages() { exit 46; }
probe_dependencies() { return 0; }
build_source() { exit 47; }
main --check
' _ "$script"
check 'malformed arguments stop early' bash -c '
source "$1"
! main --jobs 0
! main --source
! main --check --dry-run
' _ "$script"
printf '\n%s setup checks passed. No package manager or device was accessed.\n' "$passed"

View File

@ -0,0 +1,130 @@
// Offline widget tests: never creates a RobotClient or dispatches an RPC.
#include "../src/taskorchestrationwidget.cpp"
#include <stdexcept>
#include <cstdio>
#include "../src/taskdeviceoptions.h"
#include <QTabWidget>
#include <QGroupBox>
static void check(bool ok,const char* text){if(!ok)throw std::runtime_error(text);}
int main(int argc,char** argv){
QApplication app(argc,argv);ApplicationStyle::install(app);
try {
const QVariantMap six{{"jointNames",QStringList{"shoulder_pan","shoulder_lift","elbow","wrist_1","wrist_2","wrist_3"}},
{"jointLimits",QVariantMap{{"elbow",QVariantMap{{"lower",-1.0},{"upper",1.0}}}}}};
TaskJointEditor joints;joints.setDevice(six);QString error;QJsonArray out;
check(!joints.values(out,error),"empty targets must not silently become zero");
auto* table=joints.findChild<QTableWidget*>();check(table->rowCount()==6,"six actual joint rows");
check(table->item(2,0)->text()=="elbow","joint name stays next to target");
for(int i=0;i<6;++i)qobject_cast<QLineEdit*>(table->cellWidget(i,1))->setText("30");
error.clear();check(joints.values(out,error),"valid angle targets");check(std::abs(out[2].toDouble()-M_PI/6)<1e-10,"degrees become radians");
qobject_cast<QLineEdit*>(table->cellWidget(2,1))->setText("90");error.clear();check(!joints.values(out,error),"server limits enforced");
joints.setDevice(six,QJsonArray{0,0});error.clear();check(!joints.values(out,error),"mismatched target count requires fresh inputs");
joints.setDevice({});error.clear();check(!joints.values(out,error),"missing device metadata blocks position input");
TaskProtoEditor calibration;calibration.setDeviceContext(six);
calibration.setOperation("cmvr.api.ArmService","calibrateZeroQ");
auto* selector=calibration.findChild<QComboBox*>("taskJointSelector");
check(selector&&!selector->isEditable()&&selector->count()==7,"calibration selects actual device joints");
QJsonObject request;error.clear();check(!calibration.request(request,error),"calibration requires an explicit selection");
selector->setCurrentIndex(selector->findData("elbow"));error.clear();
check(calibration.request(request,error)&&request.value("joint_name")=="elbow","selected joint name is serialized");
calibration.setDeviceContext({{"jointNames",QStringList{"L1","L2"}}});
calibration.setOperation("cmvr.api.ArmService","calibrateZeroQ",request);error.clear();
check(!calibration.request(request,error),"switching device never substitutes a different joint silently");
calibration.setDeviceContext({});calibration.setOperation("cmvr.api.ArmService","calibrateZeroQ");error.clear();
selector=calibration.findChild<QComboBox*>("taskJointSelector");
check(selector&&!selector->isEnabled()&&!calibration.request(request,error),"missing metadata disables calibration selector");
const auto decoded=TaskDeviceOptions::decode("ListMotors",{{"motors",QJsonArray{QJsonObject{{"nodeId",7},{"jointName","drive_left"}}}}});
TaskProtoEditor motor;motor.setDeviceContext(decoded);motor.setOperation("cmvr.api.MotorService","setMode");
auto* motors=motor.findChild<QComboBox*>("taskMotorSelector");check(motors&&motors->count()==2,"motor list from real metadata");
motors->setCurrentIndex(1);error.clear();check(motor.request(request,error),"motor request valid");
check(request.value("node_id").toInt()==7&&request.value("joint_name")=="drive_left","motor identity serialized together");
const auto stationData=TaskDeviceOptions::decode("listStations",{{"stations",QJsonArray{QJsonObject{{"id","station-a"},{"description",QStringLiteral("工作站 A")}}}}});
TaskProtoEditor nav;nav.setDeviceContext(stationData);nav.setOperation("cmvr.api.AgvService","navigateToStation");
auto* stations=nav.findChild<QComboBox*>("taskOption_station_id");check(stations&&stations->findData("station-a")>0,"station picker uses service response");
stations->setCurrentIndex(1);error.clear();check(nav.request(request,error)&&request.value("station_id")=="station-a","station id remains machine-readable");
TaskProtoEditor map;map.setDeviceContext(TaskDeviceOptions::decode("listMaps",{{"maps",QJsonArray{"factory"}}}));map.setOperation("cmvr.api.AgvService","switchMap");
check(map.findChild<QComboBox*>("taskOption_map_name")->findData("factory")>0,"existing map picker");
const auto coordinateData=TaskDeviceOptions::decode("ListUserCoordinateSystems",{{"coordinates",QJsonArray{QJsonObject{{"name",QStringLiteral("工件 A")},{"revision","2"}}}}});
TaskProtoEditor coordinateEditor;coordinateEditor.setDeviceContext(coordinateData);coordinateEditor.setOperation("cmvr.api.ArmService","ApplyUserCoordinateSystem");
auto* coordinate=coordinateEditor.findChild<QComboBox*>("taskOption_name");check(coordinate&&coordinate->count()==2,"saved coordinate picker");
coordinate->setCurrentIndex(1);error.clear();check(coordinateEditor.request(request,error)&&request.value("name")==QStringLiteral("工件 A"),"saved coordinate request valid");
TaskProtoEditor longForm;longForm.setDeviceContext(coordinateData);
const QJsonObject pose{{"x",.1},{"y",.2},{"z",.3},{"rx",0},{"ry",0},{"rz",0}};
longForm.setOperation("cmvr.api.ArmService","moveL",{{"target",pose}});
auto* tabs=longForm.findChild<QTabWidget*>("taskParameterTabs");check(tabs&&tabs->count()>=3,"long forms split into meaningful tabs");
check(longForm.findChildren<QScrollArea*>().isEmpty(),"no nested editor scroll area");
for(auto* group:longForm.findChildren<QGroupBox*>())if(group->property("taskMessageEnabled").isValid())check(!group->isCheckable(),"message sections no longer require checkbox activation");
tabs->setCurrentIndex(2);auto state=longForm.inputState();longForm.setOperation("cmvr.api.ArmService","moveL",{{"target",pose}});longForm.restoreInputState(state);
tabs=longForm.findChild<QTabWidget*>("taskParameterTabs");check(tabs->currentIndex()==2,"metadata refresh retains active tab");
error.clear();check(longForm.request(request,error)&&request.value("target").toObject()==pose,"all tabs serialize into one unchanged RPC request");
QLineEdit* poseX=nullptr;for(auto* edit:longForm.findChildren<QLineEdit*>())if(edit->property("taskField").toString()=="x")poseX=edit;
check(poseX,"pose x control exists");poseX->setText("incomplete");state=longForm.inputState();
longForm.setOperation("cmvr.api.ArmService","moveL",{{"target",pose}});longForm.restoreInputState(state);poseX=nullptr;
for(auto* edit:longForm.findChildren<QLineEdit*>())if(edit->property("taskField").toString()=="x")poseX=edit;
check(poseX&&poseX->text()=="incomplete","refresh preserves even incomplete input");
const auto baseFrames=TaskDeviceOptions::decode("ListBaseFrame",{{"frameNames",QJsonArray{"robot_base","fixture"}}});
TaskProtoEditor poseQuery;poseQuery.setDeviceContext(baseFrames);poseQuery.setOperation("cmvr.api.ArmService","getPose");
check(poseQuery.findChild<QComboBox*>("taskOption_base_link")->findData("fixture")>0,"frame response aliases supported");
// Build every supported form and check the user-facing dictionary recursively.
const auto catalog=TaskApi::catalog();QSet<QString> seen;int count=0;
std::function<void(const QString&)> inspect=[&](const QString& name){
if(seen.contains(name))return;seen.insert(name);
for(const auto& field:catalog.value("messages").toObject().value(name).toObject().value("fields").toArray()){
const auto f=field.toObject();const auto key=f.value("name").toString();
check(TaskUi::text("fields",key)!=key,qPrintable("untranslated field: "+key));
if(f.contains("messageType"))inspect(f.value("messageType").toString());
}
};
for(const auto& service:catalog.value("services").toArray())for(const auto& value:service.toObject().value("methods").toArray()){
const auto m=value.toObject();if(m.value("clientStreaming").toBool()||m.value("serverStreaming").toBool())continue;
check(TaskUi::text("operations",m.value("method").toString())!=m.value("method").toString(),"translated operation");inspect(m.value("requestType").toString());
TaskProtoEditor editor;editor.setDeviceContext(six);editor.setOperation(m.value("service").toString(),m.value("method").toString());++count;
}
check(count==124,"all unary editors covered");
TaskOrchestrationWidget owner;owner.setDeviceInfo("right_arm",six);
owner.setDeviceInfo("left_arm",{{"jointNames",QStringList{"L1","L2","L3","L4","L5","L6","L7"}}});
const QVariantList devices{QVariantMap{{"deviceId","right_arm"},{"type",6}},QVariantMap{{"deviceId","left_arm"},{"type",6}}};
QString name=QStringLiteral("关节定位"),type=QStringLiteral("机械臂"),id="right_arm",action="MoveJ",unit="ms";
QJsonObject params{{"positions",QJsonArray{0,0,0,0,0,0}},{"velocity",.1},{"acceleration",.1}};int wait=0;QString failure;
QTimer::singleShot(100,[&]{
try {
auto* dialog=qobject_cast<QDialog*>(QApplication::activeModalWidget());check(dialog,"task dialog opened");
auto* device=dialog->findChild<QComboBox*>("taskDeviceCombo");auto* operation=dialog->findChild<QComboBox*>("taskActionCombo");
auto* jointTable=dialog->findChild<QTableWidget*>("taskJointTable");check(jointTable&&jointTable->rowCount()==6,"dialog uses device joints");
check(operation->currentText()==QStringLiteral("关节角度运动"),"friendly operation title");
qobject_cast<QLineEdit*>(jointTable->cellWidget(0,1))->setText("45");
device->setCurrentIndex(1);check(jointTable->rowCount()==7,"changing device changes DOF");
check(qobject_cast<QLineEdit*>(jointTable->cellWidget(0,1))->text().isEmpty(),"new device does not inherit targets");
device->setCurrentIndex(0);check(jointTable->rowCount()==6,"switch back restores rows");
check(qobject_cast<QLineEdit*>(jointTable->cellWidget(0,1))->text()=="45","per-device draft preserved");
QApplication::processEvents();
dialog->grab().save("build/tests/task-joints-preview.png");
operation->setCurrentIndex(operation->findData(QStringLiteral("接口 · moveJ")));
auto tables=dialog->findChildren<QTableWidget*>("taskJointTable");check(tables.size()>=2,"direct RPC also uses joint rows");
for(auto* t:tables)if(t!=jointTable)check(t->rowCount()==6,"direct RPC uses actual DOF");
operation->setCurrentIndex(operation->findData(QStringLiteral("接口 · moveL")));
auto* parameterTabs=dialog->findChild<QTabWidget*>("taskParameterTabs");check(parameterTabs&&parameterTabs->count()>=3,"modal uses parameter tabs");
check(dialog->findChildren<QScrollArea*>().size()==1,"one scrolling surface in the entire dialog");
QApplication::processEvents();check(parameterTabs->parentWidget()->height()>=parameterTabs->height(),"tab content must not be clipped by editor");dialog->grab().save("build/tests/task-movel-basic-preview.png");
parameterTabs->setCurrentIndex(2);QApplication::processEvents();dialog->grab().save("build/tests/task-movel-coordinates-preview.png");
operation->setCurrentIndex(operation->findData("MoveJ"));
auto* buttons=dialog->findChild<QDialogButtonBox*>();check(buttons,"fixed dialog footer");
auto* scroll=dialog->findChild<QScrollArea*>("taskParameterScroll");QApplication::processEvents();
QCoreApplication::sendPostedEvents(nullptr,QEvent::LayoutRequest);QApplication::processEvents();dialog->grab().save("build/tests/task-legacy-footer-preview.png");
check(scroll->mapTo(dialog,QPoint(0,scroll->height())).y()<buttons->mapTo(dialog,QPoint()).y(),"footer must not overlap parameter area");
qobject_cast<QLineEdit*>(jointTable->cellWidget(0,1))->clear();
QTimer::singleShot(0,[dialog]{if(auto* notice=qobject_cast<QDialog*>(QApplication::activeModalWidget()))if(notice!=dialog)notice->accept();});
buttons->button(QDialogButtonBox::Ok)->click();check(dialog->isVisible(),"invalid input keeps the task dialog open");
qobject_cast<QLineEdit*>(jointTable->cellWidget(0,1))->setText("45");buttons->button(QDialogButtonBox::Ok)->click();
}catch(const std::exception& e){failure=e.what();std::fprintf(stderr,"MODAL FAILURE: %s\n",e.what());if(auto* d=qobject_cast<QDialog*>(QApplication::activeModalWidget()))d->reject();}
});
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");
std::printf("PASS: 124 forms; joint/motor/station/map/coordinate selectors; tabs and one scroll area; no clipping or footer overlap; partial-input retention; JSON requests; no RPCs\n");return 0;
}catch(const std::exception& e){std::fprintf(stderr,"FAIL: %s\n",e.what());return 1;}
}

View File

@ -0,0 +1,48 @@
import assert from 'node:assert/strict';
import {readFile} from 'node:fs/promises';
import {flatten,execute} from '../docs/task-flow/task-flow.mjs';
const catalog=JSON.parse(await readFile(new URL('../docs/task-flow/task_operations.json',import.meta.url)));
const sample=JSON.parse(await readFile(new URL('../docs/task-flow/example.task.json',import.meta.url)));
const group=sample.groups[0].id;
const steps=flatten(sample,catalog,group);
assert.equal(steps.length,3);
assert.deepEqual(steps.map(s=>s.iterationPath.map(p=>p.iteration)),[[],[0],[1]]);
const plan=structuredClone(sample);
const clearWait=nodes=>{for(const n of nodes)if(n.kind==='loop')clearWait(n.children);else n.waitMs=0;};
clearWait(plan.groups[0].nodes);
let calls=[];
const result=await execute(plan,catalog,group,{rpc:async(service,method,request)=>{
calls.push({service,method,request});return {header:{success:true}};
}});
assert.equal(result.completedSteps,3);
assert.deepEqual(calls.map(c=>c.method),['ApplyUserCoordinateSystem','moveJPose','moveJPose']);
assert.equal(calls[1].request.target.x,.1);assert.equal(calls[1].request.user_coordinate_name,'测试坐标系');
assert.notEqual(calls[1].request.header.command_id,calls[2].request.header.command_id);
assert.equal(calls[1].request.header.device_id,'aubo_arm');
calls=[];
await assert.rejects(execute(plan,catalog,group,{rpc:async(s,m)=>{calls.push(m);return {header:{success:m!=='moveJPose',error_message:'fake IK failure'}};}}),/fake IK failure/);
assert.equal(calls.length,2);
const bad=structuredClone(plan);bad.groups[0].nodes[0].execution.method='torqueOn';assert.throws(()=>flatten(bad,catalog,group),/Conflicting/);
const duplicate=structuredClone(plan);duplicate.groups[0].nodes[1].id=duplicate.groups[0].nodes[0].id;assert.throws(()=>flatten(duplicate,catalog,group),/duplicate/);
const legacy=structuredClone(plan);legacy.groups[0].nodes=[{
id:'legacy',kind:'task',name:'joint',deviceType:'机械臂',deviceId:'aubo_arm',action:'MoveJ',operationId:'client.arm.move_j',
parameters:{positions:[0,0,0,0,0,0],velocity:.1,acceleration:.5},waitMs:0,waitUnit:'ms',
execution:{kind:'client_adapter',adapter:'client.arm.move_j',deviceId:'aubo_arm',parameters:{positions:[0,0,0,0,0,0],velocity:.1,acceleration:.5},completion:'adapter_callback'}
}];
await assert.rejects(execute(legacy,catalog,group,{rpc:async()=>{throw Error('must not call');}}),/Missing adapter/);
let invoked=0;await execute(legacy,catalog,group,{adapters:{'client.arm.move_j':async(p)=>{assert.equal(p.positions.length,6);invoked++;return {success:true};}}});assert.equal(invoked,1);
const abort=new AbortController();calls=[];
await assert.rejects(execute(plan,catalog,group,{signal:abort.signal,rpc:async(s,m)=>{calls.push(m);abort.abort();return {header:{success:true}};}}),/Canceled/);
assert.equal(calls.length,1);
const linear=structuredClone(plan),target=linear.groups[0].nodes[1].children[0];
target.action='接口 · moveL';target.operationId='cmvr.api.ArmService.moveL';target.parameters.method='moveL';target.execution.method='moveL';
let motionCalls=0;
await execute(linear,catalog,group,{rpc:async(s,m)=>{
if(m==='ExecuteJsonCommand')return {header:{success:true},response_json:'{"coordinate_api_version":4,"movel_target_mode":"absolute_selected_frame"}'};
if(m==='moveL')motionCalls++;return {header:{success:true}};
}});assert.equal(motionCalls,2);
motionCalls=0;await assert.rejects(execute(linear,catalog,group,{rpc:async(s,m)=>{
if(m==='ExecuteJsonCommand')return {header:{success:true},response_json:'{"coordinate_api_version":3}'};
if(m==='moveL')motionCalls++;return {header:{success:true}};
}}),/unsupported/);assert.equal(motionCalls,0);
console.log('PASS: external JSON parsing, typed catalog, loop expansion, absolute target transmission, per-call IDs, fail-stop, ambiguous/duplicate rejection, adapter preflight and cancellation; only mock transports');

66
tests/taskapi_test.cpp Normal file
View File

@ -0,0 +1,66 @@
// No QApplication, network, SDK initialization or hardware commands.
#include "../src/taskapi.h"
#include <QJsonDocument>
#include <QFile>
#include <QDir>
#include <iostream>
#include <stdexcept>
#define CHECK(x) do{if(!(x))throw std::runtime_error(#x);}while(false)
QJsonObject task(const QString& action,const QJsonObject& request={}){
const bool native=action.startsWith(QString::fromUtf8("接口 · "));
return {{"kind","task"},{"name",action},{"deviceType",QString::fromUtf8("机械臂")},{"deviceId","aubo_arm"},{"action",action},
{"parameters",native?QJsonObject{{"service","cmvr.api.ArmService"},{"method",action.mid(QString::fromUtf8("接口 · ").size())},{"request",request},{"timeoutMs",180000}}:QJsonObject{{"positions",QJsonArray{0,0,0,0,0,0}},{"velocity",.1},{"acceleration",.5}}},{"waitMs",3000},{"waitUnit","s"}};
}
QJsonObject flow(const QJsonArray& nodes){return {{"version",1},{"groups",QJsonArray{QJsonObject{{"name","offline example"},{"nodes",nodes}}}}};}
int main(){try{
QString error;
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;
CHECK(catalog.value("messages").toObject().contains(m.value("requestType").toString()));}
CHECK(unary>100 && streams>0);
CHECK(TaskApi::definition("cmvr.api.MotorService","setMode").value("editorFields").toArray().contains("mode"));
CHECK(!TaskApi::definition("cmvr.api.MotorService","setMode").value("editorFields").toArray().contains("q"));
CHECK(TaskApi::definition("cmvr.api.MotorService","setLimitQd").value("editorFields").toArray().contains("qd"));
CHECK(!TaskApi::definition("cmvr.api.ArmService","ApplyUserCoordinateSystem").value("editorFields").toArray().contains("coordinate"));
for(const auto& adapter:catalog.value("clientAdapters").toArray())CHECK(adapter.toObject().contains("parametersSchema"));
auto legacy=flow(QJsonArray{task("MoveJ")});CHECK(TaskApi::normalize(legacy,error));CHECK(!legacy.contains("version"));CHECK(TaskApi::normalize(legacy,error));CHECK(!legacy.contains("version"));
auto exported=legacy;CHECK(TaskApi::serverDocument(exported,error));
const auto exportedNode=exported.value("groups").toArray()[0].toObject().value("nodes").toArray()[0].toObject();
CHECK(exportedNode.value("operationId")=="cmvr.api.ArmService.moveJ");
CHECK(exportedNode.value("execution").toObject().value("request").toObject().value("target").toObject().value("position").toArray().size()==6);
QJsonArray friendly;
for(const auto& value:catalog.value("clientAdapters").toArray()){
auto a=value.toObject();QJsonObject p;auto props=a.value("parametersSchema").toObject().value("properties").toObject();
for(auto it=props.begin();it!=props.end();++it){const auto t=it.value().toObject().value("type").toString();p.insert(it.key(),t=="array"?QJsonValue(QJsonArray{.1,.2}):t=="string"?QJsonValue("example"):QJsonValue(it.key()=="sampleRate"?48000:it.key()=="channels"?1:.5));}
friendly.append(QJsonObject{{"kind","task"},{"name",a.value("action")},{"deviceType",a.value("deviceType")},{"deviceId","offline-device"},{"action",a.value("action")},{"parameters",p},{"waitMs",0},{"waitUnit","ms"}});
}
auto allExported=flow(friendly);CHECK(TaskApi::serverDocument(allExported,error));
for(const auto& value:allExported.value("groups").toArray()[0].toObject().value("nodes").toArray()){
auto n=value.toObject();if(n.value("execution").toObject().value("kind")=="client_adapter")CHECK(!n.value("serverCalls").toArray().isEmpty());
}
QFile exportFile("docs/task-flow/example.server-export.json");CHECK(exportFile.open(QIODevice::WriteOnly));exportFile.write(QJsonDocument(allExported).toJson(QJsonDocument::Indented));exportFile.close();
auto again=legacy;CHECK(TaskApi::normalize(again,error));CHECK(again==legacy);
auto simple=TaskApi::execution(QString::fromUtf8("机械臂"),QString::fromUtf8("接口 · torqueOn"),"arm-b",{{"request",QJsonObject()}});
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 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 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");
CHECK(TaskApi::responseSucceeded(true,R"({"success":true})",detail));CHECK(!TaskApi::responseSucceeded(false,"transport failure",detail));CHECK(!TaskApi::responseSucceeded(true,"{}",detail));
auto nan=flow(QJsonArray{task(QString::fromUtf8("接口 · moveL"),{{"target",QJsonObject{{"x","NaN"}}}})});CHECK(!TaskApi::normalize(nan,error));
auto fixture=sample;auto fixedGroups=fixture.value("groups").toArray();auto fixedGroup=fixedGroups[0].toObject();fixedGroup.insert("id","example-group");auto fixedNodes=fixedGroup.value("nodes").toArray();auto fixedApply=fixedNodes[0].toObject();fixedApply.insert("id","example-apply");fixedNodes[0]=fixedApply;auto fixedLoop=fixedNodes[1].toObject();fixedLoop.insert("id","example-loop");auto fixedChildren=fixedLoop.value("children").toArray();auto fixedPose=fixedChildren[0].toObject();fixedPose.insert("id","example-movej-pose");fixedChildren[0]=fixedPose;fixedLoop.insert("children",fixedChildren);fixedNodes[1]=fixedLoop;fixedGroup.insert("nodes",fixedNodes);fixedGroups[0]=fixedGroup;fixture.insert("groups",fixedGroups);sample=fixture;
QDir().mkpath("docs/task-flow");
for(const auto& pair:QList<QPair<QString,QJsonObject>>{{"task_operations.json",catalog},{"example.task.json",sample}}){QFile file("docs/task-flow/"+pair.first);CHECK(file.open(QIODevice::WriteOnly));file.write(QJsonDocument(pair.second).toJson(QJsonDocument::Indented));}
QFile saved("bin/release/data/task_orchestration.json");if(saved.open(QIODevice::ReadOnly)){auto doc=QJsonDocument::fromJson(saved.readAll()).object();CHECK(TaskApi::normalize(doc,error));}
std::cout<<"PASS: "<<unary<<" unary interfaces, "<<streams<<" streaming definitions; typed descriptors, legacy migration, id stability, header placement, loop limits, ambiguity rejection, business errors, existing-file read-only validation and example/catalog export; no network or hardware calls\n";
}catch(const std::exception& e){std::cerr<<"FAIL: "<<e.what()<<"\n";return 1;}return 0;}

View File

@ -0,0 +1,48 @@
// Loopback fake service only: no device manager, SDK or real device connection.
#include "../src/taskrpcrunner.h"
#include "../src/taskapi.h"
#include "cmvr/api/arm_service.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <QCoreApplication>
#include <QElapsedTimer>
#include <QThread>
#include <QTimer>
#include <iostream>
#include <stdexcept>
#include <atomic>
#define CHECK(x) do{if(!(x))throw std::runtime_error(#x);}while(false)
struct TaskRpcTestAccess {static void configure(TaskRpcRunner& r,int port){r.m_endpoint=QString("127.0.0.1:%1").arg(port);r.m_connected=true;}};
class FakeArm final:public cmvr::api::ArmService::Service {
public:
std::atomic<bool> block{false},receivedHeader{false};std::atomic<int> capability{4},motions{0};
grpc::Status GetArmInfo(grpc::ServerContext* ctx,const cmvr::api::GetArmInfo::Request*,cmvr::api::GetArmInfo::Response* r)override{
while(block.load()&&!ctx->IsCancelled())std::this_thread::sleep_for(std::chrono::milliseconds(2));
if(ctx->IsCancelled())return {grpc::StatusCode::CANCELLED,"fake canceled"};r->mutable_header()->set_success(true);return grpc::Status::OK;
}
grpc::Status torqueOn(grpc::ServerContext*,const cmvr::api::CommandHeader::Request* q,cmvr::api::CommandHeader::Feedback* r)override{
receivedHeader.store(q->device_id()=="fake-arm"&&!q->command_id().empty()&&q->timestamp().seconds()>0);r->set_success(true);return grpc::Status::OK;
}
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;
}
grpc::Status moveL(grpc::ServerContext*,const cmvr::api::MoveL::Request*,cmvr::api::MoveL::Response* r)override{motions++;r->mutable_header()->set_success(true);return grpc::Status::OK;}
};
int main(int argc,char** argv){QCoreApplication app(argc,argv);try{
FakeArm fake;grpc::ServerBuilder builder;int port=0;builder.AddListeningPort("127.0.0.1:0",grpc::InsecureServerCredentials(),&port);builder.RegisterService(&fake);auto server=builder.BuildAndStart();CHECK(server&&port);
TaskRpcRunner runner(nullptr);TaskRpcTestAccess::configure(runner,port);
auto run=[&](QString method,QJsonObject request={},bool cancel=false){
bool finished=false,ok=false;QString response;
const auto ex=TaskApi::execution(QString::fromUtf8("机械臂"),QString::fromUtf8("接口 · ")+method,"fake-arm",{{"request",request},{"timeoutMs",2000}});
runner.run(ex,[&](bool result,const QString& text){ok=result;response=text;finished=true;});
if(cancel)QTimer::singleShot(20,&runner,&TaskRpcRunner::cancel);
QElapsedTimer timer;timer.start();while(!finished&&timer.elapsed()<5000){app.processEvents();QThread::msleep(1);}CHECK(finished);return qMakePair(ok,response);
};
QString detail;auto info=run("GetArmInfo");CHECK(TaskApi::responseSucceeded(info.first,info.second,detail));
auto enable=run("torqueOn");CHECK(TaskApi::responseSucceeded(enable.first,enable.second,detail));CHECK(fake.receivedHeader.load());
QJsonObject custom{{"target",QJsonObject{{"x",.1}}},{"user_coordinate_name","fixture"},{"options",QJsonObject{{"velocity",.01},{"acceleration",.1}}}};
fake.capability=3;auto rejected=run("moveL",custom);CHECK(!rejected.first);CHECK(fake.motions==0);
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";
}catch(const std::exception& e){std::cerr<<"FAIL: "<<e.what()<<"\n";return 1;}return 0;}