diff --git a/AGENTS.md b/AGENTS.md index 0d6bf77..a5ed77b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,11 @@ # AM FreeScan 开发约定 +- 2026-11-11 用户要求所有设备组件的默认业务等待统一为120秒,前端可修改并由后端尊重显式值;旋转底座、扫描仪、机械臂、AGV与动作队列每步均适用,取消旧45秒上限和自由标定固定5秒规则。当前用例草稿中的显式业务超时按用户授权统一120秒,之后新填的自定义值不自动覆盖;冻结版本及历史执行不改写。队列总等待仍累加每步时间,边端0值语义和30分钟上限按协议保留。HTTP回执预留10秒,回零节点时限不得短于服务端等待并预留回执时间;连接建立、心跳、采样周期、画面流和清理线程收敛期限不属于业务操作超时。禁止自动重发超时运动,仍按实际停止确认释放。 + +- 2026-11-10 用户明确授权 QUIC 短暂断开恢复规则:新动作最多等待5秒重连,只在重新在线且设备校验通过后下发;不重发已经执行的动作。QUIC单独断开不取消独立的在途gRPC调用;地址、端口或边端bootId变化仍使旧通道失效。仅状态查询和停止清理可使用同一已登记设备的最后地址,不能用于新运动;停止回执与实际停止状态均确认后才释放占用,未知或失败保留。自动验证仅用本机模拟服务,不执行现场运动。 + +- 2026-11-10 用户要求机械臂操作默认等待统一为2分钟:独立接口、工作流关节/直线运动、示教和坐标系组件使用120000毫秒默认业务期限,显式配置保留。HTTP等待额外预留10秒收取回执;超时不代表动作完成,不自动重发。连接建立超时、动作队列步骤配置和扫描仪特殊操作等待独立维护。 + - 2026-11-06 用户要求移除扫描仪流程节点“已核对本次操作的目标和影响”及框架导入同类勾选项和对应的用户确认校验;已有流程中的 `confirm` 字段兼容忽略。供应商接口必需的固定 `confirm:true` 仅由 HTTP 适配层补齐,不再作为表单、发布或执行门槛;工程/会话、设备状态、停止回执和资源释放校验保持。 - 2026-11-06 用户进一步明确:本次及今后每次任务完成并验证通过后,主动删除该任务新增的测试源码(包括 `test.mjs`)、专用验证脚本、测试输入输出、验证报告、测试日志、测试编译产物及临时目录,不因属于自动化回归测试而默认永久保留,只保留任务实现、运行和维护所需的文件。项目原有回归测试、运行配置、凭据、来源指纹及明确要求保留的真实或演示数据不清理。当前进程占用的临时文件在进程正常退出后再清理,不为删除文件中断服务。 @@ -7,7 +13,8 @@ - 2026-11-07 待清理目录:`.local/verification/MAINTENANCE-20261107/dist` 是维护按钮弹窗任务的临时前端构建产物,28 项验证及完整构建已通过;测试源码、输入快照和验证日志已删除。自动审批检查以 `blocked by policy` 拒绝目录清理命令,尚未删除此构建目录;允许清理后删除上述精确目录及空批次目录,并移除本条记录。不得扩大到其他 `.local` 内容。 - 2026-11-06 用户要求配置模板放在 `am-backend/yudao-server/src/main/resources`,生产使用 `prod` profile 并通过 YAML 占位符读取部署环境变量;实际 Token、密码和私钥不新增到可提交模板。本机 scanner 连接信息继续保存在 `.local/scanner-private.yaml` 的 `cmvr.scanner` 下,仅 `local` / `dev` 自动导入;IDEA 中不重复保存 scanner 环境变量。该文件的 `cmvr.quic` 配置与证书继续保留,访问密钥不输出或提交。 -- 2026-10-30 用户再次明确旋转底座组件标题及说明使用中文;协议动作和RPC标识不翻译。旧英文默认标题可在加载时转为中文,用户自定义节点名称保留。组件分组统一使用collapseTitle,机械臂分组必须显示“机械臂示教与轨迹”,不能只剩数量。 +- 2026-11-10 用户要求爱玛扫描项目组件库将“机械臂示教与轨迹”改为“机械臂”,原机器人分组中的机械臂组件归入该组;机器人分组改为“AGV”且只显示AGV组件。相机、音频、大模型、语音交互、触控交互、闲聊等无关组件隐藏新增入口,已有流程定义和运行能力保留。 +- 2026-10-30 用户再次明确旋转底座组件标题及说明使用中文;协议动作和RPC标识不翻译。旧英文默认标题可在加载时转为中文,用户自定义节点名称保留。组件分组统一使用collapseTitle,标题与数量均须可见;机械臂分组名称按2026-11-10要求显示。 - 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`,不是测试数据,不清理。 diff --git a/README.md b/README.md index 27d0d89..5c598ad 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,8 @@ 修改 Java 后执行 `./scripts/start-backend.ps1 -Build`。本机预启动的后台实例可先用 `./scripts/stop-backend.ps1` 停止;自行在终端启动的实例用 Ctrl+C 停止,避免端口占用。日志、凭据和成果位于 Git 忽略的 `.local/`;前端源码和后端源码分别位于 `am-web/`、`am-backend/`。 +工作流与业务页面共用登录续期:平台明确返回未认证时,合并并发续期并按原参数最多重放一次。保存、上传、成果下载和预览连接均接入同一会话;取消、切换账号或租户后不会继续重放原请求。网络超时、业务失败、扫描服务带 `scannerCode` 的设备错误,以及已经打开的扫描流不会触发自动重发。续期短暂失败会保留编辑内容和会话,只有确认登录失效才提示重新登录。 + QUIC 使用 UDP `4433`,HTTP 后端使用 `48090`。本机 QUIC 私有配置位于 `.local/scanner-private.yaml`,证书和服务端私钥位于 `.local/quic-certs/`。2026-11-06 的证书保留 `192.168.0.222`,新增 `192.168.0.199`,沿用原 CA 和服务端私钥;原证书另行保留。证书来源和指纹见 [QUIC 证书更新记录](docs/quic-certificate-20261106.json)。 扫描服务的通用配置模板位于 `am-backend/yudao-server/src/main/resources/application.yaml` 的 `cmvr.scanner`,通过 `${AM_FREESCAN_SCANNER_*:}` 读取部署环境变量。本机使用 `local` / `dev` profile 时,会额外导入 Git 忽略的 `.local/scanner-private.yaml`,其中 `cmvr.scanner` 的 `host`、`port`、`api-key`、`robot-id` 和 `device-id` 覆盖通用模板。本机地址为 `192.168.0.112:18888`,绑定现有工位 `am-freescan-station-001`、设备 `am-freescan-scanner-001`;后端通过 Spring 配置绑定读取 YAML,以 `Authorization: Bearer …` 请求扫描服务。修改该私有 YAML 后,重新运行 IDEA 的 `am-backend` 配置即可生效;同文件的 `cmvr.quic` 配置继续保留。 diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmCoordinateMotionService.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmCoordinateMotionService.java index cd82cec..7350ea9 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmCoordinateMotionService.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmCoordinateMotionService.java @@ -33,7 +33,7 @@ public class ArmCoordinateMotionService { } private JSONObject step(EdgeArmMoveLVO p,String instId) { validate(p); - var query=new ArmTeachingRequest();query.setRobotId(p.getRobotId());query.setDeviceId(p.getDeviceId());query.setTimeoutMs(30000L); + var query=new ArmTeachingRequest();query.setRobotId(p.getRobotId());query.setDeviceId(p.getDeviceId());query.setTimeoutMs(ArmTimeouts.DEFAULT_MS); // Read failures must not create a physical-operation lease. teaching.validateTarget(ArmTeachingOperation.LIST_USER_COORDINATE_SYSTEMS,query); var proof=teaching.requireCoordinateProof(p.getRobotId(),p.getDeviceId(),p.getUserCoordinateName(),p.getUserCoordinateRevision()); diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmCoordinateStepParameters.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmCoordinateStepParameters.java index 10831d2..f369356 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmCoordinateStepParameters.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmCoordinateStepParameters.java @@ -36,7 +36,12 @@ public final class ArmCoordinateStepParameters { if(params!=null)for(int i=0;i!(v instanceof String s)||s.isBlank())||!("input".equals(field.getString("quoteType"))||"output".equals(field.getString("quoteType"))))throw new GlobalException("速度的引用不完整"); + p.put(name,1);continue; // Definition-only placeholder; runtime validates the resolved value. + } + if(!"input".equals(field.getString("type")))throw new GlobalException("目标位姿仅速度支持引用,坐标系和其他参数请直接配置"); p.put(name,field.get("input")); } fromInputs(p); diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingOperation.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingOperation.java index c32a4f9..c1394d4 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingOperation.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingOperation.java @@ -20,5 +20,5 @@ public enum ArmTeachingOperation { 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:30000;} + public long defaultTimeout(){return ArmTimeouts.DEFAULT_MS;} } diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingParameters.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingParameters.java index 638a74d..b7f51fb 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingParameters.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingParameters.java @@ -22,7 +22,7 @@ public final class ArmTeachingParameters { 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 op==ArmTeachingOperation.REPLAY_RECORDED_TRAJECTORY||op==ArmTeachingOperation.MOVE_TO_TRAJECTORY_START?result:Math.max(30000,result); + return result; } public static String file(String name) { if(name==null||name.isBlank()||!name.equals(name.trim())||name.startsWith(".")||name.contains("..") diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingService.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingService.java index ae5ae19..5e4e481 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingService.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingService.java @@ -30,12 +30,19 @@ public class ArmTeachingService { } 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); + if(recoveryOperation(op)) + v.validateRecovery(request.getRobotId(),request.getDeviceId(),2); else v.validate(request.getRobotId(),request.getDeviceId(),2); }); } public JSONObject execute(ArmTeachingOperation op,ArmTeachingRequest p) { + if(recoveryOperation(op))try(var scope=com.cmvr.common.robot.RecoveryRpcScope.enter()){return executeScoped(op,p);} + return executeScoped(op,p); + } + private boolean recoveryOperation(ArmTeachingOperation op) { + return op!=null&&(op.readOnly||java.util.Set.of(ArmTeachingOperation.STOP_MOTION,ArmTeachingOperation.STOP_TRAJECTORY_RECORDING,ArmTeachingOperation.EXIT_TEACHING_MODE,ArmTeachingOperation.COMPLETE_TEACHING).contains(op)); + } + private JSONObject executeScoped(ArmTeachingOperation op,ArmTeachingRequest p) { ArmTeachingParameters.validate(op,p);validateTarget(op,p); if(java.util.Set.of(ArmTeachingOperation.APPLY_USER_COORDINATE_SYSTEM,ArmTeachingOperation.UPDATE_USER_COORDINATE_SYSTEM,ArmTeachingOperation.DELETE_USER_COORDINATE_SYSTEM,ArmTeachingOperation.STOP_MOTION).contains(op))invalidateCoordinateProof(p.getRobotId(),p.getDeviceId()); var header=EdgeCommonUtil.buildRequest(p.getDeviceId()); diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingStopExtension.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingStopExtension.java index 5f4e35b..b4fa6f3 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingStopExtension.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTeachingStopExtension.java @@ -20,7 +20,7 @@ public class ArmTeachingStopExtension implements RobotStopExtension { 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); + var request=new ArmTeachingRequest();request.setRobotId(robotId);request.setDeviceId(device.getDeviceId());request.setTimeoutMs(120000L); JSONObject listing; try{listing=teaching.execute(ArmTeachingOperation.LIST_RECORDED_TRAJECTORIES,request);} catch(GlobalException unavailable) { diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTimeouts.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTimeouts.java new file mode 100644 index 0000000..258ad2b --- /dev/null +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/arm/ArmTimeouts.java @@ -0,0 +1,8 @@ +package com.cmvr.arm; +import com.cmvr.common.exception.GlobalException; +/** Business-operation deadline; independent of socket connection timeout. */ +public final class ArmTimeouts { + public static final long DEFAULT_MS=120000L; + private ArmTimeouts(){} + public static long resolve(Long value){long result=value==null?DEFAULT_MS:value;if(result<100||result>21600000)throw new GlobalException("机械臂等待超时须为100至21600000毫秒");return result;} +} diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/common/robot/RecoveryRpcScope.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/common/robot/RecoveryRpcScope.java new file mode 100644 index 0000000..d926568 --- /dev/null +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/common/robot/RecoveryRpcScope.java @@ -0,0 +1,12 @@ +package com.cmvr.common.robot; + +/** Internal thread-local permission for diagnostics and stopping a registered endpoint. */ +public final class RecoveryRpcScope implements AutoCloseable { + private static final ThreadLocal DEPTH = ThreadLocal.withInitial(() -> 0); + private final int previous; + private boolean closed; + private RecoveryRpcScope() { previous = DEPTH.get(); DEPTH.set(previous + 1); } + public static RecoveryRpcScope enter() { return new RecoveryRpcScope(); } + public static boolean active() { return DEPTH.get() > 0; } + @Override public void close() { if (!closed) { closed = true; if (previous == 0) DEPTH.remove(); else DEPTH.set(previous); } } +} diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/common/robot/RobotEndpointResolver.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/common/robot/RobotEndpointResolver.java index 2652a17..891a418 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/common/robot/RobotEndpointResolver.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/common/robot/RobotEndpointResolver.java @@ -3,4 +3,6 @@ package com.cmvr.common.robot; public interface RobotEndpointResolver { RobotEndpoint resolve(String robotId); + /** Only trusted platform recovery/read operations may use the last registered address. */ + default RobotEndpoint resolveForRecovery(String robotId) { return resolve(robotId); } } diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/manage/GrpcServiceManager.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/manage/GrpcServiceManager.java index bd1e2ad..bf490e9 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/manage/GrpcServiceManager.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/manage/GrpcServiceManager.java @@ -68,7 +68,10 @@ public class GrpcServiceManager { */ @SuppressWarnings("unchecked") public T getGrpcClient(String robotId, Class serviceClass) { - ManagedChannel channel = grpcChannelCache.get(robotId, this::createChannel); + // Resolve before taking the cache's per-robot compute lock: a reconnect event + // must be able to commit while a node is waiting for that reconnect. + InetSocketAddress endpoint = getGrpcServiceEndpoint(robotId); + ManagedChannel channel = grpcChannelCache.get(robotId, key -> createChannel(endpoint)); GrpcClientFactory factory = (GrpcClientFactory) clientFactories.get(serviceClass); if (factory == null) { @@ -81,8 +84,7 @@ public class GrpcServiceManager { /** * 创建gRPC通道 */ - private ManagedChannel createChannel(String robotId) { - InetSocketAddress endpoint = getGrpcServiceEndpoint(robotId); + private ManagedChannel createChannel(InetSocketAddress endpoint) { return io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder.forAddress(endpoint.getHostString(), endpoint.getPort()) .withOption(io.grpc.netty.shaded.io.netty.channel.ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000) .usePlaintext() @@ -94,7 +96,8 @@ public class GrpcServiceManager { * 获取终端地址 */ private InetSocketAddress getGrpcServiceEndpoint(String robotId) { - RobotEndpoint endpoint = robotEndpointResolver.resolve(robotId); + RobotEndpoint endpoint = com.cmvr.common.robot.RecoveryRpcScope.active() + ? robotEndpointResolver.resolveForRecovery(robotId) : robotEndpointResolver.resolve(robotId); return createEndpoint(endpoint.host(), (long) endpoint.port(), "机器人 " + robotId); } diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/arm/EdgeArmMoveJVO.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/arm/EdgeArmMoveJVO.java index 9997ec5..2450cc3 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/arm/EdgeArmMoveJVO.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/arm/EdgeArmMoveJVO.java @@ -20,10 +20,10 @@ public class EdgeArmMoveJVO extends EdgeCommonVO { @ApiModelProperty(value = "目标关节位置数组(6个关节角度,单位:弧度)", required = true) private double[] target; - @ApiModelProperty("运动速度(单位:m/s)") + @ApiModelProperty("关节运动速度(单位:rad/s)") private Double velocity; - @ApiModelProperty("加速度(单位:m/s²)") + @ApiModelProperty("关节加速度(单位:rad/s²)") private Double acceleration; @ApiModelProperty("融合半径(单位:m)") @@ -34,4 +34,6 @@ public class EdgeArmMoveJVO extends EdgeCommonVO { @ApiModelProperty("是否异步执行") private Boolean asynchronous; + @ApiModelProperty("等待超时(毫秒),默认120000") + private Long timeoutMs; } diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/system/ActionQueueInputBindings.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/system/ActionQueueInputBindings.java new file mode 100644 index 0000000..fea7662 --- /dev/null +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/system/ActionQueueInputBindings.java @@ -0,0 +1,52 @@ +package com.cmvr.edge.client.model.system; + +import com.alibaba.fastjson2.JSONArray; +import com.alibaba.fastjson2.JSONObject; +import com.cmvr.common.exception.GlobalException; +import java.util.Set; + +/** Workflow references resolve through the normal per-iteration input preparer before queue submission. */ +public final class ActionQueueInputBindings { + private ActionQueueInputBindings() {} + public static JSONObject resolve(JSONObject source, JSONObject inputs) { + var result = new JSONObject(source); + var bindings = source.getJSONObject("paramBindings"); + if (bindings == null || bindings.isEmpty()) return result; + if (source.getString("type") == null || !Set.of("ARM_MOVE_J", "ARM_MOVE_J_POSE", "ARM_MOVE_L").contains(source.getString("type")) + || !bindings.keySet().equals(Set.of("velocity"))) + throw new GlobalException("动作队列仅机械臂步骤的速度支持此参数引用"); + String name = bindings.getString("velocity"); + if (name == null || !name.matches("queue_velocity_[A-Za-z0-9_-]+")) + throw new GlobalException("动作队列速度引用标识无效"); + Object value = inputs.get(name); + if (!(value instanceof Number n) || !Double.isFinite(n.doubleValue()) || n.doubleValue() < 0) + throw new GlobalException("动作队列速度引用须返回有效的非负数值,不能使用空值、文本或旧的填写值"); + var params = source.getJSONObject("params"); + params = params == null ? new JSONObject() : new JSONObject(params); + params.put("velocity", value); + result.put("params", params); + result.remove("paramBindings"); + return result; + } + public static JSONObject validateDefinition(JSONObject source, JSONArray definitions) { + var bindings = source.getJSONObject("paramBindings"); + if (bindings == null || bindings.isEmpty()) return source; + String name = bindings.getString("velocity"); + JSONObject definition = null; + if (definitions != null) for (int i = 0; i < definitions.size(); i++) { + var candidate = definitions.getJSONObject(i); + if (java.util.Objects.equals(name, candidate.getString("name"))) { + if (definition != null) throw new GlobalException("动作队列速度参数重复"); + definition = candidate; + } + } + if (definition == null || !"quote".equals(definition.getString("type"))) + throw new GlobalException("动作队列速度未配置有效引用"); + var path = definition.getJSONArray("quote"); + if (path == null || path.size() < 3 || path.stream().anyMatch(v -> !(v instanceof String s) || s.isBlank()) + || !("input".equals(definition.getString("quoteType")) || "output".equals(definition.getString("quoteType")))) + throw new GlobalException("动作队列速度引用不完整"); + // Definition-only placeholder; runtime resolve() requires the actual current input. + return resolve(source, JSONObject.of(name, 0.1)); + } +} diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/system/ActionQueueParameters.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/system/ActionQueueParameters.java new file mode 100644 index 0000000..731482b --- /dev/null +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/system/ActionQueueParameters.java @@ -0,0 +1,117 @@ +package com.cmvr.edge.client.model.system; + +import com.alibaba.fastjson2.JSONObject; +import com.cmvr.arm.ArmUserCoordinates; +import com.cmvr.common.exception.GlobalException; + +import java.util.HashMap; +import java.util.Map; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +/** Offline queue checks. Never queries, applies a coordinate, or sends motion to an edge. */ +public final class ActionQueueParameters { + public static final String APPLY_USER_COORDINATE = "ARM_APPLY_USER_COORDINATE_SYSTEM"; + private static final Set COORDINATE_FIELDS = Set.of("name", "expectedRevision"); + private static final List LEGACY_MOVE_FIELDS = List.of( + "frame", "baseFrame", "tcpFrame", "userCoordinateName", "userCoordinateRevision", + "userFramePose", "tcpOffset", "coordinateRelativeTranslation", "base_frame", "tcp_frame", + "user_coordinate_name", "user_coordinate_revision", "user_frame_pose", "tcp_offset", + "coordinate_relative_translation", "relative", "frameReferenceMode"); + + private ActionQueueParameters() {} + + /** Device binding keys may be represented by synthetic IDs during definition validation. */ + public static void validate(List steps) { + ActionQueueTimeouts.total(steps); + Map appliedDevices = new HashMap<>(); + for (int index = 0; index < steps.size(); index++) { + EdgeActionQueueVO.Step step = steps.get(index); + if (step.getType() == null || step.getType().isBlank()) { + throw new GlobalException("动作队列第" + (index + 1) + "步缺少操作类型"); + } + String type = step.getType().trim().toUpperCase(Locale.ROOT); + JSONObject params = step.getParams() == null ? new JSONObject() : step.getParams(); + String device = step.getDeviceId() == null ? null : step.getDeviceId().trim(); + if (device != null && device.isEmpty()) device = null; + boolean selectedCoordinate = "APPLIED".equals(step.getCoordinateMode()); + if (step.getCoordinateMode() != null && !step.getCoordinateMode().isBlank() + && (!selectedCoordinate || !Set.of("ARM_MOVE_L", "ARM_MOVE_J_POSE").contains(type))) { + throw new GlobalException("动作队列第" + (index + 1) + "步的坐标系使用方式无效"); + } + switch (type) { + case APPLY_USER_COORDINATE -> { + coordinateRevision(params); + if (device != null) appliedDevices.put(device, params); + } + case "ARM_MOVE_L" -> { + boolean inherited = device != null && appliedDevices.containsKey(device); + if (selectedCoordinate && device != null && !inherited) { + throw new GlobalException("动作队列第" + (index + 1) + + "步须先为同一机械臂添加“应用用户坐标系”步骤"); + } + if (selectedCoordinate || inherited) { + for (String key : LEGACY_MOVE_FIELDS) { + Object value = params.get(key); + if (value != null && (!(value instanceof String text) || !text.isBlank())) { + throw new GlobalException("动作队列第" + (index + 1) + + "步沿用已应用坐标系,不能混填旧坐标系或增量参数:" + key); + } + } + } + } + case "ARM_MOVE_J_POSE" -> poseCoordinate(step, appliedDevices.get(device)); + case "ARM_MOVE_J" -> { /* Joint targets remain independent of the selected coordinate. */ } + default -> throw new GlobalException("动作队列不支持的操作类型:" + step.getType()); + } + } + } + + /** Resolve names from the preceding application; never convert joint targets or solve IK here. */ + public static JSONObject poseCoordinate(EdgeActionQueueVO.Step step, JSONObject application) { + if (application == null) throw new GlobalException("末端位姿MoveJ须先为同一机械臂添加应用坐标系步骤"); + JSONObject p = step.getParams() == null ? new JSONObject() : step.getParams(); + for (String axis : List.of("x", "y", "z", "rx", "ry", "rz")) ArmUserCoordinates.finite(p.get(axis), axis + "绝对目标(m/rad)"); + for (String field : List.of("velocity", "acceleration")) + if (ArmUserCoordinates.finite(p.get(field), field + "关节限值") <= 0) throw new GlobalException("末端位姿MoveJ速度和加速度须为有限正数(rad/s、rad/s²)"); + for (String key : LEGACY_MOVE_FIELDS) { + if (!Set.of("userCoordinateName", "userCoordinateRevision").contains(key) && p.get(key) != null) + throw new GlobalException("末端位姿MoveJ不能混填旧坐标系或增量字段:" + key); + } + if (p.containsKey("positions") || p.containsKey("target")) throw new GlobalException("末端位姿MoveJ须填写六维TCP位姿,不能填写关节角数组"); + for (String field : List.of("blendRadius", "jerk")) + if (p.get(field) != null && ArmUserCoordinates.finite(p.get(field), field) != 0) throw new GlobalException("末端位姿MoveJ不支持非零" + field); + String name = application.getString("name"); + long revision = coordinateRevision(application); + if (p.get("userCoordinateName") != null && !name.equals(p.get("userCoordinateName"))) throw new GlobalException("MoveJ坐标系名称必须与前序应用步骤一致"); + if (p.get("userCoordinateRevision") != null && (!(p.get("userCoordinateRevision") instanceof String text) + || text.isBlank() || ArmUserCoordinates.revision(text, false) != revision)) throw new GlobalException("MoveJ坐标系版本必须与前序应用步骤一致并使用uint64字符串"); + return JSONObject.of("name", name, "expectedRevision", Long.toUnsignedString(revision)); + } + + /** Returns the raw uint64 bits expected by protobuf; callers must preserve the input string. */ + public static long coordinateRevision(JSONObject params) { + for (String key : params.keySet()) { + if (!COORDINATE_FIELDS.contains(key)) { + throw new GlobalException("队列应用坐标系仅接受名称和记录版本,不能传入坐标内容或其他参数:" + key); + } + } + if (!(params.get("name") instanceof String name)) { + throw new GlobalException("请选择队列步骤需要应用的坐标系"); + } + ArmUserCoordinates.name(name, false); + Object revision = params.get("expectedRevision"); + if (revision != null && (!(revision instanceof String text) || text.isBlank())) { + throw new GlobalException("坐标系记录版本须为uint64十进制字符串,0表示执行时读取最新版本"); + } + long parsed = ArmUserCoordinates.revision((String) revision, false); + if (name.startsWith("__builtin_")) { + if (!Set.of("__builtin_base__", "__builtin_tool__").contains(name)) { + throw new GlobalException("动作队列仅支持基座和工具两种内置坐标系"); + } + if (parsed != 1L) throw new GlobalException("内置坐标系的记录版本固定为1"); + } + return parsed; + } +} diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/system/ActionQueueTimeouts.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/system/ActionQueueTimeouts.java index d95666d..a4ed02e 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/system/ActionQueueTimeouts.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/system/ActionQueueTimeouts.java @@ -3,17 +3,20 @@ 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. */ +/** Missing steps use 120s; zero total uses the documented edge default of five minutes. */ public final class ActionQueueTimeouts { - public static final int DEFAULT_STEP_TIMEOUT_MS = 60000; + public static final int DEFAULT_STEP_TIMEOUT_MS = 120000; + public static final int SERVER_DEFAULT_TIMEOUT_MS = 300000; + public static final int MAX_QUEUE_TIMEOUT_MS = 1800000; private ActionQueueTimeouts() {} public static int step(Integer value) { if (value == null) return DEFAULT_STEP_TIMEOUT_MS; - if (value < 0) throw new GlobalException("步骤超时不能为负数,0表示不限时"); + if (value < 0 || value > MAX_QUEUE_TIMEOUT_MS) throw new GlobalException("步骤超时须为0至1800000毫秒,0继承队列剩余时间"); return value; } public static int total(List steps) { if (steps == null || steps.isEmpty()) throw new GlobalException("动作队列至少需要一个步骤"); + if (steps.size() > 100) throw new GlobalException("动作队列最多100个步骤"); long total = 0; boolean unlimited = false; for (var item : steps) { if (item == null) throw new GlobalException("动作队列包含无效步骤"); @@ -22,7 +25,7 @@ public final class ActionQueueTimeouts { total += timeout; } if (unlimited) return 0; - if (total > Integer.MAX_VALUE) throw new GlobalException("队列总超时超出支持范围,请拆分队列或将步骤超时设为0"); + if (total > MAX_QUEUE_TIMEOUT_MS) throw new GlobalException("队列总超时最多30分钟,请拆分队列或将步骤设为0以使用边端默认5分钟"); return (int) total; } } diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/system/EdgeActionQueueVO.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/system/EdgeActionQueueVO.java index e97d9fa..479f2dc 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/system/EdgeActionQueueVO.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/model/system/EdgeActionQueueVO.java @@ -18,6 +18,8 @@ public class EdgeActionQueueVO { private String stepId; private String type; private String deviceId; + /** Platform editing intent only; never forwarded as a protobuf field. */ + private String coordinateMode; private Integer timeoutMs; private JSONObject params = new JSONObject(); } diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/AgvViewService.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/AgvViewService.java new file mode 100644 index 0000000..ece1026 --- /dev/null +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/AgvViewService.java @@ -0,0 +1,90 @@ +package com.cmvr.edge.client.service; + +import cmvr.api.*; +import cmvr.msgs.Agv; +import com.alibaba.fastjson2.*; +import com.cmvr.common.exception.GlobalException; +import com.cmvr.edge.client.manage.GrpcServiceManager; +import com.cmvr.edge.client.utils.EdgeCommonUtil; +import io.grpc.Context; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.util.*; +import java.util.concurrent.TimeUnit; +import javax.imageio.ImageIO; + +/** Read-only AGV visualization. Never starts mapping, switches maps, or issues motion. */ +@Service @RequiredArgsConstructor +public class AgvViewService { + private final GrpcServiceManager clients; + private final Map states=Collections.synchronizedMap(new LinkedHashMap<>(32,.75f,true){protected boolean removeEldestEntry(Map.Entry e){return size()>64;}}); + private final Map maps=Collections.synchronizedMap(new LinkedHashMap<>(16,.75f,true){protected boolean removeEldestEntry(Map.Entry e){return size()>16;}}); + private final Map stations=Collections.synchronizedMap(new LinkedHashMap<>(32,.75f,true){protected boolean removeEldestEntry(Map.Entry e){return size()>64;}}); + private final Object[] locks=new Object[32];{Arrays.setAll(locks,i->new Object());} + private record Entry(long at,JSONObject value){} + private Object lock(String key){return locks[(key.hashCode()&Integer.MAX_VALUE)%locks.length];} + private AgvServiceGrpc.AgvServiceBlockingStub stub(String robot,long timeout){return clients.getGrpcClient(robot,AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(timeout,TimeUnit.MILLISECONDS);} + private static void success(Common.CommandHeader.Feedback h){if(!h.getSuccess())throw new GlobalException(h.getErrorMessage().isBlank()?"AGV未返回成功回执":h.getErrorMessage());} + public JSONObject state(String robot,String device){ + String key=robot+"\n"+device; synchronized(lock(key)){ + Entry cached=states.get(key);if(cached!=null&&System.currentTimeMillis()-cached.at<800)return cached.value; + var r=stub(robot,1500).getRuntimeState(AgvCommand.AgvRuntimeStateCommand.Request.newBuilder().setHeader(EdgeCommonUtil.buildRequest(device)).build());success(r.getHeader()); + if(!r.hasState())throw new GlobalException("AGV未返回定位状态");var s=r.getState(); + var value=JSONObject.of("robotId",robot,"deviceId",device,"receivedAt",System.currentTimeMillis(),"timestamp",s.getTimestamp(),"connected",s.getConnected(),"localized",s.getLocalized(),"moving",s.getMoving(),"fault",s.getFault(),"emergencyStopped",s.getEmergencyStopped(),"currentMap",s.getCurrentMap(),"currentStation",s.getCurrentStation(),"lastError",s.getLastError()); + if(s.hasPose())value.put("pose",pose(s.getPose())); + if(s.hasVelocity())value.put("velocity",JSONObject.of("vx",s.getVelocity().getVx(),"vy",s.getVelocity().getVy(),"wz",s.getVelocity().getWz())); + states.put(key,new Entry(System.currentTimeMillis(),value));return value; + } + } + public JSONArray stations(String robot,String device,String map){ + String key=robot+"\n"+device+"\n"+map;synchronized(lock(key+"stations")){ + Entry cached=stations.get(key);if(cached!=null&&System.currentTimeMillis()-cached.at<30000)return cached.value.getJSONArray("stations"); + var r=stub(robot,2500).listStations(AgvCommand.AgvListStationsCommand.Request.newBuilder().setHeader(EdgeCommonUtil.buildRequest(device)).build());success(r.getHeader()); + var result=new JSONArray();for(var s:r.getStationsList()){if(result.size()>=10000)break;if(s.hasPose())result.add(JSONObject.of("id",s.getId(),"description",s.getDescription(),"pose",pose(s.getPose())));} + stations.put(key,new Entry(System.currentTimeMillis(),JSONObject.of("stations",result)));return result; + } + } + public JSONObject map(String robot,String device,String map){ + String key=robot+"\n"+device+"\n"+map;synchronized(lock(key+"map")){ + Entry cached=maps.get(key);if(cached!=null&&System.currentTimeMillis()-cached.at<30000)return cached.value; + try(var context=Context.current().withCancellation()){ + JSONObject value=context.call(()->{ + var request=AgvCommand.AgvMapStreamCommand.Request.newBuilder().setHeader(EdgeCommonUtil.buildRequest(device)).setDimension(Agv.AgvMapDimension.AGV_MAP_2D).setMapName(map).setSnapshot(true).setIncremental(false).setMaxChunkBytes(262144).build(); + var iterator=stub(robot,10000).streamMap(request);var chunks=new ArrayList();long receivedCells=0; + while(iterator.hasNext()){ + var reply=iterator.next();success(reply.getHeader());if(!reply.hasUpdate())continue;var u=reply.getUpdate(); + if(u.getUpdateType()==Agv.AgvMapUpdateType.AGV_MAP_UPDATE_RESET){chunks.clear();receivedCells=0;continue;} + if(!u.hasMap2D())continue;if(u.getUpdateType()!=Agv.AgvMapUpdateType.AGV_MAP_UPDATE_SNAPSHOT)throw new GlobalException("地图首次读取需要完整快照"); + if(u.getSnapshotBegin()){chunks.clear();receivedCells=0;}receivedCells+=u.getMap2D().getDataCount();if(receivedCells>4000000)throw new GlobalException("地图超过在线显示400万格限制");chunks.add(u);if(chunks.size()>1024)throw new GlobalException("地图分片数量超出在线显示限制"); + if(u.getSnapshotEnd())return encodeMap(chunks,map); + } + throw new GlobalException("地图流未返回完整二维快照"); + });maps.put(key,new Entry(System.currentTimeMillis(),value));return value; + }catch(RuntimeException e){throw e;}catch(Exception e){throw new GlobalException("读取AGV地图失败:"+e.getMessage());} + } + } + public static JSONObject pose(Agv.AgvPose2d p){return JSONObject.of("x",p.getX(),"y",p.getY(),"theta",p.getTheta());} + /** Reject incomplete, mixed or incremental snapshots instead of drawing a wrong map. */ + public static JSONObject encodeMap(List parts,String requestedMap)throws Exception{ + if(parts.isEmpty())throw new GlobalException("地图没有二维数据");var first=parts.get(0);var grid=first.getMap2D();long cells=(long)grid.getWidth()*grid.getHeight(); + if(cells<1||cells>4000000||grid.getWidth()>8192||grid.getHeight()>8192||!Double.isFinite(grid.getResolution())||grid.getResolution()<=0)throw new GlobalException("地图栅格尺寸或分辨率无效,在线显示最多400万格"); + var o=grid.getOrigin();if(!Double.isFinite(o.getX())||!Double.isFinite(o.getY())||!Double.isFinite(o.getTheta()))throw new GlobalException("地图原点无效"); + int width=grid.getWidth(),height=grid.getHeight(),offset=0;var image=new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);var objects=new JSONArray();int pointCount=0; + for(int i=0;i=cells)throw new GlobalException("地图数据多于栅格数量");int gray=cell<0?174:255-Math.min(100,cell)*2;image.getRaster().setSample(offset%width,height-1-offset/width,0,gray);offset++;} + for(var object:g.getObjectsList()){ + if(objects.size()>=10000||(pointCount+=object.getPointsCount())>100000)throw new GlobalException("地图对象超过在线显示限制"); + var points=new JSONArray();for(var p:object.getPointsList()){if(!Double.isFinite(p.getX())||!Double.isFinite(p.getY()))throw new GlobalException("地图对象坐标无效");points.add(JSONObject.of("x",p.getX(),"y",p.getY()));} + objects.add(JSONObject.of("id",object.getId(),"type",object.getType().name(),"points",points,"heading",object.getHeading(),"properties",object.getPropertiesMap())); + } + } + if(offset!=cells||!parts.get(parts.size()-1).getSnapshotEnd())throw new GlobalException("地图数据不完整"); + var output=new ByteArrayOutputStream();ImageIO.write(image,"png",output);String png=Base64.getEncoder().encodeToString(output.toByteArray()); + String version=cn.hutool.crypto.digest.DigestUtil.sha256Hex(first.getMapId()+"\n"+grid.getFrameId()+"\n"+grid.getResolution()+"\n"+o+"\n"+width+"x"+height+"\n"+png+objects.toJSONString()); + return JSONObject.of("mapId",first.getMapId(),"requestedMap",requestedMap,"version",version,"frameId",grid.getFrameId(),"width",width,"height",height,"resolution",grid.getResolution(),"origin",pose(o),"objects",objects,"image","data:image/png;base64,"+png); + } +} diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/EdgeAgvService.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/EdgeAgvService.java index 85b6b6a..21e5a2d 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/EdgeAgvService.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/EdgeAgvService.java @@ -15,7 +15,7 @@ import java.util.List; */ public interface EdgeAgvService { - int DEFAULT_BLOCKED_TIMEOUT_MS = 60_000; + int DEFAULT_BLOCKED_TIMEOUT_MS = 120_000; /** * 获取AGV运行时状态 diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/EdgeArmService.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/EdgeArmService.java index a5463c3..bda2d44 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/EdgeArmService.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/EdgeArmService.java @@ -61,8 +61,8 @@ public interface EdgeArmService { * * @param edgeCommonVO 边缘通用参数 * @param target 目标关节位置数组(6个关节角度,单位:弧度) - * @param velocity 运动速度(单位:m/s,可选) - * @param acceleration 加速度(单位:m/s²,可选) + * @param velocity 关节运动速度(单位:rad/s,可选) + * @param acceleration 关节加速度(单位:rad/s²,可选) * @param blendRadius 融合半径(单位:m,可选) * @param jointVelocityLimits 关节速度限制数组(可选) * @param asynchronous 是否异步执行(可选) @@ -71,6 +71,9 @@ public interface EdgeArmService { ArmCommand.MoveJ.Response moveJ(EdgeCommonVO edgeCommonVO, double[] target, Double velocity, Double acceleration, Double blendRadius, double[] jointVelocityLimits, Boolean asynchronous); + ArmCommand.MoveJ.Response moveJ(EdgeCommonVO edgeCommonVO, double[] target, Double velocity, + Double acceleration, Double blendRadius, + double[] jointVelocityLimits, Boolean asynchronous, Long timeoutMs); /** * 笛卡尔空间直线运动(命令码:moveL) diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeAgvServiceImpl.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeAgvServiceImpl.java index 5fe0aee..f2907d3 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeAgvServiceImpl.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeAgvServiceImpl.java @@ -32,7 +32,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { @Override public Agv.AgvRuntimeState getRuntimeState(EdgeCommonVO edgeCommonVO) { AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); AgvCommand.AgvRuntimeStateCommand.Request request = AgvCommand.AgvRuntimeStateCommand.Request.newBuilder() .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId())) .build(); @@ -42,7 +42,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { @Override public Agv.AgvNavigationStatus getNavigationStatus(EdgeCommonVO edgeCommonVO) { AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); AgvCommand.AgvNavigationStatusCommand.Request request = AgvCommand.AgvNavigationStatusCommand.Request.newBuilder() .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId())) .build(); @@ -52,7 +52,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { @Override public void emergencyStop(EdgeCommonVO edgeCommonVO) { AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); Common.CommandHeader.Request request = EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId()); executeGrpcCall(() -> stub.emergencyStop(request)); } @@ -60,7 +60,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { @Override public void clearFault(EdgeCommonVO edgeCommonVO) { AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); Common.CommandHeader.Request request = EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId()); executeGrpcCall(() -> stub.clearFault(request)); } @@ -71,7 +71,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { throw new GlobalException("重定位位姿不能为空"); } AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); AgvCommand.AgvRelocalizeCommand.Request request = AgvCommand.AgvRelocalizeCommand.Request.newBuilder() .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId())) .setPose(pose) @@ -85,7 +85,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { throw new GlobalException("平移距离必须大于0"); } AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); AgvCommand.AgvTranslateCommand.Request request = AgvCommand.AgvTranslateCommand.Request.newBuilder() .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId())) .setTranslation(translation) @@ -106,13 +106,13 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { } AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); AgvCommand.AgvNavigateToPoseCommand.Request request = AgvCommand.AgvNavigateToPoseCommand.Request.newBuilder() .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId())) .setPose(pose) .setOptions(normalizeNavigationOptions(options)) .build(); - executeGrpcCall(() -> stub.navigateToPose(request)); + executeGrpcCall(() -> stub.withDeadlineAfter(normalizeNavigationOptions(options).getBlockedTimeoutMs()+10000L, java.util.concurrent.TimeUnit.MILLISECONDS).navigateToPose(request)); } @Override @@ -128,13 +128,13 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { } AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); AgvCommand.AgvNavigateToStationCommand.Request request = AgvCommand.AgvNavigateToStationCommand.Request.newBuilder() .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId())) .setOptions(normalizeNavigationOptions(options)) .setStationId(stationId) .build(); - executeGrpcCall(() -> stub.navigateToStation(request)); + executeGrpcCall(() -> stub.withDeadlineAfter(normalizeNavigationOptions(options).getBlockedTimeoutMs()+10000L, java.util.concurrent.TimeUnit.MILLISECONDS).navigateToStation(request)); } @Override @@ -150,19 +150,19 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { } AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); AgvCommand.AgvFollowPathCommand.Request request = AgvCommand.AgvFollowPathCommand.Request.newBuilder() .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId())) .addAllPath(pathSegments) .setOptions(normalizeNavigationOptions(options)) .build(); - executeGrpcCall(() -> stub.followPath(request)); + executeGrpcCall(() -> stub.withDeadlineAfter(normalizeNavigationOptions(options).getBlockedTimeoutMs()+10000L, java.util.concurrent.TimeUnit.MILLISECONDS).followPath(request)); } @Override public void pauseNavigation(EdgeCommonVO edgeCommonVO) { AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); Common.CommandHeader.Request request = EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId()); executeGrpcCall(() -> stub.pauseNavigation(request)); } @@ -170,7 +170,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { @Override public void resumeNavigation(EdgeCommonVO edgeCommonVO) { AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); Common.CommandHeader.Request request = EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId()); executeGrpcCall(() -> stub.resumeNavigation(request)); } @@ -178,7 +178,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { @Override public void cancelNavigation(EdgeCommonVO edgeCommonVO) { AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); Common.CommandHeader.Request request = EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId()); executeGrpcCall(() -> stub.cancelNavigation(request)); } @@ -190,7 +190,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { } AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); AgvCommand.AgvSetVelocityCommand.Request request = AgvCommand.AgvSetVelocityCommand.Request.newBuilder() .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId())) .setVelocity(velocity) @@ -201,7 +201,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { @Override public void stopVelocityControl(EdgeCommonVO edgeCommonVO) { AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); Common.CommandHeader.Request request = EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId()); executeGrpcCall(() -> stub.stopVelocityControl(request)); } @@ -209,7 +209,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { @Override public List listMaps(EdgeCommonVO edgeCommonVO) { AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); AgvCommand.AgvListMapsCommand.Request request = AgvCommand.AgvListMapsCommand.Request.newBuilder() .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId())) .build(); @@ -219,7 +219,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { @Override public List listStations(EdgeCommonVO edgeCommonVO) { AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); AgvCommand.AgvListStationsCommand.Request request = AgvCommand.AgvListStationsCommand.Request.newBuilder() .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId())) .build(); @@ -233,7 +233,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { } AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); AgvCommand.AgvMapCommand.Request request = AgvCommand.AgvMapCommand.Request.newBuilder() .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId())) .setMapName(mapName) @@ -251,7 +251,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { } AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); AgvCommand.AgvMapCommand.Request request = AgvCommand.AgvMapCommand.Request.newBuilder() .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId())) .setMapName(mapName) @@ -267,7 +267,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { } AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); AgvCommand.AgvMapCommand.Request request = AgvCommand.AgvMapCommand.Request.newBuilder() .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId())) .setMapName(mapName) @@ -278,7 +278,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { @Override public String startMapping(EdgeCommonVO edgeCommonVO, Agv.AgvMapDimension dimension, String mapName, boolean realTime) { AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); AgvCommand.AgvStartMappingCommand.Request.Builder requestBuilder = AgvCommand.AgvStartMappingCommand.Request.newBuilder() .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId())) .setDimension(dimension != null ? dimension : Agv.AgvMapDimension.AGV_MAP_DIMENSION_UNSPECIFIED) @@ -295,7 +295,7 @@ public class EdgeAgvServiceImpl implements EdgeAgvService { @Override public void stopMapping(EdgeCommonVO edgeCommonVO) { AgvServiceGrpc.AgvServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class); + edgeCommonVO.getRobotId(), AgvServiceGrpc.AgvServiceBlockingStub.class).withDeadlineAfter(120000, java.util.concurrent.TimeUnit.MILLISECONDS); Common.CommandHeader.Request request = EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId()); executeGrpcCall(() -> stub.stopMapping(request)); } diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeArmServiceImpl.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeArmServiceImpl.java index 27dfc35..68895dc 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeArmServiceImpl.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeArmServiceImpl.java @@ -38,7 +38,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 requirePowerFeedback(executeGrpcCall(() -> stub.withDeadlineAfter(30,java.util.concurrent.TimeUnit.SECONDS).torqueOff(request))); + return requirePowerFeedback(executeGrpcCall(() -> stub.withDeadlineAfter(com.cmvr.arm.ArmTimeouts.DEFAULT_MS,java.util.concurrent.TimeUnit.MILLISECONDS).torqueOff(request))); } @Override @@ -46,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 requirePowerFeedback(executeGrpcCall(() -> stub.withDeadlineAfter(30,java.util.concurrent.TimeUnit.SECONDS).torqueOn(request))); + return requirePowerFeedback(executeGrpcCall(() -> stub.withDeadlineAfter(com.cmvr.arm.ArmTimeouts.DEFAULT_MS,java.util.concurrent.TimeUnit.MILLISECONDS).torqueOn(request))); } @Override @@ -54,7 +54,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.withDeadlineAfter(30,java.util.concurrent.TimeUnit.SECONDS).clearFault(request)); + return executeGrpcCall(() -> stub.withDeadlineAfter(com.cmvr.arm.ArmTimeouts.DEFAULT_MS,java.util.concurrent.TimeUnit.MILLISECONDS).clearFault(request)); } @Override @@ -92,6 +92,14 @@ public class EdgeArmServiceImpl implements EdgeArmService { public ArmCommand.MoveJ.Response moveJ(EdgeCommonVO edgeCommonVO, double[] target, Double velocity, Double acceleration, Double blendRadius, double[] jointVelocityLimits, Boolean asynchronous) { + return moveJ(edgeCommonVO,target,velocity,acceleration,blendRadius,jointVelocityLimits,asynchronous,null); + } + + @Override + public ArmCommand.MoveJ.Response moveJ(EdgeCommonVO edgeCommonVO, double[] target, Double velocity, + Double acceleration, Double blendRadius, + double[] jointVelocityLimits, Boolean asynchronous, Long timeoutMs) { + long waiting=com.cmvr.arm.ArmTimeouts.resolve(timeoutMs); if (target == null || target.length == 0) { throw new GlobalException("目标关节位置不能为空"); } @@ -132,7 +140,7 @@ public class EdgeArmServiceImpl implements EdgeArmService { .setOptions(optionsBuilder.build()) .build(); - return executeGrpcCall(() -> stub.withDeadlineAfter(30,java.util.concurrent.TimeUnit.SECONDS).moveJ(request)); + return executeGrpcCall(() -> stub.withDeadlineAfter(waiting,java.util.concurrent.TimeUnit.MILLISECONDS).moveJ(request)); } @Override @@ -199,8 +207,8 @@ public class EdgeArmServiceImpl implements EdgeArmService { .setFrame(frameType), JSONObject.of("baseFrame",baseFrame,"tcpFrame",tcpFrame)),extra) .build(); - // Ordinary calls default to thirty seconds; longer configured executions remain explicit. - var motionStub=stub.withDeadlineAfter(30,java.util.concurrent.TimeUnit.SECONDS); + // Default business wait is two minutes; an explicitly configured deadline remains effective. + var motionStub=stub.withDeadlineAfter(com.cmvr.arm.ArmTimeouts.DEFAULT_MS,java.util.concurrent.TimeUnit.MILLISECONDS); if(extra.get("timeoutMs")!=null){long deadline=extra.getLongValue("timeoutMs");if(deadline<100||deadline>21600000)throw new GlobalException("直线运动超时须为100至21600000毫秒");motionStub=stub.withDeadlineAfter(deadline,java.util.concurrent.TimeUnit.MILLISECONDS);} final var selectedStub=motionStub; var response=executeGrpcCall(() -> selectedStub.moveL(request)); @@ -236,7 +244,7 @@ public class EdgeArmServiceImpl implements EdgeArmService { requestBuilder.setDuration(duration); } - return executeGrpcCall(() -> stub.withDeadlineAfter(30,java.util.concurrent.TimeUnit.SECONDS).speedJ(requestBuilder.build())); + return executeGrpcCall(() -> stub.withDeadlineAfter(com.cmvr.arm.ArmTimeouts.DEFAULT_MS,java.util.concurrent.TimeUnit.MILLISECONDS).speedJ(requestBuilder.build())); } @Override @@ -271,7 +279,7 @@ public class EdgeArmServiceImpl implements EdgeArmService { ArmCommand.ArmFrameType frameType = parseFrameType(frame); requestBuilder.setFrame(frameType); - return executeGrpcCall(() -> stub.withDeadlineAfter(30,java.util.concurrent.TimeUnit.SECONDS).speedL(requestBuilder.build())); + return executeGrpcCall(() -> stub.withDeadlineAfter(com.cmvr.arm.ArmTimeouts.DEFAULT_MS,java.util.concurrent.TimeUnit.MILLISECONDS).speedL(requestBuilder.build())); } @Override @@ -295,7 +303,7 @@ public class EdgeArmServiceImpl implements EdgeArmService { .setTarget(targetCommand) .build(); - return executeGrpcCall(() -> stub.withDeadlineAfter(30,java.util.concurrent.TimeUnit.SECONDS).servoJ(request)); + return executeGrpcCall(() -> stub.withDeadlineAfter(com.cmvr.arm.ArmTimeouts.DEFAULT_MS,java.util.concurrent.TimeUnit.MILLISECONDS).servoJ(request)); } @Override @@ -303,7 +311,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.withDeadlineAfter(30,java.util.concurrent.TimeUnit.SECONDS).stopMotion(request)); + return executeGrpcCall(() -> stub.withDeadlineAfter(com.cmvr.arm.ArmTimeouts.DEFAULT_MS,java.util.concurrent.TimeUnit.MILLISECONDS).stopMotion(request)); } @Override @@ -313,7 +321,7 @@ public class EdgeArmServiceImpl implements EdgeArmService { ArmCommand.JointRequest request = ArmCommand.JointRequest.newBuilder() .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId())) .build(); - return executeGrpcCall(() -> stub.withDeadlineAfter(30,java.util.concurrent.TimeUnit.SECONDS).getJointState(request)); + return executeGrpcCall(() -> stub.withDeadlineAfter(com.cmvr.arm.ArmTimeouts.DEFAULT_MS,java.util.concurrent.TimeUnit.MILLISECONDS).getJointState(request)); } @Override @@ -331,7 +339,7 @@ public class EdgeArmServiceImpl implements EdgeArmService { requestBuilder.setBaseLink(frame).setEeLink(end); - var response=executeGrpcCall(() -> stub.withDeadlineAfter(30,java.util.concurrent.TimeUnit.SECONDS).getPose(requestBuilder.build())); + var response=executeGrpcCall(() -> stub.withDeadlineAfter(com.cmvr.arm.ArmTimeouts.DEFAULT_MS,java.util.concurrent.TimeUnit.MILLISECONDS).getPose(requestBuilder.build())); if(!response.hasHeader()||!response.getHeader().getSuccess()||!response.hasPose())throw new GlobalException("读取机械臂位姿失败:"+(!response.hasHeader()?"缺少业务反馈":!response.getHeader().getSuccess()?response.getHeader().getErrorMessage():"缺少位姿数据")); if(!frame.equals(response.getReferenceFrame())||!("tool0".equals(end)?"flange":end).equals(response.getEndFrame()))throw new GlobalException("边端返回的参考坐标系或末端不匹配,禁止将此位姿作为目标"); var p=response.getPose();for(double value:new double[]{p.getX(),p.getY(),p.getZ(),p.getRx(),p.getRy(),p.getRz()})if(!Double.isFinite(value))throw new GlobalException("实际位姿包含无效数值"); @@ -350,7 +358,7 @@ public class EdgeArmServiceImpl implements EdgeArmService { requestBuilder.setJointName(jointName); } - return executeGrpcCall(() -> stub.withDeadlineAfter(30,java.util.concurrent.TimeUnit.SECONDS).calibrateZeroQ(requestBuilder.build())); + return executeGrpcCall(() -> stub.withDeadlineAfter(com.cmvr.arm.ArmTimeouts.DEFAULT_MS,java.util.concurrent.TimeUnit.MILLISECONDS).calibrateZeroQ(requestBuilder.build())); } @Override @@ -368,7 +376,7 @@ public class EdgeArmServiceImpl implements EdgeArmService { requestBuilder.setEeLink(eeLink); } - return executeGrpcCall(() -> stub.withDeadlineAfter(30,java.util.concurrent.TimeUnit.SECONDS).getPoseMatrix(requestBuilder.build())); + return executeGrpcCall(() -> stub.withDeadlineAfter(com.cmvr.arm.ArmTimeouts.DEFAULT_MS,java.util.concurrent.TimeUnit.MILLISECONDS).getPoseMatrix(requestBuilder.build())); } @Override @@ -401,14 +409,14 @@ public class EdgeArmServiceImpl implements EdgeArmService { requestBuilder.setEeLink(eeLink); } - return executeGrpcCall(() -> stub.withDeadlineAfter(30,java.util.concurrent.TimeUnit.SECONDS).computeForwardKinematics(requestBuilder.build())); + return executeGrpcCall(() -> stub.withDeadlineAfter(com.cmvr.arm.ArmTimeouts.DEFAULT_MS,java.util.concurrent.TimeUnit.MILLISECONDS).computeForwardKinematics(requestBuilder.build())); } private ArmServiceGrpc.ArmServiceBlockingStub blockingStub(String robotId) { if (StrUtil.isBlank(robotId)) { throw new GlobalException("机器人ID不能为空"); } - return grpcServiceManager.getGrpcClient(robotId, ArmServiceGrpc.ArmServiceBlockingStub.class).withDeadlineAfter(30,java.util.concurrent.TimeUnit.SECONDS); + return grpcServiceManager.getGrpcClient(robotId, ArmServiceGrpc.ArmServiceBlockingStub.class).withDeadlineAfter(com.cmvr.arm.ArmTimeouts.DEFAULT_MS,java.util.concurrent.TimeUnit.MILLISECONDS); } private Common.JsonDeviceCommand.Feedback executeJsonCommand( diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeSystemServiceImpl.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeSystemServiceImpl.java index 8d3b06b..637e2f5 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeSystemServiceImpl.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeSystemServiceImpl.java @@ -11,6 +11,7 @@ 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.model.system.ActionQueueParameters; import com.cmvr.edge.client.service.EdgeSystemService; import com.cmvr.edge.client.utils.EdgeCommonUtil; import com.cmvr.common.exception.GlobalException; @@ -85,21 +86,32 @@ public class EdgeSystemServiceImpl implements EdgeSystemService { if (request.getSteps() == null || request.getSteps().isEmpty()) { throw new GlobalException("Action queue must contain at least one step"); } + ActionQueueParameters.validate(request.getSteps()); int totalTimeoutMs = ActionQueueTimeouts.total(request.getSteps()); SystemCommand.ActionQueueCommand.Request.Builder builder = SystemCommand.ActionQueueCommand.Request.newBuilder() .setTotalTimeoutMs(totalTimeoutMs); + java.util.Map applied = new java.util.HashMap<>(); for (EdgeActionQueueVO.Step step : request.getSteps()) { + if (step.getDeviceId() == null || step.getDeviceId().isBlank()) throw new GlobalException("动作队列步骤未选择执行机械臂"); 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)); + if (ActionQueueParameters.APPLY_USER_COORDINATE.equalsIgnoreCase(step.getType())) applied.put(step.getDeviceId().trim(), step.getParams()); + if ("ARM_MOVE_J_POSE".equalsIgnoreCase(step.getType())) { + var coordinate = ActionQueueParameters.poseCoordinate(step, applied.get(step.getDeviceId().trim())); + var p = step.getParams(); + builder.addSteps(SystemCommand.ActionStep.newBuilder().setTimeoutMs(ActionQueueTimeouts.step(step.getTimeoutMs())) + .setArmMoveJPose(ArmCommand.MoveJPose.Request.newBuilder().setHeader(requiredDeviceHeader(step)) + .setTarget(ArmCommand.CartesianPose.newBuilder().setX(p.getDoubleValue("x")).setY(p.getDoubleValue("y")).setZ(p.getDoubleValue("z")) + .setRx(p.getDoubleValue("rx")).setRy(p.getDoubleValue("ry")).setRz(p.getDoubleValue("rz"))) + .setOptions(ArmCommand.MotionOptions.newBuilder().setVelocity(p.getDoubleValue("velocity")).setAcceleration(p.getDoubleValue("acceleration")).setBlendRadius(0).setAsynchronous(false)) + .setUserCoordinateName(coordinate.getString("name")).setUserCoordinateRevision(ActionQueueParameters.coordinateRevision(coordinate)))); + } else builder.addSteps(buildActionStep(step)); } SystemServiceGrpc.SystemServiceBlockingStub stub = grpcServiceManager.getGrpcClient( request.getRobotId(), SystemServiceGrpc.SystemServiceBlockingStub.class); - // 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); + stub = stub.withDeadlineAfter((totalTimeoutMs == 0 ? ActionQueueTimeouts.SERVER_DEFAULT_TIMEOUT_MS : totalTimeoutMs) + 5000L, TimeUnit.MILLISECONDS); return stub.executeActionQueue(builder.build()); } @@ -153,8 +165,14 @@ public class EdgeSystemServiceImpl implements EdgeSystemService { .setFrame(parseArmFrame(params.getString("frame"))) .setOptions(buildArmOptions(params)),params),params)); break; + case ActionQueueParameters.APPLY_USER_COORDINATE: + builder.setArmApplyUserCoordinate(ArmCommand.UserCoordinateSystemCommand.Request.newBuilder() + .setHeader(requiredDeviceHeader(step)) + .setName(params.getString("name")) + .setExpectedRevision(ActionQueueParameters.coordinateRevision(params))); + break; default: - throw new GlobalException("当前 ActionQueue 仅支持 ARM_MOVE_J 和 ARM_MOVE_L,收到: " + step.getType()); + throw new GlobalException("动作队列不支持的操作类型:" + step.getType()); } return builder.build(); } @@ -224,11 +242,14 @@ public class EdgeSystemServiceImpl implements EdgeSystemService { @Override public String stopAll(String robotId) { + try(var scope=com.cmvr.common.robot.RecoveryRpcScope.enter()){return stopAllScoped(robotId);} + } + private String stopAllScoped(String robotId) { boolean exclusive = false; for (var extension : stopExtensions) if (extension.handles(robotId)) exclusive |= extension.stop(robotId); if (exclusive) return "ACKNOWLEDGED"; SystemServiceGrpc.SystemServiceBlockingStub stub = grpcServiceManager.getGrpcClient( - robotId, SystemServiceGrpc.SystemServiceBlockingStub.class).withDeadlineAfter(10, TimeUnit.SECONDS); + robotId, SystemServiceGrpc.SystemServiceBlockingStub.class).withDeadlineAfter(120, TimeUnit.SECONDS); SystemCommand.StopAllCommand.Feedback feedback = stub.stopAll(SystemCommand.StopAllCommand.Request.newBuilder() .setHeader(EdgeCommonUtil.buildRequest("")).build()); if (feedback == null || !feedback.hasHeader() || !feedback.getHeader().getSuccess()) { diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/quic/gateway/core/ConnectionSession.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/quic/gateway/core/ConnectionSession.java index c2e588e..c202ba2 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/quic/gateway/core/ConnectionSession.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/quic/gateway/core/ConnectionSession.java @@ -350,8 +350,8 @@ public final class ConnectionSession { offlinePublished = true; reassembler.clear(); broker.publishNode(NodeEventType.NODE_EVENT_TYPE_OFFLINE, snapshot(false)); - log.info("QUIC终端离线,nodeId={},sessionId={},remoteIp={}", - nodeId, sessionId, observedSourceIp); + log.info("QUIC终端离线,nodeId={},sessionId={},remoteIp={},bootId={},距最后心跳={}ms(不代表SDK控制器离线)", + nodeId, sessionId, observedSourceIp, bootId, System.currentTimeMillis()-lastHeartbeatAtMs); } public synchronized void fail(String message, Throwable error) { diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/config/ResourceRobotStateProperties.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/config/ResourceRobotStateProperties.java index b2b2616..ed9528e 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/config/ResourceRobotStateProperties.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/config/ResourceRobotStateProperties.java @@ -13,6 +13,9 @@ import java.util.Locale; @ConfigurationProperties(prefix = "cmvr.resource.robot-state") public class ResourceRobotStateProperties { private long heartbeatTimeoutMs = 15_000L; + private long reconnectGraceMs = 5_000L; + public long getReconnectGraceMs() { return reconnectGraceMs; } + public void setReconnectGraceMs(long value) { reconnectGraceMs = Math.max(0, Math.min(5_000L, value)); } private List virtualRobotIds = new ArrayList<>(); private List externalRobotIds = new ArrayList<>(); public List getExternalRobotIds() {return externalRobotIds;} diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/service/ResourceQuicStateSynchronizer.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/service/ResourceQuicStateSynchronizer.java index 30ef0b4..957eb47 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/service/ResourceQuicStateSynchronizer.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/service/ResourceQuicStateSynchronizer.java @@ -68,6 +68,7 @@ public class ResourceQuicStateSynchronizer { String oldHost = robot.getIpAddress(); Long oldPort = robot.getPort(); + String oldBoot = robot.getQuicBootId(); Date eventTime = new Date(event.getEventTimeUnixMs() == 0 ? System.currentTimeMillis() : event.getEventTimeUnixMs()); if (!offline) { @@ -97,8 +98,10 @@ public class ResourceQuicStateSynchronizer { } else { synchronizeDevices(robotId, node, eventTime); } - if (offline || !Objects.equals(oldHost, robot.getIpAddress()) - || !Objects.equals(oldPort, robot.getPort())) { + // Telemetry reconnects must not cancel an independent SDK motion RPC. + if (!offline && (!Objects.equals(oldHost, robot.getIpAddress()) + || !Objects.equals(oldPort, robot.getPort()) + || oldBoot != null && !Objects.equals(oldBoot, robot.getQuicBootId()))) { grpcServiceManager.invalidateRobot(robotId); } return true; @@ -115,7 +118,6 @@ public class ResourceQuicStateSynchronizer { continue; } deviceMapper.markAllOffline(robot.getRobotId(), now); - grpcServiceManager.invalidateRobot(robot.getRobotId()); count++; } return count; diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/service/ResourceRobotDeviceAssignmentValidator.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/service/ResourceRobotDeviceAssignmentValidator.java index 0b002c3..640e1b9 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/service/ResourceRobotDeviceAssignmentValidator.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/service/ResourceRobotDeviceAssignmentValidator.java @@ -14,6 +14,7 @@ import java.util.Locale; @Service @RequiredArgsConstructor public class ResourceRobotDeviceAssignmentValidator implements RobotDeviceAssignmentValidator { + private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ResourceRobotDeviceAssignmentValidator.class); private static final int MICROPHONE_DEVICE_KIND = 9; private static final String RECORDING_STREAM_CONFLICT = "cannot start streaming while microphone recording is active"; @@ -31,12 +32,16 @@ public class ResourceRobotDeviceAssignmentValidator implements RobotDeviceAssign } @Override public void validateAssignment(String robotId,String deviceId,Integer expectedDeviceKind) {validateAndGet(robotId,deviceId,expectedDeviceKind,true);} + @Override public void validateRecovery(String robotId,String deviceId,Integer expectedDeviceKind) {validateAndGet(robotId,deviceId,expectedDeviceKind,true,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) { + return validateAndGet(robotId,deviceId,expectedDeviceKind,management,false); + } + private ResourceDevice validateAndGet(String robotId, String deviceId, Integer expectedDeviceKind,boolean management,boolean recovery) { if (stateProperties.isVirtualRobot(robotId)) { throw new GlobalException("虚拟机器人不能绑定边缘设备:" + robotId); } @@ -52,13 +57,25 @@ public class ResourceRobotDeviceAssignmentValidator implements RobotDeviceAssign if (expectedDeviceKind != null && !expectedDeviceKind.equals(actualKind)) { throw new GlobalException("设备[" + deviceId + "]的类型与流程设备用途不匹配"); } + if (recovery) return device; 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 + "]当前离线,请重新选择在线设备"); + long grace=stateProperties.getReconnectGraceMs(); + boolean recent=device.getOfflineTime()!=null&&System.currentTimeMillis()-device.getOfflineTime().getTime()<=grace; + long deadline=System.nanoTime()+java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(recent?grace:0); + if(recent&&grace>0)log.info("设备终端上报中断,等待重连后校验,robotId={}, deviceId={}, graceMs={}",robotId,deviceId,grace); + while(!"1".equals(device.getOnlineStatus())&&System.nanoTime()65535) { throw new GlobalException("机器人尚未上报gRPC地址:" + normalized); } return new RobotEndpoint(robot.getIpAddress(), robot.getPort().intValue()); diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/rotarybase/RotaryBaseClient.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/rotarybase/RotaryBaseClient.java index 341dad2..8be47bd 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/rotarybase/RotaryBaseClient.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/rotarybase/RotaryBaseClient.java @@ -30,7 +30,7 @@ public class RotaryBaseClient { } 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); + var stub=MotorServiceGrpc.newBlockingStub(channel()).withDeadlineAfter(timeoutMs>0?timeoutMs:settings.getRpcTimeoutMs(),TimeUnit.MILLISECONDS); return switch(action) { case MOTOR_SET_MODE -> stub.setMode(request); case MOTOR_ENABLE -> stub.torqueOn(request); @@ -48,12 +48,12 @@ public class RotaryBaseClient { }; } public MotorListResponse list(MotorRequest request,long timeoutMs) { - return MotorServiceGrpc.newBlockingStub(channel()).withDeadlineAfter(Math.min(timeoutMs,settings.getRpcTimeoutMs()),TimeUnit.MILLISECONDS).listMotors(request); + return MotorServiceGrpc.newBlockingStub(channel()).withDeadlineAfter(timeoutMs>0?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. + // Business wait is editable; allow ten seconds to receive the final homing acknowledgement. long limit=(long)Math.ceil(request.getTimeoutS()*1000)+10000; - return MotorServiceGrpc.newBlockingStub(channel()).withDeadlineAfter(Math.min(timeoutMs,limit),TimeUnit.MILLISECONDS).home(request); + return MotorServiceGrpc.newBlockingStub(channel()).withDeadlineAfter(Math.min((timeoutMs>0?timeoutMs:settings.getRpcTimeoutMs())+10000,limit),TimeUnit.MILLISECONDS).home(request); } @PreDestroy public synchronized void close() {if(channel!=null)channel.shutdownNow();} } diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/rotarybase/RotaryBaseParameters.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/rotarybase/RotaryBaseParameters.java index 4dfe873..a3c9aee 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/rotarybase/RotaryBaseParameters.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/rotarybase/RotaryBaseParameters.java @@ -19,7 +19,7 @@ public final class RotaryBaseParameters { 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(number(input,"timeoutMs")2*Math.PI+1e-12) - throw new GlobalException("旋转底座绝对位置须在±360°(±2π rad)内"); + if(action==ActionEnum.MOTOR_MOVE&&Math.abs(number(input,"targetPosition")*factor)>10*Math.PI+1e-12) + throw new GlobalException("旋转底座绝对位置须在±1800°(±10π 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)"); diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/rotarybase/RotaryBaseProperties.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/rotarybase/RotaryBaseProperties.java index 8fc5ff9..4e0c165 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/rotarybase/RotaryBaseProperties.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/rotarybase/RotaryBaseProperties.java @@ -19,7 +19,7 @@ public class RotaryBaseProperties { private String managerId="aima_motor"; private int nodeId=1; private String jointName="motor_1"; - private int rpcTimeoutMs=45000; + private int rpcTimeoutMs=120000; 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 diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerCommandJournal.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerCommandJournal.java index 3753c45..1ee9ec8 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerCommandJournal.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerCommandJournal.java @@ -54,6 +54,8 @@ public class ScannerCommandJournal { public void accepted(String key,String taskId){jdbc.update("UPDATE lab_scanner_command SET state='ACCEPTED',remote_task_id=?,updated_at=CURRENT_TIMESTAMP WHERE command_key=? AND state='INTENT'",taskId,key);} public void uncertain(String key,String message){jdbc.update("UPDATE lab_scanner_command SET state='UNKNOWN',error_message=?,updated_at=CURRENT_TIMESTAMP WHERE command_key=? AND state IN ('INTENT','ACCEPTED')",message,key);} public void finish(String key,boolean success,JsonNode result,String error){jdbc.update("UPDATE lab_scanner_command SET state=?,result_json=?,error_message=?,active_endpoint=NULL,updated_at=CURRENT_TIMESTAMP WHERE command_key=? AND state IN ('INTENT','ACCEPTED')",success?"SUCCEEDED":"FAILED",result==null?null:result.toString(),error,key);} + /** Preserve SDK completion even if archiving fails; retrying a download must never resend the device command. */ + public void archiveResult(String key,String previous,JsonNode archived){jdbc.update("UPDATE lab_scanner_command SET result_json=?,updated_at=CURRENT_TIMESTAMP WHERE command_key=? AND state='SUCCEEDED' AND result_json=?",archived.toString(),key,previous);} public boolean retireExpired(Entry entry,JsonNode proof) { com.fasterxml.jackson.databind.node.ObjectNode record=entry.result()==null?ScannerRequestValidator.JSON.createObjectNode():(com.fasterxml.jackson.databind.node.ObjectNode)parseContext(entry.result()).deepCopy(); String state="FAILED".equals(entry.state())?"FAILED":"UNKNOWN"; diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerFileArchive.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerFileArchive.java new file mode 100644 index 0000000..a33db34 --- /dev/null +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerFileArchive.java @@ -0,0 +1,124 @@ +package com.cmvr.scanner; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.ContentDisposition; +import org.springframework.stereotype.Component; +import java.io.*; +import java.nio.file.*; +import java.util.*; +import java.util.function.Function; +import java.util.function.LongSupplier; + +/** Durable platform copies for every scanner export, including ordinary workflow trial runs. */ +@Component +public class ScannerFileArchive { + private static final long MAX_BYTES=100L*1024*1024; + private static final String URL="/admin-api/cmvr/scanner/files/"; + @Value("${lab.artifact.nas-root:./.local/artifacts}") private String root; + private final Object[] locks=new Object[64]; + public ScannerFileArchive(){Arrays.setAll(locks,i->new Object());} + private Object lock(String id){return locks[Math.floorMod(id.hashCode(),locks.length)];} + private Path path(String id){ + if(id==null||!id.matches("[a-f0-9]{32}"))throw failure("文件编号无效"); + return Path.of(root).toAbsolutePath().normalize().resolve("scanner-archive").resolve(id); + } + private String platformId(String endpoint,String source){return ScannerService.hash("scanner-archive:"+endpoint+":"+source).substring(0,32);} + + public JsonNode archiveTask(JsonNode task,String endpoint,Function download,LongSupplier remaining) { + if(!"succeeded".equals(task.path("state").asText())||!task.path("result").path("files").isArray())return task; + JsonNode original=task.path("result").path("files"); + if(original.size()>64)throw failure("文件清单超过64项"); + ObjectNode copy=task.deepCopy();var files=ScannerRequestValidator.JSON.createArrayNode(); + for(JsonNode source:original){ + remaining.getAsLong(); + if(!source.isObject())throw failure("文件清单格式无效"); + String remote=source.path("fileId").asText(); + if(!remote.matches("[a-fA-F0-9]{32}"))throw failure("扫描服务返回的文件编号无效"); + String id=source.path("archived").asBoolean()&&source.path("downloadUrl").asText().equals(URL+remote) + ?remote:platformId(endpoint,remote.toLowerCase(Locale.ROOT)); + ObjectNode receipt; + synchronized(lock(id)){ + receipt=metadata(id); + if(receipt==null){ + if(source.path("archived").asBoolean())throw failure("平台归档文件缺失,禁止使用旧扫描服务地址替代"); + receipt=save(id,remote,endpoint,task.path("taskId").asText(),source,download,remaining); + }else{ + verifyLength(source,receipt.path("bytes").asLong()); + if(source.hasNonNull("sha256")&&!source.path("sha256").asText().equalsIgnoreCase(receipt.path("sha256").asText()))throw failure("文件校验值与平台归档不一致"); + } + } + ObjectNode item=source.deepCopy();item.put("fileId",id);item.put("downloadUrl",URL+id); + item.put("name",receipt.path("name").asText());item.put("bytes",receipt.path("bytes").asLong()); + item.put("sha256",receipt.path("sha256").asText());item.put("archived",true);files.add(item); + } + ((ObjectNode)copy.get("result")).set("files",files);return copy; + } + + private ObjectNode save(String id,String remote,String endpoint,String task,JsonNode expected,Function download,LongSupplier remaining){ + Path target=path(id),temporary=null,metaTemporary=null; + try{ + Files.createDirectories(target.getParent());temporary=Files.createTempFile(target.getParent(),id,".part"); + String name;long bytes=0;var digest=java.security.MessageDigest.getInstance("SHA-256"); + try(var source=download.apply(remote);var out=Files.newOutputStream(temporary)){ + name=expected.path("name").asText(); + String header=header(source.headers(),"content-disposition"); + if(name.isBlank()&&header!=null)name=ContentDisposition.parse(header).getFilename(); + validateName(name); + String declared=header(source.headers(),"content-length");long length=declared==null?-1:Long.parseLong(declared); + if(length>MAX_BYTES)throw failure("单个文件超过100MiB归档限制"); + byte[] buffer=new byte[65536];int n; + while((n=source.stream().read(buffer))!=-1){ + remaining.getAsLong();bytes+=n;if(bytes>MAX_BYTES)throw failure("单个文件超过100MiB归档限制"); + digest.update(buffer,0,n);out.write(buffer,0,n); + } + if(bytes==0||length>=0&&bytes!=length)throw failure("文件为空或下载不完整"); + } + verifyLength(expected,bytes);String sha=HexFormat.of().formatHex(digest.digest()); + if(expected.hasNonNull("sha256")&&!sha.equalsIgnoreCase(expected.path("sha256").asText()))throw failure("下载文件SHA256校验失败"); + remaining.getAsLong(); + ObjectNode receipt=ScannerRequestValidator.JSON.createObjectNode(); + receipt.put("fileId",id);receipt.put("sourceFileId",remote);receipt.put("sourceEndpoint",endpoint);receipt.put("sourceTaskId",task); + receipt.put("name",name);receipt.put("bytes",bytes);receipt.put("sha256",sha);receipt.put("downloadUrl",URL+id);receipt.put("archived",true); + metaTemporary=Files.createTempFile(target.getParent(),id,".json.part");Files.writeString(metaTemporary,receipt.toString()); + Files.move(temporary,target,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);temporary=null; + Files.move(metaTemporary,target.resolveSibling(id+".json"),StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);metaTemporary=null; + return receipt; + }catch(ScannerException error){throw error;} + catch(Exception error){throw failure("文件下载或持久保存失败:"+Objects.toString(error.getMessage(),error.getClass().getSimpleName()));} + finally{for(Path part:new Path[]{temporary,metaTemporary})if(part!=null)try{Files.deleteIfExists(part);}catch(IOException ignored){}} + } + private static void verifyLength(JsonNode expected,long bytes){ + JsonNode size=expected.hasNonNull("bytes")?expected.get("bytes"):expected.get("size"); + if(size!=null&&!size.isNull()&&(!size.isIntegralNumber()||size.asLong()<=0||size.asLong()!=bytes))throw failure("文件长度与扫描服务回执不一致"); + } + private ObjectNode metadata(String id){ + Path target=path(id),meta=target.resolveSibling(id+".json"); + if(!Files.exists(target)&&!Files.exists(meta))return null; + try{ + if(Files.size(meta)>16384||Files.isSymbolicLink(target)||Files.isSymbolicLink(meta))throw new IOException("metadata"); + var receipt=ScannerRequestValidator.JSON.readTree(Files.readString(meta));validateName(receipt.path("name").asText()); + if(!receipt.isObject()||!id.equals(receipt.path("fileId").asText())||Files.size(target)<=0||Files.size(target)>MAX_BYTES + ||Files.size(target)!=receipt.path("bytes").asLong()||!cn.hutool.crypto.digest.DigestUtil.sha256Hex(target.toFile()).equals(receipt.path("sha256").asText()))throw new IOException("checksum"); + return (ObjectNode)receipt; + }catch(Exception error){throw failure("平台归档文件缺失或损坏,请检查成果存储;不会回退到临时URL");} + } + public ScannerHttpClient.Binary open(String id){ + if(id==null||!id.matches("[a-f0-9]{32}"))return null; + synchronized(lock(id)){ + var receipt=metadata(id);if(receipt==null)return null; + try{return new ScannerHttpClient.Binary(Files.newInputStream(path(id)),Map.of("content-length",List.of(receipt.path("bytes").asText()), + "content-disposition",List.of("attachment; filename*=UTF-8''"+ScannerFrameworkReferences.encode(receipt.path("name").asText())),"content-type",List.of("application/octet-stream")));} + catch(IOException error){throw failure("平台归档文件读取失败");} + } + } + /** Compatibility for old vendor URLs when a matching durable copy already exists. */ + public ScannerHttpClient.Binary openSource(String endpoint,String id){ + if(id==null||!id.matches("[a-fA-F0-9]{32}"))return null; + return open(platformId(endpoint,id.toLowerCase(Locale.ROOT))); + } + private static String header(Map> headers,String name){return headers.entrySet().stream().filter(e->e.getKey().equalsIgnoreCase(name)&&!e.getValue().isEmpty()).map(e->e.getValue().get(0)).findFirst().orElse(null);} + private static void validateName(String name){if(name==null||name.isBlank()||name.equals(".")||name.equals("..")||name.length()>240||name.chars().anyMatch(c->c<32||c==127||"<>:\"/\\|?*".indexOf(c)>=0))throw failure("文件名无效");} + private static ScannerException failure(String reason){return new ScannerException("file_archive_failed","扫描已完成,但文件未能确认归档:"+reason+"。请保留原工程,不要重新执行扫描或导出动作。",503);} +} diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerFrameworkReferenceService.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerFrameworkReferenceService.java index 7a22ce6..4824c84 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerFrameworkReferenceService.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerFrameworkReferenceService.java @@ -49,9 +49,15 @@ public class ScannerFrameworkReferenceService { throw error; } String contentHash=cn.hutool.crypto.digest.DigestUtil.sha256Hex(bytes); - String fileHash=ScannerService.hash(endpoint+":"+source.fileId()+":"+name+":"+contentHash); + String fileHash=ScannerService.hash(endpoint+":"+status.path("sessionId").asText()+":"+source.fileId()+":"+name+":"+contentHash); String fileKey=ScannerService.hash("framework-file:"+fileHash); var cached=journal.get(fileKey);JsonNode receipt; + if(cached!=null&&!registered(known(cached,fileHash),contentHash,deadline)){ + // A definite 404 permits a new byte upload, never a retry of an unconfirmed SDK import. + fileKey=ScannerService.hash("framework-file-renew:"+fileHash+":"+commandKey); + cached=journal.get(fileKey); + if(cached!=null&&!registered(known(cached,fileHash),contentHash,deadline))throw bad("当前执行的上传编号再次失效,请重新发起执行;不会盲目重传"); + } boolean reused=cached!=null; if(reused)receipt=known(cached,fileHash); else { @@ -85,6 +91,13 @@ public class ScannerFrameworkReferenceService { return status; } } + private boolean registered(JsonNode receipt,String expectedHash,long deadline) throws IOException { + try(var file=client.remoteFile(receipt.path("fileId").asText(),budget(deadline))){ + byte[] bytes=file.stream().readNBytes(ScannerFrameworkService.MAX_BYTES+1); + if(bytes.length==0||bytes.length>ScannerFrameworkService.MAX_BYTES||!expectedHash.equals(cn.hutool.crypto.digest.DigestUtil.sha256Hex(bytes)))throw bad("扫描服务已登记文件与平台框架点校验值不一致"); + return true; + }catch(ScannerException error){if(error.remoteStatus==404)return false;throw error;} + } 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);} diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerHttpClient.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerHttpClient.java index e85a4b6..ec55c4c 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerHttpClient.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerHttpClient.java @@ -17,6 +17,8 @@ public class ScannerHttpClient { private final ScannerProperties settings; @org.springframework.beans.factory.annotation.Autowired(required=false) private ScannerFixtureFrameworkStore fixtureFrameworkStore; + @org.springframework.beans.factory.annotation.Autowired + private ScannerFileArchive fileArchive; private volatile HttpClient client; private static final ScheduledThreadPoolExecutor STREAM_TIMEOUTS = streamTimeouts(); private static ScheduledThreadPoolExecutor streamTimeouts() { @@ -107,8 +109,17 @@ public class ScannerHttpClient { public Binary frameworkFile(String id,long budgetMs) { return binary(ScannerOperation.FILE,id,Math.min(budgetMs,settings.getRequestTimeoutMs()),true); } + public Binary archivedFile(String id){return fileArchive==null?null:fileArchive.open(id);} + public Binary remoteFile(String id,long budgetMs){return remoteBinary(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;} + if(op==ScannerOperation.FILE&&fileArchive!=null){ + var saved=fileArchive.open(id);if(saved!=null)return saved; + if(settings.configured()){saved=fileArchive.openSource(endpointKey(),id);if(saved!=null)return saved;} + } + return remoteBinary(op,id,timeoutMs,bounded); + } + private Binary remoteBinary(ScannerOperation op,String id,long timeoutMs,boolean bounded) { requireConfigured(); if(!op.binary())throw new IllegalArgumentException("not binary"); long deadline=bounded?System.nanoTime()+TimeUnit.MILLISECONDS.toNanos(Math.max(1,timeoutMs)):0; diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerMonitoringService.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerMonitoringService.java index 215a2dd..cf8fd8a 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerMonitoringService.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerMonitoringService.java @@ -95,6 +95,7 @@ public class ScannerMonitoringService { ScannerOperation.FILE.route(fileId); JsonNode file=assets(instId).stream().filter(item->fileId.equals(item.path("fileId").asText())).findFirst() .orElseThrow(()->new ScannerException("file_not_owned","文件不属于本次执行",404)); + var archived=client.archivedFile(fileId);if(archived!=null)return archived; if(!file.path("binding").path("endpoint").asText().equals(client.endpointKey()))throw new ScannerException("endpoint_changed","扫描服务已变更,原文件不能从当前地址读取",409); if(file.path("bytes").asLong()>100L*1024*1024)throw new ScannerException("model_too_large","文件超过在线三维查看的100MiB限制,请使用原始成果下载",413); return scanner.binary(ScannerOperation.FILE,fileId); diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerProperties.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerProperties.java index f313250..47d33a3 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerProperties.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerProperties.java @@ -18,7 +18,7 @@ public class ScannerProperties { private String robotId = ""; private String deviceId = ""; private int connectTimeoutMs = 5000; - private int requestTimeoutMs = 15000; + private int requestTimeoutMs = 120000; private int pollIntervalMs = 500; private int operationTimeoutMs = 120000; 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(); } diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerService.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerService.java index 9bf8b12..c527a9d 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerService.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerService.java @@ -11,11 +11,13 @@ import java.util.concurrent.locks.ReentrantLock; @Service @RequiredArgsConstructor public class ScannerService { - public static final long CALIBRATION_FREE_TIMEOUT_MS=5000; + public static final long CALIBRATION_FREE_TIMEOUT_MS=120000; private static final long CALIBRATION_FREE_POLL_INTERVAL_MS=1000; private final ScannerProperties settings; private final ScannerHttpClient client; private final ScannerCommandJournal journal; + @org.springframework.beans.factory.annotation.Autowired + private ScannerFileArchive fileArchive; private final ReentrantLock commandLock=new ReentrantLock(); /** Serialize address changes against commands and retain uncertain command ownership. */ @@ -43,11 +45,27 @@ public class ScannerService { result.put("robotId",settings.getRobotId());result.put("deviceId",settings.getDeviceId());return result; } public JsonNode get(ScannerOperation op,String id) { + return get(op,id,settings.getRequestTimeoutMs()); + } + public JsonNode get(ScannerOperation op,String id,long timeoutMs) { if(op.control()||op.binary()||op.upload())throw new IllegalArgumentException("not a JSON query"); - return client.json(op,id,null,settings.getRequestTimeoutMs()); + long deadline=deadline(timeoutMs);var result=client.json(op,id,null,timeoutMs); + return op==ScannerOperation.TASK?archiveTask(result,deadline):result; } public ScannerHttpClient.Binary binary(ScannerOperation op,String id){return client.binary(op,id);} - public ScannerCommandJournal.Entry command(String key){var entry=journal.get(key(key));if(entry!=null&&entry.state().equals("ACCEPTED"))refresh(entry);return journal.get(key);} + public ScannerCommandJournal.Entry command(String key){var entry=journal.get(key(key));if(entry!=null&&entry.state().equals("ACCEPTED"))refresh(entry);entry=journal.get(key);if(entry!=null&&entry.state().equals("SUCCEEDED"))archivedResult(entry,deadline(settings.getOperationTimeoutMs()));return journal.get(key);} + private JsonNode archiveTask(JsonNode task,long deadline){ + if(fileArchive==null||!"succeeded".equals(task.path("state").asText())||!task.path("result").path("files").isArray()||task.path("result").path("files").isEmpty())return task; + return fileArchive.archiveTask(task,client.endpointKey(),id->client.remoteFile(id,requestBudget(deadline)),()->requestBudget(deadline)); + } + private JsonNode archivedResult(ScannerCommandJournal.Entry entry,long deadline){ + JsonNode original=result(entry); + if(fileArchive!=null&&original.path("result").path("files").isArray())for(JsonNode file:original.path("result").path("files")) + if(!file.path("archived").asBoolean()&&!Objects.equals(entry.endpoint(),client.endpointKey()))throw new ScannerException("endpoint_changed","原文件尚未归档,扫描服务地址已变更,不能从新服务获取旧文件",409); + JsonNode archived=archiveTask(original,deadline); + if(!original.equals(archived))journal.archiveResult(entry.key(),entry.result(),archived); + return archived; + } public ObjectNode submit(ScannerOperation op,ObjectNode body,String commandKey,String owner) { return submit(op,body,commandKey,owner,null,0); @@ -126,7 +144,6 @@ public class ScannerService { return request; } public JsonNode executeBoundAndWait(ScannerOperation op,ObjectNode body,String key,String owner,long timeoutMs,JsonNode expectedContext) { - if(op==ScannerOperation.CALIBRATION_FREE&&timeoutMs>0)timeoutMs=Math.min(timeoutMs,CALIBRATION_FREE_TIMEOUT_MS); long deadline=deadline(timeoutMs); ObjectNode accepted; while(true){ @@ -139,21 +156,19 @@ public class ScannerService { return waitCommandUntil(key,deadline(timeoutMs)); } private JsonNode waitCommandUntil(String key,long deadline) { - long freeDeadline=deadline(CALIBRATION_FREE_TIMEOUT_MS); while(true){ requestBudget(deadline); ScannerCommandJournal.Entry entry=journal.get(key(key)); if(entry==null)throw new ScannerException("command_not_found","本地命令记录不存在",404); boolean free=ScannerOperation.CALIBRATION_FREE.name().equals(entry.operation()); - if(free&&freeDeadline-deadline<0)deadline=freeDeadline; requestBudget(deadline); requireKnown(entry); - if(entry.state().equals("SUCCEEDED"))return result(entry); + if(entry.state().equals("SUCCEEDED"))return archivedResult(entry,deadline); if(entry.state().equals("FAILED"))throw taskFailure(entry); try {refresh(entry,deadline);}catch(ScannerException error){if(!transientQuery(error)&&!(free&&error.scannerCode.equals("invalid_response")))throw error;} entry=journal.get(key); requestBudget(deadline); - if(entry.state().equals("SUCCEEDED"))return result(entry); + if(entry.state().equals("SUCCEEDED"))return archivedResult(entry,deadline); if(entry.state().equals("FAILED"))throw taskFailure(entry); sleep(deadline,free?CALIBRATION_FREE_POLL_INTERVAL_MS:settings.getPollIntervalMs()); } @@ -164,7 +179,7 @@ public class ScannerService { try {task=query(ScannerOperation.TASK,id,deadline);}catch(ScannerException error){if(!transientQuery(error))throw error;sleep(deadline);continue;} if(!id.equals(task.path("taskId").asText()))throw new ScannerException("task_mismatch","任务响应编号不匹配",409); String state=task.path("state").asText(); - if(state.equals("succeeded"))return task; + if(state.equals("succeeded"))return archiveTask(task,deadline); if(state.equals("failed"))throw failure(task); if(!Set.of("queued","running").contains(state))throw new ScannerException("invalid_task_state","设备任务状态无效",502); sleep(deadline); diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerWorkflowAdapter.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerWorkflowAdapter.java index c7e65df..f7e8629 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerWorkflowAdapter.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerWorkflowAdapter.java @@ -27,12 +27,11 @@ public class ScannerWorkflowAdapter implements WorkcellDeviceAdapter { JSONObject input=message.getInputParams();ScannerOperation op=ScannerOperation.forAction(message.getAction().getAction()); input=ScannerRequestComposer.resolve(op,input); validateConfiguration(message.getRobotId(),input.getString("deviceId")); - // This node has a fixed completion policy, including previously published flows. - long timeout=op==ScannerOperation.CALIBRATION_FREE?ScannerService.CALIBRATION_FREE_TIMEOUT_MS:input.getLongValue("timeoutMs"); + long timeout=input.containsKey("timeoutMs")?input.getLongValue("timeoutMs"):settings.getOperationTimeoutMs(); 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);} + else if(!op.control()){result=service.get(op,null,timeout);} else { String commandKey=input.getString("commandKey"); if(message.getInstId()!=null&&!message.getInstId().isBlank()){ diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/engine/FlowRuntimeDefinitionValidator.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/engine/FlowRuntimeDefinitionValidator.java index ab5fa56..3e0f0ab 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/engine/FlowRuntimeDefinitionValidator.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/engine/FlowRuntimeDefinitionValidator.java @@ -39,6 +39,11 @@ public class FlowRuntimeDefinitionValidator { JSONObject p = nodes.getJSONObject(i).getJSONObject("properties"); if (p == null) continue; ActionEnum action = ActionEnum.fromAction(p.getString("action")); + if (action == ActionEnum.SYSTEM_EXECUTE_ACTION_QUEUE) { + try { validateQueueLiterals(p.getJSONArray("nodeParams")); } + catch (RuntimeException error) { throw new GlobalException("节点[" + p.getString("name") + "]参数错误:" + error.getMessage()); } + continue; + } if(action==ActionEnum.ARM_MOVE_COORDINATE_STEP){ try{com.cmvr.arm.ArmCoordinateStepParameters.validateLiterals(p.getJSONArray("nodeParams"));} catch(RuntimeException error){throw new GlobalException("节点["+p.getString("name")+"]参数错误:"+error.getMessage());} @@ -186,6 +191,31 @@ public class FlowRuntimeDefinitionValidator { } } + private static void validateQueueLiterals(JSONArray params) { + if (params == null) return; + for (int i = 0; i < params.size(); i++) { + JSONObject param = params.getJSONObject(i); + if (!"steps".equals(param.getString("name")) || "quote".equals(param.getString("type"))) continue; + Object raw = param.get("input"); + if (raw == null) throw new GlobalException("动作队列至少需要一个步骤"); + JSONArray values = raw instanceof String text ? JSON.parseArray(text) : JSON.parseArray(JSON.toJSONString(raw)); + if (values == null) throw new GlobalException("动作队列步骤须为数组"); + var steps = new java.util.ArrayList(); + for (int j = 0; j < values.size(); j++) { + JSONObject value = values.getJSONObject(j); + if (value == null) throw new GlobalException("动作队列包含无效步骤"); + value = com.cmvr.edge.client.model.system.ActionQueueInputBindings.validateDefinition(value, params); + var step = value.toJavaObject(com.cmvr.edge.client.model.system.EdgeActionQueueVO.Step.class); + // During preflight, slot bindings stand for the device to be assigned at runtime. + String binding = value.getString("deviceSlotKey"); + if (StrUtil.isBlank(binding)) binding = value.getString("deviceBindingKey"); + if (StrUtil.isNotBlank(binding)) step.setDeviceId("slot:" + binding); + steps.add(step); + } + com.cmvr.edge.client.model.system.ActionQueueParameters.validate(steps); + } + } + private RobotRuntimeMemberVO firstMember(ResourceRuntimeAssignmentVO assignment) { return assignment == null || assignment.getMembers() == null || assignment.getMembers().isEmpty() ? null : assignment.getMembers().get(0); diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/engine/RobotDeviceAssignmentValidator.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/engine/RobotDeviceAssignmentValidator.java index ec59583..1a3e321 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/engine/RobotDeviceAssignmentValidator.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/engine/RobotDeviceAssignmentValidator.java @@ -6,6 +6,8 @@ public interface RobotDeviceAssignmentValidator { void validate(String robotId, String deviceId, Integer expectedDeviceKind); default void validateAssignment(String robotId,String deviceId,Integer expectedDeviceKind) {validate(robotId,deviceId,expectedDeviceKind);} + /** Identity check for diagnostics and stop/cleanup, never for new motion. */ + default void validateRecovery(String robotId,String deviceId,Integer expectedDeviceKind) {validateAssignment(robotId,deviceId,expectedDeviceKind);} default void validateForAction(String robotId,String deviceId,Integer expectedDeviceKind,com.cmvr.test.enums.ActionEnum action) {validate(robotId,deviceId,expectedDeviceKind);} } diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/AgvNavigationWaiter.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/AgvNavigationWaiter.java index 943e294..76f0c73 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/AgvNavigationWaiter.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/AgvNavigationWaiter.java @@ -11,7 +11,7 @@ import java.util.concurrent.TimeUnit; @Slf4j public final class AgvNavigationWaiter { - public static final long DEFAULT_WAIT_TIMEOUT_MS = TimeUnit.MINUTES.toMillis(15); + public static final long DEFAULT_WAIT_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(120); public static final long DEFAULT_POLL_INTERVAL_MS = 1000L; // Values mirror cmvr-es AgvTaskState: None, Waiting, Running, Paused, diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/EdgeActionQueueOperateService.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/EdgeActionQueueOperateService.java index 5e7c174..0cf4bb6 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/EdgeActionQueueOperateService.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/EdgeActionQueueOperateService.java @@ -45,9 +45,12 @@ public class EdgeActionQueueOperateService implements EdgeOperateService { List requestSteps = new ArrayList<>(); for (int i = 0; i < steps.size(); i++) { JSONObject source = steps.getJSONObject(i); + if (source == null) throw new GlobalException("动作队列第" + (i + 1) + "步配置无效"); + source = com.cmvr.edge.client.model.system.ActionQueueInputBindings.resolve(source, input); EdgeActionQueueVO.Step step = new EdgeActionQueueVO.Step(); step.setStepId(StringUtils.defaultIfBlank(source.getString("stepId"), "step_" + (i + 1))); step.setType(source.getString("type")); + step.setCoordinateMode(source.getString("coordinateMode")); step.setTimeoutMs(source.getInteger("timeoutMs")); step.setParams(source.getJSONObject("params")); String deviceId = source.getString("deviceId"); @@ -62,14 +65,21 @@ public class EdgeActionQueueOperateService implements EdgeOperateService { SystemCommand.ActionQueueCommand.Feedback feedback = edgeSystemService.executeActionQueue(request); if (feedback == null || !feedback.hasHeader()) { - throw new GlobalException("Action queue response is missing status information"); + throw new GlobalException("动作队列回执缺少状态信息"); } if (!feedback.getHeader().getSuccess() || feedback.getResult() != SystemCommand.ActionResultCode.ACTION_RESULT_CODE_COMPLETED) { String failedAt = feedback.hasFailedStepIndex() - ? ", failed step index: " + feedback.getFailedStepIndex() : ""; + ? ",失败步骤: 第" + (Integer.toUnsignedLong(feedback.getFailedStepIndex()) + 1) + + "步(索引" + Integer.toUnsignedString(feedback.getFailedStepIndex()) + ")" : ""; throw new GlobalException(StringUtils.defaultIfBlank(feedback.getHeader().getErrorMessage(), - "Action queue execution failed") + failedAt); + "动作队列执行失败") + " [" + feedback.getResult().name() + "]" + failedAt + + ",已完成 " + Integer.toUnsignedString(feedback.getCompletedSteps()) + "/" + requestSteps.size() + " 步"); + } + if (Integer.toUnsignedLong(feedback.getCompletedSteps()) != requestSteps.size() + || feedback.hasFailedStepIndex()) { + throw new GlobalException("动作队列成功回执与步骤数不一致,请检查边端执行结果;已完成 " + + Integer.toUnsignedString(feedback.getCompletedSteps()) + "/" + requestSteps.size() + " 步"); } JSONObject output = new JSONObject(); diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/EdgeArmOperateService.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/EdgeArmOperateService.java index bcfd897..99f210f 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/EdgeArmOperateService.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/EdgeArmOperateService.java @@ -25,6 +25,13 @@ import org.springframework.stereotype.Service; @RequiredArgsConstructor public class EdgeArmOperateService implements EdgeOperateService { + private static Double resolvedSpeed(JSONObject input) { + Object value=input.get("velocity"); + if(!(value instanceof Number n)||!Double.isFinite(n.doubleValue())||n.doubleValue()<0) + throw new GlobalException("机械臂速度须为有效的非负数值,请检查填写值或当前运行的引用结果"); + return n.doubleValue(); + } + private final EdgeArmService edgeArmService; @org.springframework.beans.factory.annotation.Autowired private com.cmvr.arm.ArmTeachingService teaching; @org.springframework.beans.factory.annotation.Autowired private com.cmvr.arm.ArmCoordinateMotionService coordinateMotion; @@ -86,7 +93,7 @@ public class EdgeArmOperateService implements EdgeOperateService { Double ry = inputParams.getDouble("ry"); Double rz = inputParams.getDouble("rz"); String frame = inputParams.getString("frame"); - Double velocity = inputParams.getDouble("velocity"); + Double velocity = resolvedSpeed(inputParams); Double acceleration = inputParams.getDouble("acceleration"); Double blendRadius = inputParams.getDouble("blendRadius"); @@ -128,6 +135,8 @@ public class EdgeArmOperateService implements EdgeOperateService { } private void executeMoveJ(EdgeCommonVO edgeCommonVO, JSONObject inputParams) { + Object rawTimeout=inputParams.get("timeoutMs"); + if(rawTimeout!=null&&(!(rawTimeout instanceof Number number)||!Double.isFinite(number.doubleValue())||number.doubleValue()!=Math.rint(number.doubleValue())))throw new GlobalException("机械臂等待超时须为整数毫秒"); double[] target = parseDoubleArray(inputParams.get("target"), "target", true); double[] jointVelocityLimits = parseDoubleArray( inputParams.get("jointVelocityLimits"), "jointVelocityLimits", false); @@ -137,11 +146,12 @@ public class EdgeArmOperateService implements EdgeOperateService { edgeArmService.moveJ( edgeCommonVO, target, - inputParams.getDouble("velocity"), + resolvedSpeed(inputParams), inputParams.getDouble("acceleration"), inputParams.getDouble("blendRadius"), jointVelocityLimits, - inputParams.getBoolean("asynchronous") + inputParams.getBoolean("asynchronous"), + inputParams.getLong("timeoutMs") ); log.info("机械臂关节空间运动任务下发成功,设备ID: {}", edgeCommonVO.getDeviceId()); } diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/web/controller/api/EdgeArmController.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/web/controller/api/EdgeArmController.java index 0b4f3e3..73e10a1 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/web/controller/api/EdgeArmController.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/web/controller/api/EdgeArmController.java @@ -119,7 +119,8 @@ public class EdgeArmController { moveJVO.getAcceleration(), moveJVO.getBlendRadius(), moveJVO.getJointVelocityLimits(), - moveJVO.getAsynchronous() + moveJVO.getAsynchronous(), + moveJVO.getTimeoutMs() ); return AjaxResult.ok(); } diff --git a/am-backend/yudao-module-cmvr/src/main/proto/cmvr/api/arm_command.proto b/am-backend/yudao-module-cmvr/src/main/proto/cmvr/api/arm_command.proto index 9cbf483..5b44712 100644 --- a/am-backend/yudao-module-cmvr/src/main/proto/cmvr/api/arm_command.proto +++ b/am-backend/yudao-module-cmvr/src/main/proto/cmvr/api/arm_command.proto @@ -398,6 +398,15 @@ message JointResponse { } // 机械臂静态能力与 SDK 自动识别信息。 +// Per-joint position limits, matched by name; radians. Missing/invalid limits are not zero limits. +message ArmJointLimit { + string joint_name = 1; + bool position_limits_available = 2; + double lower = 3; + double upper = 4; + // aubo_sdk: controller readback; driver_model: driver model/configuration/URDF, not hardware readback. + string source = 5; +} message GetArmInfo { message Request { CommandHeader.Request header = 1; @@ -416,6 +425,7 @@ message GetArmInfo { string description_id = 10; bool detected_from_sdk = 11; string driver_type = 12; + repeated ArmJointLimit joint_limits = 13; } } @@ -539,3 +549,16 @@ message ComputeForwardKinematics { TransformMatrix4x4 matrix = 2; } } + +// Joint-space motion to an absolute TCP pose in an explicitly applied coordinate. +// AUBO converts with SDK Math, solves IK near current joints, then calls moveJoint. +message MoveJPose { + message Request { + CommandHeader.Request header = 1; + CartesianPose target = 2; // Absolute TCP pose: m / rad, RzRyRx. + MotionOptions options = 3; // Joint limits: rad/s, rad/s^2; AUBO does not use jerk. + string user_coordinate_name = 4; // Required. Apply this saved/builtin coordinate first. + uint64 user_coordinate_revision = 5; // 0 = latest saved revision; active revision must match. + } + message Response { CommandHeader.Feedback header = 1; } +} diff --git a/am-backend/yudao-module-cmvr/src/main/proto/cmvr/api/arm_service.proto b/am-backend/yudao-module-cmvr/src/main/proto/cmvr/api/arm_service.proto index 2defa9f..d75fa4b 100644 --- a/am-backend/yudao-module-cmvr/src/main/proto/cmvr/api/arm_service.proto +++ b/am-backend/yudao-module-cmvr/src/main/proto/cmvr/api/arm_service.proto @@ -14,6 +14,7 @@ service ArmService { // 清除机械臂可恢复故障;不包含数值参数,无单位。 rpc clearFault(CommandHeader.Request) returns (CommandHeader.Feedback); // 执行关节空间点到点运动;目标角度单位为 rad。 + rpc moveJPose(MoveJPose.Request) returns (MoveJPose.Response); rpc moveJ(MoveJ.Request) returns (MoveJ.Response); // 执行所选坐标系下的绝对TCP目标直线运动,位置m、姿态rad;不接受增量目标。 rpc moveL(MoveL.Request) returns (MoveL.Response); diff --git a/am-backend/yudao-module-cmvr/src/main/proto/cmvr/api/system_command.proto b/am-backend/yudao-module-cmvr/src/main/proto/cmvr/api/system_command.proto index ac91ae0..163d35a 100644 --- a/am-backend/yudao-module-cmvr/src/main/proto/cmvr/api/system_command.proto +++ b/am-backend/yudao-module-cmvr/src/main/proto/cmvr/api/system_command.proto @@ -14,12 +14,43 @@ enum DeviceType { Microphone = 5; Robot = 6; Speaker = 7; + BioHead = 8; + Motor = 9; + MotorSystem = 10; + MujocoWorld = 11; + MujocoViewer = 12; + CanBus = 13; Unknown = 20; } +// 设备在 cmvr-es 运行时中的稳定大类,与具体厂商驱动无关。 +enum DeviceKind { + DEVICE_KIND_UNKNOWN = 0; + DEVICE_KIND_AGV = 1; + DEVICE_KIND_ARM = 2; + DEVICE_KIND_BATTERY = 3; + DEVICE_KIND_BIO_HEAD = 4; + DEVICE_KIND_CAMERA = 5; + DEVICE_KIND_CAN_BUS = 6; + DEVICE_KIND_DEX_HAND = 7; + DEVICE_KIND_GRIPPER = 8; + DEVICE_KIND_MICROPHONE = 9; + DEVICE_KIND_MOTOR = 10; + DEVICE_KIND_MOTOR_SYSTEM = 11; + DEVICE_KIND_MUJOCO_VIEWER = 12; + DEVICE_KIND_MUJOCO_WORLD = 13; + DEVICE_KIND_ROBOT = 14; + DEVICE_KIND_SPEAKER = 15; +} + message DeviceList { string device_id = 1; DeviceType device_type = 2; + DeviceKind device_kind = 3; + // 具体运行时驱动类型,例如 AuboARM、HuayanRobot、SeerRobokitAgv。 + string driver_type = 4; + // 厂商或驱动生态,例如 AUBO、HUAYAN、SEER。 + string vendor = 5; } message GetSystemInfoCommand { @@ -91,6 +122,12 @@ message ActionStep { oneof command { MoveJ.Request arm_move_j = 10; MoveL.Request arm_move_l = 11; + MoveJPose.Request arm_move_j_pose = 13; + // Apply a saved coordinate before subsequent arm steps. Uses header.device_id, + // name and expected_revision (0 = latest); coordinate payload is not accepted. + // AUBO MoveL without legacy frame overrides follows this selection until switched. + // Switching does not move the arm. A failure aborts the remaining queue. + UserCoordinateSystemCommand.Request arm_apply_user_coordinate = 12; } } diff --git a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/arm/ArmTeachingIntegrationTest.java b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/arm/ArmTeachingIntegrationTest.java index a5b8f2f..ae1b0e7 100644 --- a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/arm/ArmTeachingIntegrationTest.java +++ b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/arm/ArmTeachingIntegrationTest.java @@ -73,15 +73,15 @@ public class ArmTeachingIntegrationTest { } @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 powerAndDefaultStatusDeadlinesAreThirtySeconds(){ + @Test public void powerAndDefaultStatusDeadlinesAreTwoMinutes(){ var arm=new com.cmvr.edge.client.service.impl.EdgeArmServiceImpl(clients); var target=new com.cmvr.edge.client.model.EdgeCommonVO();target.setRobotId("robot");target.setDeviceId("aubo_arm"); arm.torqueOn(target);arm.torqueOff(target);service.execute(ArmTeachingOperation.GET_ROBOT_STATE,request()); - for(String method:List.of("enable","disable","state")){assertNotNull(deadlines.get(method));assertTrue(deadlines.get(method)>20000);assertTrue(deadlines.get(method)<=30000);} + for(String method:List.of("enable","disable","state")){assertNotNull(deadlines.get(method));assertTrue(deadlines.get(method)>110000);assertTrue(deadlines.get(method)<=120000);} } - @Test public void savedShortControlTimeoutsUpgradeToThirtySecondsWithoutTruncatingReplay(){ - assertEquals(30000,ArmTeachingParameters.timeout(ArmTeachingOperation.GET_ROBOT_STATE,10000L)); - assertEquals(30000,ArmTeachingParameters.timeout(ArmTeachingOperation.STOP_MOTION,null)); + @Test public void defaultControlsUseTwoMinutesAndExplicitTimeoutsRemainEffective(){ + assertEquals(10000,ArmTeachingParameters.timeout(ArmTeachingOperation.GET_ROBOT_STATE,10000L)); + assertEquals(120000,ArmTeachingParameters.timeout(ArmTeachingOperation.STOP_MOTION,null)); assertEquals(300000,ArmTeachingParameters.timeout(ArmTeachingOperation.REPLAY_RECORDED_TRAJECTORY,300000L)); } @Test public void allRpcShapesWorkAndUint64IsNotRounded() { diff --git a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/arm/ArmTeachingParametersTest.java b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/arm/ArmTeachingParametersTest.java index 71684f2..643618c 100644 --- a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/arm/ArmTeachingParametersTest.java +++ b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/arm/ArmTeachingParametersTest.java @@ -23,6 +23,7 @@ public class ArmTeachingParametersTest { @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(34,cmvr.api.ArmServiceGrpc.getServiceDescriptor().getMethods().size()); + assertEquals(35,cmvr.api.ArmServiceGrpc.getServiceDescriptor().getMethods().size()); + assertTrue(cmvr.api.ArmServiceGrpc.getServiceDescriptor().getMethods().stream().anyMatch(method->method.getFullMethodName().endsWith("/moveJPose"))); } } diff --git a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/edge/client/service/impl/ActionQueueTimeoutTest.java b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/edge/client/service/impl/ActionQueueTimeoutTest.java index 3317174..8736cce 100644 --- a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/edge/client/service/impl/ActionQueueTimeoutTest.java +++ b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/edge/client/service/impl/ActionQueueTimeoutTest.java @@ -14,13 +14,13 @@ import static org.mockito.Mockito.*; public class ActionQueueTimeoutTest { @Test public void defaultsZeroAndOverflow(){ - assertEquals(120000,ActionQueueTimeouts.total(List.of(step(null),step(null)))); + assertEquals(240000,ActionQueueTimeouts.total(List.of(step(null),step(null)))); assertEquals(0,ActionQueueTimeouts.total(List.of(step(0),step(5000)))); assertThrows(RuntimeException.class,()->ActionQueueTimeouts.total(List.of(step(-1)))); assertThrows(RuntimeException.class,()->ActionQueueTimeouts.total(List.of(step(0),step(-1)))); assertThrows(RuntimeException.class,()->ActionQueueTimeouts.total(List.of(step(Integer.MAX_VALUE),step(1)))); } - @Test public void grpcCarriesCalculatedTotalAndNoDeadlineForZero() throws Exception { + @Test public void grpcCarriesCalculatedTotalAndEdgeDefaultDeadlineForZero() throws Exception { AtomicReference captured=new AtomicReference<>();AtomicReference deadline=new AtomicReference<>(); Server server=io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder.forAddress(new java.net.InetSocketAddress("127.0.0.1",0)) .intercept(new ServerInterceptor(){public ServerCall.Listener interceptCall(ServerCall call,Metadata headers,ServerCallHandler next){deadline.set(Context.current().getDeadline());return next.startCall(call,headers);}}) @@ -30,7 +30,7 @@ public class ActionQueueTimeoutTest { var manager=mock(GrpcServiceManager.class);when(manager.getGrpcClient(eq("test"),eq(SystemServiceGrpc.SystemServiceBlockingStub.class))).thenReturn(SystemServiceGrpc.newBlockingStub(channel));var service=new EdgeSystemServiceImpl(manager); var r=new EdgeActionQueueVO();r.setRobotId("test");r.setTotalTimeoutMs(1);r.setSteps(List.of(step(60000),step(30000)));service.executeActionQueue(r); assertEquals(90000,captured.get().getTotalTimeoutMs());assertNotNull(deadline.get());assertTrue(deadline.get().timeRemaining(TimeUnit.SECONDS)>80); - r.setSteps(List.of(step(0),step(60000)));service.executeActionQueue(r);assertEquals(0,captured.get().getTotalTimeoutMs());assertEquals(0,captured.get().getSteps(0).getTimeoutMs());assertNull(deadline.get()); + r.setSteps(List.of(step(0),step(60000)));service.executeActionQueue(r);assertEquals(0,captured.get().getTotalTimeoutMs());assertEquals(0,captured.get().getSteps(0).getTimeoutMs());assertNotNull(deadline.get());assertTrue(deadline.get().timeRemaining(TimeUnit.SECONDS)>290); }finally{channel.shutdownNow().awaitTermination(5,TimeUnit.SECONDS);server.shutdownNow().awaitTermination(5,TimeUnit.SECONDS);} } private static EdgeActionQueueVO.Step step(Integer timeout){var s=new EdgeActionQueueVO.Step();s.setType("ARM_MOVE_J");s.setDeviceId("fake-arm");s.setTimeoutMs(timeout);s.setParams(JSONObject.of("positions",List.of(0D,0D,0D,0D,0D,0D)));return s;} diff --git a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/rotarybase/RotaryBaseIntegrationTest.java b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/rotarybase/RotaryBaseIntegrationTest.java index bd41ef0..bf2001c 100644 --- a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/rotarybase/RotaryBaseIntegrationTest.java +++ b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/rotarybase/RotaryBaseIntegrationTest.java @@ -160,7 +160,7 @@ public class RotaryBaseIntegrationTest { for(String key:List.of("method","fastSpeed","slowSpeed","acceleration","timeoutSeconds","offset","timeoutMs")) { var values=homing();values.remove(key);msg.setInputParams(values);assertThrows(GlobalException.class,()->adapter.execute(msg)); } - for(var bad:List.of(JSONObject.of("method",0),JSONObject.of("fastSpeed",0),JSONObject.of("slowSpeed",0.2),JSONObject.of("acceleration",0),JSONObject.of("timeoutSeconds",301),JSONObject.of("offset",7),JSONObject.of("timeoutMs",300000))) { + for(var bad:List.of(JSONObject.of("method",0),JSONObject.of("fastSpeed",0),JSONObject.of("slowSpeed",0.2),JSONObject.of("acceleration",0),JSONObject.of("timeoutSeconds",301),JSONObject.of("offset",7),JSONObject.of("timeoutMs",299999))) { var values=homing();values.putAll(bad);msg.setInputParams(values);assertThrows(GlobalException.class,()->adapter.execute(msg)); } assertTrue(homeRequests.isEmpty());assertTrue(methods.isEmpty()); diff --git a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerFrameworkReferenceTest.java b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerFrameworkReferenceTest.java index 4e0e640..cfb6f9b 100644 --- a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerFrameworkReferenceTest.java +++ b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerFrameworkReferenceTest.java @@ -28,6 +28,7 @@ public class ScannerFrameworkReferenceTest { AtomicReference data=new AtomicReference<>(new byte[]{1,2,3}); AtomicBoolean changeProject=new AtomicBoolean(),noHeader=new AtomicBoolean(),badReceipt=new AtomicBoolean(); AtomicBoolean emptyErrorObject=new AtomicBoolean(); + AtomicBoolean registrationExpired=new AtomicBoolean(); AtomicReference importedBody=new AtomicReference<>(); @Before public void setup() throws Exception { server=HttpServer.create(new InetSocketAddress("127.0.0.1",0),0);executor=Executors.newCachedThreadPool();server.setExecutor(executor); @@ -37,6 +38,7 @@ public class ScannerFrameworkReferenceTest { String path=e.getRequestURI().getPath(),response;int status=200; if(path.startsWith("/api/v1/files/")) { downloads.incrementAndGet();Thread.sleep(delay.get()); + if(path.endsWith(REGISTERED)&®istrationExpired.get()){e.sendResponseHeaders(404,-1);e.close();return;} if(downloadStatus.get()!=200) {e.getResponseHeaders().set("Location","http://127.0.0.1:1/leak");if(emptyErrorObject.get()){byte[] bytes="{}".getBytes(StandardCharsets.UTF_8);e.sendResponseHeaders(downloadStatus.get(),bytes.length);e.getResponseBody().write(bytes);}else e.sendResponseHeaders(downloadStatus.get(),-1);e.close();return;} if(!noHeader.get())e.getResponseHeaders().set("Content-Disposition","attachment; filename=\""+fileName.get()+"\""); byte[] bytes=data.get();if(bytes.length==0)e.sendResponseHeaders(200,-1);else {e.sendResponseHeaders(200,bytes.length);e.getResponseBody().write(bytes);}e.close();return; @@ -75,7 +77,7 @@ public class ScannerFrameworkReferenceTest { assertTrue(importedBody.get().contains(REGISTERED));assertFalse(importedBody.get().contains(SOURCE)); assertEquals(url(),first.getOutputParams().getJSONArray("frameworkTransfer").getJSONObject(0).getString("sourceUrl")); adapter.execute(message(0));assertEquals(1,downloads.get());assertEquals(1,uploads.get());assertEquals(1,imports.get()); - adapter.execute(message(1));assertEquals(2,downloads.get());assertEquals(1,uploads.get());assertEquals(2,imports.get()); + adapter.execute(message(1));assertEquals(3,downloads.get());assertEquals(1,uploads.get());assertEquals(2,imports.get()); assertEquals(3,jdbc.queryForObject("SELECT COUNT(*) FROM lab_scanner_framework_transfer WHERE owner_ref='workflow:E2E-URL-fixture'",Integer.class).intValue()); } @Test public void archivedLocalFileIsUploadedAndImportedWithoutDownloadingFromScanner() throws Exception { @@ -108,7 +110,12 @@ public class ScannerFrameworkReferenceTest { } @Test public void configuredAbsoluteAndProxyRelativeUrlsWorkWithoutForwardingTheirHost() { prepare("framework-absolute","http://127.0.0.1:"+settings.getPort()+url()); - prepare("framework-proxy","/admin-api/cmvr/scanner/files/"+SOURCE);assertEquals(2,downloads.get());assertEquals(1,uploads.get()); + prepare("framework-proxy","/admin-api/cmvr/scanner/files/"+SOURCE);assertEquals(3,downloads.get());assertEquals(1,uploads.get()); + } + @Test public void expiredUploadRegistrationIsRenewedOnlyAfterDefinite404ForNewExecution() { + prepare("registered-first",url());registrationExpired.set(true); + prepare("registered-next",url());assertEquals(2,uploads.get());assertEquals(0,imports.get()); + prepare("registered-next",url());assertEquals(2,uploads.get()); } @Test public void wrongScanModeFailsBeforeDownload() { mode.set("photogrammetry");assertEquals("framework_import_not_ready",assertThrows(ScannerException.class,()->prepare("framework-mode",url())).scannerCode);assertEquals(0,downloads.get()); diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/cmvr/LabAgvViewController.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/cmvr/LabAgvViewController.java new file mode 100644 index 0000000..17eacd2 --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/cmvr/LabAgvViewController.java @@ -0,0 +1,19 @@ +package cn.iocoder.yudao.module.lab.controller.admin.cmvr; +import cn.iocoder.yudao.framework.common.pojo.CommonResult; +import cn.iocoder.yudao.module.lab.service.execution.LabAgvViewService; +import com.alibaba.fastjson2.*; +import lombok.RequiredArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import java.util.*; +@RestController @RequestMapping("/lab/execution/agv-view") +@PreAuthorize("@ss.hasAnyPermissions('lab:execution:query','lab:execution:dispatch','lab:task:query')") +@RequiredArgsConstructor +public class LabAgvViewController { + private final LabAgvViewService views; + @GetMapping("/targets") public CommonResult targets(@RequestParam(required=false) Long executionId,@RequestParam(required=false) List robotIds){return CommonResult.success(views.targets(executionId,robotIds==null?List.of():robotIds));} + @GetMapping("/state") public CommonResult state(@RequestParam(required=false) Long executionId,@RequestParam String robotId,@RequestParam String deviceId,@RequestParam(defaultValue="0") long afterAt){return CommonResult.success(views.state(executionId,robotId,deviceId,afterAt));} + @GetMapping("/map") public CommonResult map(@RequestParam(required=false) Long executionId,@RequestParam String robotId,@RequestParam String deviceId,@RequestParam(required=false) String version){return CommonResult.success(views.map(executionId,robotId,deviceId,version));} + @ExceptionHandler(com.cmvr.common.exception.GlobalException.class) public CommonResult invalid(com.cmvr.common.exception.GlobalException error){return CommonResult.error(400,error.getMessage());} + @ExceptionHandler(io.grpc.StatusRuntimeException.class) public CommonResult unavailable(io.grpc.StatusRuntimeException error){return CommonResult.error(503,"AGV只读查询暂不可用:"+error.getStatus().getCode());} +} diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabAgvViewService.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabAgvViewService.java new file mode 100644 index 0000000..a958b37 --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabAgvViewService.java @@ -0,0 +1,108 @@ +package cn.iocoder.yudao.module.lab.service.execution; + +import cn.iocoder.yudao.module.lab.dal.dataobject.execution.LabExecutionDO; +import cn.iocoder.yudao.module.lab.dal.mysql.execution.LabExecutionMapper; +import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils; +import com.alibaba.fastjson2.*; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.cmvr.common.exception.GlobalException; +import com.cmvr.edge.client.service.AgvViewService; +import com.cmvr.resource.domain.ResourceDevice; +import com.cmvr.resource.service.ResourceDeviceService; +import jakarta.annotation.PreDestroy; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; + +/** Execution-owned position traces; sampling does not depend on an open browser tab. */ +@Service @RequiredArgsConstructor +public class LabAgvViewService { + private final LabExecutionMapper executions; + private final ResourceDeviceService devices; + private final AgvViewService views; + @Value("${lab.artifact.nas-root:./.local/artifacts}") private String archiveRoot; + private final Map traces=new ConcurrentHashMap<>(); + private final Set pending=ConcurrentHashMap.newKeySet(); + private final ExecutorService worker=new ThreadPoolExecutor(2,2,0,TimeUnit.SECONDS,new ArrayBlockingQueue<>(64),r->{var t=new Thread(r,"agv-position-monitor");t.setDaemon(true);return t;},new ThreadPoolExecutor.AbortPolicy()); + private final ExecutorService mapWorker=new ThreadPoolExecutor(2,2,0,TimeUnit.SECONDS,new ArrayBlockingQueue<>(16),r->{var t=new Thread(r,"agv-map-monitor");t.setDaemon(true);return t;},new ThreadPoolExecutor.AbortPolicy()); + private static class Trace { JSONObject data;long saved,mapChecked,nextStateAt;boolean mapLoading;int segment,failures;Trace(JSONObject data){this.data=data;var points=data.getJSONArray("points");if(points!=null&&!points.isEmpty())segment=points.getJSONObject(points.size()-1).getIntValue("segment")+1;} } + public LabExecutionDO required(Long id){CmvrMethodBindingService.requirePrimaryTenant();var e=executions.selectById(id);if(e==null)throw new GlobalException("执行记录不存在");return e;} + public static boolean active(LabExecutionDO e){return Set.of("RUNNING","PAUSED").contains(e.getStatus());} + public JSONArray targets(Long id,List robots){ + CmvrMethodBindingService.requirePrimaryTenant();if(id!=null)robots=robots(required(id)); + if(robots==null||robots.size()>32)throw new GlobalException("请选择不超过32个机器人");var result=new JSONArray();var seen=new HashSet(); + for(String robot:robots){if(robot==null||robot.isBlank())continue;var q=new ResourceDevice();q.setRobotId(robot);q.setDeviceKind(1); + for(var d:devices.list(q,false)){String key=robot+"\n"+d.getDeviceId();if(!seen.add(key))continue;result.add(JSONObject.of("robotId",robot,"deviceId",d.getDeviceId(),"name",d.getDeviceName(),"online","1".equals(d.getOnlineStatus()),"enabled","1".equals(d.getEnabled())));} + }return result; + } + private List robots(LabExecutionDO e){ + var p=e.getRunParams()==null?new JSONObject():new JSONObject(e.getRunParams());var result=new LinkedHashSet();var assignments=p.getJSONArray("_cmvrRuntimeAssignments"); + if(assignments!=null)for(int i=0;i(result); + } + private JSONObject target(Long id,String robot,String device){ + var list=targets(id,id==null?List.of(robot):null);for(Object item:list){var t=(JSONObject)item;if(Objects.equals(robot,t.getString("robotId"))&&Objects.equals(device,t.getString("deviceId")))return t;}throw new GlobalException("AGV不属于本次执行分配的机器人,或设备未登记"); + } + public JSONObject state(Long id,String robot,String device,long afterAt){ + target(id,robot,device);if(id==null){try{return JSONObject.of("state",views.state(robot,device),"points",new JSONArray(),"history",false);}catch(Exception e){return JSONObject.of("points",new JSONArray(),"history",false,"message","定位暂不可用:"+message(e));}} + var execution=required(id);String key=key(id,robot,device);var trace=traces.get(key);if(trace==null){JSONObject file=read(id,robot,device);if(file!=null)trace=new Trace(file);} + if(trace==null)return JSONObject.of("history",!active(execution),"points",new JSONArray(),"message",active(execution)?"正在等待本次执行的定位采样":"本次执行尚无已记录的AGV轨迹"); + synchronized(trace){var data=new JSONObject(trace.data);data.remove("map");data.remove("stations");if(afterAt>0){var points=new JSONArray();for(Object item:trace.data.getJSONArray("points")){var p=(JSONObject)item;if(p.getLongValue("at")>afterAt)points.add(p);}data.put("points",points);}data.put("history",!active(execution));return JSON.parseObject(data.toJSONString());} + } + public JSONObject map(Long id,String robot,String device,String version){ + target(id,robot,device);JSONObject map;JSONArray stationList;String error=""; + if(id==null){try{var state=views.state(robot,device);String name=state.getString("currentMap");map=views.map(robot,device,name==null?"":name);try{stationList=views.stations(robot,device,name);}catch(Exception e){stationList=new JSONArray();}}catch(Exception e){return JSONObject.of("available",false,"message","地图暂不可用:"+message(e));}} + else {var execution=required(id);var trace=traces.get(key(id,robot,device));JSONObject data;if(trace==null)data=read(id,robot,device);else synchronized(trace){data=JSON.parseObject(trace.data.toJSONString());} + map=data==null?null:data.getJSONObject("map");stationList=data==null?new JSONArray():data.getJSONArray("stations");error=data==null?"":data.getString("mapError"); + if(map==null)return JSONObject.of("available",false,"message",error!=null&&!error.isBlank()?error:active(execution)?"正在读取本次执行的地图":"本次执行未归档地图,仍可查看已记录的定位轨迹"); + } + if(Objects.equals(version,map.getString("version")))return JSONObject.of("available",true,"unchanged",true,"version",version,"stations",stationList); + var result=JSON.parseObject(map.toJSONString());result.put("available",true);result.put("stations",stationList);return result; + } + @Scheduled(fixedDelay=1000) public void sampleExecutions(){ + TenantUtils.execute(1L,()->{ + var active=executions.selectList(new LambdaQueryWrapper().in(LabExecutionDO::getStatus,"RUNNING","PAUSED").orderByDesc(LabExecutionDO::getId).last("LIMIT 64"));var alive=new HashSet(); + for(var e:active)for(Object item:targets(e.getId(),null)){var target=(JSONObject)item;String key=key(e.getId(),target.getString("robotId"),target.getString("deviceId"));alive.add(key);if(!pending.add(key))continue; + try{worker.submit(()->{try{TenantUtils.execute(1L,()->sample(e,target,key));}finally{pending.remove(key);}});}catch(RejectedExecutionException full){pending.remove(key);} + } + for(var entry:traces.entrySet())if(!alive.contains(entry.getKey())&&!pending.contains(entry.getKey())){synchronized(entry.getValue()){save(entry.getValue());}traces.remove(entry.getKey(),entry.getValue());} + }); + } + private void sample(LabExecutionDO execution,JSONObject target,String key){ + String robot=target.getString("robotId"),device=target.getString("deviceId");var trace=traces.computeIfAbsent(key,k->{var old=read(execution.getId(),robot,device);return new Trace(old==null?JSONObject.of("executionId",String.valueOf(execution.getId()),"robotId",robot,"deviceId",device,"points",new JSONArray()):old);}); + synchronized(trace){ + if(System.currentTimeMillis()=.015||Math.abs(pose.getDoubleValue("theta")-previous.getDoubleValue("theta"))>=.03){ + var point=new JSONObject(pose);point.put("at",state.getLongValue("receivedAt"));point.put("mapId",map);point.put("segment",trace.segment);point.put("mapEpoch",trace.data.getIntValue("mapEpoch"));points.add(point);if(points.size()>20000){var reduced=new JSONArray();for(int i=0;i0&&points.getJSONObject(i).getIntValue("segment")!=points.getJSONObject(i-1).getIntValue("segment"))reduced.add(points.get(i));if(reduced.size()>20000)reduced=new JSONArray(reduced.subList(reduced.size()-20000,reduced.size()));trace.data.put("points",reduced);trace.data.put("sampled",true);} + } + }else trace.segment++; + if(!trace.mapLoading&&System.currentTimeMillis()-trace.mapChecked>30000){trace.mapLoading=true;trace.mapChecked=System.currentTimeMillis();try{mapWorker.submit(()->TenantUtils.execute(1L,()->loadMap(trace,robot,device,map)));}catch(RejectedExecutionException busy){trace.mapLoading=false;}} + }catch(Exception error){trace.data.put("message","定位读取失败:"+message(error));trace.segment++;trace.nextStateAt=System.currentTimeMillis()+Math.min(15000,1000L<5000)save(trace); + } + } + private void loadMap(Trace trace,String robot,String device,String name){ + try{if(!active(required(trace.data.getLong("executionId"))))return;var map=views.map(robot,device,name==null?"":name);JSONArray stationList;try{stationList=views.stations(robot,device,name);}catch(Exception e){stationList=new JSONArray();}if(!active(required(trace.data.getLong("executionId"))))return; + synchronized(trace){if(Objects.equals(name,trace.data.getJSONObject("state").getString("currentMap"))){var old=trace.data.getJSONObject("map");if(old!=null&&(!Objects.equals(old.get("origin"),map.get("origin"))||!Objects.equals(old.getString("frameId"),map.getString("frameId")))){trace.segment++;trace.data.put("mapEpoch",trace.data.getIntValue("mapEpoch")+1);}trace.data.put("map",map);trace.data.put("stations",stationList);trace.data.remove("mapError");save(trace);}} + }catch(Exception error){synchronized(trace){trace.data.put("mapError","地图读取失败:"+message(error));save(trace);}}finally{synchronized(trace){trace.mapLoading=false;}} + } + private static boolean validPose(JSONObject p){if(p==null)return false;for(String axis:List.of("x","y","theta"))if(!(p.get(axis) instanceof Number n)||!Double.isFinite(n.doubleValue()))return false;return true;} + private static String message(Exception e){String text=e.getMessage();return text==null?"设备暂不可用":text.substring(0,Math.min(text.length(),300));} + private String key(Long id,String robot,String device){return id+"/"+cn.hutool.crypto.digest.DigestUtil.sha256Hex(robot+"\n"+device);} + private Path file(Long id,String robot,String device){return Path.of(archiveRoot).toAbsolutePath().normalize().resolve("agv-traces").resolve(key(id,robot,device)+".json");} + private JSONObject read(Long id,String robot,String device){var f=file(id,robot,device);try{if(!Files.exists(f)||Files.size(f)>16000000)return null;return JSON.parseObject(Files.readString(f));}catch(Exception e){return null;}} + private void save(Trace t){try{var d=t.data;Path f=file(d.getLong("executionId"),d.getString("robotId"),d.getString("deviceId"));Files.createDirectories(f.getParent());Path temp=f.resolveSibling(f.getFileName()+".tmp");Files.writeString(temp,d.toJSONString());try{Files.move(temp,f,StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.ATOMIC_MOVE);}catch(AtomicMoveNotSupportedException unsupported){Files.move(temp,f,StandardCopyOption.REPLACE_EXISTING);}t.saved=System.currentTimeMillis();}catch(Exception e){t.data.put("archiveError","轨迹归档失败,当前只能查看内存记录");}} + @PreDestroy public void close(){worker.shutdownNow();mapWorker.shutdownNow();try{worker.awaitTermination(3,TimeUnit.SECONDS);mapWorker.awaitTermination(3,TimeUnit.SECONDS);}catch(InterruptedException e){Thread.currentThread().interrupt();}for(var t:traces.values())synchronized(t){save(t);}} +} diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskService.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskService.java index df7226e..a36af0d 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskService.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskService.java @@ -22,6 +22,8 @@ public interface ScanOnlyTaskService { Long startSupplement(ScanTaskRequests.Supplement request); void finishSupplement(ScanTaskRequests.FinishSupplement request); void cancel(Long taskId,String reason); + /** Internal emergency-stop observer only; never exposed as a user cancellation endpoint. */ + void emergencyStop(Long taskId,List expectedLeaseIds,String source); void confirmStop(Long taskId,String reason); void pause(Long taskId); void resume(Long taskId); diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskServiceImpl.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskServiceImpl.java index 7fbfd3c..9a0bc34 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskServiceImpl.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskServiceImpl.java @@ -384,6 +384,22 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService { if(ScanOnlyRules.blank(reason))throw invalidParamException("取消任务必须填写原因"); LabTestTaskDO task=owned(taskId,false);ScanTaskConfigDO c=config(taskId); if("COMPLETED".equals(task.getStatus()))throw invalidParamException("已完成任务不能取消"); + cancelAndConfirm(task,c,reason); + } + + /** The observer has no logged-in user. Limit its authority to the exact, still-held task leases. */ + @Override @Transactional(rollbackFor=Exception.class) + public void emergencyStop(Long taskId,List expectedLeaseIds,String source) { + LabTestTaskDO task=required(taskId,true); + if(expectedLeaseIds==null||expectedLeaseIds.isEmpty()||!resources.leaseIds("TASK:"+taskId).equals(expectedLeaseIds))return; + if(Set.of("COMPLETED","CANCELLED").contains(task.getStatus()))return; + ScanTaskConfigDO c=config(taskId); + if(!Boolean.TRUE.equals(c.getCancelRequested()))audit(task,"SCAN_EMERGENCY_STOP",map("source",source,"message","检测到工位急停,终止流程并确认全部关联设备停止;复位后不自动继续")); + cancelAndConfirm(task,c,"工位急停:"+source); + } + + private void cancelAndConfirm(LabTestTaskDO task,ScanTaskConfigDO c,String reason) { + Long taskId=task.getId(); c.setCancelRequested(true);task.setCancelReason(reason); List active=executions.selectActiveByTaskId(taskId); if(active.isEmpty()&&!Boolean.TRUE.equals(c.getStopPending())&&c.getResourcesAcquiredAt()==null) { diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanResourceService.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanResourceService.java index af63c1f..f352e7f 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanResourceService.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanResourceService.java @@ -126,12 +126,17 @@ public class ScanResourceService extends ResourceOccupationStore { } /** Stop outside database locks; immutable operation IDs prevent a stale acknowledgement releasing a successor. */ public void clearOccupation(String owner,String reason) { + clearOccupation(owner,reason,null); + } + /** Internal recovery must never act on a replacement lease created while polling hardware. */ + void clearOccupation(String owner,String reason,List expectedLeaseIds) { primary();if(owner==null||!(owner.startsWith("NATIVE:")||owner.startsWith("MANUAL:"))||reason==null||reason.isBlank())throw invalidParamException("请选择试运行或人工占用并填写说明;扫描任务请从工作台停止"); var held=rows("SELECT * FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1 AND deleted=0",owner);if(held.isEmpty())throw invalidParamException("占用已经释放,请刷新"); Set robots=new TreeSet<>();for(var row:held)if("ROBOT".equals(row.get("resource_type")))robots.add(row.get("resource_id").toString()); try(var gate=RobotResourceOperationGate.lock(robots)) { held=rows("SELECT * FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1 AND deleted=0",owner); if(held.isEmpty())throw invalidParamException("该操作已停止并释放,请刷新"); + if(expectedLeaseIds!=null&&!leaseIds(owner).equals(expectedLeaseIds))throw invalidParamException("占用已变化,忽略旧急停处理"); for(String robot:robots)if(nativeTasks.isRobotLocked("robot:"+robot))throw invalidParamException("流程仍在运行或暂停,请先停止流程,再确认释放"); for(String robot:robots) { try { edgeSystem.stopAll(robot); } @@ -144,6 +149,9 @@ public class ScanResourceService extends ResourceOccupationStore { jdbc.update("DELETE FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1",owner); } } + List leaseIds(String owner) { + return jdbc.queryForList("SELECT id FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1 AND deleted=0 ORDER BY id",Long.class,owner); + } public void guardReservationMutation(String type,Long resourceId) { if(resourceId==null||resourceId<=0)throw invalidParamException("请提供有效的资源编号"); if(!Set.of("DEVICE","LAB").contains(Objects.toString(type,"")))throw invalidParamException("资源类型无效"); diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/StationEmergencyStopRecovery.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/StationEmergencyStopRecovery.java new file mode 100644 index 0000000..1794a5e --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/StationEmergencyStopRecovery.java @@ -0,0 +1,145 @@ +package cn.iocoder.yudao.module.lab.service.scanonly; + +import cn.hutool.core.util.IdUtil; +import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils; +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; +import com.cmvr.arm.ArmTeachingOperation; +import com.cmvr.arm.ArmTeachingRequest; +import com.cmvr.arm.ArmTeachingService; +import com.cmvr.resource.mapper.ResourceDeviceMapper; +import com.cmvr.test.flow.context.TaskInstHolder; +import com.cmvr.test.flow.context.TaskThreadRegistry; +import com.cmvr.test.flow.control.FlowControlService; +import jakarta.annotation.PreDestroy; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.concurrent.*; + +/** Observe an explicit arm emergency signal; never infer a stop from a timeout or loss of QUIC. + * The signal only stops its own execution. Every device still goes through normal stop confirmation. + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class StationEmergencyStopRecovery { + private final JdbcTemplate jdbc; + private final ScanResourceService resources; + private final ResourceDeviceMapper devices; + private final ArmTeachingService teaching; + private final TaskInstHolder tasks; + private final TaskThreadRegistry threads; + private final FlowControlService controls; + private final ScanOnlyTaskService scanTasks; + private final Set inFlight=ConcurrentHashMap.newKeySet(); + private final Map warnings=new ConcurrentHashMap<>(); + private final Map retryAfter=new ConcurrentHashMap<>(); + private final ExecutorService workers=new ThreadPoolExecutor(2,2,0,TimeUnit.SECONDS, + new ArrayBlockingQueue<>(16),r->{Thread t=new Thread(r,"station-emergency-stop");t.setDaemon(true);return t;},new ThreadPoolExecutor.AbortPolicy()); + + @Scheduled(initialDelayString="${cmvr.emergency-stop.poll-ms:2000}",fixedDelayString="${cmvr.emergency-stop.poll-ms:2000}") + public void scheduledCheck() { + TenantUtils.execute(1L,()->{ + Set owners=new HashSet<>(jdbc.queryForList(""" + SELECT DISTINCT owner_key FROM lab_resource_occupation + WHERE tenant_id=1 AND deleted=0 AND resource_type='ROBOT' + ORDER BY owner_key + """,String.class)); + warnings.keySet().retainAll(owners); + retryAfter.keySet().retainAll(owners); + for(String owner:owners) { + if(!supportedOwner(owner)||!inFlight.add(owner))continue; + try { workers.execute(()->{ + try { TenantUtils.execute(1L,()->checkOwner(owner)); } + catch(RuntimeException error) { warn(owner,error); } + finally { inFlight.remove(owner); } + }); } catch(RejectedExecutionException busy) { inFlight.remove(owner); } + } + }); + } + + // A bounded worker performs reads/cleanup; the shared Spring scheduler never waits for a stop RPC. + void checkOwner(String owner) { + if(!supportedOwner(owner))return; + List leaseIds=resources.leaseIds(owner); + if(leaseIds.isEmpty())return; + String source=latchedSource(owner,leaseIds); + if(source!=null&&System.nanoTime() parameters=new ArrayList<>();parameters.add(owner);parameters.addAll(leaseIds); + jdbc.update("UPDATE lab_resource_occupation SET status='STOP_PENDING' WHERE owner_key=? AND tenant_id=1 AND deleted=0 AND id IN (" + +String.join(",",Collections.nCopies(leaseIds.size(),"?"))+")",parameters.toArray()); + if(!resources.leaseIds(owner).equals(leaseIds))return; + retryAfter.put(owner,System.nanoTime()+TimeUnit.SECONDS.toNanos(10)); + if(owner.startsWith("TASK:")) { + scanTasks.emergencyStop(Long.valueOf(owner.substring(5)),leaseIds,source); + } else { + if(owner.startsWith("NATIVE:")) { + String inst=owner.substring(7); + if(tasks.getContext(inst)!=null||jdbc.queryForObject("SELECT COUNT(*) FROM te_task_inst WHERE id=? AND status IN ('1','3')",Integer.class,inst)>0) { + try { controls.stop(inst); } + catch(RuntimeException error) { warn(owner,error); } + } + if(resources.leaseIds(owner).isEmpty()){warnings.remove(owner);return;} + // A late RPC may still be in flight. Never release its lease until the old threads converge. + if(tasks.getContext(inst)!=null||!threads.getPendingNodes(inst).isEmpty())return; + if(jdbc.queryForObject("SELECT COUNT(*) FROM te_task_inst WHERE id=? AND status IN ('2','4')",Integer.class,inst)!=1)return; + } + if(!resources.leaseIds(owner).equals(leaseIds))return; + resources.clearOccupation(owner,"工位急停后自动收尾:已确认本次执行全部关联设备停止;"+source,leaseIds); + } + warnings.remove(owner); + } + + private String emergencySource(String owner) { + var robots=jdbc.queryForList("SELECT resource_id FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1 AND deleted=0 AND resource_type='ROBOT' ORDER BY resource_id",String.class,owner); + for(String robot:robots)for(var device:devices.selectByRobotId(robot,2,false)) { + if(!"1".equals(device.getEnabled()))continue; + ArmTeachingRequest request=new ArmTeachingRequest();request.setRobotId(robot);request.setDeviceId(device.getDeviceId());request.setTimeoutMs(2000L); + try { + JSONObject reply=teaching.execute(ArmTeachingOperation.GET_ROBOT_STATE,request); + JSONObject state=reply==null?null:reply.getJSONObject("state"); + if(reply!=null&&Boolean.TRUE.equals(reply.getBoolean("success"))&&state!=null&&Boolean.TRUE.equals(state.getBoolean("connected"))&&Boolean.TRUE.equals(state.getBoolean("emergencyStopped")))return robot+" / "+device.getDeviceId(); + } catch(RuntimeException error) { + // Unavailable/legacy endpoints are not evidence of emergency or of being stopped. + warn(owner,error); + } + } + return null; + } + + // Persist the latch so resetting the emergency button or restarting the platform cannot resume a stopped run. + private String latchedSource(String owner,List leaseIds) { + var events=jdbc.query("SELECT reason,resources_json FROM lab_resource_occupation_event WHERE owner_key=? AND action='EMERGENCY_STOP' AND tenant_id=1 ORDER BY id DESC LIMIT 1", + (rs,row)->Map.of("reason",rs.getString("reason"),"resources_json",rs.getString("resources_json")),owner); + if(events.isEmpty())return null; + var event=events.get(0); + try { + if(leaseIds.equals(JSON.parseArray(event.get("resources_json"),Long.class)))return event.get("reason").replaceFirst("^工位急停:",""); + } catch(RuntimeException invalid) { log.warn("急停记录无法匹配当前占用,重新查询设备状态: owner={}",owner); } + return null; + } + + private static boolean supportedOwner(String owner) { + return owner!=null&&(owner.startsWith("NATIVE:")&&owner.length()>7||owner.startsWith("MANUAL:")&&owner.length()>7||owner.matches("TASK:[0-9]+")); + } + private void warn(String owner,RuntimeException error) { + String message=Objects.toString(error.getMessage(),error.getClass().getSimpleName()); + if(!message.equals(warnings.put(owner,message)))log.warn("急停监测/停止确认未完成,占用保留: owner={}, reason={}",owner,message); + } + @PreDestroy void close() { workers.shutdownNow(); } +} diff --git a/am-backend/yudao-server/src/main/resources/application.yaml b/am-backend/yudao-server/src/main/resources/application.yaml index 6df613e..47ce598 100644 --- a/am-backend/yudao-server/src/main/resources/application.yaml +++ b/am-backend/yudao-server/src/main/resources/application.yaml @@ -7,7 +7,7 @@ cmvr: manager-id: ${AM_FREESCAN_ROTARY_BASE_MANAGER_ID:aima_motor} node-id: ${AM_FREESCAN_ROTARY_BASE_NODE_ID:1} joint-name: ${AM_FREESCAN_ROTARY_BASE_JOINT_NAME:motor_1} - rpc-timeout-ms: 45000 + rpc-timeout-ms: 120000 resource: robot-state: external-robot-ids: @@ -20,7 +20,7 @@ cmvr: robot-id: ${AM_FREESCAN_SCANNER_ROBOT_ID:am-freescan-station-001} device-id: ${AM_FREESCAN_SCANNER_DEVICE_ID:am-freescan-scanner-001} connect-timeout-ms: 5000 - request-timeout-ms: 15000 + request-timeout-ms: 120000 operation-timeout-ms: 120000 poll-interval-ms: 500 diff --git a/am-web/src/api/lab/dimension/index.ts b/am-web/src/api/lab/dimension/index.ts index c282529..9b9ae6f 100644 --- a/am-web/src/api/lab/dimension/index.ts +++ b/am-web/src/api/lab/dimension/index.ts @@ -1,5 +1,5 @@ import request from '@/config/axios' -import { getAccessToken, getTenantId, getVisitTenantId } from '@/utils/auth' +import { authenticatedFetch } from '@/config/axios/authenticatedFetch' import { readScannerBinary } from '@/views/lab/scan-task/scannerBinary.mjs' const base = '/lab/dimension' export const page = (params: any) => request.get({ url: base + '/page', params }) @@ -41,14 +41,7 @@ export const register = (data: FormData) => timeout: 180000 }) async function response(path: string, signal?: AbortSignal) { - const headers: Record = { - Authorization: `Bearer ${getAccessToken()}`, - 'tenant-id': String(getTenantId() || 1) - } - const visit = getVisitTenantId() - if (visit) headers['visit-tenant-id'] = String(visit) - const res = await fetch(`${import.meta.env.VITE_BASE_URL}/admin-api${base}${path}`, { - headers, + const res = await authenticatedFetch(`${import.meta.env.VITE_BASE_URL}/admin-api${base}${path}`, { signal }) if (!res.ok || res.headers.get('content-type')?.includes('application/json')) { diff --git a/am-web/src/api/lab/scan-task/agvView.ts b/am-web/src/api/lab/scan-task/agvView.ts new file mode 100644 index 0000000..13e606c --- /dev/null +++ b/am-web/src/api/lab/scan-task/agvView.ts @@ -0,0 +1,5 @@ +import request from '@/config/axios' +const base = '/lab/execution/agv-view' +export const agvTargets = (params: any, signal?: AbortSignal) => request.get({ url: base + '/targets', params, signal }) +export const agvState = (params: any, signal?: AbortSignal) => request.get({ url: base + '/state', params, signal }) +export const agvMap = (params: any, signal?: AbortSignal) => request.get({ url: base + '/map', params, signal, timeout: 15000 }) diff --git a/am-web/src/api/lab/scan-task/scannerView.ts b/am-web/src/api/lab/scan-task/scannerView.ts index fdaa64a..9602a0e 100644 --- a/am-web/src/api/lab/scan-task/scannerView.ts +++ b/am-web/src/api/lab/scan-task/scannerView.ts @@ -1,5 +1,5 @@ import request from '@/config/axios' -import { getAccessToken, getTenantId, getVisitTenantId } from '@/utils/auth' +import { authenticatedFetch } from '@/config/axios/authenticatedFetch' import { readScannerBinary } from '@/views/lab/scan-task/scannerBinary.mjs' import { consumeScannerMjpeg } from '@/cmvr/common/utils/scannerMjpeg.mjs' import { scannerPreviewTarget } from '@/views/lab/scan-task/scannerPreviewTarget.mjs' @@ -36,14 +36,8 @@ export const createScannerSnapshot = (executionId: string | number, commandKey: export const getScannerSnapshotCommand = (executionId: string | number, commandKey: string, signal?: AbortSignal) => request.get({ url: path + '/snapshot-command', params: { executionId, commandKey }, signal }) -function scannerHeaders() { - const headers: Record = { Authorization: `Bearer ${getAccessToken()}`, 'tenant-id': String(getTenantId() || 1) } - const visit = getVisitTenantId() - if (visit) headers['visit-tenant-id'] = String(visit) - return headers -} export async function getScannerAsset(executionId: string | number, fileId: string, signal: AbortSignal) { - const response = await fetch(`${import.meta.env.VITE_BASE_URL}/admin-api${path}/asset/${encodeURIComponent(fileId)}?executionId=${encodeURIComponent(executionId)}`, { headers: scannerHeaders(), signal }) + const response = await authenticatedFetch(`${import.meta.env.VITE_BASE_URL}/admin-api${path}/asset/${encodeURIComponent(fileId)}?executionId=${encodeURIComponent(executionId)}`, { signal }) if (!response.ok || response.headers.get('content-type')?.includes('application/json')) { const error = await response.json().catch(() => ({})) throw new Error(error.msg || '三维文件不可用;扫描服务重启后原下载编号可能失效') @@ -52,13 +46,7 @@ export async function getScannerAsset(executionId: string | number, fileId: stri } export async function getScannerExecutionImage(executionId: string | number, signal: AbortSignal) { - const headers: Record = { - Authorization: `Bearer ${getAccessToken()}`, - 'tenant-id': String(getTenantId() || 1) - } - const visit = getVisitTenantId() - if (visit) headers['visit-tenant-id'] = String(visit) - const response = await fetch(`${import.meta.env.VITE_BASE_URL}/admin-api${path}/image?executionId=${encodeURIComponent(executionId)}`, { headers, signal, cache: 'no-store' }) + const response = await authenticatedFetch(`${import.meta.env.VITE_BASE_URL}/admin-api${path}/image?executionId=${encodeURIComponent(executionId)}`, { signal, cache: 'no-store' }) if (!response.ok || !response.headers.get('content-type')?.startsWith('image/jpeg')) { const error = await response.json().catch(() => ({})) throw new Error(error.msg || '扫描画面暂不可用,正在重新核对状态') @@ -69,8 +57,8 @@ export async function getScannerExecutionImage(executionId: string | number, sig export async function streamScannerExecution(executionId: string | number, onFrame: (bytes: Uint8Array) => void, signal: AbortSignal, scope: 'execution' | 'fixture' = 'execution') { const target = scannerPreviewTarget(scope, executionId) const query = new URLSearchParams(Object.entries(target.params).map(([key,value]) => [key,String(value)])) - const response = await fetch(`${import.meta.env.VITE_BASE_URL}/admin-api${target.path}/${target.stream}?${query}`, { - headers: scannerHeaders(), signal, cache: 'no-store' + const response = await authenticatedFetch(`${import.meta.env.VITE_BASE_URL}/admin-api${target.path}/${target.stream}?${query}`, { + signal, cache: 'no-store' }) if (!response.ok || !response.headers.get('content-type')?.startsWith('multipart/x-mixed-replace') || !response.body) { const error = await response.json().catch(() => ({})) diff --git a/am-web/src/cmvr/aima/utils/actionQueue.js b/am-web/src/cmvr/aima/utils/actionQueue.js index 46e0286..96b516f 100644 --- a/am-web/src/cmvr/aima/utils/actionQueue.js +++ b/am-web/src/cmvr/aima/utils/actionQueue.js @@ -1,373 +1,2 @@ -import { actionQueueTotalTimeout } from '../../common/utils/actionQueueTimeout.mjs' -const deepClone = (value) => JSON.parse(JSON.stringify(value)) - -const ACTION_QUEUE_ACTION = 'SYSTEM_EXECUTE_ACTION_QUEUE' -const REFERENCE_KEYS = new Set(['quote', 'nameQuote']) - -const createKey = (prefix) => { - const random = globalThis.crypto?.randomUUID?.().replace(/-/g, '') - || `${Date.now()}${Math.random().toString(16).slice(2)}` - return `${prefix}_${random}` -} - -const paramsToObject = (node) => Object.fromEntries( - (node?.properties?.nodeParams || []).map((param) => [param.name, param.input]), -) - -const numberValue = (value, fallback = 0) => { - if (value === '' || value === null || value === undefined) return fallback - const result = Number(value) - return Number.isFinite(result) ? result : fallback -} - -const arrayValue = (value) => { - if (Array.isArray(value)) return deepClone(value) - if (typeof value !== 'string') return value - try { - const result = JSON.parse(value) - return Array.isArray(result) ? result : value - } catch { - return value - } -} - -const nodeToQueueStep = (node) => { - const action = node?.properties?.action - const params = paramsToObject(node) - const common = { - stepName: node?.properties?.name || '导入步骤', - sourceNode: deepClone(node), - } - if (node?.type === 'sleep' || String(action).toLowerCase() === 'sleep') { - const durationMs = numberValue(params.delayMs) - return { - ...common, - type: 'DELAY', - timeoutMs: 60000, - params: { durationMs }, - } - } - if (action === 'AGV_MOVE_TO_POINT') { - return { - ...common, - type: 'AGV_NAVIGATE_TO_POSE', - timeoutMs: 60000, - params: { - x: numberValue(params.x), - y: numberValue(params.y), - theta: numberValue(params.theta), - maxSpeed: numberValue(params.maxSpeed, 0.5), - blockedTimeoutMs: numberValue(params.blockedTimeoutMs, 60000), - }, - } - } - if (action === 'AGV_MOVE_TO_STATION') { - return { - ...common, - type: 'AGV_NAVIGATE_TO_STATION', - timeoutMs: 60000, - params: { - stationId: params.stationId ?? '', - maxSpeed: numberValue(params.maxSpeed, 0.5), - blockedTimeoutMs: numberValue(params.blockedTimeoutMs, 60000), - }, - } - } - if (action === 'ARM_MOVE_TO_POINT') { - return { - ...common, - type: 'ARM_MOVE_L', - timeoutMs: 60000, - params: { - x: numberValue(params.x), - y: numberValue(params.y), - z: numberValue(params.z), - rx: numberValue(params.rx), - ry: numberValue(params.ry), - rz: numberValue(params.rz), - frame: params.frame || 'BASE', - velocity: numberValue(params.velocity, 2.1), - acceleration: numberValue(params.acceleration, 2.2), - }, - } - } - if (action === 'ARM_MOVE_TO_J') { - return { - ...common, - type: 'ARM_MOVE_J', - timeoutMs: 60000, - params: { - positions: arrayValue(params.target), - velocity: numberValue(params.velocity, 0.1), - acceleration: numberValue(params.acceleration, 0.2), - }, - } - } - return null -} - -const validateConvertibleNodeParams = (node) => { - const action = node?.properties?.action - const params = paramsToObject(node) - const requiredByAction = { - AGV_MOVE_TO_POINT: ['x', 'y', 'theta'], - AGV_MOVE_TO_STATION: ['stationId'], - ARM_MOVE_TO_POINT: ['x', 'y', 'z', 'rx', 'ry', 'rz'], - ARM_MOVE_TO_J: ['target'], - } - const missing = (requiredByAction[action] || []).find((name) => ( - params[name] === '' || params[name] === null || params[name] === undefined - )) - if (missing) return `节点[${node.properties?.name || node.id}]的参数 ${missing} 尚未配置` - if (action === 'ARM_MOVE_TO_J') { - const positions = arrayValue(params.target) - if (!Array.isArray(positions) || positions.length === 0) return '机械臂关节位置必须是非空 JSON 数组' - } - if ((node?.type === 'sleep' || String(action).toLowerCase() === 'sleep') - && numberValue(params.delayMs) < 0) return '睡眠时长不能小于 0' - return '' -} - -const hasReference = (value, referencedNodeId, parentKey = '') => { - if (Array.isArray(value)) { - if (REFERENCE_KEYS.has(parentKey) && value[0] === referencedNodeId) return true - return value.some((item) => hasReference(item, referencedNodeId)) - } - if (!value || typeof value !== 'object') return false - return Object.entries(value).some(([key, item]) => hasReference(item, referencedNodeId, key)) -} - -const hasDynamicInput = (node) => (node?.properties?.nodeParams || []).some((param) => ( - param?.type === 'quote' - || (Array.isArray(param?.quote) && param.quote.length > 0) -)) - -const getNodeParam = (node, name, fallback) => ( - node.properties?.nodeParams?.find((param) => param.name === name)?.input ?? fallback -) - -const setNodeParam = (node, name, input, defaults = {}) => { - node.properties ||= {} - node.properties.nodeParams ||= [] - const param = node.properties.nodeParams.find((item) => item.name === name) - if (param) param.input = input - else node.properties.nodeParams.push({ name, type: 'input', input, ...defaults }) -} - -const queueSteps = (queueNode) => { - const value = getNodeParam(queueNode, 'steps', []) - return Array.isArray(value) ? deepClone(value) : [] -} - -const edgeExists = (edges, sourceNodeId, targetNodeId) => edges.some((edge) => ( - edge.sourceNodeId === sourceNodeId && edge.targetNodeId === targetNodeId -)) - -const createEdge = (sourceNodeId, targetNodeId, sourceAnchorId, targetAnchorId) => ({ - id: createKey('edge'), - type: 'bezier', - sourceNodeId, - targetNodeId, - sourceAnchorId: sourceAnchorId || `${sourceNodeId}_1`, - targetAnchorId: targetAnchorId || `${targetNodeId}_3`, -}) - -const normalizeQueueStepIds = (steps) => steps.map((step, index) => ({ - ...step, - stepId: `step_${index + 1}`, -})) - -const updateQueueDefinition = (queueNode, steps) => { - const normalizedSteps = normalizeQueueStepIds(steps) - setNodeParam(queueNode, 'steps', normalizedSteps, { required: true }) - setNodeParam( - queueNode, - 'totalTimeoutMs', - actionQueueTotalTimeout(normalizedSteps), - { componentType: 'number', required: true }, - ) - const bindings = normalizedSteps.filter((step) => step.deviceBindingKey && step.deviceSlotKey).map((step) => ({ - parameterName: step.deviceBindingKey, - slotKey: step.deviceSlotKey, - })) - queueNode.properties.executionTarget = { - ...(queueNode.properties.executionTarget || {}), - dispatchPolicy: 'ONE', - deviceBindings: bindings, - } -} - -export const isNodeConvertibleToActionQueue = (node) => Boolean(nodeToQueueStep(node)) - -/** - * Converts one workflow node into an edge action-queue step and rewrites its former - * linear position out of the graph. The source definition is retained for extraction. - */ -export const appendNodeToActionQueue = (sourceGraph, nodeId, queueId) => { - const graph = deepClone(sourceGraph || { nodes: [], edges: [] }) - const node = graph.nodes.find((item) => item.id === nodeId) - const queueNode = graph.nodes.find((item) => item.id === queueId) - if (!node || !queueNode) return { ok: false, message: '未找到要移动的节点或动作队列' } - if (node.id === queueNode.id) return { ok: false, message: '动作队列不能放入自身' } - if (queueNode.properties?.action !== ACTION_QUEUE_ACTION) return { ok: false, message: '目标节点不是动作队列' } - const step = nodeToQueueStep(node) - if (!step) return { ok: false, message: `节点[${node.properties?.name || node.id}]暂不支持放入动作队列` } - const paramError = validateConvertibleNodeParams(node) - if (paramError) return { ok: false, message: paramError } - if (node.properties?.parentId !== queueNode.properties?.parentId) { - return { ok: false, message: '节点和动作队列必须位于同一个流程或循环体中' } - } - if (hasDynamicInput(node)) return { ok: false, message: '引用其他节点参数的节点暂不能放入动作队列' } - const referencedBy = graph.nodes.find((item) => item.id !== nodeId && hasReference(item.properties, nodeId)) - if (referencedBy) { - return { ok: false, message: `节点[${referencedBy.properties?.name || referencedBy.id}]正在引用该节点的输出` } - } - - const incoming = graph.edges.filter((edge) => edge.targetNodeId === nodeId) - const outgoing = graph.edges.filter((edge) => edge.sourceNodeId === nodeId) - if (incoming.length > 1 || outgoing.length > 1) { - return { ok: false, message: '存在分支连线的节点不能放入动作队列' } - } - if (incoming.length === 1 - && outgoing.length === 1 - && incoming[0].sourceNodeId === outgoing[0].targetNodeId) { - return { ok: false, message: '节点处于回路中,不能放入动作队列' } - } - - const nodeRoleKey = node.properties?.executionTarget?.roleKey - const queueRoleKey = queueNode.properties?.executionTarget?.roleKey - if (nodeRoleKey && queueRoleKey && nodeRoleKey !== queueRoleKey) { - return { ok: false, message: '节点与动作队列使用的机器人角色不同' } - } - if (nodeRoleKey && !queueRoleKey) queueNode.properties.executionTarget = { roleKey: nodeRoleKey } - - const deviceSlotKey = node.properties?.executionTarget?.deviceSlotKey - if (deviceSlotKey) { - step.deviceBindingKey = createKey('queue_device') - step.deviceSlotKey = deviceSlotKey - } - step.stepId = `step_${queueSteps(queueNode).length + 1}` - const steps = [...queueSteps(queueNode), step] - updateQueueDefinition(queueNode, steps) - - graph.nodes = graph.nodes.filter((item) => item.id !== nodeId) - graph.nodes.forEach((item) => { - if (Array.isArray(item.children)) item.children = item.children.filter((childId) => childId !== nodeId) - }) - graph.edges = graph.edges.filter((edge) => edge.sourceNodeId !== nodeId && edge.targetNodeId !== nodeId) - - const predecessorId = incoming[0]?.sourceNodeId - const successorId = outgoing[0]?.targetNodeId - if (predecessorId && successorId && predecessorId !== successorId - && !edgeExists(graph.edges, predecessorId, successorId)) { - graph.edges.push(createEdge( - predecessorId, - successorId, - incoming[0].sourceAnchorId, - outgoing[0].targetAnchorId, - )) - } - return { ok: true, graph, queueId, step } -} - -const remapNodeAnchors = (node, previousId, nextId) => { - const properties = node.properties || (node.properties = {}) - if (!Array.isArray(properties.anchor)) return - properties.anchor = properties.anchor.map((anchor) => ({ - ...anchor, - id: String(anchor.id || '').startsWith(`${previousId}_`) - ? `${nextId}${String(anchor.id).slice(previousId.length)}` - : anchor.id, - })) -} - -/** Restores an imported queue step as a workflow node. */ -export const extractActionQueueStep = (sourceGraph, queueId, stepIndex, placement = 'detached') => { - const graph = deepClone(sourceGraph || { nodes: [], edges: [] }) - const queueNode = graph.nodes.find((item) => item.id === queueId) - if (!queueNode) return { ok: false, message: '动作队列不存在' } - const steps = queueSteps(queueNode) - const step = steps[stepIndex] - if (!step) return { ok: false, message: '要移出的步骤不存在' } - if (!step.sourceNode) return { ok: false, message: '该步骤不是由工作流节点移入,无法还原为原节点' } - - const node = deepClone(step.sourceNode) - const previousId = node.id - node.id = createKey('node') - remapNodeAnchors(node, previousId, node.id) - delete node.children - node.properties ||= {} - node.properties.parentId = queueNode.properties?.parentId - if (!node.properties.parentId) delete node.properties.parentId - const horizontalOffset = placement === 'before' ? -460 : 460 - node.x = numberValue(queueNode.x) + (placement === 'detached' ? 0 : horizontalOffset) - node.y = numberValue(queueNode.y) + (placement === 'detached' ? 260 : 0) - - const incoming = graph.edges.filter((edge) => edge.targetNodeId === queueId) - const outgoing = graph.edges.filter((edge) => edge.sourceNodeId === queueId) - if ((placement === 'before' && incoming.length > 1) || (placement === 'after' && outgoing.length > 1)) { - return { ok: false, message: '动作队列存在多条相关连线,请选择“仅移出,不连线”' } - } - - graph.nodes.push(node) - if (steps.length === 1) { - graph.nodes = graph.nodes.filter((item) => item.id !== queueId) - graph.edges.forEach((edge) => { - if (edge.sourceNodeId === queueId) { - edge.sourceNodeId = node.id - edge.sourceAnchorId = `${node.id}_1` - } - if (edge.targetNodeId === queueId) { - edge.targetNodeId = node.id - edge.targetAnchorId = `${node.id}_3` - } - }) - return { ok: true, graph, node, removedQueue: true } - } - - steps.splice(stepIndex, 1) - updateQueueDefinition(queueNode, steps) - if (placement === 'before') { - graph.edges = graph.edges.filter((edge) => edge.targetNodeId !== queueId) - const previous = incoming[0] - if (previous) graph.edges.push(createEdge(previous.sourceNodeId, node.id, previous.sourceAnchorId, `${node.id}_3`)) - graph.edges.push(createEdge(node.id, queueId, `${node.id}_1`, `${queueId}_3`)) - } else if (placement === 'after') { - graph.edges = graph.edges.filter((edge) => edge.sourceNodeId !== queueId) - const next = outgoing[0] - graph.edges.push(createEdge(queueId, node.id, `${queueId}_1`, `${node.id}_3`)) - if (next) graph.edges.push(createEdge(node.id, next.targetNodeId, `${node.id}_1`, next.targetAnchorId)) - } - return { ok: true, graph, node, removedQueue: false } -} - -export const getActionQueueStepName = (step, index) => { - const name = String(step?.stepName || '').trim() - return name || `步骤 ${index + 1}` -} - -export const moveActionQueueStep = (steps, index, offset) => { - const targetIndex = index + offset - if (!Array.isArray(steps) || index < 0 || targetIndex < 0 || targetIndex >= steps.length) return false - const [step] = steps.splice(index, 1) - steps.splice(targetIndex, 0, step) - return true -} - -export const copyActionQueueStep = (step, overrides = {}) => { - const copied = deepClone(step) - const originalName = String(step?.stepName || '').trim() - return { - ...copied, - ...overrides, - stepName: `${originalName || '未命名步骤'} - 副本`, - } -} - -export const toActionQueueExecutionSteps = (steps) => (Array.isArray(steps) ? steps : []).map((step, index) => ({ - stepId: `step_${index + 1}`, - type: step.type, - ...(step.deviceId ? { deviceId: step.deviceId } : {}), - timeoutMs: Number(step.timeoutMs ?? 60000), - params: deepClone(step.params || {}), -})) +// Share queue conversion and coordinate validation with the common workflow. +export * from '../../common/utils/actionQueue.js' diff --git a/am-web/src/cmvr/common/api/device/armTeaching.js b/am-web/src/cmvr/common/api/device/armTeaching.js index a59d5b3..2a6c1f2 100644 --- a/am-web/src/cmvr/common/api/device/armTeaching.js +++ b/am-web/src/cmvr/common/api/device/armTeaching.js @@ -22,7 +22,7 @@ export function armTeachingRequest(operation, data, { quiet = false } = {}) { url: `${base}/${operation}`, method: 'get', params: data, - timeout: ARM_REQUEST_TIMEOUT_MS, + timeout: armRequestTimeout(operation, data), silentError: quiet }) : request({ diff --git a/am-web/src/cmvr/common/api/flow/flow.js b/am-web/src/cmvr/common/api/flow/flow.js index e06fc14..5d5dee5 100644 --- a/am-web/src/cmvr/common/api/flow/flow.js +++ b/am-web/src/cmvr/common/api/flow/flow.js @@ -1,5 +1,6 @@ import request from '@/cmvr/common/utils/request' import { actionQueueRequestTimeout } from '@/cmvr/common/utils/actionQueueTimeout.mjs' +import { ARM_REQUEST_TIMEOUT_MS, armRequestTimeout } from '@/cmvr/common/utils/armTimeouts.mjs' // 发布流程 export function flowDeploy(data) { @@ -50,7 +51,7 @@ export function flowAction(data) { return request({ url: '/flow/action', method: 'post', - timeout: data.action === 'SYSTEM_EXECUTE_ACTION_QUEUE' ? actionQueueRequestTimeout(data.payload?.steps || []) : String(data.action || '').startsWith('SCANNER_') ? Math.min(3600000, Number(data.payload?.timeoutMs) || 120000) + 10000 : 60000, + timeout: data.action === 'SYSTEM_EXECUTE_ACTION_QUEUE' ? actionQueueRequestTimeout(data.payload?.steps || []) : String(data.action || '').startsWith('ARM_') ? armRequestTimeout(data.action,data.payload) : /^(SCANNER_|MOTOR_|AGV_)/.test(String(data.action || '')) ? Math.min(3600000, Number(data.payload?.timeoutMs ?? data.payload?.waitTimeoutMs ?? data.payload?.blockedTimeoutMs) || 120000) + 10000 : 60000, data: data }) } @@ -106,7 +107,7 @@ export function submitAudioCorrection(nodeInstId, data) { export function getArmStatus(params) { return request({ url: '/api/arm/getPose', - timeout: 30000, + timeout: ARM_REQUEST_TIMEOUT_MS, method: 'get', params: params }) @@ -131,7 +132,7 @@ export function getAgvStations(params) { export function getArmJointState(params) { return request({ url: '/api/arm/getJointState', - timeout: 30000, + timeout: ARM_REQUEST_TIMEOUT_MS, method: 'get', params: params }) diff --git a/am-web/src/cmvr/common/api/scanner/index.js b/am-web/src/cmvr/common/api/scanner/index.js index 092aba0..ed14804 100644 --- a/am-web/src/cmvr/common/api/scanner/index.js +++ b/am-web/src/cmvr/common/api/scanner/index.js @@ -1,5 +1,5 @@ import request, { cmvrApiBase } from '@/cmvr/request' -import { getAccessToken, getTenantId } from '@/utils/auth' +import { authenticatedFetch } from '@/config/axios/authenticatedFetch' import { SCANNER_OPERATIONS } from '../../utils/scannerOperations.mjs' const base = '/scanner' @@ -31,12 +31,12 @@ export function submitScanner(key, requestJson, commandKey) { headers: { 'Content-Type': 'application/json', 'X-Scanner-Command-Key': commandKey }, }) } -// Upload is synchronous, sends raw bytes once, and does not issue an SDK import. +// Synchronous raw upload. Only platform authentication rejection can resend; +// ambiguous transport/SDK failures must never upload the file again. export async function uploadScannerFramework(file) { - const response = await fetch(cmvrApiBase + base + '/framework/files', { + const response = await authenticatedFetch(cmvrApiBase + base + '/framework/files', { method: 'POST', body: file, - headers: { Authorization: `Bearer ${getAccessToken()}`, 'tenant-id': String(getTenantId() || 1), - 'Content-Type': 'application/octet-stream', 'X-File-Name': encodeURIComponent(file.name) }, + headers: { 'Content-Type': 'application/octet-stream', 'X-File-Name': encodeURIComponent(file.name) }, }) const result = await response.json().catch(() => ({})) if (!response.ok || ![0, 200].includes(result.code)) throw new Error(result.msg || `框架上传未确认(${response.status}),请核对服务,勿自动重传`) @@ -45,8 +45,8 @@ export async function uploadScannerFramework(file) { export async function scannerBinary(key, id, signal) { const op = operation(key) if (!['FILE', 'PREVIEW_IMAGE', 'PREVIEW_STREAM'].includes(key)) throw new Error('此操作不返回文件或图像') - const response = await fetch(cmvrApiBase + base + op.path.replace('{fileId}', encodeURIComponent(id || '')), { - headers: { Authorization: `Bearer ${getAccessToken()}`, 'tenant-id': String(getTenantId() || 1) }, signal, + const response = await authenticatedFetch(cmvrApiBase + base + op.path.replace('{fileId}', encodeURIComponent(id || '')), { + signal, }) if (!response.ok || response.headers.get('content-type')?.includes('application/json')) { const error = await response.json().catch(() => ({})) diff --git a/am-web/src/cmvr/common/components/Editor/index.vue b/am-web/src/cmvr/common/components/Editor/index.vue index 6aa2a73..2a1e94c 100644 --- a/am-web/src/cmvr/common/components/Editor/index.vue +++ b/am-web/src/cmvr/common/components/Editor/index.vue @@ -7,7 +7,7 @@ :on-error="handleUploadError" name="file" :show-file-list="false" - :headers="headers" + :http-request="cmvrUploadRequest" class="editor-img-uploader" v-if="type == 'url'" > @@ -27,19 +27,14 @@ diff --git a/am-web/src/cmvr/common/components/ExcelImportDialog/index.vue b/am-web/src/cmvr/common/components/ExcelImportDialog/index.vue index 549c0a7..426ce07 100644 --- a/am-web/src/cmvr/common/components/ExcelImportDialog/index.vue +++ b/am-web/src/cmvr/common/components/ExcelImportDialog/index.vue @@ -1,6 +1,6 @@