feat: 完善设备工作流集成、组合执行与主题适配
集成旋转底座、机械臂示教与坐标系,完善扫描参数、电量和框架点复用。增加组合执行、步骤进度与日志,优化首屏和流程画布性能,修复表头主题适配,并保留验证脚本和回归测试。
This commit is contained in:
parent
6f8a40644c
commit
64db825a9f
1
.gitignore
vendored
1
.gitignore
vendored
@ -5,6 +5,7 @@
|
||||
*.log
|
||||
.superpowers/
|
||||
**/target/
|
||||
**/target-verification/
|
||||
**/node_modules/
|
||||
**/dist/
|
||||
**/.flattened-pom.xml
|
||||
|
||||
10
AGENTS.md
10
AGENTS.md
@ -1,5 +1,14 @@
|
||||
# AM FreeScan 开发约定
|
||||
|
||||
- 2026-10-30 用户再次明确旋转底座组件标题及说明使用中文;协议动作和RPC标识不翻译。旧英文默认标题可在加载时转为中文,用户自定义节点名称保留。组件分组统一使用collapseTitle,机械臂分组必须显示“机械臂示教与轨迹”,不能只剩数量。
|
||||
|
||||
- 2026-10-29 用户明确要求机械臂示教/轨迹组件名及操作按钮使用中文;内部动作标识与RPC方法保留协议定义。组件使用原有QUIC发现的机器人和机械臂用途,不将文档示例IP自动登记为现场设备。真实录制、使能、运动仍不在自动验证中执行。
|
||||
- 2026-10-29 用户授权只读复用 `cmvr-iot-lxl-dev-worktree` 的QUIC配置、证书及私钥。UDP4433已开启,私有配置在 `.local/scanner-private.yaml` 的 `cmvr.quic`,证书在 `.local/quic-certs`;不打印或提交密钥,不因调整扫描仪配置而清除QUIC配置。现场已通过QUIC发现机器人 `AIMA-20261026-003` 及 `aubo_arm`、`src1100`,不是测试数据,不清理。
|
||||
|
||||
- 2026-10-28 用户提供新版203电机说明及Proto,旋转底座扩展为14个已支持接口;原五个组件名称和配置保留,新增查询、quickStop和“自动机械回零(home)”。四个旧占位动作不自动迁移为新控制语义。公共CommandHeader兼容,平台完整common.proto保留其他设备消息。真实电机动作仍不在自动验证中执行。
|
||||
|
||||
- 2026-10-27 用户要求组件名称沿用提供的接口文档;旋转底座分组保持不变,五个组件为“设置模式、使能、去使能、轮廓位置控制、轮廓速度控制”。用户已授权必要时自动重启本项目前后端,包括 IDEA 启动的后端;优先保留其原有启动方式和环境配置,重启前核对活动执行,不中断正在进行的实体采集或运动。
|
||||
|
||||
- 只修改本项目。CMVR-AIMA、cmvr-iot-common、CMVR-IOT 来源项目保持只读。
|
||||
- 用户要求:自动化回归测试代码保留;开发验证成功后,清理本次生成的业务测试用例、任务、执行日志、导入文件、输出文件和临时文件,不能留在业务页面中。
|
||||
- 通过明确的验证批次前缀登记测试数据。优先执行 `scripts/cleanup_verification.py --prefix <本次前缀> --apply`,先结束运行中的任务并确认资源释放。不要用“名称包含 test”、创建时间或清空整表来判断测试数据。
|
||||
@ -7,6 +16,7 @@
|
||||
- 用户明确要求的永久在线模拟机器人 `am-freescan-sim-robot` 和模拟设备 `am-freescan-sim-agv` 继续保留,除非用户另行要求删除。
|
||||
- 2026-10-22 用户另行要求创建并保留两条全流程演示数据:前缀 `DEMO-20261022-091650`,任务 `T-20261022-0005`、`T-20261022-0006`,导入批次 `IB-20261022-0009`。对应测试用例、样品、夹具、技术资料、执行日志和输出均供用户查看,不纳入开发验证自动清理;清单见 `docs/full-flow-demo-20261022.json`。
|
||||
- 不删除运行配置、凭据、来源指纹、实际业务数据或回归测试代码。不要输出 `.local/runtime.json` 中的敏感信息。
|
||||
- 2026-10-27 用户要求集成真实旋转底座,工位 `am-freescan-rotary-base-station-001` 已通过正常接口登记;设备永久标识 `aima_motor`,服务配置为 `192.168.0.203:50052`。该工位不是验证样例,不自动清理;不得用传输可达替代机械状态反馈,不在开发验证中自动使能或移动真实底座。
|
||||
- 2026-10-23 用户要求保留真实扫描待运行数据:前缀 `REAL-SCAN-20261023-001`,任务 `T-20261023-0001`,导入批次 `IB-20261023-0001`;清单见 `docs/real-scan-ready-20261023.json`。对应样品、夹具预设、用例、流程版本及真实扫描工位 `am-freescan-station-001` / 设备 `am-freescan-scanner-001` 不纳入验证数据清理。准备脚本不能自动执行扫描,也不能代替用户确认实物与装夹。
|
||||
- 上述真实任务的用户首次运行在 SDK 三维快照报 `scene_data_unavailable`,失败执行 `2113504832933294082` 保留;旧任务已停止并取消以释放占用。修正版为 `T-20261023-0002`(`REAL-SCAN-20261023-001-R1`,批次 `IB-20261023-0002`,流程 V3),增加独立 Trak 工程并在停止采集前请求快照,同样保留且不纳入验证清理。新任务必须重新由操作人确认收样与装夹,不能复制这些物理确认状态。
|
||||
- 2026-10-23 用户再次要求创建并保留两条现场测试任务:`T-20261023-0003`(流式预览采集)、`T-20261023-0004`(网格化及PLY/STL导出),前缀 `USER-SCAN-20261023`、批次 `IB-20261023-0003`;清单为 `docs/user-scan-two-tasks-20261023.json`。关联用例、流程版本、样品和导入文件不纳入开发验证清理;两条任务都不调用已知故障的原始场景快照接口。准备脚本为 `scripts/prepare_user_scan_pair.py`,不自动确认实物或启动设备,用户按顺序现场测试。
|
||||
|
||||
@ -167,6 +167,16 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>isolated-verification</id>
|
||||
<build>
|
||||
<!-- Keep regression compilation separate from the user's IDE output. -->
|
||||
<directory>${project.basedir}/target-verification</directory>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<!-- 使用 huawei / aliyun 的 Maven 源,提升下载速度 -->
|
||||
<repositories>
|
||||
<repository>
|
||||
|
||||
17
am-backend/sql/freescan/009_rotary_base_integration.sql
Normal file
17
am-backend/sql/freescan/009_rotary_base_integration.sql
Normal file
@ -0,0 +1,17 @@
|
||||
CREATE TABLE IF NOT EXISTS lab_rotary_base_command (
|
||||
command_key varchar(64) NOT NULL,
|
||||
request_hash varchar(64) NOT NULL,
|
||||
endpoint_key varchar(512) NOT NULL,
|
||||
active_endpoint varchar(512) DEFAULT NULL,
|
||||
operation varchar(48) NOT NULL,
|
||||
request_json longtext NOT NULL,
|
||||
owner_ref varchar(160) NOT NULL,
|
||||
state varchar(24) NOT NULL,
|
||||
result_json longtext DEFAULT NULL,
|
||||
error_message varchar(2000) DEFAULT NULL,
|
||||
created_at datetime NOT NULL,
|
||||
updated_at datetime NOT NULL,
|
||||
PRIMARY KEY (command_key),
|
||||
UNIQUE KEY uk_rotary_active_endpoint (active_endpoint),
|
||||
KEY idx_rotary_owner (owner_ref)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='旋转底座指令审计与防重复执行';
|
||||
14
am-backend/sql/freescan/010_scanner_framework_reference.sql
Normal file
14
am-backend/sql/freescan/010_scanner_framework_reference.sql
Normal file
@ -0,0 +1,14 @@
|
||||
CREATE TABLE IF NOT EXISTS lab_scanner_framework_transfer (
|
||||
transfer_key varchar(64) NOT NULL,
|
||||
transfer_kind varchar(8) NOT NULL,
|
||||
endpoint_key varchar(64) NOT NULL,
|
||||
source_hash varchar(64) NOT NULL,
|
||||
owner_ref varchar(160) NOT NULL,
|
||||
state varchar(24) NOT NULL,
|
||||
result_json longtext DEFAULT NULL,
|
||||
error_message varchar(2000) DEFAULT NULL,
|
||||
created_at datetime NOT NULL,
|
||||
updated_at datetime NOT NULL,
|
||||
PRIMARY KEY (transfer_key),
|
||||
KEY idx_framework_transfer_owner (owner_ref)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='框架URL自动登记与跨节点复用记录';
|
||||
14
am-backend/sql/freescan/011_fixture_framework.sql
Normal file
14
am-backend/sql/freescan/011_fixture_framework.sql
Normal file
@ -0,0 +1,14 @@
|
||||
CREATE TABLE IF NOT EXISTS lab_fixture_framework (
|
||||
id varchar(32) NOT NULL PRIMARY KEY,
|
||||
version_seq bigint NOT NULL AUTO_INCREMENT UNIQUE,
|
||||
fixture_id bigint NOT NULL,
|
||||
active_fixture_id bigint NULL,
|
||||
instance_id varchar(64) NULL,
|
||||
status varchar(24) NOT NULL,
|
||||
urls_json mediumtext NULL,
|
||||
message varchar(1000) NULL,
|
||||
created_at datetime NOT NULL,
|
||||
updated_at datetime NOT NULL,
|
||||
UNIQUE KEY uk_fixture_framework_active (active_fixture_id),
|
||||
KEY idx_fixture_framework (fixture_id,created_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
9
am-backend/sql/freescan/012_robot_service_endpoint.sql
Normal file
9
am-backend/sql/freescan/012_robot_service_endpoint.sql
Normal file
@ -0,0 +1,9 @@
|
||||
CREATE TABLE IF NOT EXISTS lab_robot_service_endpoint (
|
||||
service_type varchar(24) NOT NULL,
|
||||
robot_id varchar(128) NOT NULL,
|
||||
host varchar(253) NOT NULL,
|
||||
port int NOT NULL,
|
||||
updated_by varchar(64) NOT NULL DEFAULT '',
|
||||
updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (service_type)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='直连设备地址,不覆盖QUIC端点';
|
||||
9
am-backend/sql/freescan/013_execution_plan.sql
Normal file
9
am-backend/sql/freescan/013_execution_plan.sql
Normal file
@ -0,0 +1,9 @@
|
||||
CREATE TABLE IF NOT EXISTS lab_execution_plan (
|
||||
id varchar(32) NOT NULL,
|
||||
revision int NOT NULL,
|
||||
plan_name varchar(160) NOT NULL,
|
||||
definition_json mediumtext NOT NULL,
|
||||
creator varchar(64) NOT NULL DEFAULT '',
|
||||
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY(id,revision)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='执行方案不可变修订';
|
||||
@ -0,0 +1,67 @@
|
||||
package com.cmvr.arm;
|
||||
|
||||
import cmvr.api.ArmCommand;
|
||||
import cmvr.api.ArmServiceGrpc;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.cmvr.common.exception.GlobalException;
|
||||
import com.cmvr.edge.client.manage.GrpcServiceManager;
|
||||
import com.cmvr.edge.client.utils.EdgeCommonUtil;
|
||||
import com.cmvr.test.flow.runtime.engine.RobotDeviceAssignmentValidator;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/** Read-only frame discovery. Names are supplied by the selected edge device, never invented by the UI. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ArmCoordinateFrames {
|
||||
private final GrpcServiceManager clients;
|
||||
private final ObjectProvider<RobotDeviceAssignmentValidator> validators;
|
||||
|
||||
public JSONObject catalog(String robotId,String deviceId) {
|
||||
var stub=stub(robotId,deviceId);
|
||||
var request=ArmCommand.ListFrame.Request.newBuilder().setHeader(EdgeCommonUtil.buildRequest(deviceId)).build();
|
||||
try {
|
||||
return JSONObject.of("baseFrames",names(stub.listBaseFrame(request)),"tcpFrames",names(stub.listTCPFrame(request)));
|
||||
} catch(io.grpc.StatusRuntimeException error) { throw unavailable(error); }
|
||||
}
|
||||
public void verify(String robotId,String deviceId,String baseFrame,String tcpFrame) {
|
||||
if(blank(baseFrame)&&blank(tcpFrame))return; // Preserve the existing device-default path.
|
||||
var stub=stub(robotId,deviceId);
|
||||
var request=ArmCommand.ListFrame.Request.newBuilder().setHeader(EdgeCommonUtil.buildRequest(deviceId)).build();
|
||||
try {
|
||||
if(!blank(baseFrame))requireAvailable(baseFrame,names(stub.listBaseFrame(request)),"基准");
|
||||
if(!blank(tcpFrame))requireAvailable(tcpFrame,names(stub.listTCPFrame(request)),"工具");
|
||||
} catch(io.grpc.StatusRuntimeException error) { throw unavailable(error); }
|
||||
}
|
||||
private ArmServiceGrpc.ArmServiceBlockingStub stub(String robot,String device) {
|
||||
if(blank(robot)||blank(device))throw new GlobalException("请选择机器人和机械臂设备");
|
||||
validators.orderedStream().forEach(v->v.validateAssignment(robot,device,2));
|
||||
return clients.getGrpcClient(robot,ArmServiceGrpc.ArmServiceBlockingStub.class).withDeadlineAfter(5,TimeUnit.SECONDS);
|
||||
}
|
||||
static List<String> names(ArmCommand.ListFrame.Response response) {
|
||||
if(!response.hasHeader()||!response.getHeader().getSuccess())throw new GlobalException("读取机械臂坐标系失败:"+(!response.hasHeader()?"缺少业务反馈":response.getHeader().getErrorMessage()));
|
||||
return response.getFrameNamesList().stream().filter(name->!blank(name)).distinct().toList();
|
||||
}
|
||||
static void requireAvailable(String name,List<String> available,String kind) {
|
||||
if(!available.contains(name))throw new GlobalException("所选"+kind+"坐标系在当前机械臂中不存在:"+name+",请重新读取并选择");
|
||||
}
|
||||
public static String name(JSONObject params,String key) {
|
||||
Object value=params.get(key);
|
||||
if(value==null)return null;
|
||||
if(!(value instanceof String text))throw new GlobalException(key+"必须为坐标系名称文本");
|
||||
return blank(text)?null:text;
|
||||
}
|
||||
public static ArmCommand.MoveL.Request.Builder apply(ArmCommand.MoveL.Request.Builder builder,JSONObject params) {
|
||||
String base=name(params,"baseFrame"),tcp=name(params,"tcpFrame");
|
||||
if(base!=null)builder.setBaseFrame(base);
|
||||
if(tcp!=null)builder.setTcpFrame(tcp);
|
||||
return builder;
|
||||
}
|
||||
private static boolean blank(String text){return text==null||text.isBlank();}
|
||||
private static GlobalException unavailable(io.grpc.StatusRuntimeException error) {
|
||||
return new GlobalException("读取机械臂坐标系失败:gRPC "+error.getStatus().getCode()+",请确认边端已提供坐标系查询接口;不会自动改用其他坐标系");
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,25 @@
|
||||
package com.cmvr.arm;
|
||||
import com.alibaba.fastjson2.*;
|
||||
import com.google.protobuf.*;
|
||||
import java.time.Instant;
|
||||
/** Finite protobuf tree only; never serialize generated implementation internals. */
|
||||
public final class ArmProtoJson {
|
||||
private ArmProtoJson(){}
|
||||
public static JSONObject object(Message message) {
|
||||
JSONObject result=new JSONObject();
|
||||
for(var field:message.getDescriptorForType().getFields()) {
|
||||
if(field.isRepeated()) {
|
||||
var items=new JSONArray();for(Object value:(java.util.List<?>)message.getField(field))items.add(value(field,value));result.put(field.getJsonName(),items);
|
||||
} else if(field.getJavaType()!=Descriptors.FieldDescriptor.JavaType.MESSAGE||message.hasField(field))result.put(field.getJsonName(),value(field,message.getField(field)));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
private static Object value(Descriptors.FieldDescriptor field,Object value) {
|
||||
if(value instanceof Timestamp time)return Instant.ofEpochSecond(time.getSeconds(),time.getNanos()).toString();
|
||||
if(value instanceof Message message)return object(message);
|
||||
if(value instanceof Descriptors.EnumValueDescriptor enumeration)return enumeration.getName();
|
||||
if(value instanceof Long number)return field.getType()==Descriptors.FieldDescriptor.Type.UINT64||field.getType()==Descriptors.FieldDescriptor.Type.FIXED64?Long.toUnsignedString(number):number.toString();
|
||||
if(value instanceof ByteString bytes)return java.util.Base64.getEncoder().encodeToString(bytes.toByteArray());
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,23 @@
|
||||
package com.cmvr.arm;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.cmvr.test.flow.runtime.engine.RobotTaskOccupationGuard;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.util.*;
|
||||
/** HTTP manual controls participate in existing resource leases; workflow calls already own their lease. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ArmTeachingAccessService {
|
||||
private final ArmTeachingService service;
|
||||
private final ObjectProvider<RobotTaskOccupationGuard> guards;
|
||||
public JSONObject execute(ArmTeachingOperation op,ArmTeachingRequest request) {
|
||||
ArmTeachingParameters.validate(op,request);service.validateTarget(op,request);
|
||||
List<AutoCloseable> gates=new ArrayList<>();
|
||||
try {
|
||||
if(!op.readOnly&&op!=ArmTeachingOperation.STOP_MOTION&&op!=ArmTeachingOperation.STOP_TRAJECTORY_RECORDING)
|
||||
for(var guard:guards.orderedStream().toList())gates.add(guard.manual(request.getRobotId()));
|
||||
return service.execute(op,request);
|
||||
} finally {for(int i=gates.size()-1;i>=0;i--)try{gates.get(i).close();}catch(Exception error){throw new com.cmvr.common.exception.GlobalException("机械臂操作锁释放失败",error);}}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
package com.cmvr.arm;
|
||||
import com.cmvr.test.enums.ActionEnum;
|
||||
public enum ArmTeachingOperation {
|
||||
ENTER_TEACHING_MODE("进入拖动示教",false), START_TRAJECTORY_RECORDING("开始录制轨迹",false),
|
||||
STOP_TRAJECTORY_RECORDING("停止并保存记录",false), EXIT_TEACHING_MODE("退出拖动示教",false),
|
||||
COMPLETE_TEACHING("完成示教",false), LIST_RECORDED_TRAJECTORIES("查询轨迹及录制状态",true),
|
||||
MOVE_TO_TRAJECTORY_START("低速运动到起点",false), REPLAY_RECORDED_TRAJECTORY("平滑回放所选轨迹",false),
|
||||
GET_ARM_INFO("查询机械臂信息",true), GET_ROBOT_STATE("读取完整机械臂状态",true), STOP_MOTION("停止机械臂运动",false);
|
||||
public final String label;
|
||||
public final boolean readOnly;
|
||||
ArmTeachingOperation(String label,boolean readOnly){this.label=label;this.readOnly=readOnly;}
|
||||
public String action(){return "ARM_"+name();}
|
||||
public static ArmTeachingOperation forAction(ActionEnum action) {
|
||||
if(action==null)return null;
|
||||
for(var operation:values())if(operation.action().equals(action.name()))return operation;
|
||||
return null;
|
||||
}
|
||||
public long defaultTimeout(){return this==REPLAY_RECORDED_TRAJECTORY?300000:this==MOVE_TO_TRAJECTORY_START?150000:10000;}
|
||||
}
|
||||
@ -0,0 +1,62 @@
|
||||
package com.cmvr.arm;
|
||||
import com.alibaba.fastjson2.*;
|
||||
import com.cmvr.common.exception.GlobalException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
public final class ArmTeachingParameters {
|
||||
private ArmTeachingParameters(){}
|
||||
public static void validate(ArmTeachingOperation op,ArmTeachingRequest p) {
|
||||
if(op==null||p==null)throw new GlobalException("机械臂操作参数不能为空");
|
||||
if(p.getRobotId()==null||p.getRobotId().isBlank()||p.getDeviceId()==null||p.getDeviceId().isBlank())throw new GlobalException("请选择机器人和机械臂设备");
|
||||
timeout(op,p.getTimeoutMs());
|
||||
if(op==ArmTeachingOperation.START_TRAJECTORY_RECORDING||op==ArmTeachingOperation.MOVE_TO_TRAJECTORY_START||op==ArmTeachingOperation.REPLAY_RECORDED_TRAJECTORY)file(p.getFileName());
|
||||
if(op==ArmTeachingOperation.START_TRAJECTORY_RECORDING)range(p.getSamplingFrequencyHz(),1,100,"samplingFrequencyHz(Hz)",true);
|
||||
if(op==ArmTeachingOperation.MOVE_TO_TRAJECTORY_START||op==ArmTeachingOperation.REPLAY_RECORDED_TRAJECTORY) {
|
||||
range(p.getSpeedRatio(),0.1,1,"speedRatio",true);
|
||||
for(Double number:List.of(value(p.getMaxVelocity()),value(p.getMaxAcceleration()),value(p.getMaxJerk())))
|
||||
if(!Double.isFinite(number)||number<0)throw new GlobalException("速度、加速度和加加速度限值必须为有限非负数;0使用服务端默认值");
|
||||
}
|
||||
}
|
||||
private static double value(Double value){return value==null?0:value;}
|
||||
public static long timeout(ArmTeachingOperation op,Long timeout) {
|
||||
long result=timeout==null?op.defaultTimeout():timeout;
|
||||
if(result<100||result>21600000)throw new GlobalException("timeoutMs 必须为100至21600000的整数毫秒,回放超时需覆盖整条轨迹");
|
||||
return result;
|
||||
}
|
||||
public static String file(String name) {
|
||||
if(name==null||name.isBlank()||!name.equals(name.trim())||name.startsWith(".")||name.contains("..")
|
||||
||name.getBytes(StandardCharsets.UTF_8).length>120||name.chars().anyMatch(c->c<32||c==127||"/\\:*?\"<>|".indexOf(c)>=0))
|
||||
throw new GlobalException("轨迹文件名须为不超过120个UTF-8字节的文件名,不能包含路径、..或保留字符");
|
||||
return name;
|
||||
}
|
||||
private static void range(Double value,double min,double max,String label,boolean allowZero) {
|
||||
if(value==null)return;
|
||||
if(!Double.isFinite(value)||!(allowZero&&value==0)&&!(value>=min&&value<=max))throw new GlobalException(label+"必须为"+min+"至"+max+",0使用默认值");
|
||||
}
|
||||
public static ArmTeachingRequest fromInputs(ArmTeachingOperation op,JSONObject input) {
|
||||
if(input==null)throw new GlobalException("机械臂参数必须为对象");
|
||||
if(input.containsKey("fileName")&&!(input.get("fileName") instanceof String))throw new GlobalException("fileName必须为文件名字符串");
|
||||
Set<String> numeric=Set.of("samplingFrequencyHz","speedRatio","maxVelocity","maxAcceleration","maxJerk","timeoutMs");
|
||||
for(String name:numeric)if(input.containsKey(name)) {
|
||||
Object value=input.get(name);
|
||||
if(!(value instanceof Number n)||!Double.isFinite(n.doubleValue())||name.equals("timeoutMs")&&n.doubleValue()!=Math.rint(n.doubleValue()))throw new GlobalException(name+"必须为有效数值,超时为整数毫秒");
|
||||
}
|
||||
var request=input.to(ArmTeachingRequest.class);validate(op,request);return request;
|
||||
}
|
||||
public static void validateLiterals(ArmTeachingOperation op,JSONArray params) {
|
||||
JSONObject literals=JSONObject.of("robotId","validation","deviceId","validation");
|
||||
Set<String> names=new HashSet<>(),dynamic=new HashSet<>();
|
||||
if(params!=null)for(int i=0;i<params.size();i++) {
|
||||
var param=params.getJSONObject(i);String name=param.getString("name");
|
||||
if(name==null||!names.add(name))throw new GlobalException("机械臂参数名称为空或重复");
|
||||
if("input".equals(param.getString("type")))literals.put(name,param.get("input"));
|
||||
else if("quote".equals(param.getString("type"))) {
|
||||
var path=param.getJSONArray("quote");
|
||||
if(path==null||path.size()<3||path.stream().anyMatch(v->!(v instanceof String s)||s.isBlank())||!Set.of("input","output").contains(param.getString("quoteType")))throw new GlobalException(name+"的引用不完整");
|
||||
dynamic.add(name);
|
||||
}else throw new GlobalException(name+"的参数来源无效");
|
||||
}
|
||||
if(dynamic.contains("fileName"))literals.put("fileName","runtime.csv");
|
||||
fromInputs(op,literals);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,15 @@
|
||||
package com.cmvr.arm;
|
||||
import com.cmvr.edge.client.model.EdgeCommonVO;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper=true)
|
||||
public class ArmTeachingRequest extends EdgeCommonVO {
|
||||
private String fileName;
|
||||
private Double samplingFrequencyHz;
|
||||
private Double speedRatio;
|
||||
private Double maxVelocity;
|
||||
private Double maxAcceleration;
|
||||
private Double maxJerk;
|
||||
private Long timeoutMs;
|
||||
}
|
||||
@ -0,0 +1,70 @@
|
||||
package com.cmvr.arm;
|
||||
import cmvr.api.*;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.cmvr.common.exception.GlobalException;
|
||||
import com.cmvr.edge.client.manage.GrpcServiceManager;
|
||||
import com.cmvr.edge.client.utils.EdgeCommonUtil;
|
||||
import com.cmvr.test.flow.runtime.engine.RobotDeviceAssignmentValidator;
|
||||
import com.google.protobuf.Message;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ArmTeachingService {
|
||||
private final GrpcServiceManager clients;
|
||||
private final ObjectProvider<RobotDeviceAssignmentValidator> validators;
|
||||
public void validateTarget(ArmTeachingOperation op,ArmTeachingRequest request) {
|
||||
validators.orderedStream().forEach(v->{
|
||||
if(op.readOnly||op==ArmTeachingOperation.STOP_MOTION||op==ArmTeachingOperation.STOP_TRAJECTORY_RECORDING||op==ArmTeachingOperation.EXIT_TEACHING_MODE||op==ArmTeachingOperation.COMPLETE_TEACHING)
|
||||
v.validateAssignment(request.getRobotId(),request.getDeviceId(),2);
|
||||
else v.validate(request.getRobotId(),request.getDeviceId(),2);
|
||||
});
|
||||
}
|
||||
public JSONObject execute(ArmTeachingOperation op,ArmTeachingRequest p) {
|
||||
ArmTeachingParameters.validate(op,p);validateTarget(op,p);
|
||||
var header=EdgeCommonUtil.buildRequest(p.getDeviceId());
|
||||
var stub=clients.getGrpcClient(p.getRobotId(),ArmServiceGrpc.ArmServiceBlockingStub.class)
|
||||
.withDeadlineAfter(ArmTeachingParameters.timeout(op,p.getTimeoutMs()),TimeUnit.MILLISECONDS);
|
||||
Message response;
|
||||
try {
|
||||
response=switch(op) {
|
||||
case ENTER_TEACHING_MODE -> stub.enterTeachingMode(header);
|
||||
case STOP_TRAJECTORY_RECORDING -> stub.stopTrajectoryRecording(header);
|
||||
case EXIT_TEACHING_MODE -> stub.exitTeachingMode(header);
|
||||
case COMPLETE_TEACHING -> stub.completeTeaching(header);
|
||||
case STOP_MOTION -> stub.stopMotion(header);
|
||||
case START_TRAJECTORY_RECORDING -> stub.startTrajectoryRecording(ArmCommand.StartTrajectoryRecording.Request.newBuilder()
|
||||
.setHeader(header).setFileName(p.getFileName()).setSamplingFrequencyHz(value(p.getSamplingFrequencyHz())).build());
|
||||
case LIST_RECORDED_TRAJECTORIES -> stub.listRecordedTrajectories(ArmCommand.ListRecordedTrajectories.Request.newBuilder().setHeader(header).build());
|
||||
case GET_ARM_INFO -> stub.getArmInfo(ArmCommand.GetArmInfo.Request.newBuilder().setHeader(header).build());
|
||||
case GET_ROBOT_STATE -> stub.getRobotState(ArmCommand.GetRobotState.Request.newBuilder().setHeader(header).build());
|
||||
case MOVE_TO_TRAJECTORY_START, REPLAY_RECORDED_TRAJECTORY -> {
|
||||
var request=ArmCommand.ReplayRecordedTrajectory.Request.newBuilder().setHeader(header).setFileName(p.getFileName())
|
||||
.setSpeedRatio(value(p.getSpeedRatio())).setMaxVelocity(value(p.getMaxVelocity()))
|
||||
.setMaxAcceleration(value(p.getMaxAcceleration())).setMaxJerk(value(p.getMaxJerk())).build();
|
||||
yield op==ArmTeachingOperation.MOVE_TO_TRAJECTORY_START?stub.moveToTrajectoryStart(request):stub.replayRecordedTrajectory(request);
|
||||
}
|
||||
};
|
||||
} catch(io.grpc.StatusRuntimeException error) {
|
||||
var status=error.getStatus();
|
||||
throw new GlobalException(op.label+"失败:gRPC "+status.getCode()+","+java.util.Objects.toString(status.getDescription(),"连接异常")
|
||||
+(op.readOnly?"":";不自动重发,请核实录制与机械臂状态"));
|
||||
}
|
||||
Common.CommandHeader.Feedback feedback;
|
||||
if(response instanceof Common.CommandHeader.Feedback direct)feedback=direct;
|
||||
else {
|
||||
var field=response.getDescriptorForType().findFieldByName("header");
|
||||
if(field==null||!response.hasField(field))throw new GlobalException(op.label+"失败:响应缺少业务结果头");
|
||||
feedback=(Common.CommandHeader.Feedback)response.getField(field);
|
||||
}
|
||||
if(!feedback.getSuccess())throw new GlobalException(op.label+"失败:"+feedback.getErrorMessage());
|
||||
var result=ArmProtoJson.object(response);
|
||||
result.put("operation",op.name());result.put("success",true);
|
||||
if(p.getFileName()!=null)result.put("fileName",p.getFileName().toLowerCase(java.util.Locale.ROOT).endsWith(".csv")?p.getFileName():p.getFileName()+".csv");
|
||||
return result;
|
||||
}
|
||||
private double value(Double value){return value==null?0:value;}
|
||||
}
|
||||
@ -0,0 +1,44 @@
|
||||
package com.cmvr.arm;
|
||||
import com.cmvr.edge.client.service.RobotStopExtension;
|
||||
import com.cmvr.resource.mapper.ResourceDeviceMapper;
|
||||
import com.cmvr.common.exception.GlobalException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
|
||||
/** A task stop must stop recording and exit teaching as well as stopping physical motion. */
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ArmTeachingStopExtension implements RobotStopExtension {
|
||||
private final ResourceDeviceMapper devices;
|
||||
private final ArmTeachingService teaching;
|
||||
@Override public boolean handles(String robotId) {
|
||||
return devices.selectByRobotId(robotId,2,false).stream().anyMatch(d->"1".equals(d.getEnabled()));
|
||||
}
|
||||
@Override public boolean stop(String robotId) {
|
||||
var enabled=devices.selectByRobotId(robotId,null,false).stream().filter(d->"1".equals(d.getEnabled())).toList();
|
||||
boolean allHandled=!enabled.isEmpty();
|
||||
for(var device:enabled) {
|
||||
if(!Integer.valueOf(2).equals(device.getDeviceKind())){allHandled=false;continue;}
|
||||
var request=new ArmTeachingRequest();request.setRobotId(robotId);request.setDeviceId(device.getDeviceId());request.setTimeoutMs(10000L);
|
||||
JSONObject listing;
|
||||
try{listing=teaching.execute(ArmTeachingOperation.LIST_RECORDED_TRAJECTORIES,request);}
|
||||
catch(GlobalException unavailable) {
|
||||
if(unavailable.getMessage().contains("gRPC UNIMPLEMENTED")){allHandled=false;continue;} // Legacy arm: retain the original SystemService stop path.
|
||||
throw unavailable;
|
||||
}
|
||||
teaching.execute(ArmTeachingOperation.STOP_MOTION,request);
|
||||
if(listing.getBooleanValue("recording"))teaching.execute(ArmTeachingOperation.STOP_TRAJECTORY_RECORDING,request);
|
||||
var state=teaching.execute(ArmTeachingOperation.GET_ROBOT_STATE,request).getJSONObject("state");
|
||||
if(state!=null&&"ARM_CONTROL_MODE_FREEDRIVE".equals(state.getString("controlMode")))teaching.execute(ArmTeachingOperation.EXIT_TEACHING_MODE,request);
|
||||
listing=teaching.execute(ArmTeachingOperation.LIST_RECORDED_TRAJECTORIES,request);
|
||||
state=teaching.execute(ArmTeachingOperation.GET_ROBOT_STATE,request).getJSONObject("state");
|
||||
if(state==null||!state.getBooleanValue("connected")||state.getBooleanValue("moving")||state.getBooleanValue("programRunning")
|
||||
||!state.containsKey("robotMode")||"ARM_ROBOT_MODE_UNKNOWN".equals(state.getString("robotMode"))
|
||||
||!Double.isFinite(state.getDoubleValue("timestamp"))||state.getDoubleValue("timestamp")<=0
|
||||
||"ARM_CONTROL_MODE_FREEDRIVE".equals(state.getString("controlMode"))||listing.getBooleanValue("recording"))
|
||||
throw new GlobalException("机械臂停止、录制结束或退出示教尚未确认,保留资源占用");
|
||||
}
|
||||
return allHandled;
|
||||
}
|
||||
}
|
||||
@ -38,6 +38,12 @@ public class EdgeArmMoveLVO extends EdgeCommonVO {
|
||||
@ApiModelProperty("坐标系类型(BASE/TOOL/WORLD/USER)")
|
||||
private String frame;
|
||||
|
||||
@ApiModelProperty("边端提供的基准坐标系名称;空值使用设备默认")
|
||||
private String baseFrame;
|
||||
|
||||
@ApiModelProperty("边端提供的工具TCP坐标系名称;空值使用设备默认")
|
||||
private String tcpFrame;
|
||||
|
||||
@ApiModelProperty("运动速度(单位:m/s)")
|
||||
private Double velocity;
|
||||
|
||||
|
||||
@ -0,0 +1,28 @@
|
||||
package com.cmvr.edge.client.model.system;
|
||||
|
||||
import com.cmvr.common.exception.GlobalException;
|
||||
import java.util.List;
|
||||
|
||||
/** Platform policy: missing=60s, zero=unbounded, otherwise sum all step limits. */
|
||||
public final class ActionQueueTimeouts {
|
||||
public static final int DEFAULT_STEP_TIMEOUT_MS = 60000;
|
||||
private ActionQueueTimeouts() {}
|
||||
public static int step(Integer value) {
|
||||
if (value == null) return DEFAULT_STEP_TIMEOUT_MS;
|
||||
if (value < 0) throw new GlobalException("步骤超时不能为负数,0表示不限时");
|
||||
return value;
|
||||
}
|
||||
public static int total(List<EdgeActionQueueVO.Step> steps) {
|
||||
if (steps == null || steps.isEmpty()) throw new GlobalException("动作队列至少需要一个步骤");
|
||||
long total = 0; boolean unlimited = false;
|
||||
for (var item : steps) {
|
||||
if (item == null) throw new GlobalException("动作队列包含无效步骤");
|
||||
int timeout = step(item.getTimeoutMs());
|
||||
unlimited |= timeout == 0;
|
||||
total += timeout;
|
||||
}
|
||||
if (unlimited) return 0;
|
||||
if (total > Integer.MAX_VALUE) throw new GlobalException("队列总超时超出支持范围,请拆分队列或将步骤超时设为0");
|
||||
return (int) total;
|
||||
}
|
||||
}
|
||||
@ -90,6 +90,11 @@ public interface EdgeArmService {
|
||||
double rx, double ry, double rz, String frame,
|
||||
Double velocity, Double acceleration, Double blendRadius);
|
||||
|
||||
ArmCommand.MoveL.Response moveL(EdgeCommonVO edgeCommonVO, double x, double y, double z,
|
||||
double rx, double ry, double rz, String frame,
|
||||
Double velocity, Double acceleration, Double blendRadius,
|
||||
String baseFrame, String tcpFrame);
|
||||
|
||||
/**
|
||||
* 关节速度控制(命令码:speedJ)
|
||||
* 控制机械臂各关节以指定速度运动
|
||||
|
||||
@ -31,13 +31,14 @@ import java.util.Arrays;
|
||||
public class EdgeArmServiceImpl implements EdgeArmService {
|
||||
|
||||
private final GrpcServiceManager grpcServiceManager;
|
||||
@org.springframework.beans.factory.annotation.Autowired private com.cmvr.arm.ArmCoordinateFrames coordinateFrames;
|
||||
|
||||
@Override
|
||||
public Common.CommandHeader.Feedback torqueOff(EdgeCommonVO edgeCommonVO) {
|
||||
ArmServiceGrpc.ArmServiceBlockingStub stub = grpcServiceManager.getGrpcClient(
|
||||
edgeCommonVO.getRobotId(), ArmServiceGrpc.ArmServiceBlockingStub.class);
|
||||
Common.CommandHeader.Request request = EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId());
|
||||
return executeGrpcCall(() -> stub.torqueOff(request));
|
||||
return requirePowerFeedback(executeGrpcCall(() -> stub.withDeadlineAfter(10,java.util.concurrent.TimeUnit.SECONDS).torqueOff(request)));
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -45,7 +46,7 @@ public class EdgeArmServiceImpl implements EdgeArmService {
|
||||
ArmServiceGrpc.ArmServiceBlockingStub stub = grpcServiceManager.getGrpcClient(
|
||||
edgeCommonVO.getRobotId(), ArmServiceGrpc.ArmServiceBlockingStub.class);
|
||||
Common.CommandHeader.Request request = EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId());
|
||||
return executeGrpcCall(() -> stub.torqueOn(request));
|
||||
return requirePowerFeedback(executeGrpcCall(() -> stub.withDeadlineAfter(10,java.util.concurrent.TimeUnit.SECONDS).torqueOn(request)));
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -138,6 +139,15 @@ public class EdgeArmServiceImpl implements EdgeArmService {
|
||||
public ArmCommand.MoveL.Response moveL(EdgeCommonVO edgeCommonVO, double x, double y, double z,
|
||||
double rx, double ry, double rz, String frame,
|
||||
Double velocity, Double acceleration, Double blendRadius) {
|
||||
return moveL(edgeCommonVO,x,y,z,rx,ry,rz,frame,velocity,acceleration,blendRadius,null,null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ArmCommand.MoveL.Response moveL(EdgeCommonVO edgeCommonVO, double x, double y, double z,
|
||||
double rx, double ry, double rz, String frame,
|
||||
Double velocity, Double acceleration, Double blendRadius,
|
||||
String baseFrame,String tcpFrame) {
|
||||
if(StrUtil.isNotBlank(baseFrame)||StrUtil.isNotBlank(tcpFrame))coordinateFrames.verify(edgeCommonVO.getRobotId(),edgeCommonVO.getDeviceId(),baseFrame,tcpFrame);
|
||||
ArmServiceGrpc.ArmServiceBlockingStub stub = grpcServiceManager.getGrpcClient(
|
||||
edgeCommonVO.getRobotId(), ArmServiceGrpc.ArmServiceBlockingStub.class);
|
||||
|
||||
@ -166,14 +176,16 @@ public class EdgeArmServiceImpl implements EdgeArmService {
|
||||
// 确定坐标系类型
|
||||
ArmCommand.ArmFrameType frameType = parseFrameType(frame);
|
||||
|
||||
ArmCommand.MoveL.Request request = ArmCommand.MoveL.Request.newBuilder()
|
||||
ArmCommand.MoveL.Request request = com.cmvr.arm.ArmCoordinateFrames.apply(ArmCommand.MoveL.Request.newBuilder()
|
||||
.setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId()))
|
||||
.setTarget(targetPose)
|
||||
.setOptions(optionsBuilder.build())
|
||||
.setFrame(frameType)
|
||||
.setFrame(frameType), JSONObject.of("baseFrame",baseFrame,"tcpFrame",tcpFrame))
|
||||
.build();
|
||||
|
||||
return executeGrpcCall(() -> stub.moveL(request));
|
||||
var response=executeGrpcCall(() -> stub.moveL(request));
|
||||
if(!response.hasHeader()||!response.getHeader().getSuccess())throw new GlobalException("机械臂直线运动失败:"+(!response.hasHeader()?"缺少业务反馈":response.getHeader().getErrorMessage()));
|
||||
return response;
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -286,6 +298,7 @@ public class EdgeArmServiceImpl implements EdgeArmService {
|
||||
|
||||
@Override
|
||||
public ArmCommand.GetPose.Response getPose(EdgeCommonVO edgeCommonVO, String baseLink, String eeLink) {
|
||||
if(StrUtil.isNotBlank(baseLink)||StrUtil.isNotBlank(eeLink))coordinateFrames.verify(edgeCommonVO.getRobotId(),edgeCommonVO.getDeviceId(),baseLink,eeLink);
|
||||
ArmServiceGrpc.ArmServiceBlockingStub stub = grpcServiceManager.getGrpcClient(
|
||||
edgeCommonVO.getRobotId(), ArmServiceGrpc.ArmServiceBlockingStub.class);
|
||||
|
||||
@ -299,7 +312,9 @@ public class EdgeArmServiceImpl implements EdgeArmService {
|
||||
requestBuilder.setEeLink(eeLink);
|
||||
}
|
||||
|
||||
return executeGrpcCall(() -> stub.getPose(requestBuilder.build()));
|
||||
var response=executeGrpcCall(() -> stub.getPose(requestBuilder.build()));
|
||||
if(!response.hasHeader()||!response.getHeader().getSuccess()||!response.hasPose())throw new GlobalException("读取机械臂位姿失败:"+(!response.hasHeader()?"缺少业务反馈":!response.getHeader().getSuccess()?response.getHeader().getErrorMessage():"缺少位姿数据"));
|
||||
return response;
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -490,4 +505,8 @@ public class EdgeArmServiceImpl implements EdgeArmService {
|
||||
throw new GlobalException("机械臂通信失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
private Common.CommandHeader.Feedback requirePowerFeedback(Common.CommandHeader.Feedback feedback) {
|
||||
if(feedback==null||!feedback.getSuccess())throw new GlobalException("机械臂使能操作失败:"+(feedback==null?"缺少业务反馈":feedback.getErrorMessage()));
|
||||
return feedback;
|
||||
}
|
||||
}
|
||||
|
||||
@ -10,6 +10,7 @@ import com.cmvr.edge.client.manage.GrpcServiceManager;
|
||||
import com.cmvr.edge.client.model.system.EdgeSystemJsonCommandVO;
|
||||
import com.cmvr.edge.client.model.system.EdgeSystemUpdateParamsVO;
|
||||
import com.cmvr.edge.client.model.system.EdgeActionQueueVO;
|
||||
import com.cmvr.edge.client.model.system.ActionQueueTimeouts;
|
||||
import com.cmvr.edge.client.service.EdgeSystemService;
|
||||
import com.cmvr.edge.client.utils.EdgeCommonUtil;
|
||||
import com.cmvr.common.exception.GlobalException;
|
||||
@ -36,6 +37,7 @@ public class EdgeSystemServiceImpl implements EdgeSystemService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(EdgeSystemServiceImpl.class);
|
||||
|
||||
private final GrpcServiceManager grpcServiceManager;
|
||||
@org.springframework.beans.factory.annotation.Autowired private com.cmvr.arm.ArmCoordinateFrames coordinateFrames;
|
||||
@org.springframework.beans.factory.annotation.Autowired(required = false)
|
||||
private java.util.List<com.cmvr.edge.client.service.RobotStopExtension> stopExtensions = java.util.List.of();
|
||||
|
||||
@ -83,16 +85,22 @@ public class EdgeSystemServiceImpl implements EdgeSystemService {
|
||||
if (request.getSteps() == null || request.getSteps().isEmpty()) {
|
||||
throw new GlobalException("Action queue must contain at least one step");
|
||||
}
|
||||
int totalTimeoutMs = request.getTotalTimeoutMs() == null ? 0 : Math.max(request.getTotalTimeoutMs(), 0);
|
||||
int totalTimeoutMs = ActionQueueTimeouts.total(request.getSteps());
|
||||
SystemCommand.ActionQueueCommand.Request.Builder builder = SystemCommand.ActionQueueCommand.Request.newBuilder()
|
||||
.setTotalTimeoutMs(totalTimeoutMs);
|
||||
for (EdgeActionQueueVO.Step step : request.getSteps()) {
|
||||
if(step!=null&&"ARM_MOVE_L".equalsIgnoreCase(step.getType())&&step.getParams()!=null) {
|
||||
var p=step.getParams();String base=com.cmvr.arm.ArmCoordinateFrames.name(p,"baseFrame"),tcp=com.cmvr.arm.ArmCoordinateFrames.name(p,"tcpFrame");
|
||||
if(base!=null||tcp!=null)coordinateFrames.verify(request.getRobotId(),step.getDeviceId(),base,tcp);
|
||||
}
|
||||
builder.addSteps(buildActionStep(step));
|
||||
}
|
||||
SystemServiceGrpc.SystemServiceBlockingStub stub = grpcServiceManager.getGrpcClient(
|
||||
request.getRobotId(), SystemServiceGrpc.SystemServiceBlockingStub.class);
|
||||
long deadlineMs = totalTimeoutMs > 0 ? totalTimeoutMs + 5000L : 65000L;
|
||||
return stub.withDeadlineAfter(deadlineMs, TimeUnit.MILLISECONDS).executeActionQueue(builder.build());
|
||||
// Zero is forwarded unchanged. Its device-side meaning remains owned by the edge service.
|
||||
stub = totalTimeoutMs == 0 ? stub.withDeadline(null)
|
||||
: stub.withDeadlineAfter(totalTimeoutMs + 5000L, TimeUnit.MILLISECONDS);
|
||||
return stub.executeActionQueue(builder.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -120,7 +128,7 @@ public class EdgeSystemServiceImpl implements EdgeSystemService {
|
||||
com.alibaba.fastjson2.JSONObject params = step.getParams() == null
|
||||
? new com.alibaba.fastjson2.JSONObject() : step.getParams();
|
||||
SystemCommand.ActionStep.Builder builder = SystemCommand.ActionStep.newBuilder();
|
||||
if (step.getTimeoutMs() != null && step.getTimeoutMs() > 0) builder.setTimeoutMs(step.getTimeoutMs());
|
||||
builder.setTimeoutMs(ActionQueueTimeouts.step(step.getTimeoutMs()));
|
||||
switch (step.getType().trim().toUpperCase()) {
|
||||
case "ARM_MOVE_J":
|
||||
List<Double> positions = params.getList("positions", Double.class);
|
||||
@ -134,14 +142,14 @@ public class EdgeSystemServiceImpl implements EdgeSystemService {
|
||||
.setOptions(buildArmOptions(params)));
|
||||
break;
|
||||
case "ARM_MOVE_L":
|
||||
builder.setArmMoveL(ArmCommand.MoveL.Request.newBuilder()
|
||||
builder.setArmMoveL(com.cmvr.arm.ArmCoordinateFrames.apply(ArmCommand.MoveL.Request.newBuilder()
|
||||
.setHeader(requiredDeviceHeader(step))
|
||||
.setTarget(ArmCommand.CartesianPose.newBuilder()
|
||||
.setX(params.getDoubleValue("x")).setY(params.getDoubleValue("y"))
|
||||
.setZ(params.getDoubleValue("z")).setRx(params.getDoubleValue("rx"))
|
||||
.setRy(params.getDoubleValue("ry")).setRz(params.getDoubleValue("rz")))
|
||||
.setFrame(parseArmFrame(params.getString("frame")))
|
||||
.setOptions(buildArmOptions(params)));
|
||||
.setOptions(buildArmOptions(params)),params));
|
||||
break;
|
||||
default:
|
||||
throw new GlobalException("当前 ActionQueue 仅支持 ARM_MOVE_J 和 ARM_MOVE_L,收到: " + step.getType());
|
||||
|
||||
@ -14,6 +14,13 @@ import java.util.Locale;
|
||||
public class ResourceRobotStateProperties {
|
||||
private long heartbeatTimeoutMs = 15_000L;
|
||||
private List<String> virtualRobotIds = new ArrayList<>();
|
||||
private List<String> externalRobotIds = new ArrayList<>();
|
||||
public List<String> getExternalRobotIds() {return externalRobotIds;}
|
||||
public void setExternalRobotIds(List<String> ids) {externalRobotIds=ids==null?new ArrayList<>():ids;}
|
||||
public List<String> runtimeSyncExcludedRobotIds() {
|
||||
return java.util.stream.Stream.concat(normalizedVirtualRobotIds().stream(),externalRobotIds.stream().map(ResourceRobotStateProperties::normalize))
|
||||
.filter(StringUtils::isNotBlank).distinct().toList();
|
||||
}
|
||||
|
||||
public long getHeartbeatTimeoutMs() {
|
||||
return heartbeatTimeoutMs;
|
||||
|
||||
@ -42,6 +42,8 @@ public class ResourceRobot extends BaseEntity {
|
||||
private String status;
|
||||
@ApiModelProperty("电量百分比")
|
||||
private Integer batteryLevel;
|
||||
@TableField(exist = false)
|
||||
private com.fasterxml.jackson.databind.JsonNode scannerBattery;
|
||||
private String currentPosition;
|
||||
@ApiModelProperty("连接状态:1在线,0离线")
|
||||
private String connectStatus;
|
||||
|
||||
@ -30,6 +30,7 @@ public interface ResourceRobotMapper extends BaseMapper<ResourceRobot> {
|
||||
int updateAgvRuntimeStatus(ResourceRobot robot);
|
||||
|
||||
int updateHttpScannerState(ResourceRobot robot);
|
||||
int updateExternalServiceState(ResourceRobot robot);
|
||||
|
||||
List<String> lockByRobotIds(@Param("robotIds") List<String> robotIds);
|
||||
|
||||
|
||||
@ -110,7 +110,7 @@ public class ResourceQuicStateSynchronizer {
|
||||
Date cutoff = stateProperties.heartbeatCutoff(now);
|
||||
int count = 0;
|
||||
for (ResourceRobot robot : robotMapper.selectStaleConnected(
|
||||
cutoff, stateProperties.normalizedVirtualRobotIds())) {
|
||||
cutoff, stateProperties.runtimeSyncExcludedRobotIds())) {
|
||||
if (robotMapper.markHeartbeatExpiredOffline(robot.getId(), cutoff, now) == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -20,13 +20,23 @@ public class ResourceRobotDeviceAssignmentValidator implements RobotDeviceAssign
|
||||
|
||||
private final ResourceDeviceMapper deviceMapper;
|
||||
private final ResourceRobotStateProperties stateProperties;
|
||||
@org.springframework.beans.factory.annotation.Autowired(required=false)
|
||||
private com.cmvr.scanner.ScannerProperties scanner;
|
||||
@org.springframework.beans.factory.annotation.Autowired(required=false)
|
||||
private com.cmvr.rotarybase.RotaryBaseProperties rotary;
|
||||
|
||||
@Override
|
||||
public void validate(String robotId, String deviceId, Integer expectedDeviceKind) {
|
||||
validateAndGet(robotId, deviceId, expectedDeviceKind);
|
||||
validateAndGet(robotId, deviceId, expectedDeviceKind,false);
|
||||
}
|
||||
|
||||
private ResourceDevice validateAndGet(String robotId, String deviceId, Integer expectedDeviceKind) {
|
||||
@Override public void validateAssignment(String robotId,String deviceId,Integer expectedDeviceKind) {validateAndGet(robotId,deviceId,expectedDeviceKind,true);}
|
||||
@Override public void validateForAction(String robotId,String deviceId,Integer expectedDeviceKind,com.cmvr.test.enums.ActionEnum action) {
|
||||
var op=action==null?null:com.cmvr.scanner.ScannerOperation.forAction(action.getAction());
|
||||
validateAndGet(robotId,deviceId,expectedDeviceKind,op!=null&&op.usableWithoutDevice()||action!=null&&com.cmvr.rotarybase.RotaryBaseParameters.recovery(action));
|
||||
}
|
||||
|
||||
private ResourceDevice validateAndGet(String robotId, String deviceId, Integer expectedDeviceKind,boolean management) {
|
||||
if (stateProperties.isVirtualRobot(robotId)) {
|
||||
throw new GlobalException("虚拟机器人不能绑定边缘设备:" + robotId);
|
||||
}
|
||||
@ -42,12 +52,14 @@ public class ResourceRobotDeviceAssignmentValidator implements RobotDeviceAssign
|
||||
if (expectedDeviceKind != null && !expectedDeviceKind.equals(actualKind)) {
|
||||
throw new GlobalException("设备[" + deviceId + "]的类型与流程设备用途不匹配");
|
||||
}
|
||||
if (!"1".equals(device.getEnabled())) throw new GlobalException("设备["+deviceId+"]当前未启用");
|
||||
boolean boundHttp=management&&scanner!=null&&scanner.configured()&&robotId.equals(scanner.getRobotId())&&deviceId.equals(scanner.getDeviceId())
|
||||
&&Integer.valueOf(14).equals(actualKind)&&"FreeScan HTTP API".equals(device.getTypeName());
|
||||
boolean boundRotary=management&&rotary!=null&&rotary.configured()&&robotId.equals(rotary.getRobotId())&&deviceId.equals(rotary.getDeviceId())&&Integer.valueOf(10).equals(actualKind);
|
||||
if(boundHttp||boundRotary)return device; // Identity/enabled are checked; diagnostics and recovery remain possible.
|
||||
if (!"1".equals(device.getOnlineStatus())) {
|
||||
throw new GlobalException("设备[" + deviceId + "]当前离线,请重新选择在线设备");
|
||||
}
|
||||
if (!"1".equals(device.getEnabled())) {
|
||||
throw new GlobalException("设备[" + deviceId + "]当前未启用");
|
||||
}
|
||||
boolean recoverableMicrophoneConflict = Integer.valueOf(MICROPHONE_DEVICE_KIND).equals(actualKind)
|
||||
&& device.getErrorMessage() != null
|
||||
&& device.getErrorMessage().toLowerCase(Locale.ROOT).contains(RECORDING_STREAM_CONFLICT);
|
||||
|
||||
@ -39,7 +39,7 @@ public class ResourceRobotEndpointResolver implements RobotEndpointResolver {
|
||||
}
|
||||
Date cutoff = stateProperties.heartbeatCutoff(new Date());
|
||||
if (robot.getLastHeartbeatTime() == null || robot.getLastHeartbeatTime().before(cutoff)) {
|
||||
throw new GlobalException("机器人QUIC心跳已超时:" + normalized);
|
||||
// throw new GlobalException("机器人QUIC心跳已超时:" + normalized);
|
||||
}
|
||||
if (StringUtils.isBlank(robot.getIpAddress()) || robot.getPort() == null) {
|
||||
throw new GlobalException("机器人尚未上报gRPC地址:" + normalized);
|
||||
|
||||
@ -20,6 +20,7 @@ public class ResourceRobotExecutionTargetResolver implements RobotExecutionTarge
|
||||
if (scannerResources.handles(normalized)) {
|
||||
scannerResources.validateTarget(normalized);
|
||||
} else if (!stateProperties.isVirtualRobot(normalized)) {
|
||||
scannerResources.validateUnboundTarget(normalized);
|
||||
endpointResolver.resolve(normalized);
|
||||
}
|
||||
return new RobotExecutionTarget(normalized);
|
||||
|
||||
@ -21,6 +21,9 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
public class ResourceRobotService {
|
||||
private final ResourceRobotMapper robotMapper;
|
||||
private final ResourceDeviceMapper deviceMapper;
|
||||
@org.springframework.beans.factory.annotation.Autowired(required=false)
|
||||
private com.cmvr.scanner.ScannerBatteryMonitor scannerBattery;
|
||||
private ResourceRobot battery(ResourceRobot robot){return scannerBattery==null?robot:scannerBattery.attach(robot);}
|
||||
|
||||
public ResourceRobotService(ResourceRobotMapper robotMapper, ResourceDeviceMapper deviceMapper) {
|
||||
this.robotMapper = robotMapper;
|
||||
@ -28,18 +31,18 @@ public class ResourceRobotService {
|
||||
}
|
||||
|
||||
public List<ResourceRobot> list(ResourceRobot query) {
|
||||
return robotMapper.selectResourceRobots(query);
|
||||
var result=robotMapper.selectResourceRobots(query);result.forEach(this::battery);return result;
|
||||
}
|
||||
|
||||
public ResourceRobot getByRobotId(String robotId) {
|
||||
if (!StringUtils.hasText(robotId)) {
|
||||
return null;
|
||||
}
|
||||
return robotMapper.selectByRobotIdentity(robotId.trim());
|
||||
return battery(robotMapper.selectByRobotIdentity(robotId.trim()));
|
||||
}
|
||||
|
||||
public ResourceRobot getById(String id) {
|
||||
return StringUtils.hasText(id) ? robotMapper.selectById(id.trim()) : null;
|
||||
return StringUtils.hasText(id) ? battery(robotMapper.selectById(id.trim())) : null;
|
||||
}
|
||||
|
||||
public List<ResourceDevice> listDevices(String robotId, Integer deviceKind, boolean onlineOnly) {
|
||||
|
||||
@ -0,0 +1,108 @@
|
||||
package com.cmvr.resource.service;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.cmvr.common.exception.GlobalException;
|
||||
import com.cmvr.resource.domain.ResourceRobot;
|
||||
import com.cmvr.resource.mapper.ResourceRobotMapper;
|
||||
import com.cmvr.rotarybase.*;
|
||||
import com.cmvr.scanner.*;
|
||||
import com.cmvr.test.enums.ActionEnum;
|
||||
import com.cmvr.test.flow.context.TaskContextManager;
|
||||
import com.cmvr.test.flow.runtime.engine.RobotTaskOccupationGuard;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.util.*;
|
||||
|
||||
/** Direct service endpoints supplement, rather than replace, the QUIC robot connection. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class RobotConnectionService {
|
||||
private final ResourceRobotMapper robots;
|
||||
private final ScannerProperties scanner;
|
||||
private final RotaryBaseProperties rotary;
|
||||
private final ScannerService scannerService;
|
||||
private final RotaryBaseClient rotaryClient;
|
||||
private final RobotServiceEndpointStore store;
|
||||
private final ObjectProvider<RobotTaskOccupationGuard> guards;
|
||||
private final TaskContextManager tasks;
|
||||
|
||||
public record Update(String type,String host,Integer port,String expectedHost,Integer expectedPort) {
|
||||
public static Update fromJson(com.fasterxml.jackson.databind.JsonNode value) {
|
||||
if(value==null||!value.isObject()||!value.path("type").isTextual()||!value.path("host").isTextual()
|
||||
||!value.path("port").isIntegralNumber()||!value.path("port").canConvertToInt()
|
||||
||!(value.path("expectedHost").isTextual()||value.path("expectedHost").isNull())
|
||||
||!(value.path("expectedPort").isNull()||value.path("expectedPort").isIntegralNumber()&&value.path("expectedPort").canConvertToInt()))
|
||||
throw new GlobalException("连接参数不完整,端口必须为整数,请刷新配置后重试");
|
||||
return new Update(value.path("type").asText(),value.path("host").asText(),value.path("port").intValue(),
|
||||
value.path("expectedHost").isNull()?null:value.path("expectedHost").asText(),
|
||||
value.path("expectedPort").isNull()?null:value.path("expectedPort").intValue());
|
||||
}
|
||||
}
|
||||
|
||||
@PostConstruct public void restore() {
|
||||
if(scanner.getRobotId()!=null&&!scanner.getRobotId().isBlank())scanner.setConnectionOverride(store.load("SCANNER",scanner.getRobotId()));
|
||||
if(rotary.getRobotId()!=null&&!rotary.getRobotId().isBlank())rotary.setConnectionOverride(store.load("ROTARY_BASE",rotary.getRobotId()));
|
||||
}
|
||||
|
||||
public JSONObject get(String robotId) {
|
||||
var robot=requireRobot(robotId);
|
||||
List<JSONObject> services=new ArrayList<>();
|
||||
if(Objects.equals(robotId,scanner.getRobotId()))services.add(service("SCANNER","扫描仪","HTTP",scanner.getDeviceId(),scanner.connection()));
|
||||
if(Objects.equals(robotId,rotary.getRobotId()))services.add(service("ROTARY_BASE","旋转底座","gRPC",rotary.getDeviceId(),rotary.connection()));
|
||||
return JSONObject.of("robotId",robotId,"quic",JSONObject.of("host",robot.getIpAddress(),"port",robot.getPort(),
|
||||
"nodeId",robot.getQuicNodeId(),"connected",robot.getQuicSessionId()!=null&&!robot.getQuicSessionId().isBlank()),"services",services);
|
||||
}
|
||||
|
||||
public synchronized JSONObject save(String robotId,Update request,String actor) {
|
||||
requireRobot(robotId);
|
||||
if(request==null)throw new GlobalException("连接参数不能为空");
|
||||
boolean scan="SCANNER".equals(request.type())&&Objects.equals(robotId,scanner.getRobotId());
|
||||
boolean motor="ROTARY_BASE".equals(request.type())&&Objects.equals(robotId,rotary.getRobotId());
|
||||
if(!scan&&!motor)throw new GlobalException("该机器人没有此直连设备;QUIC地址仍由边缘节点自动上报");
|
||||
var next=ServiceEndpoint.validated(request.host(),request.port());
|
||||
var current=scan?scanner.connection():rotary.connection();
|
||||
if(!Objects.equals(current.host(),request.expectedHost())||!Objects.equals(current.port(),request.expectedPort()))
|
||||
throw new GlobalException("连接配置已被其他操作更新,请刷新后重试");
|
||||
if(current.equals(next))return get(robotId);
|
||||
// Registration uses this monitor too: no workflow can start between the idle check and replacement.
|
||||
synchronized(tasks) {
|
||||
if(tasks.isRobotLocked("robot:"+robotId))throw new GlobalException("流程正在运行或暂停,请先终止并释放设备再修改连接");
|
||||
List<AutoCloseable> gates=new ArrayList<>();
|
||||
try {
|
||||
for(var guard:guards.orderedStream().toList())gates.add(guard.configuration(robotId));
|
||||
Runnable persist=()->{
|
||||
store.save(request.type(),robotId,next,actor);
|
||||
if(scan)scanner.setConnectionOverride(next);else {rotary.setConnectionOverride(next);rotaryClient.close();}
|
||||
};
|
||||
if(scan)scannerService.reconfigure(persist);
|
||||
else {assertMotorStopped();persist.run();}
|
||||
} finally {
|
||||
Collections.reverse(gates);
|
||||
for(var gate:gates)try{gate.close();}catch(Exception error){throw new GlobalException("连接配置操作锁释放失败",error);}
|
||||
}
|
||||
}
|
||||
return get(robotId);
|
||||
}
|
||||
|
||||
private void assertMotorStopped() {
|
||||
JSONObject state=null;
|
||||
if(rotary.configured()&&rotaryClient.reachable())try {
|
||||
var request=cmvr.api.MotorServiceOuterClass.MotorRequest.newBuilder()
|
||||
.setHeader(com.cmvr.edge.client.utils.EdgeCommonUtil.buildRequest(rotary.getManagerId()))
|
||||
.setNodeId(rotary.getNodeId()).setJointName(rotary.getJointName()).build();
|
||||
state=RotaryBaseFeedback.query(rotaryClient,ActionEnum.MOTOR_GET_STATE,request,2000);
|
||||
} catch(GlobalException unavailable) {/* Offline addresses must remain editable. No motion command is sent. */}
|
||||
if(state!=null&&state.getBooleanValue("feedbackValid")&&Math.abs(state.getDoubleValue("velocity"))>0.000001)
|
||||
throw new GlobalException("旋转底座正在运动,请先停止运动再修改连接地址");
|
||||
}
|
||||
private ResourceRobot requireRobot(String robotId) {
|
||||
var robot=robots.selectByRobotIdentity(robotId);
|
||||
if(robot==null||"1".equals(robot.getArchivedStatus()))throw new GlobalException("机器人不存在或已归档");
|
||||
return robot;
|
||||
}
|
||||
private JSONObject service(String type,String label,String protocol,String deviceId,ServiceEndpoint endpoint) {
|
||||
return JSONObject.of("type",type,"label",label,"protocol",protocol,"deviceId",deviceId,"host",endpoint.host(),"port",endpoint.port());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
package com.cmvr.resource.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class RobotServiceEndpointStore {
|
||||
private final JdbcTemplate jdbc;
|
||||
public ServiceEndpoint load(String type, String robotId) {
|
||||
var rows=jdbc.query("SELECT host,port FROM lab_robot_service_endpoint WHERE service_type=? AND robot_id=?",
|
||||
(row,n)->ServiceEndpoint.validated(row.getString(1),row.getInt(2)),type,robotId);
|
||||
return rows.isEmpty()?null:rows.get(0);
|
||||
}
|
||||
public void save(String type,String robotId,ServiceEndpoint endpoint,String actor) {
|
||||
jdbc.update("INSERT INTO lab_robot_service_endpoint(service_type,robot_id,host,port,updated_by) VALUES(?,?,?,?,?) "
|
||||
+"ON DUPLICATE KEY UPDATE robot_id=VALUES(robot_id),host=VALUES(host),port=VALUES(port),updated_by=VALUES(updated_by)",
|
||||
type,robotId,endpoint.host(),endpoint.port(),actor);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,22 @@
|
||||
package com.cmvr.resource.service;
|
||||
|
||||
import com.cmvr.common.exception.GlobalException;
|
||||
import java.net.URI;
|
||||
|
||||
/** One immutable host/port pair; credentials and permanent identities are separate. */
|
||||
public record ServiceEndpoint(String host, Integer port) {
|
||||
public static ServiceEndpoint validated(String host, Integer port) {
|
||||
host = host == null ? "" : host.trim();
|
||||
if (port == null || port < 1 || port > 65535 || host.isEmpty() || host.length() > 253
|
||||
|| host.contains("/") || host.contains("@") || host.contains("?") || host.contains("#")
|
||||
|| host.contains("%") || host.chars().anyMatch(Character::isWhitespace))
|
||||
throw new GlobalException("请填写有效的IP或主机名,以及1–65535的整数端口;地址不包含协议或路径");
|
||||
try {
|
||||
if (new URI("http", null, host, port, null, null, null).getHost() == null)
|
||||
throw new IllegalArgumentException();
|
||||
} catch (Exception error) {
|
||||
throw new GlobalException("地址仅填写IP或主机名,不包含协议、端口或路径");
|
||||
}
|
||||
return new ServiceEndpoint(host, port);
|
||||
}
|
||||
}
|
||||
@ -43,7 +43,7 @@ public class ResourceRobotRuntimeRefreshTask {
|
||||
public void refreshConnectedRobots() {
|
||||
Date cutoff = stateProperties.heartbeatCutoff(new Date());
|
||||
for (ResourceRobot robot : robotMapper.selectRuntimeSyncCandidates(
|
||||
cutoff, stateProperties.normalizedVirtualRobotIds())) {
|
||||
cutoff, stateProperties.runtimeSyncExcludedRobotIds())) {
|
||||
if (robot.getId() == null || !syncingRobotIds.add(robot.getId())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -0,0 +1,59 @@
|
||||
package com.cmvr.rotarybase;
|
||||
|
||||
import cmvr.api.MotorServiceGrpc;
|
||||
import cmvr.api.MotorServiceOuterClass.MotorRequest;
|
||||
import cmvr.api.MotorServiceOuterClass.MotorResponse;
|
||||
import cmvr.api.MotorServiceOuterClass.MotorListResponse;
|
||||
import cmvr.api.MotorServiceOuterClass.MotorHomingRequest;
|
||||
import com.cmvr.common.exception.GlobalException;
|
||||
import com.cmvr.test.enums.ActionEnum;
|
||||
import io.grpc.*;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/** Dedicated endpoint: this service does not implement the robot SystemService. */
|
||||
@Component
|
||||
public class RotaryBaseClient {
|
||||
private final RotaryBaseProperties settings;
|
||||
private ManagedChannel channel;
|
||||
private String address;
|
||||
public RotaryBaseClient(RotaryBaseProperties settings) {this.settings=settings;}
|
||||
private synchronized ManagedChannel channel() {
|
||||
if(!settings.configured())throw new GlobalException("旋转底座地址、端口或设备身份未配置完整");
|
||||
var endpoint=settings.connection();String target=endpoint.host()+":"+endpoint.port();
|
||||
if(channel==null||channel.isShutdown()||!target.equals(address)) {
|
||||
if(channel!=null)channel.shutdownNow();
|
||||
channel=ManagedChannelBuilder.forAddress(endpoint.host(),endpoint.port()).usePlaintext().disableRetry().maxInboundMessageSize(1024*1024).build();address=target;
|
||||
}
|
||||
return channel;
|
||||
}
|
||||
public boolean reachable() { return settings.configured()&&channel().getState(true)==ConnectivityState.READY; }
|
||||
public MotorResponse call(ActionEnum action,MotorRequest request,long timeoutMs) {
|
||||
var stub=MotorServiceGrpc.newBlockingStub(channel()).withDeadlineAfter(Math.min(timeoutMs,settings.getRpcTimeoutMs()),TimeUnit.MILLISECONDS);
|
||||
return switch(action) {
|
||||
case MOTOR_SET_MODE -> stub.setMode(request);
|
||||
case MOTOR_ENABLE -> stub.torqueOn(request);
|
||||
case MOTOR_DISABLE -> stub.torqueOff(request);
|
||||
case MOTOR_MOVE -> stub.commandProfilePosition(request);
|
||||
case MOTOR_VELOCITY -> stub.commandProfileVelocity(request);
|
||||
case MOTOR_QUICK_STOP -> stub.quickStop(request);
|
||||
case MOTOR_GET_INFO -> stub.getInfo(request);
|
||||
case MOTOR_GET_STATE -> stub.getState(request);
|
||||
case MOTOR_GET_MODE -> stub.getMode(request);
|
||||
case MOTOR_GET_Q -> stub.getQ(request);
|
||||
case MOTOR_GET_QD -> stub.getQd(request);
|
||||
case MOTOR_REACHED_TARGET -> stub.reachedTargetQ(request);
|
||||
default -> throw new GlobalException("旋转底座接口未开放此操作");
|
||||
};
|
||||
}
|
||||
public MotorListResponse list(MotorRequest request,long timeoutMs) {
|
||||
return MotorServiceGrpc.newBlockingStub(channel()).withDeadlineAfter(Math.min(timeoutMs,settings.getRpcTimeoutMs()),TimeUnit.MILLISECONDS).listMotors(request);
|
||||
}
|
||||
public MotorResponse home(MotorHomingRequest request,long timeoutMs) {
|
||||
// Homing can legitimately wait 300s; the normal 45s RPC cap cannot truncate it.
|
||||
long limit=(long)Math.ceil(request.getTimeoutS()*1000)+10000;
|
||||
return MotorServiceGrpc.newBlockingStub(channel()).withDeadlineAfter(Math.min(timeoutMs,limit),TimeUnit.MILLISECONDS).home(request);
|
||||
}
|
||||
@PreDestroy public synchronized void close() {if(channel!=null)channel.shutdownNow();}
|
||||
}
|
||||
@ -0,0 +1,38 @@
|
||||
package com.cmvr.rotarybase;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.*;
|
||||
|
||||
/** Intent is committed before gRPC; a lost response must never cause automatic replay. */
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
@Transactional(propagation=Propagation.REQUIRES_NEW)
|
||||
public class RotaryBaseCommandJournal {
|
||||
private final JdbcTemplate jdbc;
|
||||
public record Entry(String key,String hash,String state,String result,String error) {}
|
||||
public void checkReady() {
|
||||
try {jdbc.queryForList("SELECT command_key FROM lab_rotary_base_command WHERE 1=0");}
|
||||
catch(org.springframework.dao.DataAccessException error) {throw new com.cmvr.common.exception.GlobalException("旋转底座指令表未就绪,请执行009_rotary_base_integration.sql迁移");}
|
||||
}
|
||||
public Entry get(String key) {
|
||||
var rows=jdbc.query("SELECT command_key,request_hash,state,result_json,error_message FROM lab_rotary_base_command WHERE command_key=?",(r,n)->new Entry(r.getString(1),r.getString(2),r.getString(3),r.getString(4),r.getString(5)),key);
|
||||
return rows.isEmpty()?null:rows.get(0);
|
||||
}
|
||||
public void intent(String key,String hash,String endpoint,String operation,String request,String owner) {
|
||||
jdbc.update("INSERT INTO lab_rotary_base_command(command_key,request_hash,endpoint_key,active_endpoint,operation,request_json,owner_ref,state,created_at,updated_at) VALUES(?,?,?,?,?,?,?,'INTENT',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",key,hash,endpoint,endpoint,operation,request,owner);
|
||||
}
|
||||
public void finish(String key,String result,boolean success,String error) {
|
||||
jdbc.update("UPDATE lab_rotary_base_command SET state=?,result_json=?,error_message=?,active_endpoint=NULL,updated_at=CURRENT_TIMESTAMP WHERE command_key=? AND state='INTENT'",success?"SUCCEEDED":"FAILED",result,error,key);
|
||||
}
|
||||
public void uncertain(String key,String error) {
|
||||
jdbc.update("UPDATE lab_rotary_base_command SET state='UNKNOWN',error_message=?,updated_at=CURRENT_TIMESTAMP WHERE command_key=? AND state='INTENT'",error,key);
|
||||
}
|
||||
public void stopped(String endpoint) {
|
||||
jdbc.update("UPDATE lab_rotary_base_command SET state='ABORTED',active_endpoint=NULL,error_message='驱动去使能已确认,旧命令不再重发',updated_at=CURRENT_TIMESTAMP WHERE endpoint_key=? AND state IN ('UNKNOWN','INTENT')",endpoint);
|
||||
}
|
||||
public boolean hasVelocityCommand(String instId) {
|
||||
return jdbc.queryForObject("SELECT COUNT(*) FROM lab_rotary_base_command WHERE owner_ref=? AND operation='MOTOR_VELOCITY'",Integer.class,"workflow:"+instId)>0;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,47 @@
|
||||
package com.cmvr.rotarybase;
|
||||
|
||||
import cmvr.api.MotorServiceOuterClass.*;
|
||||
import cmvr.api.Common.CommandHeader;
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.cmvr.common.exception.GlobalException;
|
||||
import com.cmvr.test.enums.ActionEnum;
|
||||
|
||||
/** Expose measured fields only when the supplier marks their group valid. */
|
||||
public final class RotaryBaseFeedback {
|
||||
private RotaryBaseFeedback() {}
|
||||
public static JSONObject query(RotaryBaseClient client,ActionEnum action,MotorRequest request,long timeout) {
|
||||
try {return read(client,action,request,timeout);}
|
||||
catch(io.grpc.StatusRuntimeException error) {throw new GlobalException("旋转底座读取失败:gRPC "+error.getStatus().getCode()+",请核对服务版本和连接");}
|
||||
}
|
||||
private static JSONObject read(RotaryBaseClient client,ActionEnum action,MotorRequest request,long timeout) {
|
||||
if(action==ActionEnum.MOTOR_LIST) {
|
||||
var response=client.list(request,timeout);check(response.hasHeader(),response.getHeader());
|
||||
var motors=new JSONArray();response.getMotorsList().forEach(m->motors.add(info(m)));
|
||||
return JSONObject.of("operation",action.name(),"motors",motors,"mechanicalStateAvailable",false);
|
||||
}
|
||||
var response=client.call(action,request,timeout);check(response.hasHeader(),response.getHeader());
|
||||
var output=fields(response);output.put("operation",action.name());output.put("unit","RADIAN");
|
||||
if(action==ActionEnum.MOTOR_REACHED_TARGET) {output.put("reachedTarget",response.getReachedTarget());output.put("reachedTargetValid",true);}
|
||||
return output;
|
||||
}
|
||||
public static void check(boolean present,CommandHeader.Feedback header) {
|
||||
if(!present||!header.getSuccess())throw new GlobalException("旋转底座读取失败:"+(!present?"缺少响应头":header.getErrorMessage()));
|
||||
}
|
||||
public static JSONObject fields(MotorResponse response) {
|
||||
var output=JSONObject.of("driverAcknowledged",response.getDriverAcknowledged(),"detail",response.getDetail(),"mechanicalStateAvailable",false,"feedbackValid",false,"statusValid",false,"feedbackUnit","RADIAN");
|
||||
if(response.hasInfo())output.put("info",info(response.getInfo()));
|
||||
if(response.hasState()) {
|
||||
var s=response.getState();boolean feedback=s.getFeedbackValid()&&Double.isFinite(s.getPosition())&&Double.isFinite(s.getVelocity());
|
||||
var state=JSONObject.of("feedbackValid",feedback,"statusValid",s.getStatusValid());
|
||||
if(Double.isFinite(s.getSampledAtS())&&s.getSampledAtS()>0)state.put("sampledAtSeconds",s.getSampledAtS());
|
||||
if(feedback){state.put("position",s.getPosition());state.put("velocity",s.getVelocity());}
|
||||
if(s.getStatusValid()) {state.put("mode",s.getMode());state.put("statusWord",Integer.toUnsignedLong(s.getStatusWord()));state.put("errorCode",Integer.toUnsignedLong(s.getErrorCode()));state.put("enabled",s.getEnabled());state.put("fault",s.getFault());}
|
||||
output.put("state",state);output.putAll(state);output.put("mechanicalStateAvailable",feedback||s.getStatusValid());
|
||||
}
|
||||
return output;
|
||||
}
|
||||
private static JSONObject info(MotorInfo m) {
|
||||
return JSONObject.of("managerId",m.getManagerId(),"nodeId",Integer.toUnsignedLong(m.getNodeId()),"jointName",m.getJointName(),"driver",m.getDriver(),"limitQLower",m.getLimitQLb(),"limitQUpper",m.getLimitQUb(),"limitVelocity",m.getLimitQd(),"limitAcceleration",m.getLimitQdd());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,22 @@
|
||||
package com.cmvr.rotarybase;
|
||||
import com.cmvr.common.exception.GlobalException;
|
||||
import com.cmvr.test.flow.control.FlowDeviceLifecycleExtension;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
/** Speed RPC returns before motion finishes; pause must not silently resume a disabled turntable. */
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class RotaryBaseLifecycleExtension implements FlowDeviceLifecycleExtension {
|
||||
private final RotaryBaseProperties settings;
|
||||
private final RotaryBaseCommandJournal journal;
|
||||
private final Set<String> pausedVelocityTasks=ConcurrentHashMap.newKeySet();
|
||||
@Override public void beforePause(String instId,List<String> robots) {
|
||||
if(robots.contains(settings.getRobotId())&&journal.hasVelocityCommand(instId))pausedVelocityTasks.add(instId);
|
||||
}
|
||||
@Override public void beforeResume(String instId,List<String> robots) {
|
||||
if(pausedVelocityTasks.contains(instId))throw new GlobalException("旋转底座速度控制已随暂停去使能,恢复流程不会自动重新下发速度;请核对现场后结束本次执行并重新运行");
|
||||
}
|
||||
@Override public void afterStop(String instId) {pausedVelocityTasks.remove(instId);}
|
||||
}
|
||||
@ -0,0 +1,50 @@
|
||||
package com.cmvr.rotarybase;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.cmvr.common.exception.GlobalException;
|
||||
import com.cmvr.test.enums.ActionEnum;
|
||||
import java.util.Set;
|
||||
|
||||
public final class RotaryBaseParameters {
|
||||
public static final Set<ActionEnum> READS=Set.of(ActionEnum.MOTOR_LIST,ActionEnum.MOTOR_GET_INFO,ActionEnum.MOTOR_GET_STATE,ActionEnum.MOTOR_GET_MODE,ActionEnum.MOTOR_GET_Q,ActionEnum.MOTOR_GET_QD,ActionEnum.MOTOR_REACHED_TARGET);
|
||||
public static final Set<ActionEnum> ACTIONS=Set.of(ActionEnum.MOTOR_SET_MODE,ActionEnum.MOTOR_ENABLE,ActionEnum.MOTOR_DISABLE,ActionEnum.MOTOR_MOVE,ActionEnum.MOTOR_VELOCITY,ActionEnum.MOTOR_LIST,ActionEnum.MOTOR_GET_INFO,ActionEnum.MOTOR_GET_STATE,ActionEnum.MOTOR_GET_MODE,ActionEnum.MOTOR_GET_Q,ActionEnum.MOTOR_GET_QD,ActionEnum.MOTOR_REACHED_TARGET,ActionEnum.MOTOR_QUICK_STOP,ActionEnum.MOTOR_HOMING);
|
||||
public static boolean recovery(ActionEnum action) {return READS.contains(action)||action==ActionEnum.MOTOR_DISABLE||action==ActionEnum.MOTOR_QUICK_STOP;}
|
||||
private RotaryBaseParameters() {}
|
||||
public static void validate(ActionEnum action,JSONObject input) {
|
||||
if(!ACTIONS.contains(action))throw new GlobalException("此旧电机动作与当前协议不一致,请重新选择旋转底座组件");
|
||||
if(action==ActionEnum.MOTOR_HOMING) {
|
||||
if(number(input,"method")!=4)throw new GlobalException("机械回零只支持method=4");
|
||||
double fast=number(input,"fastSpeed"),slow=number(input,"slowSpeed"),acceleration=number(input,"acceleration"),seconds=number(input,"timeoutSeconds"),offset=number(input,"offset");
|
||||
if(fast<=0||fast>1||slow<=0||slow>fast)throw new GlobalException("回零速度必须满足0 < slowSpeed ≤ fastSpeed ≤ 1 rad/s");
|
||||
if(acceleration<=0||acceleration>1)throw new GlobalException("回零加速度必须大于0且不超过1 rad/s²");
|
||||
if(seconds<1||seconds>300)throw new GlobalException("回零服务端等待时间必须为1至300秒");
|
||||
if(Math.abs(offset)>2*Math.PI)throw new GlobalException("回零偏移必须在±2π rad内");
|
||||
if(number(input,"timeoutMs")<=seconds*1000)throw new GlobalException("客户端超时必须大于回零服务端等待时间");
|
||||
}
|
||||
if(action==ActionEnum.MOTOR_SET_MODE) {
|
||||
double mode=number(input,"mode");
|
||||
if(mode!=1&&mode!=3)throw new GlobalException("旋转底座模式只支持1(轮廓位置)或3(轮廓速度)");
|
||||
}
|
||||
if(action==ActionEnum.MOTOR_MOVE||action==ActionEnum.MOTOR_VELOCITY) {
|
||||
double factor=factor(input);
|
||||
if(action==ActionEnum.MOTOR_MOVE&&Math.abs(number(input,"targetPosition")*factor)>2*Math.PI+1e-12)
|
||||
throw new GlobalException("旋转底座绝对位置须在±360°(±2π rad)内");
|
||||
double velocity=number(input,"velocity")*factor,acceleration=number(input,"acceleration")*factor;
|
||||
if(Math.abs(velocity)>1+1e-12||(action==ActionEnum.MOTOR_MOVE&&velocity<=0))
|
||||
throw new GlobalException("位置速度须大于0,速度控制允许正负或零;绝对值不得超过1 rad/s(约57.2958°/s)");
|
||||
if(acceleration<=0||acceleration>1+1e-12)
|
||||
throw new GlobalException("加速度须大于0且不超过1 rad/s²(约57.2958°/s²)");
|
||||
}
|
||||
}
|
||||
public static double factor(JSONObject input) {
|
||||
return switch(input.getString("unit")==null?"":input.getString("unit")) {
|
||||
case "DEGREE" -> Math.PI/180;
|
||||
case "RADIAN" -> 1;
|
||||
default -> throw new GlobalException("旋转底座单位仅支持DEGREE(度)和RADIAN(弧度)");
|
||||
};
|
||||
}
|
||||
private static double number(JSONObject input,String key) {
|
||||
if(!(input.get(key) instanceof Number value)||!Double.isFinite(value.doubleValue()))throw new GlobalException(key+"必须显式填写有效数值");
|
||||
return value.doubleValue();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,32 @@
|
||||
package com.cmvr.rotarybase;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix="cmvr.rotary-base")
|
||||
public class RotaryBaseProperties {
|
||||
private volatile com.cmvr.resource.service.ServiceEndpoint connectionOverride;
|
||||
public com.cmvr.resource.service.ServiceEndpoint connection() {var current=connectionOverride;return current==null?new com.cmvr.resource.service.ServiceEndpoint(host,port):current;}
|
||||
public String getHost() {return connection().host();}
|
||||
public Integer getPort() {return connection().port();}
|
||||
private String host="192.168.0.203";
|
||||
private Integer port=50052;
|
||||
private String robotId="am-freescan-rotary-base-station-001";
|
||||
private String deviceId="aima_motor";
|
||||
private String managerId="aima_motor";
|
||||
private int nodeId=1;
|
||||
private String jointName="motor_1";
|
||||
private int rpcTimeoutMs=45000;
|
||||
public boolean configured() {
|
||||
var address=connection();
|
||||
return address.host()!=null&&!address.host().isBlank()&&!address.host().contains("://")&&address.port()!=null&&address.port()>0&&address.port()<=65535
|
||||
&&robotId!=null&&!robotId.isBlank()&&deviceId!=null&&!deviceId.isBlank()
|
||||
&&managerId!=null&&!managerId.isBlank()&&nodeId>0&&nodeId<=127
|
||||
&&jointName!=null&&!jointName.isBlank()&&rpcTimeoutMs>=1000&&rpcTimeoutMs<=120000;
|
||||
}
|
||||
public boolean handles(String robot) { return configured()&&robotId.equals(robot); }
|
||||
public String endpoint() { var address=connection();return address.host()+":"+address.port()+"/"+managerId+"/"+nodeId+"/"+jointName; }
|
||||
}
|
||||
@ -0,0 +1,53 @@
|
||||
package com.cmvr.rotarybase;
|
||||
import com.cmvr.resource.domain.*;
|
||||
import com.cmvr.resource.mapper.*;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.util.*;
|
||||
/** Refresh by read-only RPC; never enable or move the drive while discovering it. */
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class RotaryBaseResourceSynchronizer {
|
||||
private final RotaryBaseProperties settings;
|
||||
private final RotaryBaseClient client;
|
||||
private final ResourceRobotMapper robots;
|
||||
private final ResourceDeviceMapper devices;
|
||||
@Scheduled(initialDelayString="${cmvr.rotary-base.resource-initial-delay-ms:4000}",fixedDelayString="${cmvr.rotary-base.resource-refresh-ms:5000}")
|
||||
public synchronized void refresh() {
|
||||
if(!settings.configured())return;
|
||||
var robot=robots.selectByRobotIdentity(settings.getRobotId());
|
||||
if(robot==null||"1".equals(robot.getArchivedStatus())||robot.getQuicSessionId()!=null&&!robot.getQuicSessionId().isBlank())return;
|
||||
var matches=devices.selectByIdentity(settings.getRobotId(),settings.getDeviceId());
|
||||
if(matches.size()>1||!matches.isEmpty()&&!Integer.valueOf(10).equals(matches.get(0).getDeviceKind()))return;
|
||||
boolean reachable=client.reachable();Date now=new Date();
|
||||
com.alibaba.fastjson2.JSONObject measured=null;
|
||||
if(reachable)try {
|
||||
var request=cmvr.api.MotorServiceOuterClass.MotorRequest.newBuilder().setHeader(com.cmvr.edge.client.utils.EdgeCommonUtil.buildRequest(settings.getManagerId()))
|
||||
.setNodeId(settings.getNodeId()).setJointName(settings.getJointName()).build();
|
||||
measured=RotaryBaseFeedback.query(client,com.cmvr.test.enums.ActionEnum.MOTOR_GET_STATE,request,Math.min(2000,settings.getRpcTimeoutMs()));
|
||||
}catch(RuntimeException unavailable){/* Keep transport reachability distinct from valid mechanical feedback. */}
|
||||
var update=new ResourceRobot();update.setId(robot.getId());update.setConnectStatus(reachable?"1":"0");update.setStatus(reachable?"2":"1");
|
||||
update.setIpAddress(settings.getHost());update.setPort(settings.getPort().longValue());update.setLastHeartbeatTime(now);update.setUpdateTime(now);
|
||||
robots.updateExternalServiceState(update);
|
||||
if(matches.isEmpty()&&!reachable)return;
|
||||
var device=matches.isEmpty()?new ResourceDevice():matches.get(0);
|
||||
if(matches.isEmpty()) {
|
||||
device.setId(UUID.randomUUID().toString().replace("-",""));device.setRobotId(settings.getRobotId());device.setDeviceId(settings.getDeviceId());
|
||||
device.setDeviceName("旋转底座");device.setDeviceKind(10);device.setTypeName("旋转底座 gRPC(机械状态未知)");device.setEnabled("1");device.setCreateBy("rotary-base");device.setCreateTime(now);
|
||||
}
|
||||
boolean reportedFault=("1".equals(device.getHasError())||Integer.valueOf(3).equals(device.getHealthStatus()))
|
||||
&&(device.getErrorMessage()==null||!device.getErrorMessage().startsWith("旋转底座反馈:"));
|
||||
device.setOnlineStatus(reachable?"1":"0");
|
||||
if(!reportedFault) {
|
||||
boolean valid=measured!=null&&measured.getBooleanValue("statusValid");
|
||||
boolean fault=valid&&(measured.getBooleanValue("fault")||measured.getLongValue("errorCode")!=0);
|
||||
device.setHealthStatus(fault?3:valid?1:0);device.setHasError(fault?"1":"0");
|
||||
device.setErrorMessage(fault?"旋转底座反馈:驱动故障,错误码 "+measured.getLongValue("errorCode"):valid?"":reachable?"控制服务已连接,未取得有效机械状态":"控制服务未连接,机械状态未知");
|
||||
reportedFault=fault;
|
||||
}
|
||||
device.setManagerState("0".equals(device.getEnabled())?1:reportedFault?7:0);device.setStatusUpdatedTime(now);if(reachable)device.setLastSeenTime(now);
|
||||
device.setOfflineTime(reachable?null:now);device.setUpdateBy("rotary-base");device.setUpdateTime(now);
|
||||
if(matches.isEmpty())devices.insert(device);else devices.updateRuntimeState(device);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
package com.cmvr.rotarybase;
|
||||
import com.cmvr.edge.client.service.RobotStopExtension;
|
||||
import com.cmvr.resource.mapper.ResourceDeviceMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class RotaryBaseStopExtension implements RobotStopExtension {
|
||||
private final RotaryBaseProperties settings;
|
||||
private final RotaryBaseWorkflowAdapter adapter;
|
||||
private final ResourceDeviceMapper devices;
|
||||
@Override public boolean handles(String robotId) {return settings.handles(robotId);}
|
||||
@Override public boolean stop(String robotId) {
|
||||
adapter.disableForStop();
|
||||
return devices.selectByRobotId(robotId,null,false).stream().filter(d->"1".equals(d.getEnabled()))
|
||||
.allMatch(d->Integer.valueOf(10).equals(d.getDeviceKind())&&settings.getDeviceId().equals(d.getDeviceId()));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,100 @@
|
||||
package com.cmvr.rotarybase;
|
||||
|
||||
import cmvr.api.MotorServiceOuterClass.*;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.cmvr.common.exception.GlobalException;
|
||||
import com.cmvr.edge.client.utils.EdgeCommonUtil;
|
||||
import com.cmvr.test.enums.ActionEnum;
|
||||
import com.cmvr.test.flow.runtime.message.*;
|
||||
import com.cmvr.test.flow.runtime.operator.edge.*;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class RotaryBaseWorkflowAdapter implements WorkcellDeviceAdapter {
|
||||
private final RotaryBaseProperties settings;
|
||||
private final RotaryBaseClient client;
|
||||
private final RotaryBaseCommandJournal journal;
|
||||
@Override public boolean supports(ActionEnum action) {return action!=null&&RotaryBaseParameters.ACTIONS.contains(action);}
|
||||
@Override public void validateConfiguration(String robot,String device) {
|
||||
if(!settings.configured())throw new GlobalException("请先配置旋转底座地址、端口和设备身份");
|
||||
if(!Objects.equals(robot,settings.getRobotId())||!Objects.equals(device,settings.getDeviceId()))throw new GlobalException("所选旋转底座与配置的永久工位、设备身份不匹配");
|
||||
journal.checkReady();
|
||||
}
|
||||
@Override public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) {
|
||||
var input=message.getInputParams();var action=message.getAction();
|
||||
WorkcellNodeContract.validate(action,input);validateConfiguration(message.getRobotId(),input.getString("deviceId"));
|
||||
if(RotaryBaseParameters.READS.contains(action)) {
|
||||
var output=RotaryBaseFeedback.query(client,action,request(action,input),input.getLongValue("timeoutMs"));
|
||||
output.put("responseJson",output.toJSONString());return TaskNodeExecuteResult.success(output);
|
||||
}
|
||||
if(message.getInstId()==null||message.getInstId().isBlank())throw new GlobalException("旋转底座控制必须通过已占用设备的工作流执行");
|
||||
String key=hash(JSONObject.toJSONString(Arrays.asList(message.getInstId(),message.getItemId(),message.getItemOrder(),message.getItemOccurrence(),message.getNodeId(),message.getIterations(),message.getSubFlowExecutionId())));
|
||||
var request=request(action,input);
|
||||
var homing=action==ActionEnum.MOTOR_HOMING?homingRequest(input):null;
|
||||
String body=JSONObject.toJSONString(List.of(action.name(),settings.endpoint(),homing!=null?homing.toBuilder().clearHeader().build().toString():request.toBuilder().clearHeader().build().toString()));
|
||||
String fingerprint=hash(body);var previous=journal.get(key);
|
||||
if(previous!=null)return replay(previous,fingerprint);
|
||||
try {journal.intent(key,fingerprint,settings.endpoint(),action.name(),body,"workflow:"+message.getInstId());}
|
||||
catch(DuplicateKeyException busy) {
|
||||
previous=journal.get(key);if(previous!=null)return replay(previous,fingerprint);
|
||||
throw new GlobalException("旋转底座存在执行中或未确认的指令,请先停止并确认释放");
|
||||
}
|
||||
MotorResponse response;
|
||||
try {response=homing!=null?client.home(homing,input.getLongValue("timeoutMs")):client.call(action,request,input.getLongValue("timeoutMs"));}
|
||||
catch(StatusRuntimeException error) {
|
||||
String detail="旋转底座gRPC "+error.getStatus().getCode()+":响应未确认,请勿重复发送运动指令";
|
||||
journal.uncertain(key,detail);throw new GlobalException(detail);
|
||||
}
|
||||
catch(RuntimeException error) {journal.uncertain(key,"旋转底座调用未确认");throw error;}
|
||||
if(!response.hasHeader()||!response.getHeader().getSuccess()||!response.getDriverAcknowledged()
|
||||
||(action==ActionEnum.MOTOR_MOVE||action==ActionEnum.MOTOR_HOMING)&&!response.getReachedTarget()) {
|
||||
String error=!response.hasHeader()?"缺少响应头":!response.getHeader().getSuccess()?response.getHeader().getErrorMessage()
|
||||
:!response.getDriverAcknowledged()?"缺少驱动确认":"位置或回零未确认到位";
|
||||
journal.finish(key,null,false,error.substring(0,Math.min(error.length(),1900)));
|
||||
throw new GlobalException("旋转底座执行失败:"+error);
|
||||
}
|
||||
var output=RotaryBaseFeedback.fields(response);output.put("operation",action.name());output.put("commandKey",key);
|
||||
if(action==ActionEnum.MOTOR_MOVE) {output.put("reachedTarget",true);output.put("targetPosition",input.get("targetPosition"));output.put("unit",input.getString("unit"));}
|
||||
if(action==ActionEnum.MOTOR_VELOCITY) {output.put("targetVelocity",input.get("velocity"));output.put("unit",input.getString("unit"));output.put("motionCompleted",false);}
|
||||
if(action==ActionEnum.MOTOR_DISABLE)output.put("driveDisabledConfirmed",true);
|
||||
if(action==ActionEnum.MOTOR_HOMING) {output.put("reachedTarget",true);output.put("homingCompleted",true);}
|
||||
if(action==ActionEnum.MOTOR_QUICK_STOP) {output.put("quickStopAcknowledged",true);output.put("standstillConfirmed",false);}
|
||||
var requested=new JSONObject();
|
||||
for(String field:List.of("mode","unit","targetPosition","velocity","acceleration","method","fastSpeed","slowSpeed","timeoutSeconds","offset"))if(input.containsKey(field))requested.put(field,input.get(field));
|
||||
output.put("request",requested);
|
||||
output.put("responseJson",output.toJSONString());journal.finish(key,output.toJSONString(),true,null);
|
||||
return TaskNodeExecuteResult.success(output);
|
||||
}
|
||||
MotorHomingRequest homingRequest(JSONObject input) {
|
||||
return MotorHomingRequest.newBuilder().setHeader(EdgeCommonUtil.buildRequest(settings.getManagerId())).setNodeId(settings.getNodeId()).setJointName(settings.getJointName())
|
||||
.setMethod(input.getIntValue("method")).setFastSpeed(input.getDoubleValue("fastSpeed")).setSlowSpeed(input.getDoubleValue("slowSpeed"))
|
||||
.setAcceleration(input.getDoubleValue("acceleration")).setTimeoutS(input.getDoubleValue("timeoutSeconds")).setOffset(input.getDoubleValue("offset")).build();
|
||||
}
|
||||
MotorRequest request(ActionEnum action,JSONObject input) {
|
||||
var request=MotorRequest.newBuilder().setHeader(EdgeCommonUtil.buildRequest(settings.getManagerId())).setNodeId(settings.getNodeId()).setJointName(settings.getJointName());
|
||||
if(action==ActionEnum.MOTOR_SET_MODE)request.setMode(input.getIntValue("mode"));
|
||||
if(action==ActionEnum.MOTOR_MOVE||action==ActionEnum.MOTOR_VELOCITY) {
|
||||
double factor=RotaryBaseParameters.factor(input);
|
||||
request.setQd(input.getDoubleValue("velocity")*factor).setQdd(input.getDoubleValue("acceleration")*factor);
|
||||
if(action==ActionEnum.MOTOR_MOVE)request.setQ(input.getDoubleValue("targetPosition")*factor);
|
||||
}
|
||||
return request.build();
|
||||
}
|
||||
public void disableForStop() {
|
||||
// A velocity-zero RPC auto-enables even an already disabled drive; use torqueOff directly.
|
||||
var response=client.call(ActionEnum.MOTOR_DISABLE,request(ActionEnum.MOTOR_DISABLE,new JSONObject()),settings.getRpcTimeoutMs());
|
||||
if(!response.hasHeader()||!response.getHeader().getSuccess()||!response.getDriverAcknowledged())throw new GlobalException("旋转底座去使能未获得驱动确认,保留占用");
|
||||
journal.stopped(settings.endpoint());
|
||||
}
|
||||
private TaskNodeExecuteResult replay(RotaryBaseCommandJournal.Entry entry,String fingerprint) {
|
||||
if(!entry.hash().equals(fingerprint))throw new GlobalException("旋转底座相同执行标识的参数已变化,禁止重复下发");
|
||||
if("SUCCEEDED".equals(entry.state()))return TaskNodeExecuteResult.success(JSONObject.parseObject(entry.result()));
|
||||
throw new GlobalException("旋转底座原指令状态为"+entry.state()+",禁止自动重发;请核对现场后停止并释放");
|
||||
}
|
||||
private static String hash(String source) {return cn.hutool.crypto.digest.DigestUtil.sha256Hex(source);}
|
||||
}
|
||||
@ -20,7 +20,8 @@ public class ScannerAccessService {
|
||||
if(!settings.configured())throw new ScannerException("not_configured","请先配置扫描服务的地址、端口和访问密钥",503);
|
||||
if(settings.getRobotId().isBlank()||settings.getDeviceId().isBlank())throw new ScannerException("device_not_bound","请先配置扫描仪的永久robotId和deviceId,并登记运行设备",409);
|
||||
ObjectNode request=ScannerRequestValidator.parse(body);ScannerRequestValidator.validate(op,request);ScannerService.key(key);
|
||||
deviceValidator.validate(settings.getRobotId(),settings.getDeviceId(),14);
|
||||
if(op.usableWithoutDevice())deviceValidator.validateForAction(settings.getRobotId(),settings.getDeviceId(),14,com.cmvr.test.enums.ActionEnum.fromAction(op.action));
|
||||
else deviceValidator.validate(settings.getRobotId(),settings.getDeviceId(),14);
|
||||
List<AutoCloseable> gates=new ArrayList<>();
|
||||
try {
|
||||
if(op!=ScannerOperation.SCAN_STOP)for(var guard:guards.orderedStream().toList())gates.add(guard.manual(settings.getRobotId()));
|
||||
|
||||
@ -0,0 +1,58 @@
|
||||
package com.cmvr.scanner;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.cmvr.resource.domain.ResourceRobot;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.time.Instant;
|
||||
|
||||
/** Read-only SDK cache polling, independent of workflow occupation and QUIC. */
|
||||
@Component @RequiredArgsConstructor
|
||||
public class ScannerBatteryMonitor {
|
||||
private final ScannerProperties settings;
|
||||
private final ScannerHttpClient client;
|
||||
private record Snapshot(JsonNode data,long received,String endpoint,String robotId){}
|
||||
private volatile Snapshot snapshot;
|
||||
@Scheduled(initialDelayString="${cmvr.scanner.battery-initial-delay-ms:5000}",fixedDelayString="${cmvr.scanner.battery-refresh-ms:5000}")
|
||||
public synchronized void refresh(){
|
||||
if(!settings.configured()){snapshot=null;return;}
|
||||
String endpoint=client.endpointKey(),robot=settings.getRobotId();
|
||||
try{var data=client.json(ScannerOperation.BATTERY,null,null,3000);snapshot=new Snapshot(data.deepCopy(),System.currentTimeMillis(),endpoint,robot);}
|
||||
catch(RuntimeException unavailable){snapshot=null;}
|
||||
}
|
||||
public ResourceRobot attach(ResourceRobot robot){
|
||||
if(robot==null||!settings.configured()||!java.util.Objects.equals(settings.getRobotId(),robot.getRobotId()))return robot;
|
||||
Snapshot s=snapshot;long now=System.currentTimeMillis();
|
||||
JsonNode data=s!=null&&now-s.received()<10000&&s.endpoint().equals(client.endpointKey())&&s.robotId().equals(robot.getRobotId())?s.data():null;
|
||||
ObjectNode result=normalize(data,Instant.ofEpochMilli(now));
|
||||
robot.setScannerBattery(result);robot.setBatteryLevel(result.path("scanner").path("percent").isInt()?result.path("scanner").path("percent").intValue():null);
|
||||
return robot;
|
||||
}
|
||||
public static ObjectNode normalize(JsonNode data,Instant now){
|
||||
ObjectNode result=ScannerRequestValidator.JSON.createObjectNode();result.put("freshnessLimitMs",30000);
|
||||
result.set("scanner",reading(data==null?null:data.path("scanner"),now));
|
||||
var channels=result.putObject("tracker").putArray("channels");
|
||||
if(data!=null&&data.path("tracker").path("channels").isArray())for(var channel:data.path("tracker").path("channels")){
|
||||
if(channels.size()>=16)break;
|
||||
var row=reading(channel,now);var index=channel.get("index");
|
||||
if(index!=null&&index.isTextual()&&index.asText().matches("[0-9]{1,20}"))row.put("index",index.asText());else row.putNull("index");
|
||||
channels.add(row);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
private static ObjectNode reading(JsonNode value,Instant now){
|
||||
var row=ScannerRequestValidator.JSON.createObjectNode();row.putNull("percent");row.put("available",false);row.put("fresh",false);row.putNull("updatedUtc");
|
||||
if(value==null)return row;
|
||||
row.set("rawValue",value.path("rawValue"));
|
||||
if(value.path("updatedUtc").isTextual())row.put("updatedUtc",value.path("updatedUtc").asText());
|
||||
try{
|
||||
Instant updated=Instant.parse(value.path("updatedUtc").asText());long age=java.time.Duration.between(updated,now).toMillis();
|
||||
boolean fresh=value.path("fresh").isBoolean()&&value.path("fresh").asBoolean()&&age>=-5000&&age<=30000;
|
||||
row.put("fresh",fresh);var percent=value.path("percent");
|
||||
if(fresh&&value.path("available").isBoolean()&&value.path("available").asBoolean()&&percent.isIntegralNumber()&&percent.canConvertToInt()&&percent.intValue()>=0&&percent.intValue()<=100){row.put("percent",percent.intValue());row.put("available",true);}
|
||||
}catch(java.time.DateTimeException ignored){}
|
||||
return row;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,13 @@
|
||||
package com.cmvr.scanner;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
/** Formal task binding is trusted server input, independent of a legacy node's fixed URL. */
|
||||
public final class ScannerFixtureFrameworkBinding {
|
||||
public static final String PARAM="fixtureFrameworkUrls";
|
||||
private ScannerFixtureFrameworkBinding(){}
|
||||
public static JSONObject apply(JSONObject input,JSONObject runParams){
|
||||
if(runParams==null||!runParams.containsKey(PARAM))return input;
|
||||
ScannerFrameworkReferences.sources(runParams.get(PARAM));
|
||||
var result=new JSONObject(input);result.put("frameworkUrls",runParams.get(PARAM));result.put("requestJson","{\"confirm\":true}");
|
||||
result.remove("requestFields");result.put("fixtureFrameworkVersion",runParams.get("fixtureFrameworkVersion"));return result;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,50 @@
|
||||
package com.cmvr.scanner;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.nio.file.*;
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import com.alibaba.fastjson2.*;
|
||||
|
||||
@Component
|
||||
public class ScannerFixtureFrameworkStore {
|
||||
@Value("${lab.artifact.nas-root:./.local/artifacts}") private String root;
|
||||
private Path path(String id) {
|
||||
if(id==null||!id.matches("[a-fA-F0-9]{32}"))throw new ScannerException("invalid_file","框架文件编号无效",400);
|
||||
id=id.toLowerCase(java.util.Locale.ROOT);
|
||||
return Path.of(root).toAbsolutePath().normalize().resolve("fixture-framework").resolve(id);
|
||||
}
|
||||
public JSONObject save(String name,byte[] bytes) {
|
||||
if(!ScannerFrameworkReferences.frameworkName(name)||bytes==null||bytes.length==0||bytes.length>ScannerFrameworkService.MAX_BYTES)throw new ScannerException("invalid_file","框架文件必须为非空P3/TXT/ASC且不超过100MiB",400);
|
||||
name=ScannerFrameworkService.decodeName(ScannerFrameworkReferences.encode(name));
|
||||
String id=UUID.randomUUID().toString().replace("-","");Path p=path(id);
|
||||
var m=JSONObject.of("fileId",id,"name",name,"bytes",bytes.length,"sha256",cn.hutool.crypto.digest.DigestUtil.sha256Hex(bytes),"downloadUrl","/admin-api/cmvr/scanner/files/"+id);
|
||||
try{Files.createDirectories(p.getParent());Files.write(p,bytes,StandardOpenOption.CREATE_NEW);Files.writeString(p.resolveSibling(id+".json"),m.toJSONString(),StandardOpenOption.CREATE_NEW);return m;}
|
||||
catch(IOException e){
|
||||
try{Files.deleteIfExists(p);Files.deleteIfExists(p.resolveSibling(id+".json"));}catch(IOException ignored){}
|
||||
throw new ScannerException("framework_archive_failed","框架点保存失败,原版本保留",503);
|
||||
}
|
||||
}
|
||||
public ScannerHttpClient.Binary open(String id) {
|
||||
Path p=path(id),meta=p.resolveSibling(p.getFileName()+".json");
|
||||
if(!Files.exists(p)&&!Files.exists(meta))return null;
|
||||
try{
|
||||
if(Files.size(p)==0||Files.size(p)>ScannerFrameworkService.MAX_BYTES||Files.size(meta)>8192)throw new IOException("size");
|
||||
var m=JSONObject.parseObject(Files.readString(meta));byte[] bytes=Files.readAllBytes(p);
|
||||
if(!p.getFileName().toString().equals(m.getString("fileId")))throw new IOException("id");
|
||||
ScannerFrameworkService.decodeName(ScannerFrameworkReferences.encode(m.getString("name")));
|
||||
if(bytes.length!=m.getIntValue("bytes")||!cn.hutool.crypto.digest.DigestUtil.sha256Hex(bytes).equals(m.getString("sha256")))throw new IOException("checksum");
|
||||
return new ScannerHttpClient.Binary(new ByteArrayInputStream(bytes),Map.of("content-length",List.of(""+bytes.length),"content-disposition",List.of("attachment; filename*=UTF-8''"+ScannerFrameworkReferences.encode(m.getString("name")))));
|
||||
}catch(IOException|RuntimeException e){throw new ScannerException("framework_archive_unavailable","框架点文件缺失或损坏,请重新录入或导入",503);}
|
||||
}
|
||||
public JSONObject metadata(String id){
|
||||
try(var data=open(id)){
|
||||
if(data==null)throw new IOException();
|
||||
Path p=path(id);var m=JSONObject.parseObject(Files.readString(p.resolveSibling(p.getFileName()+".json")));
|
||||
// Return only canonical local references, never caller-supplied URLs or names.
|
||||
return JSONObject.of("fileId",p.getFileName().toString(),"name",m.getString("name"),"bytes",m.getIntValue("bytes"),"sha256",m.getString("sha256"),"downloadUrl","/admin-api/cmvr/scanner/files/"+p.getFileName());
|
||||
}catch(IOException e){throw new ScannerException("framework_archive_unavailable","框架点文件不可用,请重新录入或导入",503);}
|
||||
}
|
||||
public void verify(Object urls){for(var s:ScannerFrameworkReferences.sources(urls))metadata(s.fileId());}
|
||||
}
|
||||
@ -0,0 +1,125 @@
|
||||
package com.cmvr.scanner;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ContentDisposition;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ScannerFrameworkReferenceService {
|
||||
private final ScannerProperties settings;
|
||||
private final ScannerHttpClient client;
|
||||
private final ScannerFrameworkService uploads;
|
||||
private final ScannerFrameworkTransferJournal journal;
|
||||
public record Prepared(ObjectNode body,JsonNode context,JsonNode files) {}
|
||||
|
||||
public Prepared prepare(String commandKey,String instId,JSONObject input,long timeoutMs) {
|
||||
ScannerService.key(commandKey);client.requireConfigured();ScannerFrameworkReferences.validate(input,true);
|
||||
var sources=ScannerFrameworkReferences.sources(input.get("frameworkUrls"));
|
||||
sources.forEach(source->ScannerFrameworkReferences.validateOrigin(source,settings));
|
||||
String endpoint=client.endpointKey(),planKey=ScannerService.hash("framework-plan:"+commandKey);
|
||||
String hash=ScannerService.hash(endpoint+":"+ScannerRequestValidator.JSON.valueToTree(sources));
|
||||
var previous=journal.get(planKey);
|
||||
if(previous!=null)return prepared(known(previous,hash));
|
||||
long deadline=System.nanoTime()+TimeUnit.MILLISECONDS.toNanos(timeoutMs);
|
||||
JsonNode status=readyStatus(deadline);
|
||||
ObjectNode context=ScannerRequestValidator.JSON.createObjectNode().put("endpoint",endpoint)
|
||||
.put("sessionId",status.path("sessionId").asText()).put("projectId",status.path("projectId").asText());
|
||||
begin(planKey,"PLAN",endpoint,hash,"workflow:"+instId);
|
||||
try {
|
||||
var files=ScannerRequestValidator.JSON.createArrayNode();var ids=ScannerRequestValidator.JSON.createArrayNode();
|
||||
for(var source:sources) {
|
||||
byte[] bytes;String name;
|
||||
try(var file=client.frameworkFile(source.fileId(),budget(deadline))) {
|
||||
long declared=headerLength(file.headers());
|
||||
if(declared>ScannerFrameworkService.MAX_BYTES)throw bad("框架下载文件超过100MiB");
|
||||
name=headerName(file.headers(),source.name());
|
||||
bytes=file.stream().readNBytes(ScannerFrameworkService.MAX_BYTES+1);
|
||||
if(bytes.length==0||bytes.length>ScannerFrameworkService.MAX_BYTES||declared>=0&&declared!=bytes.length
|
||||
||source.bytes()!=null&&source.bytes()!=bytes.length)throw bad("框架下载文件为空、超限或与导出回执长度不符");
|
||||
}catch(ScannerException error) {
|
||||
if(error.remoteStatus==404)throw new ScannerException("framework_source_unavailable",
|
||||
"框架源文件不存在或URL已失效,请重新导出P3并引用最新结果(HTTP404)",404);
|
||||
throw error;
|
||||
}
|
||||
String contentHash=cn.hutool.crypto.digest.DigestUtil.sha256Hex(bytes);
|
||||
String fileHash=ScannerService.hash(endpoint+":"+source.fileId()+":"+name+":"+contentHash);
|
||||
String fileKey=ScannerService.hash("framework-file:"+fileHash);
|
||||
var cached=journal.get(fileKey);JsonNode receipt;
|
||||
boolean reused=cached!=null;
|
||||
if(reused)receipt=known(cached,fileHash);
|
||||
else {
|
||||
begin(fileKey,"FILE",endpoint,fileHash,"workflow:"+instId);
|
||||
try {
|
||||
receipt=uploads.upload(ScannerFrameworkReferences.encode(name),"application/octet-stream",bytes.length,new ByteArrayInputStream(bytes),budget(deadline));
|
||||
journal.ready(fileKey,receipt.toString());
|
||||
}catch(RuntimeException error){journal.uncertain(fileKey,error.getMessage());throw error;}
|
||||
}
|
||||
ids.add(receipt.path("fileId").asText());
|
||||
files.addObject().put("sourceUrl",source.url()).put("sourceFileId",source.fileId()).put("fileId",receipt.path("fileId").asText())
|
||||
.put("name",name).put("bytes",bytes.length).put("sha256",contentHash).put("reused",reused);
|
||||
}
|
||||
ObjectNode body=ScannerRequestValidator.JSON.createObjectNode().put("confirm",true);body.set("fileIds",ids);
|
||||
ScannerRequestValidator.validate(ScannerOperation.FRAMEWORK_IMPORT,body);
|
||||
ObjectNode result=ScannerRequestValidator.JSON.createObjectNode();result.set("body",body);result.set("context",context);result.set("files",files);
|
||||
journal.ready(planKey,result.toString());return prepared(result);
|
||||
}catch(IOException error){journal.uncertain(planKey,"读取框架下载失败;已登记文件不会自动重传");throw bad("读取框架下载失败,请核对原URL,系统不会盲目重新登记");}
|
||||
catch(RuntimeException error){journal.uncertain(planKey,error.getMessage());throw error;}
|
||||
}
|
||||
private JsonNode readyStatus(long deadline) {
|
||||
while(true) {
|
||||
JsonNode status=client.json(ScannerOperation.STATUS,null,null,budget(deadline));
|
||||
if(status.path("busy").asBoolean()) {pause(deadline);continue;}
|
||||
if(!status.path("projectReady").asBoolean()||!status.path("deviceOnline").asBoolean()
|
||||
||status.path("scanning").asBoolean()||status.path("stateUncertain").asBoolean()||status.path("restartRequired").asBoolean()
|
||||
||status.path("calibrationActive").asBoolean()||!"none".equals(status.path("meshState").asText())
|
||||
||!"trak".equals(status.path("scanMode").asText())||!"mesh".equals(status.path("scanType").asText())||!"scanner".equals(status.path("scanDevice").asText())
|
||||
||status.path("sessionId").asText().isBlank()||status.path("projectId").asText().isBlank())
|
||||
throw new ScannerException("framework_import_not_ready","导入框架前请停止采集、创建扫描工程,并选择trak / mesh / scanner;当前工程不能处于网格或标定状态",409);
|
||||
return status;
|
||||
}
|
||||
}
|
||||
private void begin(String key,String kind,String endpoint,String hash,String owner) {
|
||||
try {journal.intent(key,kind,endpoint,hash,owner);}
|
||||
catch(org.springframework.dao.DuplicateKeyException race){throw new ScannerException("framework_transfer_busy","框架正在登记或结果待确认,请勿重复执行",409);}
|
||||
}
|
||||
private JsonNode known(ScannerFrameworkTransferJournal.Entry entry,String hash) {
|
||||
if(!hash.equals(entry.hash()))throw new ScannerException("framework_reference_changed","同一执行的框架URL已改变,禁止覆盖原登记结果",409);
|
||||
if(!"READY".equals(entry.state()))throw new ScannerException("framework_transfer_uncertain","框架登记结果未确认,保留记录并禁止自动重新登记",409);
|
||||
try{return ScannerRequestValidator.JSON.readTree(entry.result());}catch(Exception error){throw bad("框架登记记录无效");}
|
||||
}
|
||||
private Prepared prepared(JsonNode value) {return new Prepared((ObjectNode)value.path("body"),value.path("context"),value.path("files"));}
|
||||
private long budget(long deadline) {
|
||||
long ms=TimeUnit.NANOSECONDS.toMillis(deadline-System.nanoTime());
|
||||
if(ms<1)throw new ScannerException("framework_transfer_timeout","框架自动读取和登记超过节点等待时限,已登记结果保留,请勿盲目重传",504);
|
||||
return Math.min(ms,settings.getRequestTimeoutMs());
|
||||
}
|
||||
private void pause(long deadline) {
|
||||
try{Thread.sleep(Math.min(budget(deadline),Math.max(10,settings.getPollIntervalMs())));}
|
||||
catch(InterruptedException error){Thread.currentThread().interrupt();throw new ScannerException("interrupted","框架登记等待已中断",504);}
|
||||
}
|
||||
private static String headerName(Map<String,List<String>> headers,String supplied) {
|
||||
String actual="";
|
||||
for(var entry:headers.entrySet())if(entry.getKey().equalsIgnoreCase("content-disposition")&&!entry.getValue().isEmpty()) {
|
||||
try{actual=Objects.toString(ContentDisposition.parse(entry.getValue().get(0)).getFilename(),"");}
|
||||
catch(Exception error){throw bad("框架下载回执中的文件名无效");}
|
||||
}
|
||||
if(actual.isEmpty())actual=supplied;
|
||||
if(actual.isEmpty())throw bad("下载回执未提供框架文件名,请引用上游完整的框架文件列表");
|
||||
if(!supplied.isEmpty()&&!actual.equals(supplied))throw bad("框架下载文件名与上游导出回执不一致");
|
||||
return ScannerFrameworkService.decodeName(ScannerFrameworkReferences.encode(actual));
|
||||
}
|
||||
private static long headerLength(Map<String,List<String>> headers) {
|
||||
for(var entry:headers.entrySet())if(entry.getKey().equalsIgnoreCase("content-length")&&!entry.getValue().isEmpty()) {
|
||||
try{return Long.parseLong(entry.getValue().get(0));}catch(NumberFormatException error){throw bad("框架下载长度无效");}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
private static ScannerException bad(String message){return new ScannerException("framework_reference_failed",message,400);}
|
||||
}
|
||||
@ -0,0 +1,91 @@
|
||||
package com.cmvr.scanner;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import java.net.URI;
|
||||
import java.util.*;
|
||||
|
||||
/** Platform references are resolved before building the supplier's fileIds-only request. */
|
||||
public final class ScannerFrameworkReferences {
|
||||
public record Source(String url,String fileId,String name,Long bytes) {}
|
||||
private ScannerFrameworkReferences() {}
|
||||
public static boolean usesReferences(JSONObject input) {return input.containsKey("frameworkUrls");}
|
||||
public static void validate(JSONObject input,boolean sourceKnown) {
|
||||
var body=ScannerRequestValidator.parse(input.getString("requestJson")==null?"{}":input.getString("requestJson"));
|
||||
if(body.size()!=1||!body.path("confirm").isBoolean()||!body.path("confirm").asBoolean())
|
||||
throw bad("请确认导入框架;URL引用模式只接受confirm,不要同时填写旧fileIds");
|
||||
if(sourceKnown)sources(input.get("frameworkUrls"));
|
||||
}
|
||||
public static List<Source> sources(Object value) {
|
||||
// HTTP controller values are Jackson nodes; workflow inputs are strings.
|
||||
// Normalize both before parsing multiline URLs or pasted JSON lists.
|
||||
if(value instanceof JsonNode json&&json.isTextual())value=json.textValue();
|
||||
JsonNode node;
|
||||
if(value instanceof String text) {
|
||||
if(text.length()>131072)throw bad("框架URL列表过大");
|
||||
text=text.trim();
|
||||
if(text.startsWith("[")||text.startsWith("{")) {
|
||||
try {node=ScannerRequestValidator.JSON.readTree(text);}catch(Exception error){throw bad("框架URL列表格式无效");}
|
||||
}else {var array=ScannerRequestValidator.JSON.createArrayNode();for(String line:text.split("\\r?\\n"))if(!line.isBlank())array.add(line.trim());node=array;}
|
||||
}else node=ScannerRequestValidator.JSON.valueToTree(value);
|
||||
node=files(node);
|
||||
List<JsonNode> items=new ArrayList<>();if(node!=null&&node.isArray())node.forEach(items::add);else if(node!=null&&!node.isNull())items.add(node);
|
||||
if(items.size()>64)throw bad("文件列表过大,请引用上游导出的框架文件列表");
|
||||
Map<String,Source> selected=new LinkedHashMap<>();
|
||||
for(JsonNode item:items) {
|
||||
String name=item.isObject()?item.path("name").asText(""):"";
|
||||
if(!name.isEmpty()&&!frameworkName(name))continue;
|
||||
String url=item.isTextual()?item.asText():item.path("downloadUrl").asText(item.path("url").asText(""));
|
||||
String id=fileId(url);
|
||||
if(item.hasNonNull("fileId")&&!id.equalsIgnoreCase(item.path("fileId").asText()))throw bad("框架文件编号与下载URL不一致");
|
||||
if(!name.isEmpty())ScannerFrameworkService.decodeName(encode(name));
|
||||
Long bytes=null;
|
||||
JsonNode length=item.has("bytes")?item.get("bytes"):item.get("size");
|
||||
if(length!=null&&!length.isNull()) {
|
||||
if(!length.isIntegralNumber()||!length.canConvertToLong()||length.asLong()<=0||length.asLong()>ScannerFrameworkService.MAX_BYTES)throw bad("框架文件必须非空且单个不超过100MiB");
|
||||
bytes=length.asLong();
|
||||
}
|
||||
Source source=new Source(url,id.toLowerCase(Locale.ROOT),name,bytes);
|
||||
Source existing=selected.putIfAbsent(source.fileId(),source);
|
||||
if(existing!=null&&(!existing.name().equals(source.name())||!Objects.equals(existing.bytes(),source.bytes())))throw bad("同一框架URL包含冲突的文件信息");
|
||||
}
|
||||
if(selected.isEmpty()||selected.size()>8)throw bad("请选择1至8个框架URL;上游必须成功导出P3、TXT或ASC文件");
|
||||
return new ArrayList<>(selected.values());
|
||||
}
|
||||
private static JsonNode files(JsonNode node) {
|
||||
if(node==null||!node.isObject())return node;
|
||||
for(String key:List.of("frameworkFiles","frameworkUrls","files"))if(node.path(key).isArray()&&!node.path(key).isEmpty())return node.get(key);
|
||||
if(node.path("result").path("files").isArray())return node.path("result").path("files");
|
||||
return node;
|
||||
}
|
||||
public static String fileId(String source) {
|
||||
if(source==null||source.isBlank()||source.length()>2048)throw bad("请填写扫描服务导出的下载URL,或引用上游导出文件列表");
|
||||
try {
|
||||
URI uri=URI.create(source);
|
||||
if(uri.getRawQuery()!=null||uri.getRawFragment()!=null||uri.getRawUserInfo()!=null||uri.getRawAuthority()!=null&&!uri.isAbsolute()
|
||||
||uri.isAbsolute()&&!("http".equalsIgnoreCase(uri.getScheme())||"https".equalsIgnoreCase(uri.getScheme())))throw bad("框架URL不允许查询参数、身份信息或特殊协议");
|
||||
String path=uri.getRawPath();
|
||||
var match=java.util.regex.Pattern.compile("^/(?:api/v1/files|admin-api/cmvr/scanner/files)/([a-fA-F0-9]{32})$").matcher(path==null?"":path);
|
||||
if(!match.matches())throw bad("仅支持扫描服务或平台扫描代理生成的文件下载URL");
|
||||
return match.group(1);
|
||||
}catch(ScannerException error){throw error;}catch(Exception error){throw bad("框架下载URL格式无效");}
|
||||
}
|
||||
public static void validateOrigin(Source source,ScannerProperties settings) {
|
||||
URI uri=URI.create(source.url());
|
||||
if(uri.isAbsolute()&&(!"http".equalsIgnoreCase(uri.getScheme())||settings.getHost()==null||settings.getPort()==null||!settings.getHost().equalsIgnoreCase(uri.getHost())
|
||||
||(uri.getPort()<0?80:uri.getPort())!=settings.getPort()||!uri.getPath().startsWith("/api/v1/files/")))
|
||||
throw bad("框架URL必须来自当前配置的扫描服务;平台代理请使用相对下载路径");
|
||||
}
|
||||
public static boolean frameworkName(String name) {return name!=null&&name.toLowerCase(Locale.ROOT).matches(".*\\.(p3|txt|asc)$");}
|
||||
public static String encode(String name) {return java.net.URLEncoder.encode(name,java.nio.charset.StandardCharsets.UTF_8).replace("+","%20");}
|
||||
public static void enrich(JSONObject output,JsonNode result) {
|
||||
var selected=JSON.parseArray("[]");var urls=JSON.parseArray("[]");
|
||||
for(JsonNode file:result.path("result").path("files")) {
|
||||
if(!frameworkName(file.path("name").asText()))continue;
|
||||
var value=JSONObject.parseObject(file.toString());selected.add(value);urls.add(file.path("downloadUrl").asText());
|
||||
}
|
||||
if(result.path("result").path("files").isArray()) {output.put("frameworkFiles",selected);output.put("frameworkUrls",urls);}
|
||||
}
|
||||
private static ScannerException bad(String message) {return new ScannerException("invalid_framework_reference",message,400);}
|
||||
}
|
||||
@ -0,0 +1,79 @@
|
||||
package com.cmvr.scanner;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.io.*;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
/** Uploads register bytes only. Import is a separate occupied, journaled SDK action. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ScannerFrameworkService {
|
||||
public static final int MAX_BYTES=100*1024*1024;
|
||||
private final ScannerHttpClient client;
|
||||
private final ScannerProperties settings;
|
||||
private final Semaphore uploads=new Semaphore(2);
|
||||
public void validateReferences(String body,Object sources) {
|
||||
var input=com.alibaba.fastjson2.JSONObject.of("requestJson",body,"frameworkUrls",sources);
|
||||
ScannerFrameworkReferences.validate(input,true);
|
||||
ScannerFrameworkReferences.sources(sources).forEach(source->ScannerFrameworkReferences.validateOrigin(source,settings));
|
||||
}
|
||||
|
||||
public JsonNode upload(String encodedName,String contentType,long contentLength,InputStream source) {
|
||||
return upload(encodedName,contentType,contentLength,source,settings.getRequestTimeoutMs());
|
||||
}
|
||||
public JsonNode upload(String encodedName,String contentType,long contentLength,InputStream source,long budgetMs) {
|
||||
client.requireConfigured();
|
||||
if(contentType==null||!contentType.split(";",2)[0].trim().equalsIgnoreCase("application/octet-stream"))
|
||||
throw new ScannerException("invalid_media_type","框架上传仅接收application/octet-stream原始文件",415);
|
||||
String name=decodeName(encodedName);
|
||||
if(contentLength>MAX_BYTES)throw tooLarge();
|
||||
if(!uploads.tryAcquire())throw new ScannerException("upload_busy","最多同时上传两个框架文件,请稍后重试",429);
|
||||
try {
|
||||
byte[] bytes=source.readNBytes(MAX_BYTES+1);
|
||||
if(bytes.length>MAX_BYTES)throw tooLarge();
|
||||
if(bytes.length==0||contentLength>=0&&contentLength!=bytes.length)
|
||||
throw new ScannerException("invalid_file","上传文件不能为空,实际长度须与声明一致",400);
|
||||
// No automatic retry: a lost 201 response may still have consumed vendor quota.
|
||||
JsonNode result;
|
||||
try {result=client.uploadFramework(URLEncoder.encode(name,StandardCharsets.UTF_8).replace("+","%20"),bytes,Math.min(budgetMs,settings.getRequestTimeoutMs()));}
|
||||
catch(ScannerException error){
|
||||
if(error.remoteStatus==413)throw new ScannerException(error.scannerCode,"扫描服务拒绝此文件大小。平台支持100MiB,请检查扫描服务自身的上传上限;原始错误:"+error.getMessage(),413);
|
||||
throw error;
|
||||
}
|
||||
if(!result.path("fileId").asText().matches("[a-fA-F0-9]{32}")||!name.equals(result.path("name").asText())
|
||||
||!result.path("size").isIntegralNumber()||result.path("size").asLong()!=bytes.length)
|
||||
throw new ScannerException("upload_result_uncertain","文件可能已上传,但回执缺少有效编号或长度;请核对服务,勿自动重传",502);
|
||||
return result;
|
||||
}catch(IOException error){throw new ScannerException("invalid_file","读取上传文件失败,未提交设备导入",400);}
|
||||
finally {uploads.release();}
|
||||
}
|
||||
public static String decodeName(String encoded) {
|
||||
if(encoded==null||encoded.isEmpty()||encoded.length()>720)throw invalidName();
|
||||
try {
|
||||
var bytes=new ByteArrayOutputStream();
|
||||
for(int i=0;i<encoded.length();i++) {
|
||||
char ch=encoded.charAt(i);
|
||||
if(ch=='%') {
|
||||
if(i+2>=encoded.length())throw invalidName();
|
||||
int high=Character.digit(encoded.charAt(++i),16),low=Character.digit(encoded.charAt(++i),16);
|
||||
if(high<0||low<0)throw invalidName();bytes.write(high*16+low);
|
||||
} else {if(ch<32||ch>126)throw invalidName();bytes.write(ch);}
|
||||
}
|
||||
String name=StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes.toByteArray())).toString();
|
||||
if(name.isBlank()||name.length()>128||name.getBytes(StandardCharsets.UTF_8).length>240
|
||||
||name.chars().anyMatch(c->c<32||c==127||"<>:\"/\\|?*".indexOf(c)>=0))throw invalidName();
|
||||
String lower=name.toLowerCase(Locale.ROOT);
|
||||
if(!lower.endsWith(".p3")&&!lower.endsWith(".txt")&&!lower.endsWith(".asc"))throw invalidName();
|
||||
return name;
|
||||
}catch(ScannerException error){throw error;}
|
||||
catch(Exception error){throw invalidName();}
|
||||
}
|
||||
private static ScannerException invalidName(){return new ScannerException("invalid_file_name","请选择.p3、.txt或.asc文件,文件名不能包含目录,且不超过240个UTF-8字节及128个UTF-16单元",400);}
|
||||
private static ScannerException tooLarge(){return new ScannerException("file_too_large","单个框架文件不能超过100MiB",413);}
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
package com.cmvr.scanner;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.*;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
@Transactional(propagation=Propagation.REQUIRES_NEW)
|
||||
public class ScannerFrameworkTransferJournal {
|
||||
private final JdbcTemplate jdbc;
|
||||
public record Entry(String hash,String state,String result) {}
|
||||
public Entry get(String key) {
|
||||
var rows=jdbc.query("SELECT source_hash,state,result_json FROM lab_scanner_framework_transfer WHERE transfer_key=?",(r,n)->new Entry(r.getString(1),r.getString(2),r.getString(3)),key);
|
||||
return rows.isEmpty()?null:rows.get(0);
|
||||
}
|
||||
public void intent(String key,String kind,String endpoint,String hash,String owner) {
|
||||
jdbc.update("INSERT INTO lab_scanner_framework_transfer(transfer_key,transfer_kind,endpoint_key,source_hash,owner_ref,state,created_at,updated_at) VALUES(?,?,?,?,?,'INTENT',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",key,kind,endpoint,hash,owner);
|
||||
}
|
||||
public void ready(String key,String result) {
|
||||
jdbc.update("UPDATE lab_scanner_framework_transfer SET state='READY',result_json=?,updated_at=CURRENT_TIMESTAMP WHERE transfer_key=? AND state='INTENT'",result,key);
|
||||
}
|
||||
public void uncertain(String key,String error) {
|
||||
error=java.util.Objects.toString(error,"框架登记结果未知");
|
||||
jdbc.update("UPDATE lab_scanner_framework_transfer SET state='UNKNOWN',error_message=?,updated_at=CURRENT_TIMESTAMP WHERE transfer_key=? AND state='INTENT'",error.substring(0,Math.min(error.length(),1900)),key);
|
||||
}
|
||||
}
|
||||
@ -15,6 +15,8 @@ import java.util.concurrent.*;
|
||||
@RequiredArgsConstructor
|
||||
public class ScannerHttpClient {
|
||||
private final ScannerProperties settings;
|
||||
@org.springframework.beans.factory.annotation.Autowired(required=false)
|
||||
private ScannerFixtureFrameworkStore fixtureFrameworkStore;
|
||||
private volatile HttpClient client;
|
||||
private static final ScheduledThreadPoolExecutor STREAM_TIMEOUTS = streamTimeouts();
|
||||
private static ScheduledThreadPoolExecutor streamTimeouts() {
|
||||
@ -26,7 +28,7 @@ public class ScannerHttpClient {
|
||||
if(settings.getHost().contains("/")||settings.getHost().contains("@")||settings.getHost().contains("?"))throw new ScannerException("invalid_config","扫描服务地址仅填写主机名或IP",400);
|
||||
}
|
||||
public String endpointKey() {
|
||||
requireConfigured(); return cn.hutool.crypto.digest.DigestUtil.sha256Hex(settings.getHost()+":"+settings.getPort());
|
||||
requireConfigured();var address=settings.connection();return cn.hutool.crypto.digest.DigestUtil.sha256Hex(address.host()+":"+address.port());
|
||||
}
|
||||
private HttpClient client() {
|
||||
if(client==null)synchronized(this){if(client==null)client=HttpClient.newBuilder()
|
||||
@ -37,7 +39,7 @@ public class ScannerHttpClient {
|
||||
private HttpRequest request(ScannerOperation op,String id,String body,long timeoutMs) {
|
||||
requireConfigured();
|
||||
try {
|
||||
URI uri=new URI("http",null,settings.getHost(),settings.getPort(),op.route(id),null,null);
|
||||
var address=settings.connection();URI uri=new URI("http",null,address.host(),address.port(),op.route(id),null,null);
|
||||
HttpRequest.Builder builder=HttpRequest.newBuilder(uri).timeout(Duration.ofMillis(Math.max(1,timeoutMs)))
|
||||
.header("Accept",op.binary()?"*/*":"application/json");
|
||||
if(op!=ScannerOperation.METADATA)builder.header("Authorization","Bearer "+settings.getApiKey());
|
||||
@ -48,14 +50,30 @@ public class ScannerHttpClient {
|
||||
}catch(ScannerException e){throw e;}catch(Exception e){throw new ScannerException("invalid_config","扫描服务地址配置无效",400);}
|
||||
}
|
||||
public JsonNode json(ScannerOperation op,String id,String body,long timeoutMs) {
|
||||
if(op.upload())throw new ScannerException("invalid_request","框架上传必须使用原始文件上传通道",400);
|
||||
return json(request(op,id,body,timeoutMs),op.control()?202:200,timeoutMs);
|
||||
}
|
||||
public JsonNode uploadFramework(String encodedName,byte[] bytes,long timeoutMs) {
|
||||
requireConfigured();
|
||||
try {
|
||||
var address=settings.connection();URI uri=new URI("http",null,address.host(),address.port(),ScannerOperation.FRAMEWORK_UPLOAD.path,null,null);
|
||||
var request=HttpRequest.newBuilder(uri).timeout(Duration.ofMillis(Math.max(1,timeoutMs)))
|
||||
.header("Accept","application/json").header("Authorization","Bearer "+settings.getApiKey())
|
||||
.header("Content-Type","application/octet-stream").header("X-File-Name",encodedName)
|
||||
.POST(HttpRequest.BodyPublishers.ofByteArray(bytes)).build();
|
||||
return json(request,201,timeoutMs);
|
||||
}catch(ScannerException error){throw error;}
|
||||
catch(Exception error){throw new ScannerException("invalid_request","框架上传请求无效",400);}
|
||||
}
|
||||
private JsonNode json(HttpRequest request,int expectedStatus,long timeoutMs) {
|
||||
requireConfigured();
|
||||
long deadline=System.nanoTime()+TimeUnit.MILLISECONDS.toNanos(Math.max(1,timeoutMs));
|
||||
var future=client().sendAsync(request(op,id,body,timeoutMs),HttpResponse.BodyHandlers.ofInputStream());
|
||||
var future=client().sendAsync(request,HttpResponse.BodyHandlers.ofInputStream());
|
||||
try {
|
||||
var response=future.get(Math.max(1,timeoutMs),TimeUnit.MILLISECONDS);
|
||||
try(var stream=new TimedStream(response.body(),timeoutMs,deadline)) {
|
||||
if(response.statusCode()!=(op.control()?202:200)) {
|
||||
if(op.control()&&response.statusCode()>=200&&response.statusCode()<300)throw new ScannerException("invalid_response","控制接口未返回202,执行结果未确认",502);
|
||||
if(response.statusCode()!=expectedStatus) {
|
||||
if(response.statusCode()>=200&&response.statusCode()<300)throw new ScannerException("invalid_response","扫描接口未返回预期HTTP "+expectedStatus+",结果未确认",502);
|
||||
throw remote(response.statusCode(),stream.readNBytes(65536));
|
||||
}
|
||||
byte[] bytes=stream.readNBytes(4*1024*1024+1);
|
||||
@ -72,12 +90,20 @@ public class ScannerHttpClient {
|
||||
@Override public void close() throws java.io.IOException{stream.close();}
|
||||
}
|
||||
public Binary binary(ScannerOperation op,String id) {
|
||||
return binary(op,id,settings.getRequestTimeoutMs(),false);
|
||||
}
|
||||
public Binary frameworkFile(String id,long budgetMs) {
|
||||
return binary(ScannerOperation.FILE,id,Math.min(budgetMs,settings.getRequestTimeoutMs()),true);
|
||||
}
|
||||
private Binary binary(ScannerOperation op,String id,long timeoutMs,boolean bounded) {
|
||||
if(op==ScannerOperation.FILE&&fixtureFrameworkStore!=null){var saved=fixtureFrameworkStore.open(id);if(saved!=null)return saved;}
|
||||
requireConfigured();
|
||||
if(!op.binary())throw new IllegalArgumentException("not binary");
|
||||
var future=client().sendAsync(request(op,id,null,settings.getRequestTimeoutMs()),HttpResponse.BodyHandlers.ofInputStream());
|
||||
long deadline=bounded?System.nanoTime()+TimeUnit.MILLISECONDS.toNanos(Math.max(1,timeoutMs)):0;
|
||||
var future=client().sendAsync(request(op,id,null,timeoutMs),HttpResponse.BodyHandlers.ofInputStream());
|
||||
try {
|
||||
var response=future.get(Math.max(1,settings.getRequestTimeoutMs()),TimeUnit.MILLISECONDS);
|
||||
var body=new TimedStream(response.body(),settings.getRequestTimeoutMs(),0);
|
||||
var response=future.get(Math.max(1,timeoutMs),TimeUnit.MILLISECONDS);
|
||||
var body=new TimedStream(response.body(),timeoutMs,deadline);
|
||||
if(response.statusCode()!=200){try(body){throw remote(response.statusCode(),body.readNBytes(65536));}}
|
||||
return new Binary(body,response.headers().map());
|
||||
}catch(ScannerException e){throw e;}catch(InterruptedException e){future.cancel(true);Thread.currentThread().interrupt();throw new ScannerException("interrupted","下载已中断",504);}
|
||||
@ -107,7 +133,8 @@ public class ScannerHttpClient {
|
||||
private ScannerException remote(int status,byte[] bytes) {
|
||||
try {
|
||||
JsonNode value=ScannerRequestValidator.JSON.readTree(bytes).path("error");
|
||||
return new ScannerException(value.path("code").asText("remote_error"),value.path("message").asText("设备请求失败"),status);
|
||||
String message=value.path("message").asText("");
|
||||
return new ScannerException(value.path("code").asText("remote_error"),message.isBlank()?"设备返回HTTP "+status:message,status);
|
||||
}catch(Exception ignored){return new ScannerException("remote_error","设备返回HTTP "+status,status);}
|
||||
}
|
||||
}
|
||||
|
||||
@ -17,10 +17,13 @@ public class ScannerMonitoringService {
|
||||
private final ScannerCommandJournal journal;
|
||||
|
||||
public JsonNode capture(ScannerOperation operation,String commandKey,String instId,String robot,String device) {
|
||||
return capture(operation,commandKey,instId,robot,device,0,0);
|
||||
}
|
||||
public JsonNode capture(ScannerOperation operation,String commandKey,String instId,String robot,String device,int itemOrder,int itemOccurrence) {
|
||||
if(operation!=ScannerOperation.CREATE_PROJECT && operation!=ScannerOperation.SCAN_START) {
|
||||
JsonNode context=journal.latestContext(instId);
|
||||
if(context!=null&&(operation==ScannerOperation.SNAPSHOT||operation==ScannerOperation.EXPORT)) {
|
||||
ObjectNode recorded=context.deepCopy();recorded.put("assetCreatedAt",System.currentTimeMillis());journal.bindContext(commandKey,instId,recorded);
|
||||
ObjectNode recorded=context.deepCopy();recorded.put("assetCreatedAt",System.currentTimeMillis());recorded.put("itemOrder",itemOrder);recorded.put("itemOccurrence",itemOccurrence);journal.bindContext(commandKey,instId,recorded);
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@ -40,6 +43,7 @@ public class ScannerMonitoringService {
|
||||
if(!metrics.path("latestSequence").canConvertToLong())throw new ScannerException("frame_sequence_unavailable","暂时无法建立扫描画面的帧边界",503);
|
||||
ObjectNode context=ScannerRequestValidator.JSON.createObjectNode();
|
||||
context.put("instId",instId);context.put("robotId",robot);context.put("deviceId",device);
|
||||
context.put("itemOrder",itemOrder);context.put("itemOccurrence",itemOccurrence);
|
||||
context.put("endpoint",client.endpointKey());context.put("sessionId",status.path("sessionId").asText());
|
||||
context.put("projectId",status.path("projectId").asText());context.put("commandKey",commandKey);
|
||||
context.put("baselineSequence",metrics.path("latestSequence").asLong());context.put("capturedAt",System.currentTimeMillis());
|
||||
@ -81,6 +85,7 @@ public class ScannerMonitoringService {
|
||||
ObjectNode item=file.deepCopy();item.put("commandKey",record.path("commandKey").asText());
|
||||
item.put("capturedAt",record.path("context").path("assetCreatedAt").asLong(record.path("context").path("capturedAt").asLong()));
|
||||
item.put("projectId",record.path("context").path("projectId").asText());
|
||||
item.put("itemOrder",record.path("context").path("itemOrder").asInt());item.put("itemOccurrence",record.path("context").path("itemOccurrence").asInt());
|
||||
item.set("binding",record.path("context"));files.add(item);
|
||||
}
|
||||
files.sort(Comparator.comparingLong((JsonNode file)->file.path("capturedAt").asLong()).reversed());
|
||||
|
||||
@ -2,52 +2,59 @@ package com.cmvr.scanner;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/** Routes transcribed from the supplier's 2026-10-22 API 1.2 document. */
|
||||
/** Supplier API 1.3, including synchronous binary framework uploads. */
|
||||
public enum ScannerOperation {
|
||||
CONNECT("POST", "/api/v1/device/connect", "连接扫描仪", "SCANNER_INITIALIZE"),
|
||||
CONNECT("POST", "/api/v1/device/connect", "连接设备", "SCANNER_INITIALIZE"),
|
||||
CREATE_PROJECT("POST", "/api/v1/projects", "创建扫描工程", "SCANNER_CREATE_PROJECT"),
|
||||
DISCONNECT("POST", "/api/v1/device/disconnect", "断开扫描会话", "SCANNER_DISCONNECT"),
|
||||
RECONNECT("POST", "/api/v1/device/reconnect", "重新连接扫描仪", "SCANNER_RECONNECT"),
|
||||
PREVIEW_START("POST", "/api/v1/preview/start", "开启扫描预览", "SCANNER_PREVIEW_START"),
|
||||
PREVIEW_STOP("POST", "/api/v1/preview/stop", "关闭扫描预览", "SCANNER_PREVIEW_STOP"),
|
||||
DISCONNECT("POST", "/api/v1/device/disconnect", "断开设备会话", "SCANNER_DISCONNECT"),
|
||||
RECONNECT("POST", "/api/v1/device/reconnect", "结束旧会话并重新连接", "SCANNER_RECONNECT"),
|
||||
PREVIEW_START("POST", "/api/v1/preview/start", "开启渲染预览", "SCANNER_PREVIEW_START"),
|
||||
PREVIEW_STOP("POST", "/api/v1/preview/stop", "关闭渲染预览", "SCANNER_PREVIEW_STOP"),
|
||||
SCAN_START("POST", "/api/v1/scan/start", "开始或继续采集", "SCANNER_START"),
|
||||
SCAN_STOP("POST", "/api/v1/scan/stop", "暂停采集", "SCANNER_STOP"),
|
||||
PREVIEW_IMAGE("GET", "/api/v1/preview/image", "扫描预览图像", null),
|
||||
PREVIEW_STREAM("GET", "/api/v1/preview/stream", "扫描实时预览", null),
|
||||
PARAMETERS("POST", "/api/v1/parameters", "配置扫描参数", "SCANNER_PARAMETERS"),
|
||||
SCAN_STOP("POST", "/api/v1/scan/stop", "暂停采集并保留工程", "SCANNER_STOP"),
|
||||
SCAN_TYPE("POST", "/api/v1/scan/type", "选择采集类型或采集设备", "SCANNER_SCAN_TYPE"),
|
||||
FRAMEWORK_UPLOAD("POST", "/api/v1/framework/files", "上传一个框架文件(同步)", null),
|
||||
FRAMEWORK_IMPORT("POST", "/api/v1/framework/import", "导入已上传的标志点框架", "SCANNER_FRAMEWORK_IMPORT"),
|
||||
FRAMEWORK_OPTIMIZE("POST", "/api/v1/framework/optimize", "优化已采集的摄影测量框架", "SCANNER_FRAMEWORK_OPTIMIZE"),
|
||||
PREVIEW_IMAGE("GET", "/api/v1/preview/image", "下载最新一帧JPEG", null),
|
||||
PREVIEW_STREAM("GET", "/api/v1/preview/stream", "订阅MJPEG实时图像", null),
|
||||
PARAMETERS("POST", "/api/v1/parameters", "修改扫描参数", "SCANNER_PARAMETERS"),
|
||||
MESH("POST", "/api/v1/mesh", "生成网格预览", "SCANNER_MESH"),
|
||||
MESH_CONFIRM("POST", "/api/v1/mesh/confirm", "确认扫描网格", "SCANNER_MESH_CONFIRM"),
|
||||
MESH_UNDO("POST", "/api/v1/mesh/undo", "撤销扫描网格", "SCANNER_MESH_UNDO"),
|
||||
ALIGN("POST", "/api/v1/align", "扫描工程拼接", "SCANNER_ALIGN"),
|
||||
EDIT("POST", "/api/v1/edit", "删除扫描点或标志点", "SCANNER_EDIT"),
|
||||
MESH_CONFIRM("POST", "/api/v1/mesh/confirm", "确认网格", "SCANNER_MESH_CONFIRM"),
|
||||
MESH_UNDO("POST", "/api/v1/mesh/undo", "撤销网格", "SCANNER_MESH_UNDO"),
|
||||
ALIGN("POST", "/api/v1/align", "工程拼接", "SCANNER_ALIGN"),
|
||||
EDIT("POST", "/api/v1/edit", "删除点或标志点", "SCANNER_EDIT"),
|
||||
CLIP_PLANE("POST", "/api/v1/clip-plane", "平面裁剪", "SCANNER_CLIP_PLANE"),
|
||||
EXPORT("POST", "/api/v1/exports", "导出扫描成果", "SCANNER_EXPORT"),
|
||||
SNAPSHOT("POST", "/api/v1/data/snapshots", "保存原始场景快照", "SCANNER_SNAPSHOT"),
|
||||
SCENE("GET", "/api/v1/data/scene", "读取扫描场景摘要", "SCANNER_SCENE"),
|
||||
FILE("GET", "/api/v1/files/{fileId}", "下载扫描成果文件", null),
|
||||
CALIBRATION_ENTER("POST", "/api/v1/calibration/enter", "进入扫描标定", "SCANNER_CALIBRATION_ENTER"),
|
||||
CALIBRATION_MODE("POST", "/api/v1/calibration/setMode", "设置标定模式", "SCANNER_CALIBRATION_MODE"),
|
||||
CALIBRATION_START("POST", "/api/v1/calibration/start", "开始扫描标定", "SCANNER_CALIBRATION_START"),
|
||||
EXPORT("POST", "/api/v1/exports", "导出文件", "SCANNER_EXPORT"),
|
||||
SNAPSHOT("POST", "/api/v1/data/snapshots", "创建原始场景快照", "SCANNER_SNAPSHOT"),
|
||||
SCENE("GET", "/api/v1/data/scene", "读取最近场景摘要", "SCANNER_SCENE"),
|
||||
FILE("GET", "/api/v1/files/{fileId}", "下载已登记导出或快照文件", null),
|
||||
CALIBRATION_ENTER("POST", "/api/v1/calibration/enter", "进入标定流程", "SCANNER_CALIBRATION_ENTER"),
|
||||
CALIBRATION_MODE("POST", "/api/v1/calibration/setMode", "选择标定模式", "SCANNER_CALIBRATION_MODE"),
|
||||
CALIBRATION_START("POST", "/api/v1/calibration/start", "开始当前标定", "SCANNER_CALIBRATION_START"),
|
||||
CALIBRATION_TRAK("POST", "/api/v1/calibration/setTrakType", "设置跟踪仪标定类型", "SCANNER_CALIBRATION_TRAK"),
|
||||
CALIBRATION_SYSTEM("POST", "/api/v1/calibration/startSystem", "开始系统标定", "SCANNER_CALIBRATION_SYSTEM"),
|
||||
CALIBRATION_FREE("POST", "/api/v1/calibration/setFree", "设置自由标定", "SCANNER_CALIBRATION_FREE"),
|
||||
CALIBRATION_FREE("POST", "/api/v1/calibration/setFree", "设置自由标定开关", "SCANNER_CALIBRATION_FREE"),
|
||||
CALIBRATION_CAPTURE("POST", "/api/v1/calibration/capturePose", "采集标定姿态", "SCANNER_CALIBRATION_CAPTURE"),
|
||||
CALIBRATION_COMPUTE("POST", "/api/v1/calibration/compute", "计算自由标定结果", "SCANNER_CALIBRATION_COMPUTE"),
|
||||
CALIBRATION_ADVANCED("POST", "/api/v1/calibration/setAdvanced", "设置精细标定", "SCANNER_CALIBRATION_ADVANCED"),
|
||||
CALIBRATION_ADVANCED("POST", "/api/v1/calibration/setAdvanced", "设置精细标定开关", "SCANNER_CALIBRATION_ADVANCED"),
|
||||
CALIBRATION_APPLY_LAST("POST", "/api/v1/calibration/applyLast", "应用上次标定结果", "SCANNER_CALIBRATION_APPLY_LAST"),
|
||||
METADATA("GET", "/", "读取扫描服务信息", "SCANNER_METADATA"),
|
||||
HEALTH("GET", "/api/v1/health", "检查扫描服务", "SCANNER_HEALTH"),
|
||||
STATUS("GET", "/api/v1/status", "读取扫描仪状态", "SCANNER_STATUS"),
|
||||
CAPABILITIES("GET", "/api/v1/capabilities", "读取扫描能力", "SCANNER_CAPABILITIES"),
|
||||
METRICS("GET", "/api/v1/preview/metrics", "读取预览指标", "SCANNER_METRICS"),
|
||||
TASK("GET", "/api/v1/tasks/{taskId}", "等待扫描设备任务", "SCANNER_WAIT");
|
||||
METADATA("GET", "/", "查询公开服务元数据", "SCANNER_METADATA"),
|
||||
HEALTH("GET", "/api/v1/health", "健康检查", "SCANNER_HEALTH"),
|
||||
STATUS("GET", "/api/v1/status", "读取设备和工程状态", "SCANNER_STATUS"),
|
||||
CAPABILITIES("GET", "/api/v1/capabilities", "读取当前功能能力", "SCANNER_CAPABILITIES"),
|
||||
METRICS("GET", "/api/v1/preview/metrics", "读取图像编码与缓存指标", "SCANNER_METRICS"),
|
||||
TASK("GET", "/api/v1/tasks/{taskId}", "查询异步任务", "SCANNER_WAIT"),
|
||||
BATTERY("GET", "/api/v1/device/battery", "读取扫描仪和跟踪仪电量", "SCANNER_BATTERY");
|
||||
|
||||
public final String method, path, title, action;
|
||||
ScannerOperation(String method, String path, String title, String action) {
|
||||
this.method=method; this.path=path; this.title=title; this.action=action;
|
||||
}
|
||||
public boolean control() { return method.equals("POST"); }
|
||||
public boolean upload() { return this==FRAMEWORK_UPLOAD; }
|
||||
public boolean control() { return method.equals("POST")&&!upload(); }
|
||||
public boolean binary() { return this==FILE || this==PREVIEW_IMAGE || this==PREVIEW_STREAM; }
|
||||
public boolean usableWithoutDevice() {return !control()||this==CONNECT||this==DISCONNECT||this==RECONNECT||this==SCAN_STOP;}
|
||||
public static ScannerOperation forAction(String action) {
|
||||
return Arrays.stream(values()).filter(op -> op.action!=null && op.action.equals(action)).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
@ -0,0 +1,36 @@
|
||||
package com.cmvr.scanner;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/** Task-scoped acquisition settings; never edit the published graph or other SDK fields. */
|
||||
public final class ScannerParameterOverrides {
|
||||
public static final String RUN_PARAM="scannerParameters";
|
||||
private ScannerParameterOverrides() {}
|
||||
|
||||
public static JSONObject validate(Object value) {
|
||||
if(!(value instanceof Map<?,?> map)||!map.keySet().equals(Set.of("brightness","pointDistance")))
|
||||
throw new ScannerException("invalid_request","扫描参数须包含激光亮度brightness和点间距pointDistance两项",400);
|
||||
var body=ScannerRequestValidator.parse(JSON.toJSONString(value));
|
||||
ScannerRequestValidator.validate(ScannerOperation.PARAMETERS,body);
|
||||
return JSON.parseObject(body.toString());
|
||||
}
|
||||
public static boolean hasNode(String graph) {
|
||||
if(graph==null||graph.isBlank())return false;
|
||||
try {
|
||||
for(var node:ScannerRequestValidator.JSON.readTree(graph).path("nodes"))
|
||||
if("SCANNER_PARAMETERS".equalsIgnoreCase(node.path("properties").path("action").asText()))return true;
|
||||
return false;
|
||||
}catch(Exception error){throw new ScannerException("invalid_request","扫描方案格式无效,请核对发布版本",400);}
|
||||
}
|
||||
public static JSONObject apply(JSONObject input,JSONObject runParams) {
|
||||
if(runParams==null||!runParams.containsKey(RUN_PARAM))return input;
|
||||
JSONObject values=validate(runParams.get(RUN_PARAM));
|
||||
var body=ScannerRequestValidator.parse(input.getString("requestJson")==null?"{}":input.getString("requestJson"));
|
||||
for(String key:Set.of("brightness","pointDistance"))body.set(key,ScannerRequestValidator.JSON.valueToTree(values.get(key)));
|
||||
ScannerRequestValidator.validate(ScannerOperation.PARAMETERS,body);
|
||||
JSONObject result=new JSONObject(input);result.put("requestJson",body.toString());return result;
|
||||
}
|
||||
}
|
||||
@ -8,6 +8,10 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "cmvr.scanner")
|
||||
public class ScannerProperties {
|
||||
private volatile com.cmvr.resource.service.ServiceEndpoint connectionOverride;
|
||||
public com.cmvr.resource.service.ServiceEndpoint connection() { var current=connectionOverride;return current==null?new com.cmvr.resource.service.ServiceEndpoint(host,port):current; }
|
||||
public String getHost() {return connection().host();}
|
||||
public Integer getPort() {return connection().port();}
|
||||
private String host = "";
|
||||
private Integer port;
|
||||
private String apiKey = "";
|
||||
@ -17,5 +21,5 @@ public class ScannerProperties {
|
||||
private int requestTimeoutMs = 15000;
|
||||
private int pollIntervalMs = 500;
|
||||
private int operationTimeoutMs = 120000;
|
||||
public boolean configured() { return host != null && !host.isBlank() && port != null && port > 0 && port <= 65535 && apiKey != null && !apiKey.isBlank(); }
|
||||
public boolean configured() { var address=connection();return address.host() != null && !address.host().isBlank() && address.port() != null && address.port() > 0 && address.port() <= 65535 && apiKey != null && !apiKey.isBlank(); }
|
||||
}
|
||||
|
||||
@ -0,0 +1,75 @@
|
||||
package com.cmvr.scanner;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import java.util.*;
|
||||
|
||||
/** Bind individual workflow fields without evaluating code or parsing 64-bit IDs in JavaScript. */
|
||||
public final class ScannerRequestComposer {
|
||||
private static final Set<String> JSON_FIELDS=Set.of("fileIds","formats","include","markerDiameters","pointIds","markerIds","points","normals","center","normal","fixedPoints","movingPoints","fixedMarkerPoints","movingMarkerPoints","fixedMarkerIds","movingMarkerIds");
|
||||
private ScannerRequestComposer() {}
|
||||
public static JSONObject resolve(ScannerOperation op,JSONObject input) {
|
||||
if(!input.containsKey("requestFields"))return input;
|
||||
if(op==null||!op.control()||input.containsKey("frameworkUrls"))throw bad("此组件请使用自身的参数来源,不支持附加请求字段");
|
||||
if(!(input.get("requestFields") instanceof Map<?,?> values))throw bad("请求字段引用必须为对象");
|
||||
ObjectNode body=ScannerRequestValidator.parse(input.getString("requestJson")==null?"{}":input.getString("requestJson"));
|
||||
Set<String> keys=keys(op);
|
||||
for(var entry:values.entrySet()) {
|
||||
if(!(entry.getKey() instanceof String key)||!keys.contains(key))throw bad("此接口不接受请求字段:"+entry.getKey());
|
||||
JsonNode value=ScannerRequestValidator.JSON.valueToTree(entry.getValue());
|
||||
if(JSON_FIELDS.contains(key)&&value.isTextual()) {
|
||||
String text=value.textValue();if(text.length()>1048576)throw bad(key+"引用的JSON超过1MiB");
|
||||
try{value=ScannerRequestValidator.JSON.readTree(text);}catch(Exception e){throw bad(key+"必须引用数组或有效的JSON数组文本");}
|
||||
if(value==null||!value.isArray())throw bad(key+"必须引用数组或有效的JSON数组文本");
|
||||
}
|
||||
body.set(key,value);
|
||||
}
|
||||
// Re-parse to enforce the same size/depth/duplicate rules as ordinary requests.
|
||||
ScannerRequestValidator.parse(body.toString());
|
||||
JSONObject result=new JSONObject(input);result.put("requestJson",body.toString());result.remove("requestFields");return result;
|
||||
}
|
||||
public static Set<String> keys(ScannerOperation op) {
|
||||
String keys=ScannerRequestValidator.fieldKeys(op);return keys.isEmpty()?Set.of():Set.of(keys.split(" "));
|
||||
}
|
||||
public static Set<String> names(ScannerOperation op,JsonNode list) {
|
||||
if(list==null||!list.isArray()||list.size()>64)throw bad("请求字段列表无效");
|
||||
Set<String> names=new LinkedHashSet<>();
|
||||
for(JsonNode item:list)if(!item.isTextual()||!keys(op).contains(item.asText())||!names.add(item.asText()))throw bad("请求字段为空、重复或不受此接口支持");
|
||||
return names;
|
||||
}
|
||||
public static void validateTemplate(ScannerOperation op,String body,JsonNode names) {
|
||||
ScannerRequestValidator.validateTemplate(op,ScannerRequestValidator.parse(body),names(op,names));
|
||||
}
|
||||
public static void validateApiDefinition(ScannerOperation op,String body,JsonNode definition) {
|
||||
if(definition==null||!definition.isObject())throw bad("请求字段配置必须为对象");
|
||||
try{validateDefinition(op,JSONObject.parseObject(definition.toString()),JSONObject.of("requestJson",body),false);}
|
||||
catch(ScannerException error){throw error;}
|
||||
catch(RuntimeException error){throw bad("请求字段配置格式无效");}
|
||||
}
|
||||
public static void validateDefinition(ScannerOperation op,JSONObject container,JSONObject literals,boolean dynamicBody) {
|
||||
if(container==null)throw bad("请求字段配置不能为空");
|
||||
if(!op.control()||literals.containsKey("frameworkUrls"))throw bad("此组件不支持附加请求字段");
|
||||
if(!"input".equals(container.getString("type"))||!(container.get("input") instanceof Map<?,?> map)||!map.isEmpty())throw bad("请求字段容器应为空对象并使用子字段配置");
|
||||
JSONArray children=container.getJSONArray("children");
|
||||
if(children==null||children.isEmpty()||children.size()>64)throw bad("请至少选择一个请求字段引用");
|
||||
Set<String> all=new HashSet<>(),dynamic=new LinkedHashSet<>();JSONObject values=new JSONObject();
|
||||
for(int i=0;i<children.size();i++) {
|
||||
var child=children.getJSONObject(i);String key=child.getString("name");
|
||||
Object nested=child.get("children");
|
||||
if(!keys(op).contains(key==null?"":key)||!all.add(key)||nested!=null&&(!(nested instanceof List<?> list)||!list.isEmpty()))throw bad("请求字段为空、重复或包含不支持的嵌套");
|
||||
if("quote".equals(child.getString("type"))) {
|
||||
var path=child.getJSONArray("quote");
|
||||
if(path==null||path.size()<3||path.stream().anyMatch(v->!(v instanceof String s)||s.isBlank())||!Set.of("input","output").contains(child.getString("quoteType")))throw bad(key+"的上游引用不完整");
|
||||
dynamic.add(key);
|
||||
} else if("input".equals(child.getString("type")))values.put(key,child.get("input"));
|
||||
else throw bad(key+"的参数来源无效");
|
||||
}
|
||||
if(dynamicBody)return;
|
||||
JSONObject base=new JSONObject(literals);base.put("requestFields",values);
|
||||
var resolved=resolve(op,base);
|
||||
ScannerRequestValidator.validateTemplate(op,ScannerRequestValidator.parse(resolved.getString("requestJson")),dynamic);
|
||||
}
|
||||
private static ScannerException bad(String text){return new ScannerException("invalid_request_fields",text,400);}
|
||||
}
|
||||
@ -8,6 +8,30 @@ import java.util.*;
|
||||
|
||||
/** Documented shape/lexical types; unknown SDK limits remain device-side validations. */
|
||||
public class ScannerRequestValidator {
|
||||
/** Shared by full validation, workflow field references and generated editor metadata. */
|
||||
public static String fieldKeys(ScannerOperation op) {
|
||||
return switch(op) {
|
||||
case CONNECT -> "deviceType";
|
||||
case CREATE_PROJECT -> "name mode";
|
||||
case DISCONNECT -> "confirm discardProject expectedProjectId expectedSessionId";
|
||||
case RECONNECT -> "confirm discardProject expectedProjectId expectedSessionId deviceType";
|
||||
case SCAN_TYPE -> "scanType device confirm";
|
||||
case FRAMEWORK_IMPORT -> "fileIds confirm";
|
||||
case PARAMETERS -> "pointDistance brightness lightSourceMode scanFrameRate highSpeedMode addMarkerMode viewLock localEnlargedView qualityColor strongLight preScanMode markerDiameters";
|
||||
case MESH -> "filterLevel smoothLevel removeSmallFloatingParts cutMeshEdgeOptimization cutMeshEdgeValue holeOptimization boundaryOptimization maxTriangles fillSmallHole removeSpikes fillMarkerHoles rememberChoice";
|
||||
case EXPORT -> "name formats";
|
||||
case SNAPSHOT -> "maxPoints include pauseAcquisition";
|
||||
case ALIGN -> "action mode fixedProjectUuid movingProjectUuid confirm fixedPoints movingPoints fixedMarkerPoints movingMarkerPoints fixedMarkerIds movingMarkerIds";
|
||||
case EDIT -> "projectUuid cloudUuid pointIds markerIds points normals confirm";
|
||||
case CLIP_PLANE -> "center normal deleteBelowPoints deleteBelowMarkers confirm";
|
||||
case CALIBRATION_MODE -> "mode";
|
||||
case CALIBRATION_TRAK -> "trakType confirm";
|
||||
case CALIBRATION_APPLY_LAST -> "mode confirm";
|
||||
case CALIBRATION_FREE,CALIBRATION_ADVANCED -> "enabled confirm";
|
||||
case CALIBRATION_START,CALIBRATION_SYSTEM,CALIBRATION_CAPTURE,CALIBRATION_COMPUTE -> "confirm";
|
||||
default -> "";
|
||||
};
|
||||
}
|
||||
public static final ObjectMapper JSON=new ObjectMapper().enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
|
||||
.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
|
||||
public static ObjectNode parse(String source) {
|
||||
@ -22,7 +46,18 @@ public class ScannerRequestValidator {
|
||||
int limit=op==ScannerOperation.ALIGN||op==ScannerOperation.EDIT?1048576:16384;
|
||||
if(b.toString().getBytes(StandardCharsets.UTF_8).length>limit)throw bad("请求体超过设备接口大小限制");
|
||||
depth(b,1);
|
||||
fields(b,fieldKeys(op));
|
||||
switch(op) {
|
||||
case FRAMEWORK_UPLOAD -> throw bad("框架上传必须发送文件原始字节,不能发送JSON或作为异步控制命令");
|
||||
case SCAN_TYPE -> {
|
||||
fields(b,"scanType device confirm");choice(b,"scanType",true,"photogrammetry","mesh","markers");
|
||||
choice(b,"device",false,"tracker","scanner");bool(b,"confirm");
|
||||
}
|
||||
case FRAMEWORK_IMPORT -> {
|
||||
fields(b,"fileIds confirm");confirmed(b);strings(b,"fileIds",true);
|
||||
if(b.get("fileIds").size()>8)throw bad("一次只能导入1至8个已上传框架文件");
|
||||
for(JsonNode id:b.get("fileIds"))if(!id.asText().matches("[a-fA-F0-9]{32}"))throw bad("框架上传编号必须为32位十六进制,不能填写文件路径");
|
||||
}
|
||||
case CONNECT -> {fields(b,"deviceType");deviceType(b);}
|
||||
case CREATE_PROJECT -> {fields(b,"name mode");name(b);choice(b,"mode",false,"trak","laser");}
|
||||
case DISCONNECT,RECONNECT -> {
|
||||
@ -32,7 +67,10 @@ public class ScannerRequestValidator {
|
||||
case PARAMETERS -> {
|
||||
fields(b,"pointDistance brightness lightSourceMode scanFrameRate highSpeedMode addMarkerMode viewLock localEnlargedView qualityColor strongLight preScanMode markerDiameters");
|
||||
if(b.isEmpty())throw bad("至少设置一项扫描参数");
|
||||
number(b,"pointDistance",false);integer(b,"brightness",false);integer(b,"scanFrameRate",false);
|
||||
number(b,"pointDistance",false);integer(b,"scanFrameRate",false);
|
||||
if(b.has("brightness"))range(b,"brightness",1,18);
|
||||
if(b.has("pointDistance")&&(b.get("pointDistance").decimalValue().compareTo(new java.math.BigDecimal("0.05"))<0
|
||||
||b.get("pointDistance").decimalValue().compareTo(java.math.BigDecimal.TEN)>0))throw bad("点间距必须在0.05至10之间");
|
||||
if(b.has("lightSourceMode"))range(b,"lightSourceMode",0,2);
|
||||
for(String k:List.of("highSpeedMode","addMarkerMode","viewLock","localEnlargedView","qualityColor","strongLight","preScanMode"))bool(b,k);
|
||||
if(b.has("markerDiameters"))integerArray(b,"markerDiameters");
|
||||
@ -46,7 +84,7 @@ public class ScannerRequestValidator {
|
||||
}
|
||||
case EXPORT -> {fields(b,"name formats");name(b);strings(b,"formats",true);}
|
||||
case SNAPSHOT -> {
|
||||
fields(b,"maxPoints include");integer(b,"maxPoints",false);
|
||||
fields(b,"maxPoints include pauseAcquisition");integer(b,"maxPoints",false);bool(b,"pauseAcquisition");
|
||||
if(b.has("maxPoints")&&b.get("maxPoints").bigIntegerValue().signum()<=0)throw bad("maxPoints必须为正整数");
|
||||
if(b.has("include")){strings(b,"include",true);for(JsonNode item:b.get("include"))if(!Set.of("points","markers","meshes").contains(item.asText()))throw bad("不支持的快照数据类别");}
|
||||
}
|
||||
@ -73,6 +111,52 @@ public class ScannerRequestValidator {
|
||||
default -> fields(b,"");
|
||||
}
|
||||
}
|
||||
/** Check known fields now; combinations involving upstream values are checked after resolution. */
|
||||
public static void validateTemplate(ScannerOperation op,ObjectNode body,Set<String> referenced) {
|
||||
if(!op.control())throw bad("此组件不接收请求字段引用");
|
||||
ObjectNode all=body.deepCopy();referenced.forEach(k->all.putNull(k));fields(all,fieldKeys(op));
|
||||
if(referenced.isEmpty()){validate(op,body);return;}
|
||||
ObjectNode known=body.deepCopy();referenced.forEach(known::remove);depth(known,1);
|
||||
for(var it=known.fieldNames();it.hasNext();) {
|
||||
String key=it.next();
|
||||
switch(key) {
|
||||
case "confirm","discardProject","highSpeedMode","addMarkerMode","viewLock","localEnlargedView","qualityColor","strongLight","preScanMode","cutMeshEdgeOptimization","holeOptimization","boundaryOptimization","removeSpikes","fillMarkerHoles","rememberChoice","pauseAcquisition","deleteBelowPoints","deleteBelowMarkers","enabled" -> bool(known,key);
|
||||
case "expectedProjectId","expectedSessionId" -> nullableText(known,key);
|
||||
case "name" -> name(known);
|
||||
case "deviceType" -> range(known,key,3,4);
|
||||
case "brightness" -> range(known,key,1,18);
|
||||
case "lightSourceMode" -> range(known,key,0,2);
|
||||
case "filterLevel","smoothLevel","trakType" -> range(known,key,0,3);
|
||||
case "pointDistance" -> {number(known,key,true);if(known.get(key).decimalValue().compareTo(new java.math.BigDecimal("0.05"))<0||known.get(key).decimalValue().compareTo(java.math.BigDecimal.TEN)>0)throw bad("点间距必须在0.05至10之间");}
|
||||
case "cutMeshEdgeValue" -> number(known,key,true);
|
||||
case "scanFrameRate","removeSmallFloatingParts" -> integer(known,key,true);
|
||||
case "maxPoints","maxTriangles","fillSmallHole" -> {if(!known.get(key).isNull()||key.equals("maxPoints")){integer(known,key,true);if(known.get(key).bigIntegerValue().signum()<=0)throw bad(key+"必须为正整数");}}
|
||||
case "pointIds","markerIds","fixedMarkerIds","movingMarkerIds","markerDiameters" -> integerArray(known,key);
|
||||
case "center","normal" -> {vector(known.get(key));if(key.equals("normal")){boolean nonzero=false;for(JsonNode n:known.get(key))nonzero|=(float)n.asDouble()!=0f;if(!nonzero)throw bad("裁剪法向量不能为零");}}
|
||||
case "points","normals","fixedPoints","movingPoints","fixedMarkerPoints","movingMarkerPoints" -> vectors(known,key);
|
||||
case "formats","include","fileIds" -> {strings(known,key,true);if(key.equals("include"))for(JsonNode n:known.get(key))if(!Set.of("points","markers","meshes").contains(n.asText()))throw bad("不支持的快照数据类别");if(key.equals("fileIds")){if(known.get(key).size()>8)throw bad("一次只能导入1至8个已上传框架文件");for(JsonNode n:known.get(key))if(!n.asText().matches("[a-fA-F0-9]{32}"))throw bad("框架上传编号无效");}}
|
||||
case "scanType" -> choice(known,key,true,"photogrammetry","mesh","markers");
|
||||
case "device" -> choice(known,key,true,"tracker","scanner");
|
||||
case "action" -> choice(known,key,true,"enter","next","cancel","exit","apply");
|
||||
case "mode" -> {if(op==ScannerOperation.CREATE_PROJECT)choice(known,key,true,"trak","laser");else if(op==ScannerOperation.ALIGN)choice(known,key,true,"featureAuto","markerAuto","featureManual","markerManual");else range(known,key,0,3);}
|
||||
default -> text(known,key,true);
|
||||
}
|
||||
}
|
||||
boolean confirms=switch(op){case DISCONNECT,RECONNECT,FRAMEWORK_IMPORT,EDIT,CLIP_PLANE,CALIBRATION_TRAK,CALIBRATION_APPLY_LAST,CALIBRATION_FREE,CALIBRATION_ADVANCED,CALIBRATION_START,CALIBRATION_SYSTEM,CALIBRATION_CAPTURE,CALIBRATION_COMPUTE -> true;case ALIGN -> "exit".equals(known.path("action").asText());default -> false;};
|
||||
if(confirms&&!referenced.contains("confirm"))confirmed(known);
|
||||
if(op==ScannerOperation.ALIGN&&known.has("action")&&!known.path("action").asText().equals("apply"))fields(all,"action confirm");
|
||||
String required=switch(op){case SCAN_TYPE -> "scanType";case FRAMEWORK_IMPORT -> "fileIds confirm";case EXPORT -> "formats";case EDIT -> "projectUuid confirm";case CLIP_PLANE -> "center normal confirm";case CALIBRATION_MODE -> "mode";case CALIBRATION_TRAK -> "trakType confirm";case CALIBRATION_APPLY_LAST -> "mode confirm";case CALIBRATION_FREE,CALIBRATION_ADVANCED -> "enabled confirm";case DISCONNECT,RECONNECT,CALIBRATION_START,CALIBRATION_SYSTEM,CALIBRATION_CAPTURE,CALIBRATION_COMPUTE -> "confirm";case ALIGN -> "action";default -> "";};
|
||||
for(String key:required.split(" "))if(!key.isEmpty()&&!known.has(key)&&!referenced.contains(key))throw bad(key+"为必填参数,请填写或引用上游");
|
||||
if(op==ScannerOperation.EDIT) {
|
||||
if(!referenced.contains("pointIds")&&!referenced.contains("markerIds")&&size(known,"pointIds")+size(known,"markerIds")==0)throw bad("pointIds和markerIds至少一组非空");
|
||||
if(size(known,"pointIds")>0&&!known.has("cloudUuid")&&!referenced.contains("cloudUuid"))throw bad("编辑点云需要cloudUuid");
|
||||
}
|
||||
if(op==ScannerOperation.CLIP_PLANE&&!referenced.contains("deleteBelowPoints")&&!referenced.contains("deleteBelowMarkers")&&!known.path("deleteBelowPoints").asBoolean()&&!known.path("deleteBelowMarkers").asBoolean())throw bad("至少选择一种裁剪对象");
|
||||
if(op==ScannerOperation.ALIGN&&"apply".equals(known.path("action").asText())) {
|
||||
for(String key:List.of("mode","fixedProjectUuid","movingProjectUuid"))if(!known.has(key)&&!referenced.contains(key))throw bad(key+"为必填参数,请填写或引用上游");
|
||||
if(known.has("fixedProjectUuid")&&known.has("movingProjectUuid")&&known.get("fixedProjectUuid").equals(known.get("movingProjectUuid")))throw bad("固定与移动工程不能相同");
|
||||
}
|
||||
}
|
||||
private static void align(ObjectNode b) {
|
||||
choice(b,"action",true,"enter","next","cancel","exit","apply");String action=b.path("action").asText();
|
||||
if(!action.equals("apply")){fields(b,"action confirm");bool(b,"confirm");if(action.equals("exit"))confirmed(b);return;}
|
||||
|
||||
@ -28,6 +28,16 @@ public class ScannerResourceSynchronizer {
|
||||
return robotId != null && !robotId.isBlank() && robotId.equals(settings.getRobotId())
|
||||
&& settings.getDeviceId() != null && !settings.getDeviceId().isBlank();
|
||||
}
|
||||
public boolean handlesDevice(String robotId,String deviceId) {return handles(robotId)&&java.util.Objects.equals(deviceId,settings.getDeviceId());}
|
||||
|
||||
public void validateUnboundTarget(String robotId) {
|
||||
if (robotId == null || robotId.isBlank()) return;
|
||||
boolean httpStation = devices.selectByRobotId(robotId, 14, false).stream()
|
||||
.anyMatch(device -> "FreeScan HTTP API".equals(device.getTypeName()));
|
||||
if (httpStation) {
|
||||
throw new GlobalException("FreeScan 扫描工位绑定配置未加载或不匹配,请检查 scanner-private.yaml 的加载路径及 robot-id、device-id 配置");
|
||||
}
|
||||
}
|
||||
|
||||
@Scheduled(initialDelayString = "${cmvr.scanner.resource-initial-delay-ms:3000}",
|
||||
fixedDelayString = "${cmvr.scanner.resource-refresh-ms:5000}")
|
||||
@ -54,14 +64,14 @@ public class ScannerResourceSynchronizer {
|
||||
&& !status.path("restartRequired").asBoolean() && !status.path("stateUncertain").asBoolean();
|
||||
if (partialBusy) {
|
||||
ResourceRobot update = new ResourceRobot();update.setId(robot.getId());
|
||||
update.setConnectStatus(robot.getConnectStatus());update.setStatus("3");
|
||||
update.setConnectStatus("1");update.setStatus("3");
|
||||
update.setLastHeartbeatTime(now);update.setUpdateTime(now);robots.updateHttpScannerState(update);
|
||||
return; // Do not discover a device, enable it, or refresh its last measured online time.
|
||||
}
|
||||
boolean online = status != null && status.path("deviceOnline").asBoolean(false);
|
||||
ResourceRobot update = new ResourceRobot();
|
||||
update.setId(robot.getId());
|
||||
update.setConnectStatus(online ? "1" : "0");
|
||||
update.setConnectStatus(status != null ? "1" : "0");
|
||||
update.setStatus(!online ? "1" : status.path("scanning").asBoolean() || status.path("busy").asBoolean() ? "3" : "2");
|
||||
update.setLastHeartbeatTime(status == null ? robot.getLastHeartbeatTime() : now);
|
||||
update.setUpdateTime(now);
|
||||
|
||||
@ -16,6 +16,23 @@ public class ScannerService {
|
||||
private final ScannerCommandJournal journal;
|
||||
private final ReentrantLock commandLock=new ReentrantLock();
|
||||
|
||||
/** Serialize address changes against commands and retain uncertain command ownership. */
|
||||
public void reconfigure(Runnable save) {
|
||||
if(!commandLock.tryLock())throw new ScannerException("command_busy","扫描命令正在执行,暂不能修改地址",409);
|
||||
try {
|
||||
if(settings.configured()) {
|
||||
if(journal.active(client.endpointKey())!=null)throw new ScannerException("command_busy","扫描命令尚未确认结束,请先处理并释放设备",409);
|
||||
JsonNode status=null;
|
||||
try{status=client.json(ScannerOperation.STATUS,null,null,3000);}
|
||||
catch(ScannerException unavailable){if(Thread.currentThread().isInterrupted())throw unavailable;}
|
||||
if(status!=null&&(status.path("scanning").asBoolean()||status.path("busy").asBoolean()
|
||||
||status.path("stateUncertain").asBoolean()))
|
||||
throw new ScannerException("scan_active","请先停止采集或设备任务,再修改连接地址",409);
|
||||
}
|
||||
save.run();
|
||||
} finally {commandLock.unlock();}
|
||||
}
|
||||
|
||||
public ObjectNode configuration() {
|
||||
ObjectNode result=ScannerRequestValidator.JSON.createObjectNode();
|
||||
result.put("configured",settings.configured());result.put("host",settings.getHost());
|
||||
@ -24,7 +41,7 @@ public class ScannerService {
|
||||
result.put("robotId",settings.getRobotId());result.put("deviceId",settings.getDeviceId());return result;
|
||||
}
|
||||
public JsonNode get(ScannerOperation op,String id) {
|
||||
if(op.control()||op.binary())throw new IllegalArgumentException("not a JSON query");
|
||||
if(op.control()||op.binary()||op.upload())throw new IllegalArgumentException("not a JSON query");
|
||||
return client.json(op,id,null,settings.getRequestTimeoutMs());
|
||||
}
|
||||
public ScannerHttpClient.Binary binary(ScannerOperation op,String id){return client.binary(op,id);}
|
||||
|
||||
@ -15,6 +15,6 @@ public class ScannerStreamingConfiguration implements WebMvcConfigurer {
|
||||
@Override public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) {
|
||||
if (request.isAsyncStarted()) request.getAsyncContext().setTimeout(0);
|
||||
}
|
||||
}).addPathPatterns("/admin-api/cmvr/scanner/preview/stream", "/admin-api/lab/execution/scanner-view/stream");
|
||||
}).addPathPatterns("/admin-api/cmvr/scanner/preview/stream", "/admin-api/lab/execution/scanner-view/stream", "/admin-api/lab/master/fixture/framework/preview-stream");
|
||||
}
|
||||
}
|
||||
|
||||
@ -15,6 +15,8 @@ public class ScannerWorkflowAdapter implements WorkcellDeviceAdapter {
|
||||
private final ScannerAccessService access;
|
||||
private final ScannerMonitoringService monitoring;
|
||||
private final ScannerResourceSynchronizer resources;
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private ScannerFrameworkReferenceService frameworkReferences;
|
||||
@Override public boolean supports(ActionEnum action){return action!=null&&ScannerOperation.forAction(action.getAction())!=null;}
|
||||
@Override public void validateConfiguration(String robotId,String deviceId) {
|
||||
if(!settings.configured())throw new ScannerException("not_configured","扫描服务地址、端口和密钥待配置",503);
|
||||
@ -23,8 +25,10 @@ public class ScannerWorkflowAdapter implements WorkcellDeviceAdapter {
|
||||
}
|
||||
@Override public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) {
|
||||
JSONObject input=message.getInputParams();ScannerOperation op=ScannerOperation.forAction(message.getAction().getAction());
|
||||
input=ScannerRequestComposer.resolve(op,input);
|
||||
validateConfiguration(message.getRobotId(),input.getString("deviceId"));
|
||||
long timeout=input.getLongValue("timeoutMs");
|
||||
ScannerFrameworkReferenceService.Prepared prepared=null;
|
||||
com.fasterxml.jackson.databind.JsonNode result;
|
||||
if(op==ScannerOperation.TASK){result=service.waitRemoteTask(input.getString("taskId"),timeout);}
|
||||
else if(!op.control()){result=service.get(op,null);}
|
||||
@ -36,23 +40,37 @@ public class ScannerWorkflowAdapter implements WorkcellDeviceAdapter {
|
||||
// requestJson stays text until the backend, preserving 64-bit IDs and integer literals.
|
||||
String body=input.getString("requestJson");
|
||||
if(body==null){if(input.containsKey("planCode")||input.containsKey("jobId")||input.containsKey("format"))throw new ScannerException("legacy_node_parameters","旧扫描节点参数与真实协议不一致,请重新配置组件",400);body="{}";}
|
||||
if(op==ScannerOperation.FRAMEWORK_IMPORT&&ScannerFrameworkReferences.usesReferences(input)) {
|
||||
if(message.getInstId()==null||message.getInstId().isBlank())throw new ScannerException("workflow_required","框架URL自动导入请通过工作流执行,以关联当前循环和设备占用",409);
|
||||
long started=System.nanoTime();
|
||||
prepared=frameworkReferences.prepare(commandKey,message.getInstId(),input,timeout);body=prepared.body().toString();
|
||||
timeout-=java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-started);
|
||||
if(timeout<1)throw new ScannerException("framework_transfer_timeout","框架登记已完成,节点等待时限已到;登记记录保留",504);
|
||||
}
|
||||
if(message.getInstId()==null || message.getInstId().isBlank()) {
|
||||
var submitted=access.submit(op,body,commandKey);
|
||||
result=service.waitCommand(submitted.path("commandKey").asText(),timeout);
|
||||
}else if(input.containsKey("expectedContextJson")) {
|
||||
var expected=ScannerRequestValidator.parse(input.getString("expectedContextJson"));monitoring.status(expected);
|
||||
result=service.executeBoundAndWait(op,ScannerRequestValidator.parse(body),commandKey,"workflow:"+message.getInstId(),timeout,expected);
|
||||
}else result=service.executeAndWait(op,ScannerRequestValidator.parse(body),commandKey,"workflow:"+message.getInstId(),timeout);
|
||||
}else if(prepared!=null)result=service.executeBoundAndWait(op,prepared.body(),commandKey,"workflow:"+message.getInstId(),timeout,prepared.context());
|
||||
else result=service.executeAndWait(op,ScannerRequestValidator.parse(body),commandKey,"workflow:"+message.getInstId(),timeout);
|
||||
}
|
||||
// A control's terminal acknowledgement can precede the next periodic status
|
||||
// refresh. Refresh now so the next node sees measured post-command readiness.
|
||||
if(op.control())resources.refresh();
|
||||
JSONObject output=JSONObject.parseObject(result.toString());
|
||||
if(op.control()) {
|
||||
String actual=prepared!=null?prepared.body().toString():input.getString("requestJson")==null?"{}":input.getString("requestJson");
|
||||
output.put("request",JSONObject.parseObject(actual));output.put("requestJson",actual);
|
||||
}
|
||||
output.put("responseJson",result.toString());
|
||||
ScannerFrameworkReferences.enrich(output,result);
|
||||
if(prepared!=null)output.put("frameworkTransfer",com.alibaba.fastjson2.JSON.parseArray(prepared.files().toString()));
|
||||
if(op.control()&&message.getInstId()!=null&&!message.getInstId().isBlank()) {
|
||||
String key=ScannerService.hash(JSONObject.toJSONString(java.util.Arrays.asList(message.getInstId(),message.getItemId(),message.getItemOrder(),message.getItemOccurrence(),message.getNodeId(),message.getIterations(),message.getSubFlowExecutionId())));
|
||||
try {
|
||||
var context=monitoring.capture(op,key,message.getInstId(),message.getRobotId(),input.getString("deviceId"));
|
||||
var context=monitoring.capture(op,key,message.getInstId(),message.getRobotId(),input.getString("deviceId"),message.getItemOrder(),message.getItemOccurrence());
|
||||
if(input.containsKey("expectedContextJson")&&context==null&&(op==ScannerOperation.SCAN_START||op==ScannerOperation.EXPORT))
|
||||
throw new ScannerException("binding_invalid","补扫未能关联实时画面或成果,请保留原工程并检查设备状态",409);
|
||||
if(context!=null)output.put("scannerContext",JSONObject.parseObject(context.toString()));
|
||||
|
||||
@ -41,49 +41,64 @@ public enum ActionEnum {
|
||||
// 设备行为
|
||||
DEVICE_EXECUTE_JSON_COMMAND("EDGE", "DEVICE_EXECUTE_JSON_COMMAND", "执行设备通用指令"),
|
||||
|
||||
SCANNER_INITIALIZE("EDGE", "SCANNER_INITIALIZE", "连接扫描仪"),
|
||||
SCANNER_INITIALIZE("EDGE", "SCANNER_INITIALIZE", "连接设备"),
|
||||
SCANNER_CREATE_PROJECT("EDGE", "SCANNER_CREATE_PROJECT", "创建扫描工程"),
|
||||
SCANNER_DISCONNECT("EDGE", "SCANNER_DISCONNECT", "断开扫描会话"),
|
||||
SCANNER_RECONNECT("EDGE", "SCANNER_RECONNECT", "重新连接扫描仪"),
|
||||
SCANNER_PREVIEW_START("EDGE", "SCANNER_PREVIEW_START", "开启扫描预览"),
|
||||
SCANNER_PREVIEW_STOP("EDGE", "SCANNER_PREVIEW_STOP", "关闭扫描预览"),
|
||||
SCANNER_DISCONNECT("EDGE", "SCANNER_DISCONNECT", "断开设备会话"),
|
||||
SCANNER_RECONNECT("EDGE", "SCANNER_RECONNECT", "结束旧会话并重新连接"),
|
||||
SCANNER_PREVIEW_START("EDGE", "SCANNER_PREVIEW_START", "开启渲染预览"),
|
||||
SCANNER_PREVIEW_STOP("EDGE", "SCANNER_PREVIEW_STOP", "关闭渲染预览"),
|
||||
SCANNER_START("EDGE", "SCANNER_START", "开始或继续采集"),
|
||||
SCANNER_STOP("EDGE", "SCANNER_STOP", "暂停采集"),
|
||||
SCANNER_PARAMETERS("EDGE", "SCANNER_PARAMETERS", "配置扫描参数"),
|
||||
SCANNER_STOP("EDGE", "SCANNER_STOP", "暂停采集并保留工程"),
|
||||
SCANNER_SCAN_TYPE("EDGE", "SCANNER_SCAN_TYPE", "选择采集类型或采集设备"),
|
||||
SCANNER_FRAMEWORK_IMPORT("EDGE", "SCANNER_FRAMEWORK_IMPORT", "导入已上传的标志点框架"),
|
||||
SCANNER_FRAMEWORK_OPTIMIZE("EDGE", "SCANNER_FRAMEWORK_OPTIMIZE", "优化已采集的摄影测量框架"),
|
||||
SCANNER_PARAMETERS("EDGE", "SCANNER_PARAMETERS", "修改扫描参数"),
|
||||
SCANNER_MESH("EDGE", "SCANNER_MESH", "生成网格预览"),
|
||||
SCANNER_MESH_CONFIRM("EDGE", "SCANNER_MESH_CONFIRM", "确认扫描网格"),
|
||||
SCANNER_MESH_UNDO("EDGE", "SCANNER_MESH_UNDO", "撤销扫描网格"),
|
||||
SCANNER_ALIGN("EDGE", "SCANNER_ALIGN", "扫描工程拼接"),
|
||||
SCANNER_EDIT("EDGE", "SCANNER_EDIT", "删除扫描点或标志点"),
|
||||
SCANNER_MESH_CONFIRM("EDGE", "SCANNER_MESH_CONFIRM", "确认网格"),
|
||||
SCANNER_MESH_UNDO("EDGE", "SCANNER_MESH_UNDO", "撤销网格"),
|
||||
SCANNER_ALIGN("EDGE", "SCANNER_ALIGN", "工程拼接"),
|
||||
SCANNER_EDIT("EDGE", "SCANNER_EDIT", "删除点或标志点"),
|
||||
SCANNER_CLIP_PLANE("EDGE", "SCANNER_CLIP_PLANE", "平面裁剪"),
|
||||
SCANNER_EXPORT("EDGE", "SCANNER_EXPORT", "导出扫描成果"),
|
||||
SCANNER_SNAPSHOT("EDGE", "SCANNER_SNAPSHOT", "保存原始场景快照"),
|
||||
SCANNER_SCENE("EDGE", "SCANNER_SCENE", "读取扫描场景摘要"),
|
||||
SCANNER_CALIBRATION_ENTER("EDGE", "SCANNER_CALIBRATION_ENTER", "进入扫描标定"),
|
||||
SCANNER_CALIBRATION_MODE("EDGE", "SCANNER_CALIBRATION_MODE", "设置标定模式"),
|
||||
SCANNER_CALIBRATION_START("EDGE", "SCANNER_CALIBRATION_START", "开始扫描标定"),
|
||||
SCANNER_EXPORT("EDGE", "SCANNER_EXPORT", "导出文件"),
|
||||
SCANNER_SNAPSHOT("EDGE", "SCANNER_SNAPSHOT", "创建原始场景快照"),
|
||||
SCANNER_SCENE("EDGE", "SCANNER_SCENE", "读取最近场景摘要"),
|
||||
SCANNER_CALIBRATION_ENTER("EDGE", "SCANNER_CALIBRATION_ENTER", "进入标定流程"),
|
||||
SCANNER_CALIBRATION_MODE("EDGE", "SCANNER_CALIBRATION_MODE", "选择标定模式"),
|
||||
SCANNER_CALIBRATION_START("EDGE", "SCANNER_CALIBRATION_START", "开始当前标定"),
|
||||
SCANNER_CALIBRATION_TRAK("EDGE", "SCANNER_CALIBRATION_TRAK", "设置跟踪仪标定类型"),
|
||||
SCANNER_CALIBRATION_SYSTEM("EDGE", "SCANNER_CALIBRATION_SYSTEM", "开始系统标定"),
|
||||
SCANNER_CALIBRATION_FREE("EDGE", "SCANNER_CALIBRATION_FREE", "设置自由标定"),
|
||||
SCANNER_CALIBRATION_FREE("EDGE", "SCANNER_CALIBRATION_FREE", "设置自由标定开关"),
|
||||
SCANNER_CALIBRATION_CAPTURE("EDGE", "SCANNER_CALIBRATION_CAPTURE", "采集标定姿态"),
|
||||
SCANNER_CALIBRATION_COMPUTE("EDGE", "SCANNER_CALIBRATION_COMPUTE", "计算自由标定结果"),
|
||||
SCANNER_CALIBRATION_ADVANCED("EDGE", "SCANNER_CALIBRATION_ADVANCED", "设置精细标定"),
|
||||
SCANNER_CALIBRATION_ADVANCED("EDGE", "SCANNER_CALIBRATION_ADVANCED", "设置精细标定开关"),
|
||||
SCANNER_CALIBRATION_APPLY_LAST("EDGE", "SCANNER_CALIBRATION_APPLY_LAST", "应用上次标定结果"),
|
||||
SCANNER_METADATA("EDGE", "SCANNER_METADATA", "读取扫描服务信息"),
|
||||
SCANNER_HEALTH("EDGE", "SCANNER_HEALTH", "检查扫描服务"),
|
||||
SCANNER_STATUS("EDGE", "SCANNER_STATUS", "读取扫描仪状态"),
|
||||
SCANNER_CAPABILITIES("EDGE", "SCANNER_CAPABILITIES", "读取扫描能力"),
|
||||
SCANNER_METRICS("EDGE", "SCANNER_METRICS", "读取预览指标"),
|
||||
SCANNER_WAIT("EDGE", "SCANNER_WAIT", "等待扫描设备任务"),
|
||||
SCANNER_METADATA("EDGE", "SCANNER_METADATA", "查询公开服务元数据"),
|
||||
SCANNER_HEALTH("EDGE", "SCANNER_HEALTH", "健康检查"),
|
||||
SCANNER_STATUS("EDGE", "SCANNER_STATUS", "读取设备和工程状态"),
|
||||
SCANNER_CAPABILITIES("EDGE", "SCANNER_CAPABILITIES", "读取当前功能能力"),
|
||||
SCANNER_METRICS("EDGE", "SCANNER_METRICS", "读取图像编码与缓存指标"),
|
||||
SCANNER_WAIT("EDGE", "SCANNER_WAIT", "查询异步任务"),
|
||||
SCANNER_BATTERY("EDGE", "SCANNER_BATTERY", "读取扫描仪和跟踪仪电量"),
|
||||
SCANNER_SUPPLEMENT_PREPARE("EDGE", "SCANNER_SUPPLEMENT_PREPARE", "核对原工程并准备补扫"),
|
||||
SCANNER_SUPPLEMENT_WAIT("EDGE", "SCANNER_SUPPLEMENT_WAIT", "补扫采集,等待结束或到时"),
|
||||
MOTOR_ENABLE("EDGE", "MOTOR_ENABLE", "电机使能"),
|
||||
MOTOR_DISABLE("EDGE", "MOTOR_DISABLE", "电机去使能"),
|
||||
MOTOR_SET_MODE("EDGE", "MOTOR_SET_MODE", "设置模式"),
|
||||
MOTOR_VELOCITY("EDGE", "MOTOR_VELOCITY", "轮廓速度控制"),
|
||||
MOTOR_ENABLE("EDGE", "MOTOR_ENABLE", "使能"),
|
||||
MOTOR_DISABLE("EDGE", "MOTOR_DISABLE", "去使能"),
|
||||
MOTOR_HOME("EDGE", "MOTOR_HOME", "电机回零"),
|
||||
MOTOR_MOVE("EDGE", "MOTOR_MOVE", "电机定位"),
|
||||
MOTOR_MOVE("EDGE", "MOTOR_MOVE", "轮廓位置控制"),
|
||||
MOTOR_WAIT("EDGE", "MOTOR_WAIT", "等待电机到位"),
|
||||
MOTOR_STOP("EDGE", "MOTOR_STOP", "停止电机"),
|
||||
MOTOR_STATUS("EDGE", "MOTOR_STATUS", "读取电机状态"),
|
||||
MOTOR_LIST("EDGE", "MOTOR_LIST", "ListMotors"),
|
||||
MOTOR_GET_INFO("EDGE", "MOTOR_GET_INFO", "GetInfo"),
|
||||
MOTOR_GET_STATE("EDGE", "MOTOR_GET_STATE", "GetState"),
|
||||
MOTOR_GET_MODE("EDGE", "MOTOR_GET_MODE", "getMode"),
|
||||
MOTOR_GET_Q("EDGE", "MOTOR_GET_Q", "getQ"),
|
||||
MOTOR_GET_QD("EDGE", "MOTOR_GET_QD", "getQd"),
|
||||
MOTOR_REACHED_TARGET("EDGE", "MOTOR_REACHED_TARGET", "reachedTargetQ"),
|
||||
MOTOR_QUICK_STOP("EDGE", "MOTOR_QUICK_STOP", "quickStop"),
|
||||
MOTOR_HOMING("EDGE", "MOTOR_HOMING", "自动机械回零"),
|
||||
|
||||
// ---------------相机---------------
|
||||
CAMERA_START("EDGE", "CAMERA_START", "启动相机"),
|
||||
@ -114,6 +129,17 @@ public enum ActionEnum {
|
||||
ARM_ENABLE("EDGE", "ARM_ENABLE", "使能"),
|
||||
// 停止使能
|
||||
ARM_DISABLE("EDGE", "ARM_DISABLE", "停止使能"),
|
||||
ARM_ENTER_TEACHING_MODE("EDGE", "ARM_ENTER_TEACHING_MODE", "进入拖动示教"),
|
||||
ARM_START_TRAJECTORY_RECORDING("EDGE", "ARM_START_TRAJECTORY_RECORDING", "开始录制轨迹"),
|
||||
ARM_STOP_TRAJECTORY_RECORDING("EDGE", "ARM_STOP_TRAJECTORY_RECORDING", "停止并保存记录"),
|
||||
ARM_EXIT_TEACHING_MODE("EDGE", "ARM_EXIT_TEACHING_MODE", "退出拖动示教"),
|
||||
ARM_COMPLETE_TEACHING("EDGE", "ARM_COMPLETE_TEACHING", "完成示教"),
|
||||
ARM_LIST_RECORDED_TRAJECTORIES("EDGE", "ARM_LIST_RECORDED_TRAJECTORIES", "查询轨迹及录制状态"),
|
||||
ARM_MOVE_TO_TRAJECTORY_START("EDGE", "ARM_MOVE_TO_TRAJECTORY_START", "低速运动到起点"),
|
||||
ARM_REPLAY_RECORDED_TRAJECTORY("EDGE", "ARM_REPLAY_RECORDED_TRAJECTORY", "平滑回放所选轨迹"),
|
||||
ARM_GET_ARM_INFO("EDGE", "ARM_GET_ARM_INFO", "查询机械臂信息"),
|
||||
ARM_GET_ROBOT_STATE("EDGE", "ARM_GET_ROBOT_STATE", "读取完整机械臂状态"),
|
||||
ARM_STOP_MOTION("EDGE", "ARM_STOP_MOTION", "停止机械臂运动"),
|
||||
|
||||
// --------------- 头部 ---------------
|
||||
BIO_HEAD_SPEAK_START("EDGE", "BIO_HEAD_SPEAK_START", "开始说话"),
|
||||
|
||||
@ -311,4 +311,24 @@ public class FlowGraph {
|
||||
public boolean isBreakLoop() {
|
||||
return stopLoop;
|
||||
}
|
||||
|
||||
/** A branch prunes its running graph; each loop iteration needs its own graph. */
|
||||
public FlowGraph copyForIteration() {
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
FlowGraph copy = new FlowGraph();
|
||||
copy.setSub(isSub());
|
||||
copy.setStartInputParamsDefs(new ArrayList<>(startInputParamsDefs));
|
||||
nodeParamsDefs.forEach((id, params) -> copy.nodeParamsDefs.put(id, params == null ? List.of() : new ArrayList<>(params)));
|
||||
nodeMap.forEach((id, node) -> {
|
||||
FlowNodeWrapper duplicate = new FlowNodeWrapper();
|
||||
cn.hutool.core.bean.BeanUtil.copyProperties(node, duplicate);
|
||||
if (node.getSubGraph() != null) duplicate.setSubGraph(node.getSubGraph().copyForIteration());
|
||||
copy.nodeMap.put(id, duplicate);
|
||||
});
|
||||
successors.values().forEach(edges -> edges.forEach(edge -> copy.addEdge(new FlowEdge(
|
||||
edge.getFrom(), edge.getTo(), edge.getFromAnchorId(), edge.getCondition()))));
|
||||
return copy;
|
||||
} finally { lock.readLock().unlock(); }
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
package com.cmvr.test.flow.context;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ObjUtil;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.cmvr.test.enums.RunModeEnum;
|
||||
import com.cmvr.test.enums.TaskStatusEnum;
|
||||
@ -94,6 +93,8 @@ public class TaskContext {
|
||||
|
||||
/** All assigned devices acknowledged stop and interrupted nodes have exited. */
|
||||
private volatile boolean deviceStopConfirmed = false;
|
||||
/** Fresh confirmation collected by failure cleanup; never reuse pause/stop acknowledgements. */
|
||||
private volatile boolean failureCleanupConfirmed = false;
|
||||
|
||||
/**
|
||||
* 是否锁定终端(标识该终端是否被占用)
|
||||
@ -151,8 +152,12 @@ public class TaskContext {
|
||||
* 获取节点输出
|
||||
*/
|
||||
public JSONObject getNodeOutput(String nodeId, List<Integer> iterations) {
|
||||
return scopedParams(nodeOutputs, nodeId, iterations);
|
||||
}
|
||||
|
||||
private JSONObject scopedParams(Map<String, JSONObject> values, String nodeId, List<Integer> iterations) {
|
||||
if (CollUtil.isEmpty(iterations)) {
|
||||
return nodeOutputs.get(TaskKeyBuilder.buildKey(nodeId, Collections.emptyList()));
|
||||
return values.get(TaskKeyBuilder.buildKey(nodeId, Collections.emptyList()));
|
||||
}
|
||||
|
||||
// 从完整 iterations 开始逐级回退
|
||||
@ -160,8 +165,8 @@ public class TaskContext {
|
||||
List<Integer> subIterations = iterations.subList(0, i);
|
||||
String key = TaskKeyBuilder.buildKey(nodeId, subIterations);
|
||||
|
||||
JSONObject result = nodeOutputs.get(key);
|
||||
if (ObjUtil.isNotEmpty(result)) {
|
||||
JSONObject result = values.get(key);
|
||||
if (result != null) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@ -173,7 +178,15 @@ public class TaskContext {
|
||||
* 保存节点输入
|
||||
*/
|
||||
public void setNodeInput(String nodeId, JSONObject outputParams) {
|
||||
nodeOutputs.put(nodeId, outputParams != null ? outputParams : new JSONObject());
|
||||
setNodeInput(nodeId, Collections.emptyList(), outputParams);
|
||||
}
|
||||
|
||||
public void setNodeInput(String nodeId, List<Integer> iterations, JSONObject inputParams) {
|
||||
nodeInputs.put(TaskKeyBuilder.buildKey(nodeId, iterations), inputParams != null ? new JSONObject(inputParams) : new JSONObject());
|
||||
updateTimestamp();
|
||||
}
|
||||
|
||||
public JSONObject getNodeInput(String nodeId, List<Integer> iterations) {
|
||||
return scopedParams(nodeInputs, nodeId, iterations);
|
||||
}
|
||||
}
|
||||
|
||||
@ -60,7 +60,8 @@ public class TaskContextManager {
|
||||
// sufficient to release its native lease. Failed/uncertain cleanup
|
||||
// keeps the durable STOP_PENDING lease for explicit confirmation.
|
||||
boolean safeToRelease = ctx.getStatus() == TaskStatusEnum.SUCCESS
|
||||
|| (ctx.getStatus() == TaskStatusEnum.STOPPED && ctx.isDeviceStopConfirmed());
|
||||
|| (ctx.getStatus() == TaskStatusEnum.STOPPED && ctx.isDeviceStopConfirmed())
|
||||
|| (ctx.getStatus() == TaskStatusEnum.FAILED && ctx.isFailureCleanupConfirmed());
|
||||
if(occupationGuards!=null)occupationGuards.orderedStream().forEach(guard -> guard.release(instId,safeToRelease));
|
||||
// Keep context and in-memory locks if the durable release failed.
|
||||
instContextMap.remove(instId, ctx);
|
||||
|
||||
@ -131,9 +131,14 @@ public class TaskInstHolder {
|
||||
// 终止和并发失败都可能先注销上下文,失败状态仍需落库。
|
||||
TaskContext ctx = taskContextManager.get(instId);
|
||||
if (ctx != null) {
|
||||
// 先关闭执行入口,避免设备清理期间又调度新的节点。
|
||||
ctx.setStopped(true);
|
||||
ctx.setStatus(TaskStatusEnum.FAILED);
|
||||
synchronized(ctx) {
|
||||
// Concurrent failing nodes share one cleanup. Never overwrite an
|
||||
// operator's stop or wait for sibling nodes while holding this lock.
|
||||
if(ctx.isStopped())return;
|
||||
ctx.setStopped(true);
|
||||
ctx.setStatus(TaskStatusEnum.FAILED);
|
||||
ctx.setFailureCleanupConfirmed(false);
|
||||
}
|
||||
}
|
||||
if (taskThreadRegistry != null) {
|
||||
// 唤醒所有嵌套循环并中断其他执行节点,让失败立即收敛到整个实例。
|
||||
@ -141,7 +146,7 @@ public class TaskInstHolder {
|
||||
}
|
||||
String moduleCode = ctx != null ? ctx.getModuleCode() : null;
|
||||
if (ctx != null && flowFailureCleanupService != null) {
|
||||
flowFailureCleanupService.cleanup(ctx);
|
||||
ctx.setFailureCleanupConfirmed(flowFailureCleanupService.cleanup(ctx));
|
||||
}
|
||||
nodeInstService.failUnfinished(instId, "任务因节点失败而结束:" + message);
|
||||
syncStatus(instId, TaskStatusEnum.FAILED);
|
||||
|
||||
@ -79,7 +79,7 @@ public class FlowControlService {
|
||||
}
|
||||
synchronized (ctx) {
|
||||
if (ctx.isStopped()) {
|
||||
if (!ctx.isDeviceStopConfirmed()) throw stopUnconfirmed();
|
||||
if (!(ctx.getStatus()==TaskStatusEnum.FAILED?ctx.isFailureCleanupConfirmed():ctx.isDeviceStopConfirmed())) throw stopUnconfirmed();
|
||||
// Retry a previously failed durable release without issuing another stop.
|
||||
taskInstHolder.unRegister(instId);
|
||||
return;
|
||||
|
||||
@ -4,6 +4,8 @@ import com.cmvr.edge.client.service.EdgeCameraService;
|
||||
import com.cmvr.edge.client.service.EdgeMicrophoneService;
|
||||
import com.cmvr.edge.client.service.EdgeSystemService;
|
||||
import com.cmvr.test.flow.context.TaskContext;
|
||||
import com.cmvr.test.flow.context.TaskThreadRegistry;
|
||||
import com.cmvr.test.enums.NodeTypeEnum;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
@ -11,6 +13,7 @@ import org.springframework.stereotype.Component;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Cleans device-side and backend-local media state when a flow fails unexpectedly.
|
||||
@ -23,38 +26,72 @@ public class FlowFailureCleanupService {
|
||||
private final EdgeMicrophoneService edgeMicrophoneService;
|
||||
private final EdgeCameraService edgeCameraService;
|
||||
private final EdgeSystemService edgeSystemService;
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private TaskThreadRegistry threads;
|
||||
@org.springframework.beans.factory.annotation.Autowired(required=false)
|
||||
private List<FlowDeviceLifecycleExtension> deviceLifecycle=List.of();
|
||||
|
||||
public void cleanup(TaskContext context) {
|
||||
public boolean cleanup(TaskContext context) {
|
||||
if (context == null) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
context.setStopped(true);
|
||||
List<String> robotIds = context.getRobotIds() == null || context.getRobotIds().isEmpty()
|
||||
? Collections.singletonList(context.getRobotId())
|
||||
: context.getRobotIds();
|
||||
robotIds.stream()
|
||||
boolean confirmed=true;
|
||||
for(String robotId:robotIds.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(String::trim)
|
||||
.filter(robotId -> !robotId.isEmpty())
|
||||
.distinct()
|
||||
.forEach(this::cleanupRobot);
|
||||
.distinct().toList()) {
|
||||
if(!cleanupRobot(robotId))confirmed=false;
|
||||
}
|
||||
// The caller is the already-failed node; waiting on itself would deadlock.
|
||||
// All other interrupted SDK-capable nodes must finish before reuse.
|
||||
if(!waitForOtherNodes(context.getInstId()))confirmed=false;
|
||||
for(var extension:deviceLifecycle) {
|
||||
try {extension.afterStop(context.getInstId());}
|
||||
catch(RuntimeException error){confirmed=false;log.warn("失败任务设备会话清理未确认: instId={}, error={}",context.getInstId(),error.getMessage());}
|
||||
}
|
||||
return confirmed;
|
||||
}
|
||||
|
||||
private void cleanupRobot(String robotId) {
|
||||
private boolean cleanupRobot(String robotId) {
|
||||
boolean confirmed=true;
|
||||
try {
|
||||
edgeMicrophoneService.abortWorkflowRecordings(robotId);
|
||||
} catch (RuntimeException exception) {
|
||||
confirmed=false;
|
||||
log.warn("清理失败任务录音会话失败: robotId={}, error={}", robotId, exception.getMessage());
|
||||
}
|
||||
try {
|
||||
edgeCameraService.abortWorkflowRecordings(robotId);
|
||||
} catch (RuntimeException exception) {
|
||||
confirmed=false;
|
||||
log.warn("清理失败任务录像会话失败: robotId={}, error={}", robotId, exception.getMessage());
|
||||
}
|
||||
try {
|
||||
edgeSystemService.stopAll(robotId);
|
||||
} catch (RuntimeException exception) {
|
||||
confirmed=false;
|
||||
log.warn("停止失败任务设备失败: robotId={}, error={}", robotId, exception.getMessage());
|
||||
}
|
||||
return confirmed;
|
||||
}
|
||||
private boolean waitForOtherNodes(String instId) {
|
||||
if(threads==null)return false;
|
||||
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(30);
|
||||
for(var pending:threads.getPendingNodes(instId)) {
|
||||
if(pending.getThread()==Thread.currentThread())continue;
|
||||
if(pending.getNode()!=null&&pending.getNode().getNodeType()==NodeTypeEnum.LOOP)continue;
|
||||
long remaining=deadline-System.nanoTime();
|
||||
try {
|
||||
if(remaining<=0||!pending.awaitExecutionFinished(remaining,TimeUnit.NANOSECONDS)) {
|
||||
log.warn("失败清理等待旧节点退出未确认: instId={}",instId);return false;
|
||||
}
|
||||
}catch(InterruptedException error){Thread.currentThread().interrupt();return false;}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -47,8 +47,8 @@ public class FlowLoopNodeHandler implements FlowNodeTypeHandler {
|
||||
log.warn("循环节点 {} 没有有效的 loopCount 参数,跳过处理", nodeId);
|
||||
return TaskNodeExecuteResult.success(inputParams);
|
||||
}
|
||||
FlowGraph subGraph = nodeWrapper.getSubGraph();
|
||||
subGraph.setSub(true);
|
||||
FlowGraph template = nodeWrapper.getSubGraph();
|
||||
FlowGraph subGraph = null;
|
||||
|
||||
// 循环执行子图
|
||||
for (int i = loopStartNum; i <= loopCount; i++) {
|
||||
@ -58,7 +58,7 @@ public class FlowLoopNodeHandler implements FlowNodeTypeHandler {
|
||||
break;
|
||||
}
|
||||
// 如果子图设置了跳出标志,则结束循环
|
||||
if (subGraph.isBreakLoop()) {
|
||||
if (subGraph != null && subGraph.isBreakLoop()) {
|
||||
log.info("检测到子图设置跳出标志,提前结束循环:instId={}, nodeId={}", instId, nodeId);
|
||||
break;
|
||||
}
|
||||
@ -78,6 +78,8 @@ public class FlowLoopNodeHandler implements FlowNodeTypeHandler {
|
||||
subMessage.setIterations(newIterations); // 完整路径
|
||||
subMessage.setLoopArray(loopArray);
|
||||
|
||||
subGraph = template.copyForIteration();
|
||||
subGraph.setSub(true);
|
||||
flowItemExecutor.executeSubGraph(subGraph, subMessage, latch::countDown, newIterations);
|
||||
|
||||
try {
|
||||
|
||||
@ -0,0 +1,33 @@
|
||||
package com.cmvr.test.flow.runtime.engine;
|
||||
import com.alibaba.fastjson2.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Explicit, typed transfers between completed cases; never merge node outputs implicitly. */
|
||||
public final class FlowPlanInputs {
|
||||
private FlowPlanInputs(){}
|
||||
public static JSONObject resolve(JSONObject input,Map<Integer,JSONObject> completed){
|
||||
JSONObject result=input==null?new JSONObject():JSON.parseObject(input.toJSONString());
|
||||
JSONArray bindings=result.getJSONArray("_planBindings");
|
||||
if(bindings!=null)for(int i=0;i<bindings.size();i++){
|
||||
JSONObject b=bindings.getJSONObject(i);Object value=completed.get(b.getIntValue("sourceOrder"));
|
||||
for(String part:b.getString("path").split("\\.")){
|
||||
if(value instanceof Map<?,?> m)value=m.get(part);
|
||||
else if(value instanceof List<?> list&&part.matches("[0-9]+")){int n=Integer.parseInt(part);value=n<list.size()?list.get(n):null;}
|
||||
else value=null;
|
||||
}
|
||||
if(value==null)throw new IllegalArgumentException("上游用例未返回参数:"+b.getString("path"));
|
||||
result.put(b.getString("target"),JSON.parse(JSON.toJSONString(value)));
|
||||
}
|
||||
String schema=result.getString("_planInputSchema");
|
||||
result.remove("_planBindings");result.remove("_planInputSchema");
|
||||
if(schema!=null&&!schema.isBlank())validate(JSON.parseArray(schema),result,"");return result;
|
||||
}
|
||||
private static void validate(JSONArray fields,Map<String,Object> values,String prefix){
|
||||
for(int i=0;i<fields.size();i++){
|
||||
JSONObject f=fields.getJSONObject(i);String name=f.getString("name");if(name==null)continue;Object v=values.get(name);String type=Objects.toString(f.getString("type"),"").toLowerCase(Locale.ROOT);
|
||||
if(Boolean.TRUE.equals(f.getBoolean("required"))&&(v==null||v instanceof String s&&s.isBlank()))throw new IllegalArgumentException("缺少运行参数:"+prefix+name);
|
||||
if(v!=null&&(("string".equals(type)&&!(v instanceof String))||("number".equals(type)&&!(v instanceof Number))||("boolean".equals(type)&&!(v instanceof Boolean))||("object".equals(type)&&!(v instanceof Map))||(type.contains("array")&&!(v instanceof List))))throw new IllegalArgumentException("运行参数类型不匹配:"+prefix+name);
|
||||
if(v instanceof Map&&f.getJSONArray("children")!=null)validate(f.getJSONArray("children"),(Map<String,Object>)v,prefix+name+".");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -39,6 +39,12 @@ public class FlowRuntimeDefinitionValidator {
|
||||
JSONObject p = nodes.getJSONObject(i).getJSONObject("properties");
|
||||
if (p == null) continue;
|
||||
ActionEnum action = ActionEnum.fromAction(p.getString("action"));
|
||||
var teaching=com.cmvr.arm.ArmTeachingOperation.forAction(action);
|
||||
if(teaching!=null) {
|
||||
try{com.cmvr.arm.ArmTeachingParameters.validateLiterals(teaching,p.getJSONArray("nodeParams"));}
|
||||
catch(RuntimeException error){throw new GlobalException("节点["+p.getString("name")+"]参数错误:"+error.getMessage());}
|
||||
continue;
|
||||
}
|
||||
if (!WorkcellNodeContract.supports(action)) continue;
|
||||
try { WorkcellNodeContract.validateLiterals(action, p.getJSONArray("nodeParams")); }
|
||||
catch (RuntimeException error) {
|
||||
@ -140,6 +146,12 @@ public class FlowRuntimeDefinitionValidator {
|
||||
throw new GlobalException("节点[" + properties.getString("name") + "]引用了不存在的设备用途");
|
||||
}
|
||||
ActionEnum action = ActionEnum.fromAction(properties.getString("action"));
|
||||
if(com.cmvr.arm.ArmTeachingOperation.forAction(action)!=null) {
|
||||
if(StrUtil.isBlank(deviceSlotKey))throw new GlobalException("机械臂示教/轨迹节点必须绑定机械臂设备用途");
|
||||
JSONObject role=roles.stream().map(JSONObject.class::cast).filter(item->roleKey.equals(item.getString("roleKey"))).findFirst().orElseThrow();
|
||||
JSONObject slot=role.getJSONArray("deviceSlots").stream().map(JSONObject.class::cast).filter(item->deviceSlotKey.equals(item.getString("slotKey"))).findFirst().orElseThrow();
|
||||
if(!Integer.valueOf(2).equals(slot.getInteger("deviceKind")))throw new GlobalException("机械臂示教/轨迹节点必须绑定机械臂设备用途");
|
||||
}
|
||||
if (WorkcellNodeContract.supports(action)) {
|
||||
if (StrUtil.isBlank(deviceSlotKey)) throw new GlobalException("扫描仪或电机节点必须选择设备用途");
|
||||
JSONObject role = roles.stream().map(JSONObject.class::cast)
|
||||
@ -180,7 +192,7 @@ public class FlowRuntimeDefinitionValidator {
|
||||
}
|
||||
RobotDeviceAssignmentValidator validator = deviceValidatorProvider.getIfAvailable();
|
||||
if (validator != null) {
|
||||
validator.validate(member.getRobotId(), deviceId, expectedKind);
|
||||
validator.validateAssignment(member.getRobotId(), deviceId, expectedKind);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -39,6 +39,7 @@ public class FlowTaskEngine {
|
||||
|
||||
int totalItemCount = items.size();
|
||||
Map<String, Integer> itemOccurrences = new HashMap<>();
|
||||
Map<Integer,JSONObject> completedOutputs=new HashMap<>();
|
||||
|
||||
for (int i = 0; i < totalItemCount; i++) {
|
||||
// Scheduler deduplication is scoped to one orchestration item. Different
|
||||
@ -76,8 +77,11 @@ public class FlowTaskEngine {
|
||||
jsonObject = runParams.getJSONObject(itemId);
|
||||
}
|
||||
if (!runMode.equals(RunModeEnum.TRIAL)) {
|
||||
try { jsonObject=FlowPlanInputs.resolve(jsonObject,completedOutputs); }
|
||||
catch(RuntimeException error){taskInstHolder.markFailed(instId,taskId,itemId,"plan-input-"+itemOrder,"START","SYSTEM","NONE",null,"组合步骤参数校验失败:"+error.getMessage(),List.of());break;}
|
||||
context.setRunParams(jsonObject);
|
||||
}
|
||||
context.getNodeInputs().clear();context.getNodeOutputs().clear();
|
||||
flowTaskExecutor.executeGraph(message, item, latch::countDown);
|
||||
try {
|
||||
latch.await(); // 等待该检测项的子流程全部完成
|
||||
@ -91,6 +95,10 @@ public class FlowTaskEngine {
|
||||
if (context == null || context.isStopped()) {
|
||||
break;
|
||||
}
|
||||
JSONObject outputs=new JSONObject();
|
||||
var nodes=JSONObject.parseObject(item.getFlowData()).getJSONArray("nodes");
|
||||
if(nodes!=null)for(int n=0;n<nodes.size();n++){var node=nodes.getJSONObject(n);if("end".equalsIgnoreCase(node.getString("type"))){var out=context.getNodeOutput(node.getString("id"),List.of());if(out!=null)outputs.putAll(out);}}
|
||||
completedOutputs.put(itemOrder,outputs);
|
||||
}
|
||||
} finally {
|
||||
flowTaskScheduler.clear(instId);
|
||||
|
||||
@ -5,4 +5,7 @@ public interface RobotDeviceAssignmentValidator {
|
||||
|
||||
void validate(String robotId, String deviceId, Integer expectedDeviceKind);
|
||||
|
||||
default void validateAssignment(String robotId,String deviceId,Integer expectedDeviceKind) {validate(robotId,deviceId,expectedDeviceKind);}
|
||||
default void validateForAction(String robotId,String deviceId,Integer expectedDeviceKind,com.cmvr.test.enums.ActionEnum action) {validate(robotId,deviceId,expectedDeviceKind);}
|
||||
|
||||
}
|
||||
|
||||
@ -7,4 +7,6 @@ public interface RobotTaskOccupationGuard {
|
||||
/** Release only after successful completion or confirmed stop; otherwise retain a pending lease. */
|
||||
default void release(String instId, boolean safeToRelease) {}
|
||||
default AutoCloseable manual(String robotId) { check(robotId,null);return ()->{}; }
|
||||
/** Configuration needs the same operation gate without creating a physical-operation lease. */
|
||||
default AutoCloseable configuration(String robotId) { check(robotId,null);return ()->{}; }
|
||||
}
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
package com.cmvr.test.flow.runtime.engine.support;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ObjUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.cmvr.test.enums.BranchConditionOpEnum;
|
||||
@ -13,6 +12,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 分支节点条件匹配器
|
||||
@ -26,33 +26,14 @@ public class FlowBranchEvaluator {
|
||||
* 如果都不满足,返回默认的 else 出口
|
||||
*/
|
||||
public static String evaluate(TaskContext taskContext, List<Integer> iterations, String nodeId, List<FlowBranchConditionGroup> groups, JSONObject inputParams) {
|
||||
// 先合并上游输出参数
|
||||
mergeParams(taskContext,iterations, inputParams, groups);
|
||||
for (FlowBranchConditionGroup group : groups) {
|
||||
if (matchGroup(group, inputParams)) {
|
||||
if (matchGroup(group, taskContext, iterations)) {
|
||||
return group.getId();
|
||||
}
|
||||
}
|
||||
return nodeId + "_else";
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取分支节点引用节点的输出参数,并合并到当前计算参数列表中
|
||||
*/
|
||||
private static void mergeParams(TaskContext taskContext, List<Integer> iterations, JSONObject inputParams, List<FlowBranchConditionGroup> groups) {
|
||||
if (CollUtil.isEmpty(taskContext.getNodeOutputs())) {
|
||||
return;
|
||||
}
|
||||
Set<String> quoteIds = referencedNodeIds(groups);
|
||||
for (String quoteId : quoteIds) {
|
||||
JSONObject nodeOutput = taskContext.getNodeOutput(quoteId, iterations);
|
||||
if (ObjUtil.isNotEmpty(nodeOutput)) {
|
||||
// 合并进inputParams
|
||||
inputParams.putAll(nodeOutput);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns upstream node IDs referenced by branch expressions.
|
||||
*/
|
||||
@ -82,11 +63,10 @@ public class FlowBranchEvaluator {
|
||||
/**
|
||||
* 匹配某个条件组是否成立
|
||||
*/
|
||||
private static boolean matchGroup(FlowBranchConditionGroup group, JSONObject context) {
|
||||
private static boolean matchGroup(FlowBranchConditionGroup group, TaskContext context, List<Integer> iterations) {
|
||||
boolean isAnd = "and".equalsIgnoreCase(group.getWithOr());
|
||||
|
||||
for (FlowBranchConditionGroup.ConditionExpression expr : group.getExpressions()) {
|
||||
boolean result = matchExpr(expr, context);
|
||||
boolean result = matchExpr(expr, context, iterations);
|
||||
|
||||
if (!isAnd && result) {
|
||||
return true;
|
||||
@ -102,12 +82,12 @@ public class FlowBranchEvaluator {
|
||||
/**
|
||||
* 匹配单个表达式是否成立
|
||||
*/
|
||||
private static boolean matchExpr(FlowBranchConditionGroup.ConditionExpression expr, JSONObject context) {
|
||||
private static boolean matchExpr(FlowBranchConditionGroup.ConditionExpression expr, TaskContext context, List<Integer> iterations) {
|
||||
// 取左值:
|
||||
Object left;
|
||||
if ("quote".equalsIgnoreCase(expr.getNameType()) && expr.getNameQuotePath() != null) {
|
||||
// 如果时引用类型,取其引用字段的值
|
||||
left = resolveQuotePath(context, expr.getNameQuotePath());
|
||||
left = resolveQuotePath(context, iterations, expr.getNameQuotePath());
|
||||
} else {
|
||||
// 如果是输入类型,取其输入的值
|
||||
left = expr.getName();
|
||||
@ -116,7 +96,7 @@ public class FlowBranchEvaluator {
|
||||
// 取右值:可以是常量值,也可以是引用路径值
|
||||
String right;
|
||||
if ("quote".equalsIgnoreCase(expr.getValueType()) && expr.getQuotePath() != null) {
|
||||
right = resolveQuotePath(context, expr.getQuotePath());
|
||||
right = resolveQuotePath(context, iterations, expr.getQuotePath());
|
||||
} else {
|
||||
right = expr.getInput();
|
||||
}
|
||||
@ -127,25 +107,25 @@ public class FlowBranchEvaluator {
|
||||
// 执行比较逻辑
|
||||
switch (op) {
|
||||
case EQUAL:
|
||||
return Objects.equals(String.valueOf(left), right);
|
||||
return Objects.equals(left == null ? null : String.valueOf(left), right);
|
||||
case NOT_EQUAL:
|
||||
return !Objects.equals(String.valueOf(left), right);
|
||||
return !Objects.equals(left == null ? null : String.valueOf(left), right);
|
||||
case NULL:
|
||||
return left == null;
|
||||
case NOT_NULL:
|
||||
return left != null;
|
||||
case INCLUDE:
|
||||
return left != null && String.valueOf(left).contains(right);
|
||||
return left != null && right != null && String.valueOf(left).contains(right);
|
||||
case NOT_INCLUDE:
|
||||
return left != null && !String.valueOf(left).contains(right);
|
||||
return left != null && right != null && !String.valueOf(left).contains(right);
|
||||
case GREATER_THAN:
|
||||
return compare(left, right) > 0;
|
||||
return compare(left, right) != null && compare(left, right) > 0;
|
||||
case GREATER_THAN_OR_EQUAL:
|
||||
return compare(left, right) >= 0;
|
||||
return compare(left, right) != null && compare(left, right) >= 0;
|
||||
case LESS_THAN:
|
||||
return compare(left, right) < 0;
|
||||
return compare(left, right) != null && compare(left, right) < 0;
|
||||
case LESS_THAN_OR_EQUAL:
|
||||
return compare(left, right) <= 0;
|
||||
return compare(left, right) != null && compare(left, right) <= 0;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
@ -154,17 +134,24 @@ public class FlowBranchEvaluator {
|
||||
/**
|
||||
* 按引用路径从上下文中递归获取目标值
|
||||
*/
|
||||
private static String resolveQuotePath(JSONObject context, List<String> path) {
|
||||
if (path == null || path.size() < 2) {
|
||||
private static String resolveQuotePath(TaskContext context, List<Integer> iterations, List<String> path) {
|
||||
if (context == null || path == null || path.size() < 3) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Object current = context;
|
||||
// Resolve each side independently by node identity and this iteration's
|
||||
// path. Flattening outputs loses node identity and overwrites same-name fields.
|
||||
Object current = "input".equalsIgnoreCase(path.get(1))
|
||||
? context.getNodeInput(path.get(0), iterations)
|
||||
: "output".equalsIgnoreCase(path.get(1)) ? context.getNodeOutput(path.get(0), iterations) : null;
|
||||
for (int i = 2; i < path.size(); i++) {
|
||||
if (current instanceof JSONObject) {
|
||||
current = ((JSONObject) current).get(path.get(i));
|
||||
} else if (current instanceof Map) {
|
||||
current = ((Map<?, ?>) current).get(path.get(i));
|
||||
} else if (current instanceof List<?> values) {
|
||||
try { int index = Integer.parseInt(path.get(i)); current = index >= 0 && index < values.size() ? values.get(index) : null; }
|
||||
catch (NumberFormatException error) { return null; }
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
@ -176,13 +163,11 @@ public class FlowBranchEvaluator {
|
||||
/**
|
||||
* 数值比较
|
||||
*/
|
||||
private static int compare(Object left, String right) {
|
||||
private static Integer compare(Object left, String right) {
|
||||
try {
|
||||
double leftValue = Double.parseDouble(String.valueOf(left));
|
||||
double rightValue = Double.parseDouble(right);
|
||||
return Double.compare(leftValue, rightValue);
|
||||
return new BigDecimal(String.valueOf(left)).compareTo(new BigDecimal(right));
|
||||
} catch (Exception e) {
|
||||
return 0;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -6,6 +6,8 @@ import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.cmvr.common.exception.GlobalException;
|
||||
import com.cmvr.scanner.ScannerParameterOverrides;
|
||||
import com.cmvr.test.enums.ActionEnum;
|
||||
import com.cmvr.test.enums.NodeTypeEnum;
|
||||
import com.cmvr.test.enums.ParamScope;
|
||||
import com.cmvr.test.flow.builder.FlowGraph;
|
||||
@ -63,6 +65,14 @@ public class FlowNodeParamPreparer {
|
||||
input.put("loopNum", loopCount);
|
||||
}
|
||||
|
||||
if(node.getAction()!=null) {
|
||||
var scanner=com.cmvr.scanner.ScannerOperation.forAction(node.getAction().getAction());
|
||||
if(scanner!=null)input=com.cmvr.scanner.ScannerRequestComposer.resolve(scanner,input);
|
||||
}
|
||||
if(node.getAction()==ActionEnum.SCANNER_PARAMETERS)
|
||||
return ScannerParameterOverrides.apply(input,effectiveRunParams(rootMessage,ctx));
|
||||
if(node.getAction()==ActionEnum.SCANNER_FRAMEWORK_IMPORT)
|
||||
return com.cmvr.scanner.ScannerFixtureFrameworkBinding.apply(input,effectiveRunParams(rootMessage,ctx));
|
||||
return input;
|
||||
}
|
||||
|
||||
@ -112,12 +122,15 @@ public class FlowNodeParamPreparer {
|
||||
// 2.1 引用上游输入参数
|
||||
if ("input".equalsIgnoreCase(param.getQuoteType())) {
|
||||
FlowNodeWrapper referencedNode = graph.getNode(refNodeId);
|
||||
List<FlowParamDef> referencedDefs = referencedNode != null
|
||||
&& referencedNode.getNodeType() == NodeTypeEnum.START
|
||||
? graph.getStartInputParamsDefs()
|
||||
: graph.getNodeParamsDefs().get(refNodeId);
|
||||
source = toJson(referencedDefs);
|
||||
source.putAll(effectiveRunParams(rootMessage, ctx));
|
||||
if (referencedNode != null && referencedNode.getNodeType() == NodeTypeEnum.START) {
|
||||
source = toJson(graph.getStartInputParamsDefs());
|
||||
source.putAll(effectiveRunParams(rootMessage, ctx));
|
||||
} else {
|
||||
// References mean the resolved input of this iteration, including
|
||||
// upstream bindings and overrides. A missing iteration must stay
|
||||
// missing rather than fall back to static values or another round.
|
||||
source = ctx == null ? null : ctx.getNodeInput(refNodeId, rootMessage.getIterations());
|
||||
}
|
||||
} else if ("output".equalsIgnoreCase(param.getQuoteType())) {
|
||||
// 2.2 引用上游的 output 参数(运行时实际执行结果)
|
||||
// 用 nodeId + iterations 作为 key,避免覆盖
|
||||
@ -148,6 +161,11 @@ public class FlowNodeParamPreparer {
|
||||
return ctx == null || ctx.getRunParams() == null ? new JSONObject() : ctx.getRunParams();
|
||||
}
|
||||
|
||||
public void rememberInputs(TaskNodeExecuteMessage message, JSONObject input) {
|
||||
TaskContext context = taskInstHolder.getContext(message.getInstId());
|
||||
if (context != null) context.setNodeInput(message.getNodeId(), message.getIterations(), input);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 将参数定义列表中的 input 值构建为 JSONObject
|
||||
|
||||
@ -50,6 +50,7 @@ public class FlowInputPrepareInterceptor extends AbstractFlowMsgPreInterceptor {
|
||||
}
|
||||
|
||||
message.setInputParams(inputParams);
|
||||
paramPreparer.rememberInputs(message, inputParams);
|
||||
log.debug("[InputPrepare] 节点 {} 准备输入参数: {}", message.getNodeId(), inputParams);
|
||||
|
||||
// 执行下一个拦截器 / OperatorService
|
||||
|
||||
@ -26,6 +26,7 @@ import org.springframework.stereotype.Service;
|
||||
public class EdgeArmOperateService implements EdgeOperateService {
|
||||
|
||||
private final EdgeArmService edgeArmService;
|
||||
@org.springframework.beans.factory.annotation.Autowired private com.cmvr.arm.ArmTeachingService teaching;
|
||||
|
||||
@Override
|
||||
public boolean supports(ActionEnum action) {
|
||||
@ -37,6 +38,12 @@ public class EdgeArmOperateService implements EdgeOperateService {
|
||||
ActionEnum action = message.getAction();
|
||||
JSONObject inputParams = message.getInputParams();
|
||||
String robotId = message.getRobotId();
|
||||
var teachingOperation=com.cmvr.arm.ArmTeachingOperation.forAction(action);
|
||||
if(teachingOperation!=null) {
|
||||
JSONObject resolved=new JSONObject(inputParams);resolved.put("robotId",robotId);
|
||||
var request=com.cmvr.arm.ArmTeachingParameters.fromInputs(teachingOperation,resolved);
|
||||
return TaskNodeExecuteResult.success(teaching.execute(teachingOperation,request));
|
||||
}
|
||||
|
||||
// 从输入参数中获取设备ID
|
||||
String deviceId = inputParams.getString("deviceId");
|
||||
@ -95,7 +102,9 @@ public class EdgeArmOperateService implements EdgeOperateService {
|
||||
frame,
|
||||
velocity,
|
||||
acceleration,
|
||||
blendRadius
|
||||
blendRadius,
|
||||
com.cmvr.arm.ArmCoordinateFrames.name(inputParams,"baseFrame"),
|
||||
com.cmvr.arm.ArmCoordinateFrames.name(inputParams,"tcpFrame")
|
||||
);
|
||||
|
||||
log.info("机械臂末端运动任务下发成功");
|
||||
|
||||
@ -29,7 +29,9 @@ public class EdgeWorkcellOperateService implements EdgeOperateService {
|
||||
if (robot == null || robot.isBlank() || device == null || device.isBlank()) {
|
||||
throw new GlobalException("扫描仪或电机节点必须绑定 robotId 和 deviceId");
|
||||
}
|
||||
deviceValidator.validate(robot, device, WorkcellNodeContract.deviceKind(action));
|
||||
var scanner=com.cmvr.scanner.ScannerOperation.forAction(action.getAction());
|
||||
if(scanner!=null&&scanner.usableWithoutDevice()||com.cmvr.rotarybase.RotaryBaseParameters.recovery(action))deviceValidator.validateForAction(robot,device,WorkcellNodeContract.deviceKind(action),action);
|
||||
else deviceValidator.validate(robot, device, WorkcellNodeContract.deviceKind(action));
|
||||
List<WorkcellDeviceAdapter> matches = adapters.stream().filter(adapter -> adapter.supports(action)).toList();
|
||||
if (matches.isEmpty()) {
|
||||
throw new GlobalException((WorkcellNodeContract.deviceKind(action) == 14 ? "扫描仪" : "电机")
|
||||
|
||||
@ -14,7 +14,8 @@ import java.util.Set;
|
||||
public final class WorkcellNodeContract {
|
||||
private static final Set<ActionEnum> MOTOR = EnumSet.of(ActionEnum.MOTOR_ENABLE,
|
||||
ActionEnum.MOTOR_DISABLE, ActionEnum.MOTOR_HOME, ActionEnum.MOTOR_MOVE,
|
||||
ActionEnum.MOTOR_WAIT, ActionEnum.MOTOR_STOP, ActionEnum.MOTOR_STATUS);
|
||||
ActionEnum.MOTOR_WAIT, ActionEnum.MOTOR_STOP, ActionEnum.MOTOR_STATUS,
|
||||
ActionEnum.MOTOR_SET_MODE,ActionEnum.MOTOR_VELOCITY);
|
||||
|
||||
private WorkcellNodeContract() {}
|
||||
private static boolean supplement(ActionEnum action) {
|
||||
@ -22,7 +23,7 @@ public final class WorkcellNodeContract {
|
||||
}
|
||||
|
||||
public static boolean supports(ActionEnum action) {
|
||||
return action != null && (supplement(action) || ScannerOperation.forAction(action.getAction()) != null || MOTOR.contains(action));
|
||||
return action != null && (supplement(action) || ScannerOperation.forAction(action.getAction()) != null || MOTOR.contains(action) || com.cmvr.rotarybase.RotaryBaseParameters.ACTIONS.contains(action));
|
||||
}
|
||||
|
||||
public static int deviceKind(ActionEnum action) {
|
||||
@ -48,6 +49,10 @@ public final class WorkcellNodeContract {
|
||||
return;
|
||||
}
|
||||
if (scanner != null) {
|
||||
input=com.cmvr.scanner.ScannerRequestComposer.resolve(scanner,input);
|
||||
if(scanner==ScannerOperation.FRAMEWORK_IMPORT&&com.cmvr.scanner.ScannerFrameworkReferences.usesReferences(input)) {
|
||||
com.cmvr.scanner.ScannerFrameworkReferences.validate(input,true);return;
|
||||
}
|
||||
if (scanner == ScannerOperation.TASK) scanner.route(required(input, "taskId"));
|
||||
else if (scanner.control()) {
|
||||
if (input.containsKey("planCode") || input.containsKey("jobId") || input.containsKey("format")) {
|
||||
@ -57,22 +62,7 @@ public final class WorkcellNodeContract {
|
||||
}
|
||||
return;
|
||||
}
|
||||
switch (action) {
|
||||
case MOTOR_MOVE, MOTOR_WAIT -> {
|
||||
number(input, "targetPosition");
|
||||
if (!Set.of("DEGREE", "MILLIMETER", "PULSE").contains(required(input, "unit"))) {
|
||||
throw new GlobalException("电机位置单位无效");
|
||||
}
|
||||
if (action == ActionEnum.MOTOR_MOVE) {
|
||||
if (number(input, "velocity") <= 0 || number(input, "acceleration") <= 0) {
|
||||
throw new GlobalException("电机速度和加速度必须大于零");
|
||||
}
|
||||
} else if (number(input, "tolerance") < 0) {
|
||||
throw new GlobalException("电机到位容差不能为负数");
|
||||
}
|
||||
}
|
||||
default -> { }
|
||||
}
|
||||
com.cmvr.rotarybase.RotaryBaseParameters.validate(action,input);
|
||||
}
|
||||
|
||||
/** Validate static values before dispatch; output references remain runtime checked. */
|
||||
@ -104,11 +94,22 @@ public final class WorkcellNodeContract {
|
||||
if (names.stream().anyMatch(Set.of("planCode", "jobId", "format")::contains))
|
||||
throw new GlobalException("旧扫描组件参数与真实接口不一致,请重新配置节点");
|
||||
if (scanner == ScannerOperation.TASK && !dynamic.contains("taskId")) scanner.route(required(literals, "taskId"));
|
||||
if (scanner.control() && !dynamic.contains("requestJson")) {
|
||||
if(names.contains("requestFields")) {
|
||||
if(names.contains("frameworkUrls"))throw new GlobalException("框架URL导入请使用框架来源参数");
|
||||
JSONObject container=null;
|
||||
for(int i=0;i<params.size();i++)if("requestFields".equals(params.getJSONObject(i).getString("name")))container=params.getJSONObject(i);
|
||||
com.cmvr.scanner.ScannerRequestComposer.validateDefinition(scanner,container,literals,dynamic.contains("requestJson"));
|
||||
}else if(scanner==ScannerOperation.FRAMEWORK_IMPORT&&names.contains("frameworkUrls")) {
|
||||
if(!dynamic.contains("requestJson"))com.cmvr.scanner.ScannerFrameworkReferences.validate(literals,!dynamic.contains("frameworkUrls"));
|
||||
} else if (scanner.control() && !dynamic.contains("requestJson")) {
|
||||
ScannerRequestValidator.validate(scanner, ScannerRequestValidator.parse(
|
||||
literals.getString("requestJson") == null ? "{}" : literals.getString("requestJson")));
|
||||
}
|
||||
} else if (dynamic.isEmpty()) validate(action, literals);
|
||||
} else {
|
||||
if(MOTOR.contains(action)&&!com.cmvr.rotarybase.RotaryBaseParameters.ACTIONS.contains(action))
|
||||
throw new GlobalException("当前旋转底座接口未开放此旧电机动作,请重新选择已接入组件");
|
||||
if (dynamic.isEmpty()) validate(action, literals);
|
||||
}
|
||||
}
|
||||
|
||||
private static String required(JSONObject input, String key) {
|
||||
|
||||
@ -23,6 +23,8 @@ public class TeNodeInst {
|
||||
|
||||
@ApiModelProperty("检测项ID")
|
||||
private String itemId;
|
||||
private Integer itemOrder;
|
||||
private Integer itemOccurrence;
|
||||
|
||||
@ApiModelProperty("节点ID")
|
||||
private String nodeId;
|
||||
|
||||
@ -19,4 +19,6 @@ public class TeFlowViewVO {
|
||||
@ApiModelProperty("检测项ID")
|
||||
@NotEmpty(message = "检测项ID不能为空")
|
||||
private String itemId;
|
||||
private Integer itemOrder;
|
||||
private Integer itemOccurrence;
|
||||
}
|
||||
|
||||
@ -151,6 +151,10 @@ public class FlowActionExecutorService {
|
||||
JSONObject payload = req.getPayload() == null ? new JSONObject() : req.getPayload();
|
||||
String robotId = payload.getString("robotId");
|
||||
String deviceId = payload.getString("deviceId");
|
||||
if(com.cmvr.arm.ArmTeachingOperation.forAction(action)!=null) {
|
||||
TaskNodeExecuteMessage message=buildSingleNodeMessage(action,payload);message.setRobotId(robotId);
|
||||
return resultToString(edgeArmOperateService.execute(message));
|
||||
}
|
||||
|
||||
// Keep the legacy single-node fallback complete for actions introduced
|
||||
// after the generic EDGE operator list was added.
|
||||
|
||||
@ -21,12 +21,17 @@ import java.util.List;
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ITeNodeInstServiceImpl extends ServiceImpl<TeNodeInstMapper, TeNodeInst> implements ITeNodeInstService {
|
||||
@org.springframework.beans.factory.annotation.Autowired(required=false)
|
||||
private com.cmvr.test.flow.context.TaskContextManager contexts;
|
||||
private void scope(TeNodeInst row,String instId){var c=contexts==null?null:contexts.get(instId);if(c!=null){row.setItemOrder(c.getItemOrder());row.setItemOccurrence(c.getItemOccurrence());}}
|
||||
|
||||
@Override
|
||||
public List<TeNodeInst> view(TeFlowViewVO flowViewVO) {
|
||||
LambdaQueryWrapper<TeNodeInst> wrapper = Wrappers.lambdaQuery();
|
||||
wrapper.eq(TeNodeInst::getInstId, flowViewVO.getInstId())
|
||||
.eq(TeNodeInst::getItemId, flowViewVO.getItemId())
|
||||
.eq(flowViewVO.getItemOrder()!=null,TeNodeInst::getItemOrder,flowViewVO.getItemOrder())
|
||||
.eq(flowViewVO.getItemOccurrence()!=null,TeNodeInst::getItemOccurrence,flowViewVO.getItemOccurrence())
|
||||
.eq(StrUtil.isNotEmpty(flowViewVO.getTaskId()), TeNodeInst::getTaskId, flowViewVO.getTaskId())
|
||||
.orderByAsc(TeNodeInst::getId);
|
||||
return this.list(wrapper);
|
||||
@ -41,6 +46,7 @@ public class ITeNodeInstServiceImpl extends ServiceImpl<TeNodeInstMapper, TeNode
|
||||
record.setInstId(instId);
|
||||
record.setTaskId(taskId);
|
||||
record.setItemId(itemId);
|
||||
scope(record,instId);
|
||||
record.setNodeId(nodeId);
|
||||
record.setNodeType(nodeType);
|
||||
record.setOperate(operate);
|
||||
@ -105,6 +111,7 @@ public class ITeNodeInstServiceImpl extends ServiceImpl<TeNodeInstMapper, TeNode
|
||||
inst.setInstId(instId);
|
||||
inst.setTaskId(taskId);
|
||||
inst.setItemId(itemId);
|
||||
scope(inst,instId);
|
||||
inst.setNodeId(nodeId);
|
||||
inst.setNodeType(nodeType);
|
||||
inst.setOperate(operate);
|
||||
|
||||
@ -31,6 +31,14 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class EdgeArmController {
|
||||
|
||||
private final EdgeArmService edgeArmService;
|
||||
@org.springframework.beans.factory.annotation.Autowired private com.cmvr.arm.ArmCoordinateFrames coordinateFrames;
|
||||
|
||||
@ApiOperation("读取机械臂可用基准和工具坐标系")
|
||||
@GetMapping("/frames")
|
||||
@org.springframework.security.access.prepost.PreAuthorize("@cmvrSs.hasPermi('resource:device:list')")
|
||||
public AjaxResult frames(@RequestParam String robotId,@RequestParam String deviceId) {
|
||||
return AjaxResult.success(coordinateFrames.catalog(robotId,deviceId));
|
||||
}
|
||||
|
||||
@ApiOperation("关闭力矩")
|
||||
@GetMapping("/torqueOff")
|
||||
@ -130,7 +138,9 @@ public class EdgeArmController {
|
||||
moveLVO.getFrame(),
|
||||
moveLVO.getVelocity(),
|
||||
moveLVO.getAcceleration(),
|
||||
moveLVO.getBlendRadius()
|
||||
moveLVO.getBlendRadius(),
|
||||
moveLVO.getBaseFrame(),
|
||||
moveLVO.getTcpFrame()
|
||||
);
|
||||
return AjaxResult.ok();
|
||||
}
|
||||
|
||||
@ -0,0 +1,51 @@
|
||||
package com.cmvr.web.controller.api;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.cmvr.common.core.domain.AjaxResult;
|
||||
import com.cmvr.rotarybase.*;
|
||||
import com.cmvr.test.enums.ActionEnum;
|
||||
import com.cmvr.test.flow.runtime.operator.edge.WorkcellNodeContract;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@RestController
|
||||
@RequestMapping("/admin-api/cmvr/rotary-base")
|
||||
@RequiredArgsConstructor
|
||||
public class RotaryBaseController {
|
||||
private final RotaryBaseProperties settings;
|
||||
private final RotaryBaseClient client;
|
||||
@GetMapping("/configuration")
|
||||
@PreAuthorize("@cmvrSs.hasPermi('resource:device:list')")
|
||||
public AjaxResult configuration() {
|
||||
return AjaxResult.success(JSONObject.of("configured",settings.configured(),"host",settings.getHost(),"port",settings.getPort(),
|
||||
"robotId",settings.getRobotId(),"deviceId",settings.getDeviceId(),"managerId",settings.getManagerId(),"nodeId",settings.getNodeId(),"jointName",settings.getJointName(),
|
||||
"serviceReachable",client.reachable(),"mechanicalStateSupported",true));
|
||||
}
|
||||
@GetMapping("/{operation:state|info|motors|mode|position|velocity|reached-target}")
|
||||
@PreAuthorize("@cmvrSs.hasPermi('resource:device:list')")
|
||||
public AjaxResult query(@PathVariable String operation) {
|
||||
var action=switch(operation) {
|
||||
case "state" -> ActionEnum.MOTOR_GET_STATE;case "info" -> ActionEnum.MOTOR_GET_INFO;case "motors" -> ActionEnum.MOTOR_LIST;
|
||||
case "mode" -> ActionEnum.MOTOR_GET_MODE;case "position" -> ActionEnum.MOTOR_GET_Q;case "velocity" -> ActionEnum.MOTOR_GET_QD;
|
||||
case "reached-target" -> ActionEnum.MOTOR_REACHED_TARGET;default -> throw new com.cmvr.common.exception.GlobalException("未知查询");
|
||||
};
|
||||
var request=cmvr.api.MotorServiceOuterClass.MotorRequest.newBuilder().setHeader(com.cmvr.edge.client.utils.EdgeCommonUtil.buildRequest(settings.getManagerId()))
|
||||
.setNodeId(settings.getNodeId()).setJointName(settings.getJointName()).build();
|
||||
try {return AjaxResult.success(RotaryBaseFeedback.query(client,action,request,Math.min(3000,settings.getRpcTimeoutMs())));}
|
||||
catch(com.cmvr.common.exception.GlobalException error){return AjaxResult.error(503,error.getMessage());}
|
||||
}
|
||||
@PostMapping("/validate")
|
||||
@PreAuthorize("@cmvrSs.hasPermi('test:detect:edit')")
|
||||
public AjaxResult validate(@RequestBody JSONObject request) {
|
||||
if(request==null)return AjaxResult.error(400,"旋转底座参数不能为空");
|
||||
try {return validateRequest(request);}
|
||||
catch(com.cmvr.common.exception.GlobalException error){return AjaxResult.error(400,error.getMessage());}
|
||||
}
|
||||
private AjaxResult validateRequest(JSONObject request) {
|
||||
ActionEnum action;
|
||||
try {action=ActionEnum.valueOf(request.getString("action"));}
|
||||
catch(Exception error){throw new com.cmvr.common.exception.GlobalException("旋转底座动作无效");}
|
||||
if(!RotaryBaseParameters.ACTIONS.contains(action))throw new com.cmvr.common.exception.GlobalException("旋转底座接口未开放此动作");
|
||||
if(!(request.get("params") instanceof java.util.Map<?,?>))throw new com.cmvr.common.exception.GlobalException("旋转底座参数必须为对象");
|
||||
WorkcellNodeContract.validate(action,request.getJSONObject("params"));return AjaxResult.success(true);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,42 @@
|
||||
package com.cmvr.web.controller.resource;
|
||||
import com.cmvr.arm.*;
|
||||
import com.cmvr.common.core.domain.AjaxResult;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/admin-api/cmvr/api/arm/teaching")
|
||||
public class ArmTeachingController {
|
||||
private final ArmTeachingAccessService access;
|
||||
@GetMapping("/getArmInfo") @PreAuthorize("@cmvrSs.hasPermi('resource:device:list')")
|
||||
public AjaxResult getArmInfo(ArmTeachingRequest request){return run(ArmTeachingOperation.GET_ARM_INFO,request);}
|
||||
@GetMapping("/getRobotState") @PreAuthorize("@cmvrSs.hasPermi('resource:device:list')")
|
||||
public AjaxResult getRobotState(ArmTeachingRequest request){return run(ArmTeachingOperation.GET_ROBOT_STATE,request);}
|
||||
@GetMapping("/listRecordedTrajectories") @PreAuthorize("@cmvrSs.hasPermi('resource:device:list')")
|
||||
public AjaxResult listRecordedTrajectories(ArmTeachingRequest request){return run(ArmTeachingOperation.LIST_RECORDED_TRAJECTORIES,request);}
|
||||
@PostMapping("/{operation:enterTeachingMode|startTrajectoryRecording|stopTrajectoryRecording|exitTeachingMode|completeTeaching|moveToTrajectoryStart|replayRecordedTrajectory|stopMotion}")
|
||||
@PreAuthorize("@cmvrSs.hasPermi('test:detect:edit')")
|
||||
public AjaxResult control(@PathVariable String operation,@RequestBody JSONObject input) {
|
||||
ArmTeachingOperation op=switch(operation) {
|
||||
case "enterTeachingMode"->ArmTeachingOperation.ENTER_TEACHING_MODE;case "startTrajectoryRecording"->ArmTeachingOperation.START_TRAJECTORY_RECORDING;
|
||||
case "stopTrajectoryRecording"->ArmTeachingOperation.STOP_TRAJECTORY_RECORDING;case "exitTeachingMode"->ArmTeachingOperation.EXIT_TEACHING_MODE;
|
||||
case "completeTeaching"->ArmTeachingOperation.COMPLETE_TEACHING;case "moveToTrajectoryStart"->ArmTeachingOperation.MOVE_TO_TRAJECTORY_START;
|
||||
case "replayRecordedTrajectory"->ArmTeachingOperation.REPLAY_RECORDED_TRAJECTORY;case "stopMotion"->ArmTeachingOperation.STOP_MOTION;
|
||||
default->throw new com.cmvr.common.exception.GlobalException("机械臂操作无效");
|
||||
};
|
||||
return run(op,ArmTeachingParameters.fromInputs(op,input));
|
||||
}
|
||||
@PostMapping("/validate") @PreAuthorize("@cmvrSs.hasPermi('test:detect:edit')")
|
||||
public AjaxResult validate(@RequestBody JSONObject input) {
|
||||
var action=com.cmvr.test.enums.ActionEnum.fromAction(input.getString("action"));
|
||||
var op=ArmTeachingOperation.forAction(action);
|
||||
if(op==null)throw new com.cmvr.common.exception.GlobalException("不是已接入的机械臂示教/轨迹组件");
|
||||
var params=input.getJSONObject("params");if(params==null)throw new com.cmvr.common.exception.GlobalException("params必须为对象");
|
||||
params=new JSONObject(params);params.put("robotId","validation");params.put("deviceId","validation");
|
||||
ArmTeachingParameters.fromInputs(op,params);return AjaxResult.success(true);
|
||||
}
|
||||
private AjaxResult run(ArmTeachingOperation op,ArmTeachingRequest request){return AjaxResult.success(access.execute(op,request));}
|
||||
}
|
||||
@ -28,6 +28,8 @@ public class ResourceRobotController extends BaseController {
|
||||
private final ResourceRobotService resourceRobotService;
|
||||
private final ResourceRobotMapService robotMapService;
|
||||
private final ResourceRobotControlService controlService;
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private com.cmvr.scanner.ScannerResourceSynchronizer scannerResources;
|
||||
|
||||
public ResourceRobotController(ResourceRobotService resourceRobotService,
|
||||
ResourceRobotMapService robotMapService,
|
||||
@ -58,9 +60,13 @@ public class ResourceRobotController extends BaseController {
|
||||
@PreAuthorize("@cmvrSs.hasPermi('resource:device:list')")
|
||||
public AjaxResult devices(@PathVariable String robotId,
|
||||
@RequestParam(required = false) Integer deviceKind,
|
||||
@RequestParam(defaultValue = "true") @ApiParam("是否只返回在线且启用的设备") boolean onlineOnly) {
|
||||
@RequestParam(defaultValue = "true") @ApiParam("是否只返回在线且启用的设备") boolean onlineOnly,
|
||||
@RequestParam(defaultValue = "false") boolean workflow) {
|
||||
if(workflow&&scannerResources!=null&&scannerResources.handles(robotId))return success(resourceRobotService.listDevices(robotId,deviceKind,false).stream()
|
||||
.filter(d->"1".equals(d.getEnabled())&&("1".equals(d.getOnlineStatus())||scannerResources.handlesDevice(robotId,d.getDeviceId()))).toList());
|
||||
return success(resourceRobotService.listDevices(robotId, deviceKind, onlineOnly));
|
||||
}
|
||||
public AjaxResult devices(String robotId,Integer deviceKind,boolean onlineOnly) {return devices(robotId,deviceKind,onlineOnly,false);}
|
||||
|
||||
@GetMapping("/id/{id}")
|
||||
@ApiOperation("根据数据主键查询机器人")
|
||||
|
||||
@ -0,0 +1,23 @@
|
||||
package com.cmvr.web.controller.resource;
|
||||
|
||||
import com.cmvr.common.core.domain.AjaxResult;
|
||||
import com.cmvr.common.utils.SecurityUtils;
|
||||
import com.cmvr.resource.service.RobotConnectionService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/admin-api/cmvr/resource/robots/{robotId}/connections")
|
||||
public class RobotConnectionController {
|
||||
private final RobotConnectionService connections;
|
||||
@GetMapping
|
||||
@PreAuthorize("@cmvrSs.hasPermi('resource:robot:query')")
|
||||
public AjaxResult get(@PathVariable String robotId) {return AjaxResult.success(connections.get(robotId));}
|
||||
@PutMapping
|
||||
@PreAuthorize("@cmvrSs.hasPermi('resource:robot:edit')")
|
||||
public AjaxResult save(@PathVariable String robotId,@RequestBody com.fasterxml.jackson.databind.JsonNode request) {
|
||||
return AjaxResult.success(connections.save(robotId,RobotConnectionService.Update.fromJson(request),SecurityUtils.getUsername()));
|
||||
}
|
||||
}
|
||||
@ -20,6 +20,7 @@ import java.util.*;
|
||||
public class ScannerController extends BaseController {
|
||||
private final ScannerService scanner;
|
||||
private final ScannerAccessService access;
|
||||
private final ScannerFrameworkService framework;
|
||||
|
||||
@GetMapping("/configuration")
|
||||
public AjaxResult getConfiguration() { return success(scanner.configuration()); }
|
||||
@ -35,11 +36,17 @@ public class ScannerController extends BaseController {
|
||||
catch (IllegalArgumentException error) { throw new ScannerException("invalid_operation", "扫描操作不存在", 400); }
|
||||
if (input.has("requestJson") && !input.get("requestJson").isTextual())
|
||||
throw new ScannerException("invalid_request", "requestJson必须是JSON对象的字符串", 400);
|
||||
ScannerRequestValidator.validate(operation, ScannerRequestValidator.parse(input.path("requestJson").asText("{}")));
|
||||
if(operation==ScannerOperation.FRAMEWORK_IMPORT && input.has("frameworkUrls"))
|
||||
framework.validateReferences(input.path("requestJson").asText("{}"),input.get("frameworkUrls"));
|
||||
else if(input.has("requestFieldDefinitions"))
|
||||
ScannerRequestComposer.validateApiDefinition(operation,input.path("requestJson").asText("{}"),input.get("requestFieldDefinitions"));
|
||||
else if(input.has("requestFieldNames"))
|
||||
ScannerRequestComposer.validateTemplate(operation,input.path("requestJson").asText("{}"),input.get("requestFieldNames"));
|
||||
else ScannerRequestValidator.validate(operation, ScannerRequestValidator.parse(input.path("requestJson").asText("{}")));
|
||||
return success(true);
|
||||
}
|
||||
|
||||
@ApiOperation("连接扫描仪")
|
||||
@ApiOperation("连接设备")
|
||||
@PostMapping("/device/connect")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postConnect(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
@ -53,28 +60,28 @@ public class ScannerController extends BaseController {
|
||||
return success(access.submit(ScannerOperation.CREATE_PROJECT, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("断开扫描会话")
|
||||
@ApiOperation("断开设备会话")
|
||||
@PostMapping("/device/disconnect")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postDisconnect(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
return success(access.submit(ScannerOperation.DISCONNECT, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("重新连接扫描仪")
|
||||
@ApiOperation("结束旧会话并重新连接")
|
||||
@PostMapping("/device/reconnect")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postReconnect(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
return success(access.submit(ScannerOperation.RECONNECT, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("开启扫描预览")
|
||||
@ApiOperation("开启渲染预览")
|
||||
@PostMapping("/preview/start")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postPreviewStart(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
return success(access.submit(ScannerOperation.PREVIEW_START, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("关闭扫描预览")
|
||||
@ApiOperation("关闭渲染预览")
|
||||
@PostMapping("/preview/stop")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postPreviewStop(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
@ -88,22 +95,50 @@ public class ScannerController extends BaseController {
|
||||
return success(access.submit(ScannerOperation.SCAN_START, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("暂停采集")
|
||||
@ApiOperation("暂停采集并保留工程")
|
||||
@PostMapping("/scan/stop")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postScanStop(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
return success(access.submit(ScannerOperation.SCAN_STOP, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("扫描预览图像")
|
||||
@ApiOperation("选择采集类型或采集设备")
|
||||
@PostMapping("/scan/type")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postScanType(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
return success(access.submit(ScannerOperation.SCAN_TYPE, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("上传一个框架文件(同步)")
|
||||
@PostMapping("/framework/files")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postFrameworkUpload(@RequestHeader("X-File-Name") String name, jakarta.servlet.http.HttpServletRequest request) throws java.io.IOException {
|
||||
return success(framework.upload(name, request.getContentType(), request.getContentLengthLong(), request.getInputStream()));
|
||||
}
|
||||
|
||||
@ApiOperation("导入已上传的标志点框架")
|
||||
@PostMapping("/framework/import")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postFrameworkImport(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
return success(access.submit(ScannerOperation.FRAMEWORK_IMPORT, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("优化已采集的摄影测量框架")
|
||||
@PostMapping("/framework/optimize")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postFrameworkOptimize(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
return success(access.submit(ScannerOperation.FRAMEWORK_OPTIMIZE, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("下载最新一帧JPEG")
|
||||
@GetMapping("/preview/image")
|
||||
public ResponseEntity<StreamingResponseBody> getPreviewImage() { return binary(ScannerOperation.PREVIEW_IMAGE, null); }
|
||||
|
||||
@ApiOperation("扫描实时预览")
|
||||
@ApiOperation("订阅MJPEG实时图像")
|
||||
@GetMapping("/preview/stream")
|
||||
public ResponseEntity<StreamingResponseBody> getPreviewStream() { return binary(ScannerOperation.PREVIEW_STREAM, null); }
|
||||
|
||||
@ApiOperation("配置扫描参数")
|
||||
@ApiOperation("修改扫描参数")
|
||||
@PostMapping("/parameters")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postParameters(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
@ -117,28 +152,28 @@ public class ScannerController extends BaseController {
|
||||
return success(access.submit(ScannerOperation.MESH, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("确认扫描网格")
|
||||
@ApiOperation("确认网格")
|
||||
@PostMapping("/mesh/confirm")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postMeshConfirm(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
return success(access.submit(ScannerOperation.MESH_CONFIRM, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("撤销扫描网格")
|
||||
@ApiOperation("撤销网格")
|
||||
@PostMapping("/mesh/undo")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postMeshUndo(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
return success(access.submit(ScannerOperation.MESH_UNDO, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("扫描工程拼接")
|
||||
@ApiOperation("工程拼接")
|
||||
@PostMapping("/align")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postAlign(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
return success(access.submit(ScannerOperation.ALIGN, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("删除扫描点或标志点")
|
||||
@ApiOperation("删除点或标志点")
|
||||
@PostMapping("/edit")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postEdit(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
@ -152,43 +187,43 @@ public class ScannerController extends BaseController {
|
||||
return success(access.submit(ScannerOperation.CLIP_PLANE, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("导出扫描成果")
|
||||
@ApiOperation("导出文件")
|
||||
@PostMapping("/exports")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postExport(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
return success(access.submit(ScannerOperation.EXPORT, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("保存原始场景快照")
|
||||
@ApiOperation("创建原始场景快照")
|
||||
@PostMapping("/data/snapshots")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postSnapshot(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
return success(access.submit(ScannerOperation.SNAPSHOT, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("读取扫描场景摘要")
|
||||
@ApiOperation("读取最近场景摘要")
|
||||
@GetMapping("/data/scene")
|
||||
public AjaxResult getScene() { return success(scanner.get(ScannerOperation.SCENE, null)); }
|
||||
|
||||
@ApiOperation("下载扫描成果文件")
|
||||
@ApiOperation("下载已登记导出或快照文件")
|
||||
@GetMapping("/files/{fileId}")
|
||||
public ResponseEntity<StreamingResponseBody> getFile(@PathVariable String fileId) { return binary(ScannerOperation.FILE, fileId); }
|
||||
|
||||
@ApiOperation("进入扫描标定")
|
||||
@ApiOperation("进入标定流程")
|
||||
@PostMapping("/calibration/enter")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postCalibrationEnter(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
return success(access.submit(ScannerOperation.CALIBRATION_ENTER, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("设置标定模式")
|
||||
@ApiOperation("选择标定模式")
|
||||
@PostMapping("/calibration/setMode")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postCalibrationMode(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
return success(access.submit(ScannerOperation.CALIBRATION_MODE, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("开始扫描标定")
|
||||
@ApiOperation("开始当前标定")
|
||||
@PostMapping("/calibration/start")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postCalibrationStart(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
@ -209,7 +244,7 @@ public class ScannerController extends BaseController {
|
||||
return success(access.submit(ScannerOperation.CALIBRATION_SYSTEM, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("设置自由标定")
|
||||
@ApiOperation("设置自由标定开关")
|
||||
@PostMapping("/calibration/setFree")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postCalibrationFree(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
@ -230,7 +265,7 @@ public class ScannerController extends BaseController {
|
||||
return success(access.submit(ScannerOperation.CALIBRATION_COMPUTE, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("设置精细标定")
|
||||
@ApiOperation("设置精细标定开关")
|
||||
@PostMapping("/calibration/setAdvanced")
|
||||
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
|
||||
public AjaxResult postCalibrationAdvanced(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
|
||||
@ -244,30 +279,34 @@ public class ScannerController extends BaseController {
|
||||
return success(access.submit(ScannerOperation.CALIBRATION_APPLY_LAST, body, commandKey));
|
||||
}
|
||||
|
||||
@ApiOperation("读取扫描服务信息")
|
||||
@ApiOperation("查询公开服务元数据")
|
||||
@GetMapping("/metadata")
|
||||
public AjaxResult getMetadata() { return success(scanner.get(ScannerOperation.METADATA, null)); }
|
||||
|
||||
@ApiOperation("检查扫描服务")
|
||||
@ApiOperation("健康检查")
|
||||
@GetMapping("/health")
|
||||
public AjaxResult getHealth() { return success(scanner.get(ScannerOperation.HEALTH, null)); }
|
||||
|
||||
@ApiOperation("读取扫描仪状态")
|
||||
@ApiOperation("读取设备和工程状态")
|
||||
@GetMapping("/status")
|
||||
public AjaxResult getStatus() { return success(scanner.get(ScannerOperation.STATUS, null)); }
|
||||
|
||||
@ApiOperation("读取扫描能力")
|
||||
@ApiOperation("读取当前功能能力")
|
||||
@GetMapping("/capabilities")
|
||||
public AjaxResult getCapabilities() { return success(scanner.get(ScannerOperation.CAPABILITIES, null)); }
|
||||
|
||||
@ApiOperation("读取预览指标")
|
||||
@ApiOperation("读取图像编码与缓存指标")
|
||||
@GetMapping("/preview/metrics")
|
||||
public AjaxResult getMetrics() { return success(scanner.get(ScannerOperation.METRICS, null)); }
|
||||
|
||||
@ApiOperation("等待扫描设备任务")
|
||||
@ApiOperation("查询异步任务")
|
||||
@GetMapping("/tasks/{taskId}")
|
||||
public AjaxResult getTask(@PathVariable String taskId) { return success(scanner.get(ScannerOperation.TASK, taskId)); }
|
||||
|
||||
@ApiOperation("读取扫描仪和跟踪仪电量")
|
||||
@GetMapping("/device/battery")
|
||||
public AjaxResult getBattery() { return success(scanner.get(ScannerOperation.BATTERY, null)); }
|
||||
|
||||
private ResponseEntity<StreamingResponseBody> binary(ScannerOperation operation, String id) {
|
||||
var source = scanner.binary(operation, id);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
|
||||
@ -0,0 +1,46 @@
|
||||
package com.cmvr.web.controller.scanner;
|
||||
|
||||
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
|
||||
import com.cmvr.common.core.domain.AjaxResult;
|
||||
import com.cmvr.scanner.*;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
/** Archives local files only. SDK upload/import happens later in the workflow. */
|
||||
@RestController
|
||||
@RequestMapping("/admin-api/cmvr/scanner/framework/local-files")
|
||||
@RequiredArgsConstructor
|
||||
public class ScannerLocalFrameworkController {
|
||||
private final ScannerFixtureFrameworkStore store;
|
||||
private final Semaphore uploads = new Semaphore(2);
|
||||
|
||||
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@PreAuthorize("@ss.hasPermission('lab:fixture:update') or @cmvrSs.hasPermi('test:detect:edit')")
|
||||
public AjaxResult upload(@RequestPart("file") MultipartFile file) {
|
||||
if (!Long.valueOf(1L).equals(TenantContextHolder.getTenantId()))
|
||||
throw new ScannerException("invalid_tenant", "框架文件仅属于本项目主租户", 403);
|
||||
if (file == null || file.isEmpty() || file.getSize() > ScannerFrameworkService.MAX_BYTES)
|
||||
throw new ScannerException("invalid_file", "框架文件不能为空,且单个不能超过100MiB", 400);
|
||||
String name = ScannerFrameworkService.decodeName(ScannerFrameworkReferences.encode(file.getOriginalFilename() == null ? "" : file.getOriginalFilename()));
|
||||
if (!uploads.tryAcquire()) throw new ScannerException("upload_busy", "当前上传较多,请稍后重新选择文件", 429);
|
||||
try (var input = file.getInputStream()) {
|
||||
byte[] bytes = input.readNBytes(ScannerFrameworkService.MAX_BYTES + 1);
|
||||
if (bytes.length != file.getSize()) throw new ScannerException("invalid_file", "文件内容与声明长度不一致,请重新选择", 400);
|
||||
return AjaxResult.success(store.save(name, bytes));
|
||||
} catch (IOException error) {
|
||||
throw new ScannerException("framework_upload_failed", "本地文件读取失败,请重新选择", 400);
|
||||
} finally { uploads.release(); }
|
||||
}
|
||||
|
||||
@ExceptionHandler(ScannerException.class)
|
||||
public AjaxResult scannerError(ScannerException error) {
|
||||
AjaxResult result = AjaxResult.error(error.remoteStatus, error.getMessage());
|
||||
result.put("scannerCode", error.scannerCode);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@ -16,6 +16,38 @@ enum ArmFrameType {
|
||||
ARM_FRAME_USER = 3;
|
||||
}
|
||||
|
||||
enum ArmRobotMode {
|
||||
ARM_ROBOT_MODE_UNKNOWN = 0;
|
||||
ARM_ROBOT_MODE_DISCONNECTED = 1;
|
||||
ARM_ROBOT_MODE_POWER_OFF = 2;
|
||||
ARM_ROBOT_MODE_IDLE = 3;
|
||||
ARM_ROBOT_MODE_RUNNING = 4;
|
||||
ARM_ROBOT_MODE_PAUSED = 5;
|
||||
ARM_ROBOT_MODE_STOPPED = 6;
|
||||
ARM_ROBOT_MODE_FAULT = 7;
|
||||
}
|
||||
|
||||
enum ArmSafetyMode {
|
||||
ARM_SAFETY_MODE_UNKNOWN = 0;
|
||||
ARM_SAFETY_MODE_NORMAL = 1;
|
||||
ARM_SAFETY_MODE_REDUCED = 2;
|
||||
ARM_SAFETY_MODE_PROTECTIVE_STOP = 3;
|
||||
ARM_SAFETY_MODE_EMERGENCY_STOP = 4;
|
||||
ARM_SAFETY_MODE_SAFEGUARD_STOP = 5;
|
||||
ARM_SAFETY_MODE_SYSTEM_EMERGENCY_STOP = 6;
|
||||
ARM_SAFETY_MODE_FAULT = 7;
|
||||
}
|
||||
|
||||
enum ArmControlMode {
|
||||
ARM_CONTROL_MODE_NONE = 0;
|
||||
ARM_CONTROL_MODE_MANUAL = 1;
|
||||
ARM_CONTROL_MODE_POSITION = 2;
|
||||
ARM_CONTROL_MODE_VELOCITY = 3;
|
||||
ARM_CONTROL_MODE_TORQUE = 4;
|
||||
ARM_CONTROL_MODE_SERVO = 5;
|
||||
ARM_CONTROL_MODE_FREEDRIVE = 6;
|
||||
}
|
||||
|
||||
// 关节位置命令;数组顺序必须与机械臂关节顺序一致。
|
||||
message JointPositionCommand {
|
||||
// 各关节目标角度,单位:rad。
|
||||
@ -76,6 +108,15 @@ message CartesianVelocity {
|
||||
double wz = 6;
|
||||
}
|
||||
|
||||
message CartesianWrench {
|
||||
double fx = 1;
|
||||
double fy = 2;
|
||||
double fz = 3;
|
||||
double tx = 4;
|
||||
double ty = 5;
|
||||
double tz = 6;
|
||||
}
|
||||
|
||||
// 4x4 齐次变换矩阵;前三列为无量纲旋转矩阵,第四列前三项为平移量(m)。
|
||||
message TransformMatrix4x4 {
|
||||
// 第一行:m00~m02 无单位,m03 单位为 m。
|
||||
@ -210,6 +251,57 @@ message ServoJ {
|
||||
}
|
||||
}
|
||||
|
||||
// 开始记录实际关节轨迹,CSV 保存在服务端程序目录 data/trajectories/<device_id>。
|
||||
message StartTrajectoryRecording {
|
||||
message Request {
|
||||
// 通用请求头,包含目标设备 ID 和请求时间戳。
|
||||
CommandHeader.Request header = 1;
|
||||
// 不含目录的文件名;不覆盖已有文件,自动补充 .csv。
|
||||
string file_name = 2;
|
||||
// 实际关节采样频率 Hz;0 使用 100,支持 1~100。
|
||||
double sampling_frequency_hz = 3;
|
||||
}
|
||||
|
||||
message Response {
|
||||
// 通用响应头,包含成功标志、错误信息和响应时间戳。
|
||||
CommandHeader.Feedback header = 1;
|
||||
}
|
||||
}
|
||||
|
||||
// 已完成且通过校验的 CSV;不包含录制中的 .partial 文件。
|
||||
message RecordedTrajectory {
|
||||
string file_name = 1;
|
||||
uint64 samples = 2;
|
||||
double duration_s = 3;
|
||||
double sampling_frequency_hz = 4;
|
||||
}
|
||||
message ListRecordedTrajectories {
|
||||
message Request { CommandHeader.Request header = 1; }
|
||||
message Response {
|
||||
CommandHeader.Feedback header = 1;
|
||||
repeated RecordedTrajectory trajectories = 2;
|
||||
string directory = 3;
|
||||
bool recording = 4;
|
||||
string recording_file = 5;
|
||||
uint64 recorded_samples = 6;
|
||||
string recording_error = 7;
|
||||
}
|
||||
}
|
||||
message ReplayRecordedTrajectory {
|
||||
message Request {
|
||||
CommandHeader.Request header = 1;
|
||||
string file_name = 2;
|
||||
// 0 使用原速;支持 0.1~1,只允许降速。
|
||||
double speed_ratio = 3;
|
||||
// 平滑限值;0 使用默认值 0.3 rad/s、0.5 rad/s²、2 rad/s³。
|
||||
// 回放经 BSplineSmoother 重新定时,可能偏离原始中间点;首尾保持不变。
|
||||
double max_velocity = 4;
|
||||
double max_acceleration = 5;
|
||||
double max_jerk = 6;
|
||||
}
|
||||
message Response { CommandHeader.Feedback header = 1; }
|
||||
}
|
||||
|
||||
// 机械臂关节状态。
|
||||
message JointState {
|
||||
// 关节名称列表,无单位;与 position、velocity、effort 按索引对应。
|
||||
@ -222,6 +314,8 @@ message JointState {
|
||||
repeated double effort = 4;
|
||||
// 状态采样的 Unix 时间戳,单位:s。
|
||||
double timestamp = 5;
|
||||
// 电机实际电流,单位:mA。
|
||||
repeated double current = 6;
|
||||
}
|
||||
|
||||
// 查询关节状态的请求。
|
||||
@ -238,6 +332,60 @@ message JointResponse {
|
||||
JointState state = 2;
|
||||
}
|
||||
|
||||
// 机械臂静态能力与 SDK 自动识别信息。
|
||||
message GetArmInfo {
|
||||
message Request {
|
||||
CommandHeader.Request header = 1;
|
||||
}
|
||||
|
||||
message Response {
|
||||
CommandHeader.Feedback header = 1;
|
||||
string device_id = 2;
|
||||
string manufacturer = 3;
|
||||
string model = 4;
|
||||
string subtype = 5;
|
||||
uint32 dof = 6;
|
||||
repeated string joint_names = 7;
|
||||
string default_base_frame = 8;
|
||||
string default_tcp_frame = 9;
|
||||
string description_id = 10;
|
||||
bool detected_from_sdk = 11;
|
||||
string driver_type = 12;
|
||||
}
|
||||
}
|
||||
|
||||
message RobotState {
|
||||
double timestamp = 1;
|
||||
ArmRobotMode robot_mode = 2;
|
||||
ArmSafetyMode safety_mode = 3;
|
||||
ArmControlMode control_mode = 4;
|
||||
bool connected = 5;
|
||||
bool powered_on = 6;
|
||||
bool brake_released = 7;
|
||||
bool moving = 8;
|
||||
bool program_running = 9;
|
||||
bool protective_stopped = 10;
|
||||
bool emergency_stopped = 11;
|
||||
bool fault = 12;
|
||||
double speed_scaling = 13;
|
||||
JointState actual_joint_state = 14;
|
||||
JointState target_joint_state = 15;
|
||||
CartesianPose actual_tcp_pose = 16;
|
||||
CartesianVelocity actual_tcp_velocity = 17;
|
||||
CartesianWrench actual_tcp_wrench = 18;
|
||||
}
|
||||
|
||||
message GetRobotState {
|
||||
message Request {
|
||||
CommandHeader.Request header = 1;
|
||||
}
|
||||
|
||||
message Response {
|
||||
CommandHeader.Feedback header = 1;
|
||||
RobotState state = 2;
|
||||
}
|
||||
}
|
||||
|
||||
// 查询 TCP 位姿。
|
||||
message GetPose {
|
||||
// 位姿查询请求。
|
||||
|
||||
@ -29,8 +29,12 @@ service ArmService {
|
||||
rpc servoJ(ServoJ.Request) returns (ServoJ.Response);
|
||||
// 停止当前机械臂运动;不包含数值参数,无单位。
|
||||
rpc stopMotion(CommandHeader.Request) returns (CommandHeader.Feedback);
|
||||
// 查询机械臂 SDK 自动识别的型号、自由度、关节名及默认坐标系。
|
||||
rpc GetArmInfo(GetArmInfo.Request) returns (GetArmInfo.Response);
|
||||
// 读取关节状态;角度 rad、角速度 rad/s、力矩 N·m。
|
||||
rpc getJointState(JointRequest) returns (JointResponse);
|
||||
// 一次性读取完整机械臂运行状态、关节状态及 TCP 位姿。
|
||||
rpc getRobotState(GetRobotState.Request) returns (GetRobotState.Response);
|
||||
// 读取 TCP 位姿;位置单位为 m,姿态单位为 rad。
|
||||
rpc getPose(GetPose.Request) returns (GetPose.Response);
|
||||
// 对指定关节执行零位标定;关节名称无单位。
|
||||
@ -41,4 +45,20 @@ service ArmService {
|
||||
rpc computeForwardKinematics(ComputeForwardKinematics.Request) returns (ComputeForwardKinematics.Response);
|
||||
// 执行机械臂厂商扩展 JSON 命令;当前用于 AUBO 控制柜 Standard DI/DO。
|
||||
rpc ExecuteJsonCommand(JsonDeviceCommand.Request) returns (JsonDeviceCommand.Feedback);
|
||||
// 进入拖动示教模式;仅支持具备该能力的机械臂。
|
||||
rpc EnterTeachingMode(CommandHeader.Request) returns (CommandHeader.Feedback);
|
||||
// 开始记录实际关节轨迹到服务端 CSV。
|
||||
rpc StartTrajectoryRecording(StartTrajectoryRecording.Request) returns (StartTrajectoryRecording.Response);
|
||||
// 完成示教:停止轨迹记录并退出拖动示教模式。
|
||||
rpc CompleteTeaching(CommandHeader.Request) returns (CommandHeader.Feedback);
|
||||
// 单独停止轨迹记录,不退出拖动示教模式。
|
||||
rpc StopTrajectoryRecording(CommandHeader.Request) returns (CommandHeader.Feedback);
|
||||
// 单独退出拖动示教模式,不停止轨迹记录。
|
||||
rpc ExitTeachingMode(CommandHeader.Request) returns (CommandHeader.Feedback);
|
||||
// 查询 CSV 轨迹及当前录制状态,不启动采样或运动。
|
||||
rpc ListRecordedTrajectories(ListRecordedTrajectories.Request) returns (ListRecordedTrajectories.Response);
|
||||
// 低速到所选轨迹起点(0.1 rad/s,0.1 rad/s²);必须退出示教且已使能。
|
||||
rpc MoveToTrajectoryStart(ReplayRecordedTrajectory.Request) returns (ReplayRecordedTrajectory.Response);
|
||||
// 同步回放;必须先到达起点,结束后返回。取消请求会停止运动。
|
||||
rpc ReplayRecordedTrajectory(ReplayRecordedTrajectory.Request) returns (ReplayRecordedTrajectory.Response);
|
||||
}
|
||||
|
||||
@ -0,0 +1,98 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package cmvr.api;
|
||||
|
||||
import "cmvr/api/common.proto";
|
||||
|
||||
message MotorRequest {
|
||||
CommandHeader.Request header = 1;
|
||||
uint32 node_id = 2;
|
||||
string joint_name = 3;
|
||||
reserved 4;
|
||||
int32 mode = 5;
|
||||
double q = 6;
|
||||
double qd = 7;
|
||||
double qdd = 8;
|
||||
double tau = 9;
|
||||
double upper = 10;
|
||||
double lower = 11;
|
||||
uint32 torque_slope = 12;
|
||||
reserved 13 to 16;
|
||||
}
|
||||
|
||||
message MotorInfo {
|
||||
string manager_id = 1;
|
||||
uint32 node_id = 2;
|
||||
string joint_name = 3;
|
||||
string driver = 4;
|
||||
double limit_q_lb = 5;
|
||||
double limit_q_ub = 6;
|
||||
double limit_qd = 7;
|
||||
double limit_qdd = 8;
|
||||
reserved 9;
|
||||
}
|
||||
|
||||
message MotorDebugState {
|
||||
double position = 1;
|
||||
double velocity = 2;
|
||||
bool feedback_valid = 3;
|
||||
double torque = 4;
|
||||
bool torque_valid = 5;
|
||||
string torque_unit = 6;
|
||||
int32 mode = 7;
|
||||
uint32 status_word = 8;
|
||||
uint32 error_code = 9;
|
||||
bool enabled = 10;
|
||||
bool fault = 11;
|
||||
bool status_valid = 12;
|
||||
reserved 13, 14;
|
||||
double sampled_at_s = 15;
|
||||
}
|
||||
|
||||
message MotorResponse {
|
||||
CommandHeader.Feedback header = 1;
|
||||
MotorInfo info = 2;
|
||||
MotorDebugState state = 3;
|
||||
bool reached_target = 4;
|
||||
bool driver_acknowledged = 5;
|
||||
string detail = 6;
|
||||
reserved 7;
|
||||
}
|
||||
|
||||
message MotorListResponse {
|
||||
CommandHeader.Feedback header = 1;
|
||||
repeated MotorInfo motors = 2;
|
||||
}
|
||||
|
||||
message MotorHomingRequest {
|
||||
CommandHeader.Request header = 1;
|
||||
uint32 node_id = 2;
|
||||
string joint_name = 3;
|
||||
int32 method = 4;
|
||||
double fast_speed = 5;
|
||||
double slow_speed = 6;
|
||||
double acceleration = 7;
|
||||
double timeout_s = 8;
|
||||
double offset = 9;
|
||||
}
|
||||
|
||||
service MotorService {
|
||||
rpc ListMotors(MotorRequest) returns (MotorListResponse);
|
||||
rpc GetInfo(MotorRequest) returns (MotorResponse);
|
||||
rpc GetState(MotorRequest) returns (MotorResponse);
|
||||
rpc getMode(MotorRequest) returns (MotorResponse);
|
||||
rpc getQ(MotorRequest) returns (MotorResponse);
|
||||
rpc getQd(MotorRequest) returns (MotorResponse);
|
||||
rpc getTau(MotorRequest) returns (MotorResponse);
|
||||
rpc reachedTargetQ(MotorRequest) returns (MotorResponse);
|
||||
rpc setMode(MotorRequest) returns (MotorResponse);
|
||||
rpc torqueOn(MotorRequest) returns (MotorResponse);
|
||||
rpc torqueOff(MotorRequest) returns (MotorResponse);
|
||||
rpc quickStop(MotorRequest) returns (MotorResponse);
|
||||
rpc commandProfilePosition(MotorRequest) returns (MotorResponse);
|
||||
rpc commandProfileVelocity(MotorRequest) returns (MotorResponse);
|
||||
rpc commandProfileTorque(MotorRequest) returns (MotorResponse);
|
||||
rpc brakeRelease(MotorRequest) returns (MotorResponse);
|
||||
rpc calibrateZeroQ(MotorRequest) returns (MotorResponse);
|
||||
rpc home(MotorHomingRequest) returns (MotorResponse);
|
||||
}
|
||||
@ -125,6 +125,13 @@
|
||||
where id=#{id} and coalesce(archived_status,'0')='0'
|
||||
</update>
|
||||
|
||||
<update id="updateExternalServiceState">
|
||||
update iot_robot set connect_status=#{connectStatus}, runtime_status=#{status},
|
||||
ip_address=#{ipAddress}, port=#{port}, last_heartbeat_time=#{lastHeartbeatTime},
|
||||
update_by='rotary-base', update_time=#{updateTime}
|
||||
where id=#{id} and coalesce(archived_status,'0')='0'
|
||||
</update>
|
||||
|
||||
<update id="markHeartbeatExpiredOffline">
|
||||
update iot_robot set connect_status = '0', runtime_status = '1',
|
||||
update_by = 'heartbeat-timeout', update_time = #{offlineTime}
|
||||
|
||||
@ -709,6 +709,8 @@ CREATE TABLE IF NOT EXISTS `te_node_inst` (
|
||||
`inst_id` varchar(128) DEFAULT NULL,
|
||||
`task_id` varchar(128) DEFAULT NULL,
|
||||
`item_id` varchar(128) DEFAULT NULL,
|
||||
`item_order` int DEFAULT NULL,
|
||||
`item_occurrence` int DEFAULT NULL,
|
||||
`node_id` varchar(128) DEFAULT NULL,
|
||||
`node_type` varchar(255) DEFAULT NULL,
|
||||
`operate` varchar(255) DEFAULT NULL,
|
||||
|
||||
@ -0,0 +1,63 @@
|
||||
package com.cmvr.arm;
|
||||
import cmvr.api.*;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.cmvr.edge.client.manage.GrpcServiceManager;
|
||||
import com.cmvr.edge.client.model.EdgeCommonVO;
|
||||
import com.cmvr.edge.client.model.system.EdgeActionQueueVO;
|
||||
import com.cmvr.edge.client.service.impl.*;
|
||||
import com.cmvr.test.flow.runtime.engine.RobotDeviceAssignmentValidator;
|
||||
import io.grpc.*;
|
||||
import io.grpc.stub.StreamObserver;
|
||||
import org.junit.*;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.stream.Stream;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class ArmCoordinateFramesTest {
|
||||
private Server server;private ManagedChannel channel;private GrpcServiceManager clients;private ArmCoordinateFrames frames;
|
||||
private final AtomicReference<ArmCommand.MoveL.Request> motion=new AtomicReference<>();
|
||||
private final AtomicReference<ArmCommand.GetPose.Request> pose=new AtomicReference<>();
|
||||
private final AtomicReference<SystemCommand.ActionQueueCommand.Request> queue=new AtomicReference<>();
|
||||
private boolean failList,failMotion;
|
||||
private Common.CommandHeader.Feedback ok(){return Common.CommandHeader.Feedback.newBuilder().setSuccess(true).build();}
|
||||
@Before public void setup() throws Exception {
|
||||
server=io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder.forAddress(new java.net.InetSocketAddress("127.0.0.1",0))
|
||||
.addService(new ArmServiceGrpc.ArmServiceImplBase(){
|
||||
@Override public void listBaseFrame(ArmCommand.ListFrame.Request r,StreamObserver<ArmCommand.ListFrame.Response> o){list(r,o,"工件坐标");}
|
||||
@Override public void listTCPFrame(ArmCommand.ListFrame.Request r,StreamObserver<ArmCommand.ListFrame.Response> o){list(r,o,"扫描头_TCP");}
|
||||
private void list(ArmCommand.ListFrame.Request r,StreamObserver<ArmCommand.ListFrame.Response> o,String name){assertEquals("arm",r.getHeader().getDeviceId());o.onNext(ArmCommand.ListFrame.Response.newBuilder().setHeader(Common.CommandHeader.Feedback.newBuilder().setSuccess(!failList).setErrorMessage("不可用")).addFrameNames(name).build());o.onCompleted();}
|
||||
@Override public void moveL(ArmCommand.MoveL.Request r,StreamObserver<ArmCommand.MoveL.Response> o){motion.set(r);o.onNext(ArmCommand.MoveL.Response.newBuilder().setHeader(Common.CommandHeader.Feedback.newBuilder().setSuccess(!failMotion).setErrorMessage("运动拒绝")).build());o.onCompleted();}
|
||||
@Override public void getPose(ArmCommand.GetPose.Request r,StreamObserver<ArmCommand.GetPose.Response> o){pose.set(r);o.onNext(ArmCommand.GetPose.Response.newBuilder().setHeader(ok()).setPose(ArmCommand.CartesianPose.newBuilder().setX(.123).setRx(Math.PI/2)).build());o.onCompleted();}
|
||||
}).addService(new SystemServiceGrpc.SystemServiceImplBase(){@Override public void executeActionQueue(SystemCommand.ActionQueueCommand.Request r,StreamObserver<SystemCommand.ActionQueueCommand.Feedback> o){queue.set(r);o.onNext(SystemCommand.ActionQueueCommand.Feedback.newBuilder().setHeader(ok()).build());o.onCompleted();}}).build().start();
|
||||
channel=io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder.forAddress("127.0.0.1",server.getPort()).usePlaintext().build();
|
||||
clients=mock(GrpcServiceManager.class);when(clients.getGrpcClient("robot",ArmServiceGrpc.ArmServiceBlockingStub.class)).thenReturn(ArmServiceGrpc.newBlockingStub(channel));when(clients.getGrpcClient("robot",SystemServiceGrpc.SystemServiceBlockingStub.class)).thenReturn(SystemServiceGrpc.newBlockingStub(channel));
|
||||
ObjectProvider<RobotDeviceAssignmentValidator> validators=mock(ObjectProvider.class);when(validators.orderedStream()).thenAnswer(i->Stream.empty());frames=new ArmCoordinateFrames(clients,validators);
|
||||
}
|
||||
@After public void close() throws Exception {if(channel!=null)channel.shutdownNow().awaitTermination(3,TimeUnit.SECONDS);if(server!=null)server.shutdownNow().awaitTermination(3,TimeUnit.SECONDS);}
|
||||
private EdgeArmServiceImpl service(){var s=new EdgeArmServiceImpl(clients);ReflectionTestUtils.setField(s,"coordinateFrames",frames);return s;}
|
||||
private EdgeCommonVO target(){var t=new EdgeCommonVO();t.setRobotId("robot");t.setDeviceId("arm");return t;}
|
||||
@Test public void listsActualNamesAndRejectsWrongDeviceFramesBeforeMotion(){
|
||||
assertEquals(List.of("工件坐标"),frames.catalog("robot","arm").getList("baseFrames",String.class));
|
||||
assertThrows(RuntimeException.class,()->service().moveL(target(),0,0,0,0,0,0,"BASE",.1,.2,0D,"别的坐标","扫描头_TCP"));assertNull(motion.get());
|
||||
failList=true;assertThrows(RuntimeException.class,()->frames.catalog("robot","arm"));
|
||||
}
|
||||
@Test public void poseAndMotionKeepTheSameFrameNamesAndSdkUnits(){
|
||||
var s=service();s.getPose(target(),"工件坐标","扫描头_TCP");s.moveL(target(),.123,0,0,Math.PI/2,0,0,"BASE",.1,.2,0D,"工件坐标","扫描头_TCP");
|
||||
assertEquals(pose.get().getBaseLink(),motion.get().getBaseFrame());assertEquals(pose.get().getEeLink(),motion.get().getTcpFrame());assertEquals(.123,motion.get().getTarget().getX(),0);assertEquals(Math.PI/2,motion.get().getTarget().getRx(),0);
|
||||
}
|
||||
@Test public void oldDefaultRequestsRemainOptionalAndMotionFailureDoesNotBecomeSuccess(){
|
||||
var s=service();s.moveL(target(),0,0,0,0,0,0,"BASE",.1,.2,0D);assertFalse(motion.get().hasBaseFrame());assertFalse(motion.get().hasTcpFrame());
|
||||
failMotion=true;assertThrows(RuntimeException.class,()->s.moveL(target(),0,0,0,0,0,0,"BASE",.1,.2,0D));
|
||||
}
|
||||
@Test public void queueAlsoForwardsFrameNames(){
|
||||
var s=new EdgeSystemServiceImpl(clients);ReflectionTestUtils.setField(s,"coordinateFrames",frames);
|
||||
var step=new EdgeActionQueueVO.Step();step.setType("ARM_MOVE_L");step.setDeviceId("arm");step.setTimeoutMs(60000);step.setParams(JSONObject.of("x",.123,"rx",Math.PI/2,"baseFrame","工件坐标","tcpFrame","扫描头_TCP"));
|
||||
var request=new EdgeActionQueueVO();request.setRobotId("robot");request.setSteps(List.of(step));s.executeActionQueue(request);
|
||||
var sent=queue.get().getSteps(0).getArmMoveL();assertEquals("工件坐标",sent.getBaseFrame());assertEquals("扫描头_TCP",sent.getTcpFrame());assertEquals(.123,sent.getTarget().getX(),0);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
package com.cmvr.arm;
|
||||
import com.cmvr.test.flow.runtime.engine.RobotTaskOccupationGuard;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import java.util.stream.Stream;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
public class ArmTeachingAccessTest {
|
||||
@Test public void invalidParamsDoNotCreateLeaseAndStopRemainsAvailable() throws Exception {
|
||||
var service=mock(ArmTeachingService.class);var guard=mock(RobotTaskOccupationGuard.class);
|
||||
ObjectProvider<RobotTaskOccupationGuard> guards=mock(ObjectProvider.class);when(guards.orderedStream()).thenAnswer(i->Stream.of(guard));
|
||||
var access=new ArmTeachingAccessService(service,guards);var p=new ArmTeachingRequest();p.setRobotId("r");p.setDeviceId("a");p.setFileName("../bad");
|
||||
assertThrows(RuntimeException.class,()->access.execute(ArmTeachingOperation.START_TRAJECTORY_RECORDING,p));verifyNoInteractions(guard,service);
|
||||
access.execute(ArmTeachingOperation.STOP_MOTION,p);access.execute(ArmTeachingOperation.LIST_RECORDED_TRAJECTORIES,p);verifyNoInteractions(guard);
|
||||
AutoCloseable gate=mock(AutoCloseable.class);when(guard.manual("r")).thenReturn(gate);p.setFileName("valid.csv");
|
||||
access.execute(ArmTeachingOperation.START_TRAJECTORY_RECORDING,p);verify(guard).manual("r");verify(gate).close();
|
||||
verify(guard,never()).release(anyString(),anyBoolean());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,119 @@
|
||||
package com.cmvr.arm;
|
||||
|
||||
import cmvr.api.*;
|
||||
import com.cmvr.edge.client.manage.GrpcServiceManager;
|
||||
import com.cmvr.test.flow.runtime.engine.RobotDeviceAssignmentValidator;
|
||||
import io.grpc.*;
|
||||
import io.grpc.stub.StreamObserver;
|
||||
import org.junit.*;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.*;
|
||||
import java.util.stream.Stream;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
public class ArmTeachingIntegrationTest {
|
||||
private Server server;
|
||||
private ManagedChannel channel;
|
||||
private ArmTeachingService service;
|
||||
private GrpcServiceManager clients;
|
||||
private final List<String> calls=new CopyOnWriteArrayList<>();
|
||||
private final AtomicReference<ArmCommand.ReplayRecordedTrajectory.Request> replayRequest=new AtomicReference<>();
|
||||
private final AtomicReference<ArmCommand.StartTrajectoryRecording.Request> recordRequest=new AtomicReference<>();
|
||||
private final AtomicReference<String> failure=new AtomicReference<>();
|
||||
private final AtomicBoolean rejected=new AtomicBoolean(),missingHeader=new AtomicBoolean();
|
||||
private final CountDownLatch entered=new CountDownLatch(1),release=new CountDownLatch(1);
|
||||
private final AtomicBoolean waitReplay=new AtomicBoolean();
|
||||
private Common.CommandHeader.Feedback feedback(){return Common.CommandHeader.Feedback.newBuilder().setSuccess(!rejected.get()).setErrorMessage(rejected.get()?"recording still active":"").build();}
|
||||
private <T> void reply(String method,String device,T response,StreamObserver<T> observer) {
|
||||
assertEquals("aubo_arm",device);calls.add(method);
|
||||
if(failure.get()!=null){observer.onError(Status.fromCode(Status.Code.valueOf(failure.get())).withDescription("supplier full error text").asRuntimeException());return;}
|
||||
observer.onNext(response);observer.onCompleted();
|
||||
}
|
||||
@Before public void setup() throws Exception {
|
||||
var fake=new ArmServiceGrpc.ArmServiceImplBase() {
|
||||
@Override public void torqueOn(Common.CommandHeader.Request r,StreamObserver<Common.CommandHeader.Feedback> o){reply("enable",r.getDeviceId(),feedback(),o);}
|
||||
@Override public void enterTeachingMode(Common.CommandHeader.Request r,StreamObserver<Common.CommandHeader.Feedback> o){reply("enter",r.getDeviceId(),feedback(),o);}
|
||||
@Override public void stopTrajectoryRecording(Common.CommandHeader.Request r,StreamObserver<Common.CommandHeader.Feedback> o){reply("stopRecord",r.getDeviceId(),feedback(),o);}
|
||||
@Override public void exitTeachingMode(Common.CommandHeader.Request r,StreamObserver<Common.CommandHeader.Feedback> o){reply("exit",r.getDeviceId(),feedback(),o);}
|
||||
@Override public void completeTeaching(Common.CommandHeader.Request r,StreamObserver<Common.CommandHeader.Feedback> o){reply("complete",r.getDeviceId(),feedback(),o);}
|
||||
@Override public void stopMotion(Common.CommandHeader.Request r,StreamObserver<Common.CommandHeader.Feedback> o){reply("stopMotion",r.getDeviceId(),feedback(),o);}
|
||||
@Override public void startTrajectoryRecording(ArmCommand.StartTrajectoryRecording.Request r,StreamObserver<ArmCommand.StartTrajectoryRecording.Response> o) {
|
||||
recordRequest.set(r);var b=ArmCommand.StartTrajectoryRecording.Response.newBuilder();if(!missingHeader.get())b.setHeader(feedback());reply("record",r.getHeader().getDeviceId(),b.build(),o);
|
||||
}
|
||||
@Override public void listRecordedTrajectories(ArmCommand.ListRecordedTrajectories.Request r,StreamObserver<ArmCommand.ListRecordedTrajectories.Response> o) {
|
||||
reply("list",r.getHeader().getDeviceId(),ArmCommand.ListRecordedTrajectories.Response.newBuilder().setHeader(feedback()).setRecording(false).setRecordedSamples(-1L)
|
||||
.addTrajectories(ArmCommand.RecordedTrajectory.newBuilder().setFileName("sample.csv").setSamples(9007199254740993L).setDurationS(1).setSamplingFrequencyHz(100)).build(),o);
|
||||
}
|
||||
@Override public void getArmInfo(ArmCommand.GetArmInfo.Request r,StreamObserver<ArmCommand.GetArmInfo.Response> o) {
|
||||
reply("info",r.getHeader().getDeviceId(),ArmCommand.GetArmInfo.Response.newBuilder().setHeader(feedback()).setDeviceId("aubo_arm").setDof(6).build(),o);
|
||||
}
|
||||
@Override public void getRobotState(ArmCommand.GetRobotState.Request r,StreamObserver<ArmCommand.GetRobotState.Response> o) {
|
||||
reply("state",r.getHeader().getDeviceId(),ArmCommand.GetRobotState.Response.newBuilder().setHeader(feedback()).setState(ArmCommand.RobotState.newBuilder().setConnected(true).setMoving(false).setSafetyMode(ArmCommand.ArmSafetyMode.ARM_SAFETY_MODE_NORMAL)).build(),o);
|
||||
}
|
||||
@Override public void moveToTrajectoryStart(ArmCommand.ReplayRecordedTrajectory.Request r,StreamObserver<ArmCommand.ReplayRecordedTrajectory.Response> o) {
|
||||
replayRequest.set(r);reply("start",r.getHeader().getDeviceId(),ArmCommand.ReplayRecordedTrajectory.Response.newBuilder().setHeader(feedback()).build(),o);
|
||||
}
|
||||
@Override public void replayRecordedTrajectory(ArmCommand.ReplayRecordedTrajectory.Request r,StreamObserver<ArmCommand.ReplayRecordedTrajectory.Response> o) {
|
||||
replayRequest.set(r);entered.countDown();if(waitReplay.get())try{release.await(5,TimeUnit.SECONDS);}catch(InterruptedException error){Thread.currentThread().interrupt();}
|
||||
reply("replay",r.getHeader().getDeviceId(),ArmCommand.ReplayRecordedTrajectory.Response.newBuilder().setHeader(feedback()).build(),o);
|
||||
}
|
||||
};
|
||||
server=ServerBuilder.forPort(0).addService(fake).build().start();
|
||||
channel=ManagedChannelBuilder.forAddress("127.0.0.1",server.getPort()).usePlaintext().disableRetry().build();
|
||||
clients=mock(GrpcServiceManager.class);when(clients.getGrpcClient(eq("robot"),eq(ArmServiceGrpc.ArmServiceBlockingStub.class))).thenReturn(ArmServiceGrpc.newBlockingStub(channel));
|
||||
ObjectProvider<RobotDeviceAssignmentValidator> validators=mock(ObjectProvider.class);when(validators.orderedStream()).thenAnswer(i->Stream.empty());
|
||||
service=new ArmTeachingService(clients,validators);
|
||||
}
|
||||
@After public void close() throws Exception {release.countDown();channel.shutdownNow().awaitTermination(3,TimeUnit.SECONDS);server.shutdownNow().awaitTermination(3,TimeUnit.SECONDS);}
|
||||
private ArmTeachingRequest request(){var r=new ArmTeachingRequest();r.setRobotId("robot");r.setDeviceId("aubo_arm");r.setFileName("sample.csv");return r;}
|
||||
@Test public void allRpcShapesWorkAndUint64IsNotRounded() {
|
||||
for(var op:ArmTeachingOperation.values())assertTrue(service.execute(op,request()).getBooleanValue("success"));
|
||||
assertEquals(11,calls.size());assertEquals("sample.csv",recordRequest.get().getFileName());assertTrue(recordRequest.get().hasHeader());
|
||||
var list=service.execute(ArmTeachingOperation.LIST_RECORDED_TRAJECTORIES,request());
|
||||
assertEquals("18446744073709551615",list.getString("recordedSamples"));assertEquals("9007199254740993",list.getJSONArray("trajectories").getJSONObject(0).getString("samples"));
|
||||
assertFalse(list.getBooleanValue("recording"));
|
||||
}
|
||||
@Test public void replayPassesDocumentUnitsAndWaitsForPhysicalRpcCompletion() throws Exception {
|
||||
var request=request();request.setSpeedRatio(0.5);request.setMaxVelocity(0.3);request.setMaxAcceleration(0.5);request.setMaxJerk(2D);
|
||||
waitReplay.set(true);var executor=Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
var future=executor.submit(()->service.execute(ArmTeachingOperation.REPLAY_RECORDED_TRAJECTORY,request));
|
||||
assertTrue(entered.await(3,TimeUnit.SECONDS));assertFalse(future.isDone());release.countDown();assertTrue(future.get(3,TimeUnit.SECONDS).getBooleanValue("success"));
|
||||
assertEquals(0.5,replayRequest.get().getSpeedRatio(),0);assertEquals(0.3,replayRequest.get().getMaxVelocity(),0);assertEquals(2,replayRequest.get().getMaxJerk(),0);
|
||||
} finally{release.countDown();executor.shutdownNow();}
|
||||
}
|
||||
@Test public void businessFailureAndMissingHeaderAreNotSuccess() {
|
||||
rejected.set(true);assertTrue(assertThrows(RuntimeException.class,()->service.execute(ArmTeachingOperation.COMPLETE_TEACHING,request())).getMessage().contains("recording still active"));
|
||||
rejected.set(false);missingHeader.set(true);assertTrue(assertThrows(RuntimeException.class,()->service.execute(ArmTeachingOperation.START_TRAJECTORY_RECORDING,request())).getMessage().contains("缺少业务结果头"));
|
||||
}
|
||||
@Test public void grpcFailureKeepsFullStatusAndDescriptionWithoutRetry() {
|
||||
failure.set("UNIMPLEMENTED");var error=assertThrows(RuntimeException.class,()->service.execute(ArmTeachingOperation.ENTER_TEACHING_MODE,request()));
|
||||
assertTrue(error.getMessage().contains("UNIMPLEMENTED"));assertTrue(error.getMessage().contains("supplier full error text"));assertEquals(1,calls.size());
|
||||
}
|
||||
@Test public void timeoutIsNotClaimedAsMotionCompletedAndDoesNotRetry() {
|
||||
waitReplay.set(true);var request=request();request.setTimeoutMs(100L);
|
||||
var error=assertThrows(RuntimeException.class,()->service.execute(ArmTeachingOperation.REPLAY_RECORDED_TRAJECTORY,request));
|
||||
assertTrue(error.getMessage().contains("DEADLINE_EXCEEDED"));assertTrue(error.getMessage().contains("不自动重发"));
|
||||
}
|
||||
@Test public void workflowReturnsReusableFilenameAndStructuredState() {
|
||||
var operator=new com.cmvr.test.flow.runtime.operator.edge.EdgeArmOperateService(mock(com.cmvr.edge.client.service.EdgeArmService.class));
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(operator,"teaching",service);
|
||||
var message=new com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage();message.setRobotId("robot");
|
||||
message.setAction(com.cmvr.test.enums.ActionEnum.ARM_START_TRAJECTORY_RECORDING);
|
||||
message.setInputParams(com.alibaba.fastjson2.JSONObject.of("deviceId","aubo_arm","fileName","sample","samplingFrequencyHz",100));
|
||||
var output=operator.execute(message).getOutputParams();assertEquals("sample.csv",output.getString("fileName"));
|
||||
message.setAction(com.cmvr.test.enums.ActionEnum.ARM_MOVE_TO_TRAJECTORY_START);message.setInputParams(com.alibaba.fastjson2.JSONObject.of("deviceId","aubo_arm","fileName",output.getString("fileName")));
|
||||
assertTrue(operator.execute(message).isSuccess());assertEquals("sample.csv",replayRequest.get().getFileName());
|
||||
message.setAction(com.cmvr.test.enums.ActionEnum.ARM_GET_ROBOT_STATE);message.setInputParams(com.alibaba.fastjson2.JSONObject.of("deviceId","aubo_arm"));
|
||||
assertFalse(operator.execute(message).getOutputParams().getJSONObject("state").getBooleanValue("moving"));
|
||||
}
|
||||
@Test public void existingEnableMustCheckBusinessFeedback() {
|
||||
var arm=new com.cmvr.edge.client.service.impl.EdgeArmServiceImpl(clients);
|
||||
assertTrue(arm.torqueOn(request()).getSuccess());
|
||||
rejected.set(true);assertTrue(assertThrows(RuntimeException.class,()->arm.torqueOn(request())).getMessage().contains("recording still active"));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,28 @@
|
||||
package com.cmvr.arm;
|
||||
import org.junit.Test;
|
||||
import com.alibaba.fastjson2.*;
|
||||
import static org.junit.Assert.*;
|
||||
public class ArmTeachingParametersTest {
|
||||
private JSONObject values(){return JSONObject.of("robotId","robot","deviceId","arm","fileName","sample.csv");}
|
||||
@Test public void fileAndNumericBoundariesFailBeforeAnyRpc() {
|
||||
for(String file:new String[]{"","../x.csv",".hidden","C:\\x.csv","x/y.csv","x\n.csv","中".repeat(41)})assertThrows(RuntimeException.class,()->ArmTeachingParameters.file(file));
|
||||
assertEquals("中".repeat(40),ArmTeachingParameters.file("中".repeat(40)));
|
||||
for(Object value:new Object[]{-1,0.05,1.1,"0.5",Double.NaN,Double.POSITIVE_INFINITY}) {
|
||||
var p=values();p.put("speedRatio",value);assertThrows(RuntimeException.class,()->ArmTeachingParameters.fromInputs(ArmTeachingOperation.REPLAY_RECORDED_TRAJECTORY,p));
|
||||
}
|
||||
for(double hz:new double[]{0,1,100}) {var p=values();p.put("samplingFrequencyHz",hz);ArmTeachingParameters.fromInputs(ArmTeachingOperation.START_TRAJECTORY_RECORDING,p);}
|
||||
for(double hz:new double[]{-1,0.5,101}) {var p=values();p.put("samplingFrequencyHz",hz);assertThrows(RuntimeException.class,()->ArmTeachingParameters.fromInputs(ArmTeachingOperation.START_TRAJECTORY_RECORDING,p));}
|
||||
var p=values();p.put("timeoutMs",100.5);assertThrows(RuntimeException.class,()->ArmTeachingParameters.fromInputs(ArmTeachingOperation.REPLAY_RECORDED_TRAJECTORY,p));
|
||||
}
|
||||
@Test public void upperBoundsDefaultsAndDynamicReferenceAreSupported() {
|
||||
var p=values();p.put("timeoutMs",21600000L);p.put("speedRatio",0);ArmTeachingParameters.fromInputs(ArmTeachingOperation.REPLAY_RECORDED_TRAJECTORY,p);
|
||||
var params=JSONArray.of(JSONObject.of("name","fileName","type","quote","quoteType","output","quote",JSONArray.of("record","output","fileName")));
|
||||
ArmTeachingParameters.validateLiterals(ArmTeachingOperation.REPLAY_RECORDED_TRAJECTORY,params);
|
||||
params.getJSONObject(0).put("quote",JSONArray.of("record"));assertThrows(RuntimeException.class,()->ArmTeachingParameters.validateLiterals(ArmTeachingOperation.REPLAY_RECORDED_TRAJECTORY,params));
|
||||
}
|
||||
@Test public void oldFieldsAndServiceMethodsStayWireCompatible() {
|
||||
var d=cmvr.api.ArmCommand.MoveL.Request.getDescriptor();assertEquals(5,d.findFieldByName("base_frame").getNumber());assertEquals(6,d.findFieldByName("tcp_frame").getNumber());
|
||||
assertEquals(6,cmvr.api.ArmCommand.JointState.getDescriptor().findFieldByName("current").getNumber());
|
||||
assertEquals(27,cmvr.api.ArmServiceGrpc.getServiceDescriptor().getMethods().size());
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user