feat: consolidate device workflows, recovery and durable scanner archives
This commit is contained in:
parent
2ee35c4739
commit
71bd55919d
@ -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`,不是测试数据,不清理。
|
||||
|
||||
@ -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` 配置继续保留。
|
||||
|
||||
@ -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());
|
||||
|
||||
@ -36,7 +36,12 @@ public final class ArmCoordinateStepParameters {
|
||||
if(params!=null)for(int i=0;i<params.size();i++){
|
||||
var field=params.getJSONObject(i);var name=field.getString("name");
|
||||
if(name==null||!names.add(name))throw new GlobalException("目标位姿参数为空或重复");
|
||||
if(!"input".equals(field.getString("type")))throw new GlobalException("目标位姿请填写数值并从下拉框选择坐标系,不支持引用");
|
||||
if("quote".equals(field.getString("type"))&&"velocityMm".equals(name)) {
|
||||
var path=field.getJSONArray("quote");
|
||||
if(path==null||path.size()<3||path.stream().anyMatch(v->!(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);
|
||||
|
||||
@ -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;}
|
||||
}
|
||||
|
||||
@ -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("..")
|
||||
|
||||
@ -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());
|
||||
|
||||
@ -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) {
|
||||
|
||||
@ -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;}
|
||||
}
|
||||
@ -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<Integer> 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); } }
|
||||
}
|
||||
@ -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); }
|
||||
}
|
||||
|
||||
@ -68,7 +68,10 @@ public class GrpcServiceManager {
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T getGrpcClient(String robotId, Class<T> 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<T> factory = (GrpcClientFactory<T>) 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);
|
||||
}
|
||||
|
||||
|
||||
@ -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;
|
||||
}
|
||||
|
||||
@ -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));
|
||||
}
|
||||
}
|
||||
@ -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<String> COORDINATE_FIELDS = Set.of("name", "expectedRevision");
|
||||
private static final List<String> 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<EdgeActionQueueVO.Step> steps) {
|
||||
ActionQueueTimeouts.total(steps);
|
||||
Map<String, JSONObject> 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;
|
||||
}
|
||||
}
|
||||
@ -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<EdgeActionQueueVO.Step> 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;
|
||||
}
|
||||
}
|
||||
|
||||
@ -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();
|
||||
}
|
||||
|
||||
@ -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<String,Entry> states=Collections.synchronizedMap(new LinkedHashMap<>(32,.75f,true){protected boolean removeEldestEntry(Map.Entry<String,Entry> e){return size()>64;}});
|
||||
private final Map<String,Entry> maps=Collections.synchronizedMap(new LinkedHashMap<>(16,.75f,true){protected boolean removeEldestEntry(Map.Entry<String,Entry> e){return size()>16;}});
|
||||
private final Map<String,Entry> stations=Collections.synchronizedMap(new LinkedHashMap<>(32,.75f,true){protected boolean removeEldestEntry(Map.Entry<String,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<Agv.AgvUnifiedMapUpdate>();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<Agv.AgvUnifiedMapUpdate> 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<parts.size();i++){
|
||||
var u=parts.get(i);var g=u.getMap2D();
|
||||
if(u.getChunkIndex()!=i||(u.getChunkCount()!=0&&u.getChunkCount()!=parts.size())||!u.getMapId().equals(first.getMapId())||!u.getSessionId().equals(first.getSessionId())||g.getWidth()!=width||g.getHeight()!=height||g.getResolution()!=grid.getResolution()||!g.getOrigin().equals(o)||!g.getFrameId().equals(grid.getFrameId()))throw new GlobalException("地图分片不连续或坐标系不一致");
|
||||
for(int cell:g.getDataList()){if(offset>=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);
|
||||
}
|
||||
}
|
||||
@ -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运行时状态
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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<String> 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<Agv.AgvStation> 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));
|
||||
}
|
||||
|
||||
@ -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(
|
||||
|
||||
@ -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<String, com.alibaba.fastjson2.JSONObject> 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()) {
|
||||
|
||||
@ -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) {
|
||||
|
||||
@ -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<String> virtualRobotIds = new ArrayList<>();
|
||||
private List<String> externalRobotIds = new ArrayList<>();
|
||||
public List<String> getExternalRobotIds() {return externalRobotIds;}
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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()<deadline){
|
||||
try{Thread.sleep(100);}catch(InterruptedException e){Thread.currentThread().interrupt();throw new GlobalException("任务已取消,结束等待设备重连");}
|
||||
var latest=deviceMapper.selectByIdentity(robotId,deviceId);
|
||||
if(latest.size()!=1)throw new GlobalException("设备身份在等待重连期间发生变化");device=latest.get(0);
|
||||
if(!java.util.Objects.equals(device.getDeviceKind(),actualKind)||!"1".equals(device.getEnabled()))throw new GlobalException("设备配置在等待重连期间发生变化");
|
||||
}
|
||||
if(!"1".equals(device.getOnlineStatus()))throw new GlobalException("设备["+deviceId+"]的连接尚未恢复(终端上报中断),未下发本次动作");
|
||||
log.info("设备终端已重连,继续校验设备状态,robotId={}, deviceId={}",robotId,deviceId);
|
||||
}
|
||||
boolean recoverableMicrophoneConflict = Integer.valueOf(MICROPHONE_DEVICE_KIND).equals(actualKind)
|
||||
&& device.getErrorMessage() != null
|
||||
|
||||
@ -20,6 +20,11 @@ public class ResourceRobotEndpointResolver implements RobotEndpointResolver {
|
||||
|
||||
@Override
|
||||
public RobotEndpoint resolve(String robotId) {
|
||||
return resolve(robotId,false);
|
||||
}
|
||||
@Override
|
||||
public RobotEndpoint resolveForRecovery(String robotId) { return resolve(robotId,true); }
|
||||
private RobotEndpoint resolve(String robotId,boolean recovery) {
|
||||
String normalized = StringUtils.trimToNull(robotId);
|
||||
if (normalized == null) {
|
||||
throw new GlobalException("机器人ID不能为空");
|
||||
@ -34,14 +39,22 @@ public class ResourceRobotEndpointResolver implements RobotEndpointResolver {
|
||||
if ("1".equals(robot.getArchivedStatus())) {
|
||||
throw new GlobalException("机器人已归档:" + normalized);
|
||||
}
|
||||
if (!"1".equals(robot.getConnectStatus())) {
|
||||
throw new GlobalException("机器人当前离线:" + normalized);
|
||||
if (!recovery && !"1".equals(robot.getConnectStatus())) {
|
||||
long grace=stateProperties.getReconnectGraceMs();
|
||||
boolean recent=robot.getLastHeartbeatTime()!=null&&System.currentTimeMillis()-robot.getLastHeartbeatTime().getTime()<=stateProperties.getHeartbeatTimeoutMs();
|
||||
long deadline=System.nanoTime()+java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(recent?grace:0);
|
||||
while(!"1".equals(robot.getConnectStatus())&&System.nanoTime()<deadline){
|
||||
try{Thread.sleep(100);}catch(InterruptedException e){Thread.currentThread().interrupt();throw new GlobalException("任务已取消,结束等待机器人重连");}
|
||||
robot=robotMapper.selectByRobotIdentity(normalized);
|
||||
if(robot==null||"1".equals(robot.getArchivedStatus()))throw new GlobalException("机器人身份或归档状态已变化");
|
||||
}
|
||||
if(!"1".equals(robot.getConnectStatus()))throw new GlobalException("机器人终端连接尚未恢复,未下发本次动作:"+normalized);
|
||||
}
|
||||
Date cutoff = stateProperties.heartbeatCutoff(new Date());
|
||||
if (robot.getLastHeartbeatTime() == null || robot.getLastHeartbeatTime().before(cutoff)) {
|
||||
// throw new GlobalException("机器人QUIC心跳已超时:" + normalized);
|
||||
}
|
||||
if (StringUtils.isBlank(robot.getIpAddress()) || robot.getPort() == null) {
|
||||
if (StringUtils.isBlank(robot.getIpAddress()) || robot.getPort() == null || robot.getPort()<1 || robot.getPort()>65535) {
|
||||
throw new GlobalException("机器人尚未上报gRPC地址:" + normalized);
|
||||
}
|
||||
return new RobotEndpoint(robot.getIpAddress(), robot.getPort().intValue());
|
||||
|
||||
@ -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();}
|
||||
}
|
||||
|
||||
@ -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")<seconds*1000)throw new GlobalException("节点超时不得小于回零服务端等待时间");
|
||||
}
|
||||
if(action==ActionEnum.MOTOR_SET_MODE) {
|
||||
double mode=number(input,"mode");
|
||||
@ -27,8 +27,8 @@ public final class RotaryBaseParameters {
|
||||
}
|
||||
if(action==ActionEnum.MOTOR_MOVE||action==ActionEnum.MOTOR_VELOCITY) {
|
||||
double factor=factor(input);
|
||||
if(action==ActionEnum.MOTOR_MOVE&&Math.abs(number(input,"targetPosition")*factor)>2*Math.PI+1e-12)
|
||||
throw new GlobalException("旋转底座绝对位置须在±360°(±2π rad)内");
|
||||
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)");
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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";
|
||||
|
||||
@ -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<String,ScannerHttpClient.Binary> 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<String,ScannerHttpClient.Binary> 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<String,List<String>> 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);}
|
||||
}
|
||||
@ -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);}
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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(); }
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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()){
|
||||
|
||||
@ -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<com.cmvr.edge.client.model.system.EdgeActionQueueVO.Step>();
|
||||
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);
|
||||
|
||||
@ -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);}
|
||||
|
||||
}
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -45,9 +45,12 @@ public class EdgeActionQueueOperateService implements EdgeOperateService {
|
||||
List<EdgeActionQueueVO.Step> 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();
|
||||
|
||||
@ -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());
|
||||
}
|
||||
|
||||
@ -119,7 +119,8 @@ public class EdgeArmController {
|
||||
moveJVO.getAcceleration(),
|
||||
moveJVO.getBlendRadius(),
|
||||
moveJVO.getJointVelocityLimits(),
|
||||
moveJVO.getAsynchronous()
|
||||
moveJVO.getAsynchronous(),
|
||||
moveJVO.getTimeoutMs()
|
||||
);
|
||||
return AjaxResult.ok();
|
||||
}
|
||||
|
||||
@ -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; }
|
||||
}
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -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() {
|
||||
|
||||
@ -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")));
|
||||
}
|
||||
}
|
||||
|
||||
@ -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<SystemCommand.ActionQueueCommand.Request> captured=new AtomicReference<>();AtomicReference<Deadline> 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 <R,S> ServerCall.Listener<R> interceptCall(ServerCall<R,S> call,Metadata headers,ServerCallHandler<R,S> 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;}
|
||||
|
||||
@ -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());
|
||||
|
||||
@ -28,6 +28,7 @@ public class ScannerFrameworkReferenceTest {
|
||||
AtomicReference<byte[]> 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<String> 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());
|
||||
|
||||
@ -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<JSONArray> targets(@RequestParam(required=false) Long executionId,@RequestParam(required=false) List<String> robotIds){return CommonResult.success(views.targets(executionId,robotIds==null?List.of():robotIds));}
|
||||
@GetMapping("/state") public CommonResult<JSONObject> 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<JSONObject> 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());}
|
||||
}
|
||||
@ -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<String,Trace> traces=new ConcurrentHashMap<>();
|
||||
private final Set<String> 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<String> 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<String>();
|
||||
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<String> robots(LabExecutionDO e){
|
||||
var p=e.getRunParams()==null?new JSONObject():new JSONObject(e.getRunParams());var result=new LinkedHashSet<String>();var assignments=p.getJSONArray("_cmvrRuntimeAssignments");
|
||||
if(assignments!=null)for(int i=0;i<assignments.size();i++){var members=assignments.getJSONObject(i).getJSONArray("members");if(members!=null)for(int j=0;j<members.size();j++){String robot=members.getJSONObject(j).getString("robotId");if(robot!=null&&!robot.isBlank())result.add(robot);}}
|
||||
String robot=p.getString("_cmvrRobotId");if(robot!=null&&!robot.isBlank())result.add(robot);return new ArrayList<>(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<LabExecutionDO>().in(LabExecutionDO::getStatus,"RUNNING","PAUSED").orderByDesc(LabExecutionDO::getId).last("LIMIT 64"));var alive=new HashSet<String>();
|
||||
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()<trace.nextStateAt)return;
|
||||
try{
|
||||
var current=executions.selectById(execution.getId());if(current==null||!active(current))return;
|
||||
var state=views.state(robot,device);current=executions.selectById(execution.getId());if(current==null||!active(current))return;
|
||||
String oldMap=trace.data.getJSONObject("state")==null?null:trace.data.getJSONObject("state").getString("currentMap"),map=state.getString("currentMap");
|
||||
if(!Objects.equals(oldMap,map)){trace.segment++;trace.data.remove("map");trace.data.remove("stations");trace.mapChecked=0;}
|
||||
trace.data.put("state",state);trace.data.remove("message");trace.failures=0;trace.nextStateAt=0;var pose=state.getJSONObject("pose");
|
||||
if(state.getBooleanValue("connected")&&state.getBooleanValue("localized")&&validPose(pose)){
|
||||
var points=trace.data.getJSONArray("points");var previous=points.isEmpty()?null:points.getJSONObject(points.size()-1);
|
||||
if(previous==null||previous.getIntValue("segment")!=trace.segment||Math.hypot(pose.getDoubleValue("x")-previous.getDoubleValue("x"),pose.getDoubleValue("y")-previous.getDoubleValue("y"))>=.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;i<points.size();i++)if(i%2==0||i==points.size()-1||i>0&&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<<Math.min(4,trace.failures++));}
|
||||
if(System.currentTimeMillis()-trace.saved>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);}}
|
||||
}
|
||||
@ -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<Long> expectedLeaseIds,String source);
|
||||
void confirmStop(Long taskId,String reason);
|
||||
void pause(Long taskId);
|
||||
void resume(Long taskId);
|
||||
|
||||
@ -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<Long> 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<LabExecutionDO> active=executions.selectActiveByTaskId(taskId);
|
||||
if(active.isEmpty()&&!Boolean.TRUE.equals(c.getStopPending())&&c.getResourcesAcquiredAt()==null) {
|
||||
|
||||
@ -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<Long> 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<String> 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<Long> 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("资源类型无效");
|
||||
|
||||
@ -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<String> inFlight=ConcurrentHashMap.newKeySet();
|
||||
private final Map<String,String> warnings=new ConcurrentHashMap<>();
|
||||
private final Map<String,Long> 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<String> 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<Long> leaseIds=resources.leaseIds(owner);
|
||||
if(leaseIds.isEmpty())return;
|
||||
String source=latchedSource(owner,leaseIds);
|
||||
if(source!=null&&System.nanoTime()<retryAfter.getOrDefault(owner,0L))return;
|
||||
if(source==null) {
|
||||
source=emergencySource(owner);
|
||||
if(source==null||!resources.leaseIds(owner).equals(leaseIds))return;
|
||||
jdbc.update("""
|
||||
INSERT INTO lab_resource_occupation_event(id,owner_key,action,reason,resources_json,tenant_id)
|
||||
VALUES(?,?,'EMERGENCY_STOP',?,?,1)
|
||||
""",IdUtil.getSnowflakeNextId(),owner,"工位急停:"+source,JSON.toJSONString(leaseIds));
|
||||
log.warn("检测到工位急停,终止关联执行并逐一确认停止: owner={}, source={}",owner,source);
|
||||
}
|
||||
if(!resources.leaseIds(owner).equals(leaseIds))return;
|
||||
List<Object> 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<Long> 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(); }
|
||||
}
|
||||
@ -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
|
||||
|
||||
|
||||
@ -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<any>({ 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<string, string> = {
|
||||
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')) {
|
||||
|
||||
5
am-web/src/api/lab/scan-task/agvView.ts
Normal file
5
am-web/src/api/lab/scan-task/agvView.ts
Normal file
@ -0,0 +1,5 @@
|
||||
import request from '@/config/axios'
|
||||
const base = '/lab/execution/agv-view'
|
||||
export const agvTargets = (params: any, signal?: AbortSignal) => request.get<any[]>({ url: base + '/targets', params, signal })
|
||||
export const agvState = (params: any, signal?: AbortSignal) => request.get<any>({ url: base + '/state', params, signal })
|
||||
export const agvMap = (params: any, signal?: AbortSignal) => request.get<any>({ url: base + '/map', params, signal, timeout: 15000 })
|
||||
@ -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<ScannerSnapshotCommand>({ url: path + '/snapshot-command', params: { executionId, commandKey }, signal })
|
||||
|
||||
function scannerHeaders() {
|
||||
const headers: Record<string, string> = { 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<string, string> = {
|
||||
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(() => ({}))
|
||||
|
||||
@ -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'
|
||||
|
||||
@ -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({
|
||||
|
||||
@ -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
|
||||
})
|
||||
|
||||
@ -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(() => ({}))
|
||||
|
||||
@ -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 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { getTenantId } from "@/utils/auth"
|
||||
import axios from 'axios'
|
||||
import { cmvrUploadRequest, uploadCmvrForm, uploadedFilePath } from '@/config/axios/authUpload'
|
||||
import { QuillEditor } from "@vueup/vue-quill"
|
||||
import "@vueup/vue-quill/dist/vue-quill.snow.css"
|
||||
import { getToken } from "@/cmvr/common/utils/auth"
|
||||
|
||||
const { proxy } = getCurrentInstance()
|
||||
|
||||
const quillEditorRef = ref()
|
||||
const uploadUrl = ref((import.meta.env.VITE_BASE_URL + "/admin-api/cmvr") + "/common/upload") // 上传的图片服务器地址
|
||||
const headers = ref({
|
||||
Authorization: "Bearer " + getToken(), "tenant-id": getTenantId() ?? 1
|
||||
})
|
||||
|
||||
const props = defineProps({
|
||||
/* 编辑器的内容 */
|
||||
@ -153,13 +148,15 @@ function handleBeforeUpload(file) {
|
||||
// 上传成功处理
|
||||
function handleUploadSuccess(res, file) {
|
||||
// 如果上传成功
|
||||
if (res.code == 200) {
|
||||
if (res.code === 200 || res.code === 0) {
|
||||
let fileName
|
||||
try { fileName = uploadedFilePath(res) } catch (error) { handleUploadError(error); return }
|
||||
// 获取富文本实例
|
||||
let quill = toRaw(quillEditorRef.value).getQuill()
|
||||
// 获取光标位置
|
||||
let length = quill.selection.savedRange.index
|
||||
// 插入图片,res.url为服务器返回的图片链接地址
|
||||
quill.insertEmbed(length, "image", (import.meta.env.VITE_BASE_URL + "/admin-api/cmvr") + res.fileName)
|
||||
quill.insertEmbed(length, "image", /^https?:\/\//i.test(fileName) ? fileName : (import.meta.env.VITE_BASE_URL + "/admin-api/cmvr") + fileName)
|
||||
// 调整光标到最后
|
||||
quill.setSelection(length + 1)
|
||||
} else {
|
||||
@ -168,8 +165,8 @@ function handleUploadSuccess(res, file) {
|
||||
}
|
||||
|
||||
// 上传失败处理
|
||||
function handleUploadError() {
|
||||
proxy.$modal.msgError("图片插入失败")
|
||||
function handleUploadError(error) {
|
||||
proxy.$modal.msgError(error?.message || "图片插入失败")
|
||||
}
|
||||
|
||||
// 复制粘贴图片处理
|
||||
@ -190,9 +187,7 @@ function handlePasteCapture(e) {
|
||||
function insertImage(file) {
|
||||
const formData = new FormData()
|
||||
formData.append("file", file)
|
||||
axios.post(uploadUrl.value, formData, { headers: { "Content-Type": "multipart/form-data", ...headers.value } }).then(res => {
|
||||
handleUploadSuccess(res.data)
|
||||
})
|
||||
uploadCmvrForm(uploadUrl.value, formData).then(handleUploadSuccess).catch(handleUploadError)
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<el-dialog :title="title" v-model="visible" :width="width" append-to-body @close="handleClose">
|
||||
<el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="headers" :action="uploadUrl" :disabled="isUploading" :on-progress="handleProgress" :on-change="handleFileChange" :on-remove="handleFileRemove" :on-success="handleSuccess" :auto-upload="false" drag>
|
||||
<el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :http-request="cmvrUploadRequest" :action="uploadUrl" :disabled="isUploading" :on-progress="handleProgress" :on-change="handleFileChange" :on-remove="handleFileRemove" :on-success="handleSuccess" :on-error="handleError" :auto-upload="false" drag>
|
||||
<el-icon class="el-icon--upload"><upload-filled /></el-icon>
|
||||
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
|
||||
<template #tip>
|
||||
@ -15,7 +15,7 @@
|
||||
</el-upload>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button type="primary" @click="handleSubmit">确 定</el-button>
|
||||
<el-button type="primary" :loading="isUploading" @click="handleSubmit">确 定</el-button>
|
||||
<el-button @click="visible = false">取 消</el-button>
|
||||
</div>
|
||||
</template>
|
||||
@ -23,7 +23,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { getToken } from '@/cmvr/common/utils/auth'
|
||||
import { cmvrUploadRequest } from '@/config/axios/authUpload'
|
||||
|
||||
const { proxy } = getCurrentInstance()
|
||||
|
||||
@ -67,7 +67,6 @@ const visible = ref(false)
|
||||
const selectedFile = ref(null)
|
||||
const isUploading = ref(false)
|
||||
const updateSupport = ref(false)
|
||||
const headers = { Authorization: 'Bearer ' + getToken() }
|
||||
|
||||
const uploadUrl = computed(() => {
|
||||
return (import.meta.env.VITE_BASE_URL + "/admin-api/cmvr") + props.action + '?updateSupport=' + (updateSupport.value ? 1 : 0)
|
||||
@ -123,13 +122,22 @@ function handleSuccess(response) {
|
||||
emit('success')
|
||||
}
|
||||
|
||||
function handleError(error) {
|
||||
isUploading.value = false
|
||||
selectedFile.value = null
|
||||
uploadRef.value?.clearFiles()
|
||||
proxy.$modal.msgError(error?.message || '导入失败,请重新选择文件后重试')
|
||||
}
|
||||
|
||||
// 提交上传
|
||||
function handleSubmit() {
|
||||
if (isUploading.value) return
|
||||
const file = selectedFile.value
|
||||
if (!file || file.length === 0 || !file.name.toLowerCase().endsWith('.xls') && !file.name.toLowerCase().endsWith('.xlsx')) {
|
||||
proxy.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
|
||||
return
|
||||
}
|
||||
isUploading.value = true
|
||||
uploadRef.value.submit()
|
||||
}
|
||||
|
||||
|
||||
@ -11,7 +11,7 @@
|
||||
:on-exceed="handleExceed"
|
||||
:on-success="handleUploadSuccess"
|
||||
:show-file-list="false"
|
||||
:headers="headers"
|
||||
:http-request="cmvrUploadRequest"
|
||||
class="upload-file-uploader"
|
||||
ref="fileUpload"
|
||||
v-if="!disabled"
|
||||
@ -29,7 +29,7 @@
|
||||
<!-- 文件列表 -->
|
||||
<transition-group ref="uploadFileList" class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
|
||||
<li :key="file.uid" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
|
||||
<el-link :href="`${baseUrl}${file.url}`" underline="never" target="_blank">
|
||||
<el-link :href="/^https?:\/\//i.test(file.url || '') ? file.url : `${baseUrl}${file.url}`" underline="never" target="_blank">
|
||||
<span class="el-icon-document"> {{ getFileName(file.name) }} </span>
|
||||
</el-link>
|
||||
<div class="ele-upload-list__item-content-action">
|
||||
@ -41,8 +41,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { getTenantId } from "@/utils/auth"
|
||||
import { getToken } from "@/cmvr/common/utils/auth"
|
||||
import { cmvrUploadRequest, uploadedFilePath } from '@/config/axios/authUpload'
|
||||
import Sortable from 'sortablejs'
|
||||
|
||||
const props = defineProps({
|
||||
@ -94,7 +93,6 @@ const number = ref(0)
|
||||
const uploadList = ref([])
|
||||
const baseUrl = (import.meta.env.VITE_BASE_URL + "/admin-api/cmvr")
|
||||
const uploadFileUrl = ref((import.meta.env.VITE_BASE_URL + "/admin-api/cmvr") + props.action) // 上传文件服务器地址
|
||||
const headers = ref({ Authorization: "Bearer " + getToken(), "tenant-id": getTenantId() ?? 1 })
|
||||
const fileList = ref([])
|
||||
const showTip = computed(
|
||||
() => props.isShowTip && (props.fileType || props.fileSize)
|
||||
@ -156,14 +154,18 @@ function handleExceed() {
|
||||
|
||||
// 上传失败
|
||||
function handleUploadError(err) {
|
||||
proxy.$modal.msgError("上传文件失败")
|
||||
number.value = Math.max(0, number.value - 1)
|
||||
proxy.$modal.msgError(err?.message || "上传文件失败")
|
||||
proxy.$modal.closeLoading()
|
||||
uploadedSuccessfully()
|
||||
}
|
||||
|
||||
// 上传成功回调
|
||||
function handleUploadSuccess(res, file) {
|
||||
if (res.code === 200) {
|
||||
uploadList.value.push({ name: res.fileName, url: res.fileName })
|
||||
if (res.code === 200 || res.code === 0) {
|
||||
let fileName
|
||||
try { fileName = uploadedFilePath(res) } catch (error) { handleUploadError(error); return }
|
||||
uploadList.value.push({ name: fileName, url: fileName })
|
||||
uploadedSuccessfully()
|
||||
} else {
|
||||
number.value--
|
||||
|
||||
@ -14,7 +14,7 @@
|
||||
ref="imageUpload"
|
||||
:before-remove="handleDelete"
|
||||
:show-file-list="true"
|
||||
:headers="headers"
|
||||
:http-request="cmvrUploadRequest"
|
||||
:file-list="fileList"
|
||||
:on-preview="handlePictureCardPreview"
|
||||
:class="{ hide: fileList.length >= limit }"
|
||||
@ -48,8 +48,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { getTenantId } from "@/utils/auth"
|
||||
import { getToken } from "@/cmvr/common/utils/auth"
|
||||
import { cmvrUploadRequest, uploadedFilePath } from '@/config/axios/authUpload'
|
||||
import { isExternal } from "@/cmvr/common/utils/validate"
|
||||
import Sortable from 'sortablejs'
|
||||
|
||||
@ -104,7 +103,6 @@ const dialogImageUrl = ref("")
|
||||
const dialogVisible = ref(false)
|
||||
const baseUrl = (import.meta.env.VITE_BASE_URL + "/admin-api/cmvr")
|
||||
const uploadImgUrl = ref((import.meta.env.VITE_BASE_URL + "/admin-api/cmvr") + props.action) // 上传的图片服务器地址
|
||||
const headers = ref({ Authorization: "Bearer " + getToken(), "tenant-id": getTenantId() ?? 1 })
|
||||
const fileList = ref([])
|
||||
const showTip = computed(
|
||||
() => props.isShowTip && (props.fileType || props.fileSize)
|
||||
@ -173,8 +171,10 @@ function handleExceed() {
|
||||
|
||||
// 上传成功回调
|
||||
function handleUploadSuccess(res, file) {
|
||||
if (res.code === 200) {
|
||||
uploadList.value.push({ name: res.fileName, url: res.fileName })
|
||||
if (res.code === 200 || res.code === 0) {
|
||||
let fileName
|
||||
try { fileName = uploadedFilePath(res) } catch (error) { handleUploadError(error); return }
|
||||
uploadList.value.push({ name: fileName, url: fileName })
|
||||
uploadedSuccessfully()
|
||||
} else {
|
||||
number.value--
|
||||
@ -207,9 +207,11 @@ function uploadedSuccessfully() {
|
||||
}
|
||||
|
||||
// 上传失败
|
||||
function handleUploadError() {
|
||||
proxy.$modal.msgError("上传图片失败")
|
||||
function handleUploadError(error) {
|
||||
number.value = Math.max(0, number.value - 1)
|
||||
proxy.$modal.msgError(error?.message || "上传图片失败")
|
||||
proxy.$modal.closeLoading()
|
||||
uploadedSuccessfully()
|
||||
}
|
||||
|
||||
// 预览
|
||||
|
||||
@ -1,7 +1,88 @@
|
||||
import { actionQueueTotalTimeout } from './actionQueueTimeout.mjs'
|
||||
import { coordinateName, revisionText } from './armUserCoordinates.mjs'
|
||||
import { QUEUE_SPEED_PREFIX, requireStandaloneQueueSpeed } from './actionQueueSpeed.mjs'
|
||||
const deepClone = (value) => JSON.parse(JSON.stringify(value))
|
||||
|
||||
const ACTION_QUEUE_ACTION = 'SYSTEM_EXECUTE_ACTION_QUEUE'
|
||||
export const QUEUE_APPLY_COORDINATE = 'ARM_APPLY_USER_COORDINATE_SYSTEM'
|
||||
export const QUEUE_LEGACY_COORDINATE_FIELDS = [
|
||||
'frame', 'baseFrame', 'tcpFrame', 'userFramePose', 'tcpOffset',
|
||||
'userCoordinateName', 'userCoordinateRevision', 'coordinateRelativeTranslation',
|
||||
'frameReferenceMode', 'relative',
|
||||
]
|
||||
|
||||
export function validateActionQueueCoordinateParams(params = {}) {
|
||||
if (!params || typeof params !== 'object' || Array.isArray(params))
|
||||
throw new Error('应用坐标系参数必须包含记录名称和版本')
|
||||
if (Object.keys(params).some((key) => !['name', 'expectedRevision'].includes(key)))
|
||||
throw new Error('应用坐标系只接受名称和版本,不接受坐标记录或手填坐标变换')
|
||||
const name = coordinateName(params.name)
|
||||
const expectedRevision = revisionText(params.expectedRevision)
|
||||
if (name.startsWith('__builtin_') && (!['__builtin_base__', '__builtin_tool__'].includes(name) || expectedRevision !== '1'))
|
||||
throw new Error('内置坐标系仅支持基座和当前工具,版本必须为1')
|
||||
return { name, expectedRevision }
|
||||
}
|
||||
|
||||
export const isAppliedCoordinateMove = (step) => step?.type === 'ARM_MOVE_J_POSE' || (step?.type === 'ARM_MOVE_L' && step.coordinateMode === 'APPLIED')
|
||||
|
||||
export function actionQueuePoseJointParams(step, context) {
|
||||
if (!context) throw new Error('末端位姿MoveJ前须先为同一机械臂应用坐标系')
|
||||
const coordinate = validateActionQueueCoordinateParams(context.params)
|
||||
const p = step.params || {}
|
||||
for (const axis of ['x','y','z','rx','ry','rz'])
|
||||
if (typeof p[axis] !== 'number' || !Number.isFinite(p[axis])) throw new Error('末端位姿MoveJ须填写完整绝对TCP目标(m/rad)')
|
||||
for (const field of ['velocity','acceleration'])
|
||||
if (typeof p[field] !== 'number' || !Number.isFinite(p[field]) || p[field] <= 0) throw new Error('末端位姿MoveJ的关节速度和加速度须为有限正数(rad/s、rad/s²)')
|
||||
if (QUEUE_LEGACY_COORDINATE_FIELDS.filter(k=>!['userCoordinateName','userCoordinateRevision'].includes(k)).some(k=>Object.hasOwn(p,k)) || Object.hasOwn(p,'positions') || Object.hasOwn(p,'target'))
|
||||
throw new Error('末端位姿MoveJ不能混填关节角、旧坐标系或增量字段')
|
||||
for (const field of ['blendRadius','jerk']) if (p[field] != null && p[field] !== 0) throw new Error('末端位姿MoveJ不支持非零'+field)
|
||||
if (p.userCoordinateName != null && p.userCoordinateName !== coordinate.name) throw new Error('MoveJ坐标系须与前序应用一致')
|
||||
if (p.userCoordinateRevision != null && p.userCoordinateRevision !== coordinate.expectedRevision) throw new Error('MoveJ坐标系版本须与前序应用一致')
|
||||
return {...p,userCoordinateName:coordinate.name,userCoordinateRevision:coordinate.expectedRevision}
|
||||
}
|
||||
|
||||
export function actionQueueCoordinateContext(steps, index) {
|
||||
const step = steps?.[index]
|
||||
if (!step) return null
|
||||
const sameDevice = (candidate) => {
|
||||
if (step.deviceId || candidate.deviceId) return Boolean(step.deviceId && candidate.deviceId === step.deviceId)
|
||||
return Boolean(step.deviceSlotKey && candidate.deviceSlotKey === step.deviceSlotKey)
|
||||
}
|
||||
for (let i = index - 1; i >= 0; i--) {
|
||||
if (steps[i]?.type === QUEUE_APPLY_COORDINATE && sameDevice(steps[i])) return steps[i]
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function validateActionQueueCoordinateSequence(steps = []) {
|
||||
steps.forEach((step, index) => {
|
||||
if (step.type === QUEUE_APPLY_COORDINATE) validateActionQueueCoordinateParams(step.params)
|
||||
if (step.type === 'ARM_MOVE_J_POSE') { actionQueuePoseJointParams(step,actionQueueCoordinateContext(steps,index)); return }
|
||||
if (isAppliedCoordinateMove(step)) {
|
||||
if (QUEUE_LEGACY_COORDINATE_FIELDS.some((key) => Object.hasOwn(step.params || {}, key)))
|
||||
throw new Error(`步骤 ${index + 1} 沿用已应用坐标系,不能同时配置旧参考系或增量参数`)
|
||||
if (!actionQueueCoordinateContext(steps, index))
|
||||
throw new Error(`步骤 ${index + 1} 前请先为同一机械臂添加“应用坐标系”步骤`)
|
||||
} else if (step.type === 'ARM_MOVE_L' && actionQueueCoordinateContext(steps, index)) {
|
||||
throw new Error(`步骤 ${index + 1} 仍使用旧版参考系,请显式改为“沿用前序已应用坐标系”`)
|
||||
}
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
export function actionQueueSingleExecutionSteps(steps, index) {
|
||||
const step = steps?.[index]
|
||||
if (!step) throw new Error('步骤不存在')
|
||||
requireStandaloneQueueSpeed(step)
|
||||
if (step.type === 'ARM_MOVE_L' && !isAppliedCoordinateMove(step) && actionQueueCoordinateContext(steps, index))
|
||||
throw new Error('该移动仍使用旧版参考系,请先显式改为沿用前序已应用坐标系')
|
||||
if (!isAppliedCoordinateMove(step)) return [deepClone(step)]
|
||||
const context = actionQueueCoordinateContext(steps, index)
|
||||
if (!context) throw new Error('请先为同一机械臂添加“应用坐标系”步骤,再单独执行此移动')
|
||||
const result = [deepClone(context), deepClone(step)]
|
||||
validateActionQueueCoordinateSequence(result)
|
||||
return result
|
||||
}
|
||||
const REFERENCE_KEYS = new Set(['quote', 'nameQuote'])
|
||||
|
||||
const createKey = (prefix) => {
|
||||
@ -43,7 +124,7 @@ const nodeToQueueStep = (node) => {
|
||||
return {
|
||||
...common,
|
||||
type: 'DELAY',
|
||||
timeoutMs: 60000,
|
||||
timeoutMs: 120000,
|
||||
params: { durationMs },
|
||||
}
|
||||
}
|
||||
@ -51,13 +132,13 @@ const nodeToQueueStep = (node) => {
|
||||
return {
|
||||
...common,
|
||||
type: 'AGV_NAVIGATE_TO_POSE',
|
||||
timeoutMs: 60000,
|
||||
timeoutMs: 120000,
|
||||
params: {
|
||||
x: numberValue(params.x),
|
||||
y: numberValue(params.y),
|
||||
theta: numberValue(params.theta),
|
||||
maxSpeed: numberValue(params.maxSpeed, 0.5),
|
||||
blockedTimeoutMs: numberValue(params.blockedTimeoutMs, 60000),
|
||||
blockedTimeoutMs: numberValue(params.blockedTimeoutMs, 120000),
|
||||
},
|
||||
}
|
||||
}
|
||||
@ -65,11 +146,11 @@ const nodeToQueueStep = (node) => {
|
||||
return {
|
||||
...common,
|
||||
type: 'AGV_NAVIGATE_TO_STATION',
|
||||
timeoutMs: 60000,
|
||||
timeoutMs: 120000,
|
||||
params: {
|
||||
stationId: params.stationId ?? '',
|
||||
maxSpeed: numberValue(params.maxSpeed, 0.5),
|
||||
blockedTimeoutMs: numberValue(params.blockedTimeoutMs, 60000),
|
||||
blockedTimeoutMs: numberValue(params.blockedTimeoutMs, 120000),
|
||||
},
|
||||
}
|
||||
}
|
||||
@ -77,7 +158,7 @@ const nodeToQueueStep = (node) => {
|
||||
return {
|
||||
...common,
|
||||
type: 'ARM_MOVE_L',
|
||||
timeoutMs: 60000,
|
||||
timeoutMs: 120000,
|
||||
params: {
|
||||
x: numberValue(params.x),
|
||||
y: numberValue(params.y),
|
||||
@ -88,16 +169,21 @@ const nodeToQueueStep = (node) => {
|
||||
frame: params.frame || 'BASE',
|
||||
...(params.baseFrame ? {baseFrame:params.baseFrame} : {}),
|
||||
...(params.tcpFrame ? {tcpFrame:params.tcpFrame} : {}),
|
||||
...Object.fromEntries(['userCoordinateName', 'userCoordinateRevision', 'coordinateRelativeTranslation', 'userFramePose', 'tcpOffset'].filter((key) => Object.hasOwn(params, key)).map((key) => [key, params[key]])),
|
||||
velocity: numberValue(params.velocity, 2.1),
|
||||
acceleration: numberValue(params.acceleration, 2.2),
|
||||
},
|
||||
}
|
||||
}
|
||||
if (action === QUEUE_APPLY_COORDINATE) {
|
||||
return { ...common, type: QUEUE_APPLY_COORDINATE, timeoutMs: 120000,
|
||||
params: { name: params.name || '', expectedRevision: params.expectedRevision || '0' } }
|
||||
}
|
||||
if (action === 'ARM_MOVE_TO_J') {
|
||||
return {
|
||||
...common,
|
||||
type: 'ARM_MOVE_J',
|
||||
timeoutMs: 60000,
|
||||
timeoutMs: 120000,
|
||||
params: {
|
||||
positions: arrayValue(params.target),
|
||||
velocity: numberValue(params.velocity, 0.1),
|
||||
@ -111,6 +197,10 @@ const nodeToQueueStep = (node) => {
|
||||
const validateConvertibleNodeParams = (node) => {
|
||||
const action = node?.properties?.action
|
||||
const params = paramsToObject(node)
|
||||
if (action === QUEUE_APPLY_COORDINATE) {
|
||||
if (Object.hasOwn(params, 'coordinate')) return '应用坐标系只接受已有记录名称和版本,请移除坐标记录内容'
|
||||
try { validateActionQueueCoordinateParams({ name: params.name, expectedRevision: params.expectedRevision }) } catch (error) { return error.message }
|
||||
}
|
||||
const requiredByAction = {
|
||||
AGV_MOVE_TO_POINT: ['x', 'y', 'theta'],
|
||||
AGV_MOVE_TO_STATION: ['stationId'],
|
||||
@ -180,6 +270,8 @@ const normalizeQueueStepIds = (steps) => steps.map((step, index) => ({
|
||||
}))
|
||||
|
||||
const updateQueueDefinition = (queueNode, steps) => {
|
||||
const usedSpeedParams = new Set(steps.map(step => step.paramBindings?.velocity).filter(Boolean))
|
||||
queueNode.properties.nodeParams = (queueNode.properties.nodeParams || []).filter(param => !param.name?.startsWith(QUEUE_SPEED_PREFIX) || usedSpeedParams.has(param.name))
|
||||
const normalizedSteps = normalizeQueueStepIds(steps)
|
||||
setNodeParam(queueNode, 'steps', normalizedSteps, { required: true })
|
||||
setNodeParam(
|
||||
@ -292,8 +384,18 @@ export const extractActionQueueStep = (sourceGraph, queueId, stepIndex, placemen
|
||||
const step = steps[stepIndex]
|
||||
if (!step) return { ok: false, message: '要移出的步骤不存在' }
|
||||
if (!step.sourceNode) return { ok: false, message: '该步骤不是由工作流节点移入,无法还原为原节点' }
|
||||
if (step.type === QUEUE_APPLY_COORDINATE && steps.some((candidate, index) =>
|
||||
isAppliedCoordinateMove(candidate) && actionQueueCoordinateContext(steps, index) === step)) {
|
||||
return { ok: false, message: '后续移动仍沿用该坐标系,请先调整对应移动步骤,再将应用坐标系移出队列' }
|
||||
}
|
||||
|
||||
const node = deepClone(step.sourceNode)
|
||||
if (step.paramBindings?.velocity) {
|
||||
const binding = queueNode.properties.nodeParams?.find(param => param.name === step.paramBindings.velocity)
|
||||
const velocity = node.properties?.nodeParams?.find(param => param.name === 'velocity')
|
||||
if (!binding || !velocity) return { ok: false, message: '步骤速度引用配置不完整,请先检查速度来源' }
|
||||
Object.assign(velocity, deepClone(binding), { name: 'velocity', label: velocity.label })
|
||||
}
|
||||
const previousId = node.id
|
||||
node.id = createKey('node')
|
||||
remapNodeAnchors(node, previousId, node.id)
|
||||
@ -366,10 +468,14 @@ export const copyActionQueueStep = (step, overrides = {}) => {
|
||||
}
|
||||
}
|
||||
|
||||
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 || {}),
|
||||
}))
|
||||
export const toActionQueueExecutionSteps = (steps) => (Array.isArray(steps) ? steps : []).map((step, index) => {
|
||||
requireStandaloneQueueSpeed(step)
|
||||
return {
|
||||
stepId: `step_${index + 1}`,
|
||||
type: step.type,
|
||||
...(step.coordinateMode ? { coordinateMode: step.coordinateMode } : {}),
|
||||
...(step.deviceId ? { deviceId: step.deviceId } : {}),
|
||||
timeoutMs: Number(step.timeoutMs ?? 120000),
|
||||
params: deepClone(step.type === 'ARM_MOVE_J_POSE' ? actionQueuePoseJointParams(step,actionQueueCoordinateContext(steps,index)) : step.params || {}),
|
||||
}
|
||||
})
|
||||
|
||||
29
am-web/src/cmvr/common/utils/actionQueueSpeed.mjs
Normal file
29
am-web/src/cmvr/common/utils/actionQueueSpeed.mjs
Normal file
@ -0,0 +1,29 @@
|
||||
const clone = (value) => JSON.parse(JSON.stringify(value))
|
||||
export const QUEUE_SPEED_PREFIX = 'queue_velocity_'
|
||||
export const hasQueueArmSpeed = (type) => ['ARM_MOVE_J', 'ARM_MOVE_J_POSE', 'ARM_MOVE_L'].includes(type)
|
||||
export function queueSpeedSource(step, nodeParams = []) {
|
||||
const name = step.paramBindings?.velocity
|
||||
if (!name) return { type: 'input', quote: [] }
|
||||
return { ...clone(nodeParams.find(p => p.name === name) || {}), type: 'quote' }
|
||||
}
|
||||
export function encodeQueueSpeed(step, params) {
|
||||
if (!hasQueueArmSpeed(step.type) || step.speedSource?.type !== 'quote') return { params }
|
||||
const source = step.speedSource
|
||||
if (!Array.isArray(source.quote) || source.quote.length < 3 || source.quote.some(p => typeof p !== 'string' || !p.trim()) || !['input', 'output'].includes(source.quoteType))
|
||||
throw new Error('请选择机械臂速度的完整引用')
|
||||
const name = QUEUE_SPEED_PREFIX + step.deviceBindingKey
|
||||
const result = { ...params }
|
||||
delete result.velocity
|
||||
return {
|
||||
params: result,
|
||||
paramBindings: { velocity: name },
|
||||
parameter: { name, label: `${step.stepName || '机械臂步骤'} · 速度`, type: 'quote', quote: [...source.quote], quoteType: source.quoteType, required: true }
|
||||
}
|
||||
}
|
||||
// Validate the other literal fields without treating a runtime reference as a speed.
|
||||
export const queueSpeedValidationSteps = (steps) => steps.map(step => step.paramBindings?.velocity
|
||||
? { ...step, params: { ...step.params, velocity: 0.1 } } : step)
|
||||
export function requireStandaloneQueueSpeed(step) {
|
||||
if (step.paramBindings?.velocity || step.speedSource?.type === 'quote')
|
||||
throw new Error('速度引用需要上游运行结果,请通过工作流试运行执行此步骤')
|
||||
}
|
||||
@ -1,22 +1,24 @@
|
||||
export const DEFAULT_STEP_TIMEOUT_MS = 60000
|
||||
export const MAX_QUEUE_TIMEOUT_MS = 2147483647
|
||||
export const DEFAULT_STEP_TIMEOUT_MS = 120000
|
||||
export const MAX_QUEUE_TIMEOUT_MS = 1800000
|
||||
export const SERVER_DEFAULT_QUEUE_TIMEOUT_MS = 300000
|
||||
|
||||
export function actionQueueTotalTimeout(steps = []) {
|
||||
let total = 0, unlimited = false
|
||||
if (steps.length > 100) throw new Error('动作队列最多100个步骤')
|
||||
for (const step of steps) {
|
||||
const timeout = Number(step.timeoutMs ?? DEFAULT_STEP_TIMEOUT_MS)
|
||||
if (!Number.isInteger(timeout) || timeout < 0 || timeout > MAX_QUEUE_TIMEOUT_MS)
|
||||
throw new Error('步骤超时必须是有效的非负整数,0表示不限时')
|
||||
throw new Error('步骤超时须为0至1800000整数毫秒,0继承队列剩余时间')
|
||||
unlimited ||= timeout === 0
|
||||
total += timeout
|
||||
}
|
||||
if (unlimited) return 0
|
||||
if (total > MAX_QUEUE_TIMEOUT_MS) throw new Error('队列总超时超出支持范围,请拆分队列或将步骤超时设为0')
|
||||
if (total > MAX_QUEUE_TIMEOUT_MS) throw new Error('队列总超时最多30分钟,请拆分队列或将步骤设为0使用边端默认5分钟')
|
||||
return total
|
||||
}
|
||||
|
||||
// Axios timeout=0 disables its timer. Network grace is separate from device execution time.
|
||||
// Allow the unary RPC its total runtime plus transport grace; zero means edge default, not infinity.
|
||||
export function actionQueueRequestTimeout(steps) {
|
||||
const total = actionQueueTotalTimeout(steps)
|
||||
return total === 0 ? 0 : Math.min(MAX_QUEUE_TIMEOUT_MS, total + 10000)
|
||||
return (total === 0 ? SERVER_DEFAULT_QUEUE_TIMEOUT_MS : total) + 10000
|
||||
}
|
||||
|
||||
@ -1,15 +1,15 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { actionQueueTotalTimeout, actionQueueRequestTimeout } from './actionQueueTimeout.mjs'
|
||||
test('默认每步60秒,总超时自动累加', () => {
|
||||
assert.equal(actionQueueTotalTimeout([{}, {}, {}]),180000)
|
||||
test('默认每步120秒,总超时自动累加', () => {
|
||||
assert.equal(actionQueueTotalTimeout([{}, {}, {}]),360000)
|
||||
assert.equal(actionQueueTotalTimeout([{timeoutMs:12000},{timeoutMs:34000}]),46000)
|
||||
assert.equal(actionQueueRequestTimeout([{},{}]),130000)
|
||||
assert.equal(actionQueueRequestTimeout([{},{}]),250000)
|
||||
})
|
||||
test('任何步骤为0,总超时及HTTP请求均不限时', () => {
|
||||
test('任何步骤为0,总超时传0且HTTP按边端默认5分钟等待', () => {
|
||||
assert.equal(actionQueueTotalTimeout([{timeoutMs:0},{}]),0)
|
||||
assert.equal(actionQueueTotalTimeout([{timeoutMs:60000},{timeoutMs:0}]),0)
|
||||
assert.equal(actionQueueRequestTimeout([{timeoutMs:0}]),0)
|
||||
assert.equal(actionQueueRequestTimeout([{timeoutMs:0}]),310000)
|
||||
})
|
||||
test('非法值和累加溢出被明确拒绝', () => {
|
||||
for (const timeoutMs of [-1,1.2,NaN,Infinity,2147483648]) assert.throws(()=>actionQueueTotalTimeout([{timeoutMs}]))
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
import { coordinateName } from './armUserCoordinates.mjs'
|
||||
|
||||
export const isLinearArmAction = (action) => ['ARM_MOVE_TO_POINT', 'ARM_MOVE_L'].includes(action)
|
||||
export function frameNames(catalog, key) {
|
||||
const names = catalog?.[key]
|
||||
@ -75,17 +77,34 @@ export function userCoordinateCatalog(data) {
|
||||
userCoordinates: data.coordinates
|
||||
}
|
||||
}
|
||||
export function poseFrameQuery(choice, legacyFrame = 'BASE') {
|
||||
if (
|
||||
(choice.userCoordinateName && choice.userCoordinateName !== '__builtin_base__') ||
|
||||
choice.coordinateRelativeTranslation
|
||||
)
|
||||
throw new Error(
|
||||
'当前位姿返回Base坐标,不能自动回填为用户/工具坐标系目标或相对位移;请手工填写目标,或选择基座绝对目标后读取'
|
||||
)
|
||||
if (!choice.baseFrame && legacyFrame && legacyFrame !== 'BASE')
|
||||
throw new Error('当前使用旧参考系,请先选择边端提供的基准坐标系,再读取对应位置')
|
||||
export function poseFrameQuery(choice = {}, legacyFrame = 'BASE') {
|
||||
if (!choice || typeof choice !== 'object' || Array.isArray(choice))
|
||||
throw new Error('读取位姿前请选择有效的参考坐标系')
|
||||
if (choice.coordinateRelativeTranslation != null && typeof choice.coordinateRelativeTranslation !== 'boolean')
|
||||
throw new Error('相对运动方式必须为布尔值')
|
||||
if (choice.coordinateRelativeTranslation)
|
||||
throw new Error('当前位姿是绝对TCP目标,不能自动回填为相对位移,请先选择绝对目标方式')
|
||||
if (choice.baseFrame || choice.tcpFrame)
|
||||
throw new Error('旧命名坐标系已停用,请先选择新版记录并清空旧参数')
|
||||
return { baseLink: 'base', eeLink: 'tcp' }
|
||||
const name = choice.userCoordinateName == null || choice.userCoordinateName === ''
|
||||
? '' : coordinateName(choice.userCoordinateName)
|
||||
if (!name && legacyFrame && legacyFrame !== 'BASE')
|
||||
throw new Error('当前使用旧参考系,请先选择边端提供的新版坐标系,再读取对应位置')
|
||||
if (name.startsWith('__builtin_') && !['__builtin_base__', '__builtin_tool__'].includes(name))
|
||||
throw new Error('不支持的内置坐标系,请重新读取并选择')
|
||||
return { baseLink: !name || name === '__builtin_base__' ? 'base' : name, eeLink: 'tcp' }
|
||||
}
|
||||
|
||||
/** Keep SDK m/rad values unchanged, and reject a reply in any other frame. */
|
||||
export function poseFrameValues(data, choice = {}, legacyFrame = 'BASE') {
|
||||
const query = poseFrameQuery(choice, legacyFrame)
|
||||
if (data?.referenceFrame !== query.baseLink || data?.endFrame !== query.eeLink)
|
||||
throw new Error('边端返回的参考坐标系或末端与本次选择不一致,位置未回填,请重新读取')
|
||||
const values = {}
|
||||
for (const axis of ['x', 'y', 'z', 'rx', 'ry', 'rz']) {
|
||||
if (typeof data[axis] !== 'number' || !Number.isFinite(data[axis]))
|
||||
throw new Error('机械臂未返回完整有效的六维TCP位姿,位置未回填')
|
||||
values[axis] = data[axis]
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
@ -1,23 +1,30 @@
|
||||
import { ARM_DEFAULT_WAIT_MS } from './armTimeouts.mjs'
|
||||
// Labels describe the SDK contract. Never convert or rewrite saved positions or live feedback here.
|
||||
const jointActions = new Set(['ARM_MOVE_TO_J', 'ARM_MOVE_J'])
|
||||
const linearActions = new Set(['ARM_MOVE_TO_POINT', 'ARM_MOVE_L'])
|
||||
export function armMotionParamLabel(action, name) {
|
||||
const joint = jointActions.has(action)
|
||||
if (!joint && !linearActions.has(action)) return ''
|
||||
const jointPose = action === 'ARM_MOVE_J_POSE'
|
||||
if (!joint && !jointPose && !linearActions.has(action)) return ''
|
||||
if (joint && ['target', 'positions'].includes(name)) return '关节位置(rad,数组)'
|
||||
if (!joint && ['x', 'y', 'z'].includes(name)) return `${name.toUpperCase()}(m)`
|
||||
if (!joint && ['rx', 'ry', 'rz'].includes(name)) return `${name.toUpperCase()}(rad)`
|
||||
if (name === 'velocity') return `速度(${joint ? 'rad/s' : 'm/s'})`
|
||||
if (name === 'acceleration') return `加速度(${joint ? 'rad/s²' : 'm/s²'})`
|
||||
if (name === 'velocity') return `速度(${joint || jointPose ? 'rad/s' : 'm/s'})`
|
||||
if (name === 'acceleration') return `加速度(${joint || jointPose ? 'rad/s²' : 'm/s²'})`
|
||||
if (name === 'blendRadius') return '融合半径(m)'
|
||||
if (name === 'jointVelocityLimits') return '各关节速度上限(rad/s,数组)'
|
||||
return ''
|
||||
}
|
||||
export const withArmMotionUnits = (action, params = []) => params.map(param => {
|
||||
export const withArmMotionUnits = (action, params = []) => {
|
||||
const source = ['ARM_MOVE_TO_J', 'ARM_MOVE_TO_POINT'].includes(action) && !params.some(p => p.name === 'timeoutMs')
|
||||
? [...params, {name:'timeoutMs',label:'等待超时(毫秒)',type:'input',componentType:'number',input:ARM_DEFAULT_WAIT_MS,min:100,max:21600000,step:1000,required:true,disabled:true}] : params
|
||||
return source.map(param => {
|
||||
const label = armMotionParamLabel(action, param.name)
|
||||
return label ? { ...param, label } : param
|
||||
})
|
||||
return label ? { ...param, label, ...(param.name === 'velocity' ? { forceSelect: false } : {}) } : param
|
||||
})
|
||||
}
|
||||
export function armMotionUnitHint(action) {
|
||||
if (action === 'ARM_MOVE_J_POSE') return '末端位姿MoveJ:XYZ为所选坐标系下绝对TCP位置(m),RX/RY/RZ为绝对姿态(rad,RzRyRx);速度rad/s,加速度rad/s²。边端逆解后执行关节运动,途中路径不保证直线。'
|
||||
if (jointActions.has(action)) return 'SDK 单位:关节位置为 rad,速度为 rad/s,加速度为 rad/s²。示教器角度换算:1° = π/180 rad,90° ≈ 1.570796 rad。读取当前位置按 SDK 原值回填。'
|
||||
if (linearActions.has(action)) return 'SDK 单位:X/Y/Z 为 m,RX/RY/RZ 为 rad,速度为 m/s,加速度为 m/s²。示教器单位换算:1 mm = 0.001 m,90° ≈ 1.570796 rad。读取当前位置按 SDK 原值回填。'
|
||||
return ''
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { ARM_DEFAULT_WAIT_MS } from './armTimeouts.mjs'
|
||||
import {
|
||||
coordinateKeys,
|
||||
coordinateOutputFields,
|
||||
@ -8,6 +9,7 @@ import {
|
||||
COORDINATE_STEP_ACTION,
|
||||
usesCoordinateSelection,
|
||||
coordinateSelectionField,
|
||||
canReferenceArmParameter,
|
||||
workflowCoordinateStep
|
||||
} from './armWorkflowCoordinates.mjs'
|
||||
const number = (name, label, input, min, max, step = 0.1) => ({
|
||||
@ -127,7 +129,7 @@ export const ARM_TEACHING_OPERATIONS = [
|
||||
rpc: 'MoveToTrajectoryStart',
|
||||
name: '平滑运动到轨迹起点',
|
||||
desc: '会产生运动;按速度、加速度、加加速度限值规划,同步等待完成,回放倍率不决定到起点速度。',
|
||||
timeout: 150000,
|
||||
timeout: ARM_DEFAULT_WAIT_MS,
|
||||
fields: () => [
|
||||
file(),
|
||||
number('maxVelocity', '关节速度上限(rad/s)', 0.3, 0),
|
||||
@ -140,7 +142,7 @@ export const ARM_TEACHING_OPERATIONS = [
|
||||
rpc: 'ReplayRecordedTrajectory',
|
||||
name: '平滑回放所选轨迹',
|
||||
desc: '必须先到起点(每关节误差≤0.01 rad);同步等待完成,不自动到起点。',
|
||||
timeout: 300000,
|
||||
timeout: ARM_DEFAULT_WAIT_MS,
|
||||
fields: () => [
|
||||
file(),
|
||||
number('speedRatio', '回放倍率', 0.5, 0, 1),
|
||||
@ -294,7 +296,7 @@ export function createArmTeachingGroup(icon) {
|
||||
desc: op.desc,
|
||||
nodeParams: [
|
||||
...(op.fields?.() || []),
|
||||
number('timeoutMs', '等待超时(毫秒)', op.timeout || 30000, 100, 21600000, 1000)
|
||||
number('timeoutMs', '等待超时(毫秒)', op.timeout || ARM_DEFAULT_WAIT_MS, 100, 21600000, 1000)
|
||||
],
|
||||
outputParams: [
|
||||
info('success', 'boolean', '业务成功,传输失败或业务失败不会进入下一步'),
|
||||
@ -363,15 +365,16 @@ export function validateArmTeachingConfiguration(action, params) {
|
||||
params.some(
|
||||
(p) =>
|
||||
p.type === 'quote' &&
|
||||
(action === COORDINATE_STEP_ACTION ||
|
||||
(!canReferenceArmParameter(action, p.name) ||
|
||||
(usesCoordinateSelection(action) && coordinateSelectionField(p)))
|
||||
)
|
||||
)
|
||||
throw new Error('坐标系请从机械臂读取并下拉选择,名称和版本不支持引用;单步参数请直接配置')
|
||||
throw new Error('坐标系请从机械臂读取并下拉选择;目标位姿节点仅速度支持引用,其余参数请直接配置')
|
||||
const values = Object.fromEntries(
|
||||
params.filter((p) => p.type === 'input').map((p) => [p.name, p.input])
|
||||
)
|
||||
for (const p of params.filter((p) => p.type === 'quote')) {
|
||||
if (action === COORDINATE_STEP_ACTION && p.name === 'velocityMm') values.velocityMm = 1
|
||||
if (p.name === 'fileName') values.fileName = 'runtime.csv'
|
||||
if (p.name === 'name') values.name = 'runtime-coordinate'
|
||||
if (p.name === 'expectedRevision') values.expectedRevision = '1'
|
||||
|
||||
@ -1,14 +1,12 @@
|
||||
export const ARM_REQUEST_TIMEOUT_MS = 30000
|
||||
export const ARM_DEFAULT_WAIT_MS = 120000
|
||||
export const ARM_REQUEST_TIMEOUT_MS = ARM_DEFAULT_WAIT_MS + 10000
|
||||
export function armRequestTimeout(operation, data = {}) {
|
||||
const defaults = {
|
||||
moveToTrajectoryStart: 150000,
|
||||
replayRecordedTrajectory: 300000,
|
||||
moveCoordinateStep: 120000,
|
||||
moveCoordinateTarget: 120000
|
||||
moveToTrajectoryStart: ARM_DEFAULT_WAIT_MS,
|
||||
replayRecordedTrajectory: ARM_DEFAULT_WAIT_MS,
|
||||
moveCoordinateStep: ARM_DEFAULT_WAIT_MS,
|
||||
moveCoordinateTarget: ARM_DEFAULT_WAIT_MS
|
||||
}
|
||||
const configured = data.timeoutMs ?? defaults[operation] ?? ARM_REQUEST_TIMEOUT_MS
|
||||
return Math.max(
|
||||
ARM_REQUEST_TIMEOUT_MS,
|
||||
Number.isFinite(configured) ? configured : ARM_REQUEST_TIMEOUT_MS
|
||||
)
|
||||
const configured = data.timeoutMs ?? defaults[operation] ?? ARM_DEFAULT_WAIT_MS
|
||||
return (Number.isFinite(configured) && configured >= 100 ? configured : ARM_DEFAULT_WAIT_MS) + 10000
|
||||
}
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { ARM_REQUEST_TIMEOUT_MS, armRequestTimeout } from './armTimeouts.mjs'
|
||||
test('使能、关闭、状态和坐标系普通请求使用30秒', () => {
|
||||
assert.equal(ARM_REQUEST_TIMEOUT_MS, 30000)
|
||||
test('机械臂默认等待两分钟,HTTP额外预留十秒传输时间', () => {
|
||||
assert.equal(ARM_REQUEST_TIMEOUT_MS, 130000)
|
||||
for (const operation of [
|
||||
'torqueOn',
|
||||
'torqueOff',
|
||||
@ -12,10 +12,11 @@ test('使能、关闭、状态和坐标系普通请求使用30秒', () => {
|
||||
'createUserCoordinateSystem',
|
||||
'getActiveTcpOffset'
|
||||
])
|
||||
assert.equal(armRequestTimeout(operation), 30000)
|
||||
assert.equal(armRequestTimeout('stopMotion', { timeoutMs: 10000 }), 30000)
|
||||
assert.equal(armRequestTimeout(operation), 130000)
|
||||
assert.equal(armRequestTimeout('stopMotion', { timeoutMs: 10000 }), 20000)
|
||||
})
|
||||
test('运动执行等待仍按显式配置,不截断较长轨迹', () => {
|
||||
assert.equal(armRequestTimeout('replayRecordedTrajectory'), 300000)
|
||||
assert.equal(armRequestTimeout('moveCoordinateStep', { timeoutMs: 120000 }), 120000)
|
||||
assert.equal(armRequestTimeout('replayRecordedTrajectory'), 130000)
|
||||
assert.equal(armRequestTimeout('replayRecordedTrajectory', { timeoutMs: 300000 }), 310000)
|
||||
assert.equal(armRequestTimeout('moveCoordinateStep', { timeoutMs: 120000 }), 130000)
|
||||
})
|
||||
|
||||
@ -175,8 +175,8 @@ test('直线运动显式名称版本和相对平移,不混用旧名称或姿
|
||||
{ coordinateRelativeTranslation: 'true' }
|
||||
])
|
||||
assert.throws(() => validateLinearCoordinate({ ...p, ...patch }))
|
||||
assert.throws(() => poseFrameQuery(p))
|
||||
assert.throws(() => poseFrameQuery({ userCoordinateName: '__builtin_tool__' }))
|
||||
assert.deepEqual(poseFrameQuery(p), { baseLink: p.userCoordinateName, eeLink: 'tcp' })
|
||||
assert.deepEqual(poseFrameQuery({ userCoordinateName: '__builtin_tool__' }), { baseLink: '__builtin_tool__', eeLink: 'tcp' })
|
||||
assert.doesNotThrow(() => poseFrameQuery({ userCoordinateName: '__builtin_base__' }))
|
||||
})
|
||||
test('七个坐标系组件保留可引用的名称版本,起点组件显式提供三项限值', () => {
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
import { validateLinearCoordinate } from './armUserCoordinates.mjs'
|
||||
|
||||
export const COORDINATE_STEP_ACTION = 'ARM_MOVE_COORDINATE_STEP'
|
||||
export const canReferenceArmParameter = (action, name) =>
|
||||
action !== COORDINATE_STEP_ACTION || name === 'velocityMm'
|
||||
export const usesCoordinateSelection = (action) =>
|
||||
[
|
||||
'ARM_GET_USER_COORDINATE_SYSTEM',
|
||||
|
||||
@ -13,12 +13,12 @@ export function validateRotaryBaseParameters(action, values) {
|
||||
if (acceleration<=0 || acceleration>1) throw new Error('回零加速度必须大于0且不超过1 rad/s²')
|
||||
if (seconds<1 || seconds>300) throw new Error('回零服务端等待时间必须为1至300秒')
|
||||
if (Math.abs(offset)>2*Math.PI) throw new Error('回零偏移必须在±2π rad内')
|
||||
if (numeric('timeoutMs')<=seconds*1000) throw new Error('客户端超时必须大于回零服务端等待时间')
|
||||
if (numeric('timeoutMs')<seconds*1000) throw new Error('节点超时不得小于回零服务端等待时间')
|
||||
}
|
||||
if (!['MOTOR_MOVE', 'MOTOR_VELOCITY'].includes(action)) return
|
||||
if (!['DEGREE', 'RADIAN'].includes(values.unit)) throw new Error('旋转底座单位只支持度和弧度')
|
||||
const factor = values.unit === 'DEGREE' ? Math.PI / 180 : 1
|
||||
if (action === 'MOTOR_MOVE' && Math.abs(numeric('targetPosition') * factor) > 2 * Math.PI + 1e-12) throw new Error('绝对位置须在±360°(±2π rad)内')
|
||||
if (action === 'MOTOR_MOVE' && Math.abs(numeric('targetPosition') * factor) > 10 * Math.PI + 1e-12) throw new Error('绝对位置须在±1800°(±10π rad)内')
|
||||
const velocity = numeric('velocity') * factor, acceleration = numeric('acceleration') * factor
|
||||
if (Math.abs(velocity) > 1 + 1e-12 || (action === 'MOTOR_MOVE' && velocity <= 0)) throw new Error('位置速度须大于0,速度控制允许正负或零;绝对值不得超过1 rad/s(约57.2958°/s)')
|
||||
if (acceleration <= 0 || acceleration > 1 + 1e-12) throw new Error('加速度须大于0且不超过1 rad/s²(约57.2958°/s²)')
|
||||
|
||||
@ -17,10 +17,12 @@ test('旧默认英文名称转换中文,但保留用户自定义名称和动
|
||||
assert.equal(nodes[0].properties.name,'获取电机状态');assert.equal(nodes[1].properties.name,'检查底座是否就绪')
|
||||
assert.equal(nodes[0].properties.action,'MOTOR_GET_STATE')
|
||||
})
|
||||
test('单位与范围按输出轴校验,位置正负360度和速度正负1弧度可用', () => {
|
||||
for (const targetPosition of [-360, 0, 360]) validate('MOTOR_MOVE', { targetPosition, unit: 'DEGREE', velocity: 15, acceleration: 20 })
|
||||
test('单位与范围按输出轴校验,位置正负1800度和速度正负1弧度可用', () => {
|
||||
for (const targetPosition of [-1800, -360, 0, 360, 1800]) validate('MOTOR_MOVE', { targetPosition, unit: 'DEGREE', velocity: 15, acceleration: 20 })
|
||||
for (const targetPosition of [-10 * Math.PI, 0, 10 * Math.PI]) validate('MOTOR_MOVE', { targetPosition, unit: 'RADIAN', velocity: 0.1, acceleration: 0.2 })
|
||||
for (const velocity of [-1, 0, 1]) validate('MOTOR_VELOCITY', { unit: 'RADIAN', velocity, acceleration: 1 })
|
||||
for (const targetPosition of [-361, 361, undefined, null, '0', NaN]) assert.throws(() => validate('MOTOR_MOVE', { targetPosition, unit: 'DEGREE', velocity: 15, acceleration: 20 }))
|
||||
for (const targetPosition of [-1800.0001, 1800.0001, undefined, null, '0', NaN]) assert.throws(() => validate('MOTOR_MOVE', { targetPosition, unit: 'DEGREE', velocity: 15, acceleration: 20 }))
|
||||
for (const targetPosition of [-10 * Math.PI - 0.0001, 10 * Math.PI + 0.0001]) assert.throws(() => validate('MOTOR_MOVE', { targetPosition, unit: 'RADIAN', velocity: 0.1, acceleration: 0.2 }))
|
||||
for (const unit of ['PULSE', 'MILLIMETER', '']) assert.throws(() => validate('MOTOR_MOVE', { targetPosition: 0, unit, velocity: 1, acceleration: 1 }))
|
||||
})
|
||||
test('位置速度必须为正,速度指令显式支持零;加速度和模式错误在保存前阻断', () => {
|
||||
@ -40,6 +42,6 @@ test('机械回零按弧度输入,范围、两级速度和客户端超时在
|
||||
const defaults={method:4,fastSpeed:0.105,slowSpeed:0.0105,acceleration:1,timeoutSeconds:30,offset:0,timeoutMs:40000}
|
||||
validate('MOTOR_HOMING',defaults)
|
||||
validate('MOTOR_HOMING',{...defaults,timeoutSeconds:300,timeoutMs:310000})
|
||||
for (const invalid of [{method:0},{fastSpeed:0},{fastSpeed:1.1},{slowSpeed:0.2},{slowSpeed:0},{acceleration:0},{timeoutSeconds:301},{timeoutSeconds:0},{timeoutMs:30000},{offset:7},{offset:NaN}]) assert.throws(()=>validate('MOTOR_HOMING',{...defaults,...invalid}))
|
||||
for (const invalid of [{method:0},{fastSpeed:0},{fastSpeed:1.1},{slowSpeed:0.2},{slowSpeed:0},{acceleration:0},{timeoutSeconds:301},{timeoutSeconds:0},{timeoutMs:29999},{offset:7},{offset:NaN}]) assert.throws(()=>validate('MOTOR_HOMING',{...defaults,...invalid}))
|
||||
for(const key of Object.keys(defaults)) { const value={...defaults};delete value[key];assert.throws(()=>validate('MOTOR_HOMING',value)) }
|
||||
})
|
||||
|
||||
@ -9,7 +9,7 @@ export const WORKCELL_DEVICE_KIND = Object.freeze({ MOTOR: 10, SCANNER: 14 })
|
||||
const field = (name, label, input, options = {}) => ({
|
||||
name, label, type: 'input', input, required: true, disabled: true, ...options,
|
||||
})
|
||||
const timeout = () => field('timeoutMs', '超时(毫秒)', 60000, {
|
||||
const timeout = () => field('timeoutMs', '超时(毫秒)', 120000, {
|
||||
componentType: 'number', min: 1, max: 3600000, step: 1,
|
||||
})
|
||||
const unit = () => field('unit', '位置单位', 'DEGREE', {
|
||||
@ -57,7 +57,7 @@ const specs = [
|
||||
['MOTOR_SET_MODE', '设置模式', '仅设置模式;切换前先停止并去使能,再设置模式并使能', [field('mode', '控制模式', 1, { componentType: 'select', selectOptions: [{ value: 1, label: '轮廓位置' }, { value: 3, label: '轮廓速度' }] })]],
|
||||
['MOTOR_ENABLE', '使能', '新版接口以轮廓位置模式使能,不下发目标位置;速度控制由速度接口设置', []],
|
||||
['MOTOR_DISABLE', '去使能', '关闭驱动力;驱动确认不代表机械已停稳,也不是硬件急停', []],
|
||||
['MOTOR_MOVE', '轮廓位置控制', '按输出轴绝对位置定位,收到到位反馈后继续;0表示回到绝对零位', [
|
||||
['MOTOR_MOVE', '轮廓位置控制', '按输出轴绝对位置定位,范围为±1800°(弧度模式为±10π),收到到位反馈后继续;0表示回到绝对零位', [
|
||||
position(), unit(), number('velocity', '轮廓速度(所选单位/秒)', 15, 0.0001),
|
||||
number('acceleration', '加速度(所选单位/秒²)', 20, 0.0001),
|
||||
]],
|
||||
@ -75,7 +75,7 @@ const specs = [
|
||||
{...number('fastSpeed','搜索原点开关速度(弧度/秒)',0.105,0.0001),max:1},
|
||||
{...number('slowSpeed','搜索编码器零位信号速度(弧度/秒)',0.0105,0.0001),max:1},
|
||||
{...number('acceleration','回零加速度(弧度/秒²)',1,0.0001),max:1},
|
||||
{...number('timeoutSeconds','服务端等待时间(秒)',30,1),max:300},
|
||||
{...number('timeoutSeconds','服务端等待时间(秒)',120,1),max:300},
|
||||
{...number('offset','输出轴原点偏移(弧度)',0,-2*Math.PI),max:2*Math.PI,precision:undefined},
|
||||
]],
|
||||
]
|
||||
@ -132,7 +132,7 @@ export function createWorkcellNodeGroups(icons = {}) {
|
||||
...(op.method === 'POST' ? [field('requestJson', '扫描操作参数', JSON.stringify(op.key === 'FRAMEWORK_IMPORT' ? {} : op.defaultBody, null, 2))] : []),
|
||||
...(op.key === 'FRAMEWORK_IMPORT' ? [field('frameworkUrls', '框架文件URL', '', { type: 'quote', quote: [], quoteType: 'output' })] : []),
|
||||
...(op.key === 'TASK' ? [field('taskId', '设备任务编号', '')] : []),
|
||||
{ ...timeout(), input: op.waitTimeoutMs || 120000 },
|
||||
timeout(),
|
||||
],
|
||||
outputType: 'json',
|
||||
outputParams: scannerOutputs(op),
|
||||
@ -142,7 +142,7 @@ export function createWorkcellNodeGroups(icons = {}) {
|
||||
collapseTitle: '旋转底座',
|
||||
nodeList: specs.filter(([action]) => action.startsWith(`${family}_`)).map(([action, name, desc, params]) => ({
|
||||
icon: icons[family], name, desc, action, type: 'serviceNode', nodeType: 'EDGE',
|
||||
nodeParams: structuredClone([...params, { ...timeout(), input: action === 'MOTOR_HOMING' ? 40000 : 45000 }]), outputType: 'json',
|
||||
nodeParams: structuredClone([...params, timeout()]), outputType: 'json',
|
||||
outputParams: [output('driverAcknowledged', 'boolean', '驱动确认本次操作'),
|
||||
...(action === 'MOTOR_MOVE' ? [output('reachedTarget', 'boolean', '位置控制到位确认'), output('targetPosition', 'number', '本次目标位置,非实时测量位置'), output('unit', 'string', '本次目标位置单位')] : []),
|
||||
...(action === 'MOTOR_VELOCITY' ? [output('targetVelocity', 'number', '已下发的目标速度,不是实际速度'), output('unit', 'string', '本次目标速度单位'), output('motionCompleted', 'boolean', '固定false;速度接口不确认运动完成')] : []),
|
||||
|
||||
@ -1283,8 +1283,8 @@ export const SCANNER_OPERATIONS = [
|
||||
],
|
||||
"advanced": false,
|
||||
"upload": false,
|
||||
"note": "每1秒查询一次设备任务结果;仅 succeeded 判为成功,failed 立即失败。5秒内仍未取得明确终态则失败并结束流程,不重复提交开关命令。",
|
||||
"waitTimeoutMs": 5000,
|
||||
"note": "每1秒查询一次设备任务结果;仅 succeeded 判为成功,failed 立即失败。默认等待120秒,可在组件中调整;等待期内仍未取得明确终态则失败并结束流程,不重复提交开关命令。",
|
||||
"defaultWaitTimeoutMs": 120000,
|
||||
"pollIntervalMs": 1000
|
||||
},
|
||||
{
|
||||
|
||||
@ -58,6 +58,7 @@
|
||||
import { reactive, ref, watch, inject, onBeforeUnmount } from 'vue'
|
||||
import request from '@/cmvr/request'
|
||||
import { armTeachingRequest } from '@/cmvr/common/api/device/armTeaching'
|
||||
import { ARM_DEFAULT_WAIT_MS, ARM_REQUEST_TIMEOUT_MS } from '@/cmvr/common/utils/armTimeouts.mjs'
|
||||
import { coordinateLabel } from '@/cmvr/common/utils/armUserCoordinates.mjs'
|
||||
import {
|
||||
workflowCoordinateStep,
|
||||
@ -73,7 +74,7 @@ const props = defineProps({
|
||||
const emit = defineEmits(['busy-change', 'invalidated'])
|
||||
const api = inject('armCoordinateApi', armTeachingRequest)
|
||||
const readPose = inject('armCoordinatePoseReader', (params) =>
|
||||
request.get('/api/arm/getPose', { params, timeout: 30000 })
|
||||
request.get('/api/arm/getPose', { params, timeout: ARM_REQUEST_TIMEOUT_MS })
|
||||
)
|
||||
const settings = reactive({
|
||||
xMm: null,
|
||||
@ -208,7 +209,7 @@ async function stop() {
|
||||
generation++
|
||||
emit('invalidated')
|
||||
try {
|
||||
await api('stopMotion', { robotId: props.robotId, deviceId: props.deviceId, timeoutMs: 30000 })
|
||||
await api('stopMotion', { robotId: props.robotId, deviceId: props.deviceId, timeoutMs: ARM_DEFAULT_WAIT_MS })
|
||||
error.value = '停止接口已返回,请核对现场状态并重新应用坐标系后继续。'
|
||||
} catch (e) {
|
||||
error.value = '停止结果未确认:' + (e.message || '请核对现场')
|
||||
|
||||
@ -53,6 +53,7 @@ import { computed, onActivated, onDeactivated, onBeforeUnmount, ref, watch } fro
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import ArmPowerControls from './ArmPowerControls.vue'
|
||||
import { armTeachingRequest } from '@/cmvr/common/api/device/armTeaching'
|
||||
import { ARM_DEFAULT_WAIT_MS } from '@/cmvr/common/utils/armTimeouts.mjs'
|
||||
import { validateArmTeaching } from '@/cmvr/common/utils/armTeaching.mjs'
|
||||
import { armMotionReady, savedTrajectory, sameArmPosition } from '@/cmvr/common/utils/armTeachingSession.mjs'
|
||||
import { getOccupations, clearOccupation } from '@/api/lab/scan-task'
|
||||
@ -62,7 +63,7 @@ const readError = ref('')
|
||||
const powerBusy=ref(false)
|
||||
const confirmed = ref(false), busy = ref(''), stopping = ref(false), refreshing = ref(false), releasing = ref(false)
|
||||
const recordName = ref(`teach_${Date.now()}.csv`), frequency = ref(100), selectedFile = ref('')
|
||||
const speedRatio = ref(0.5), velocity = ref(0.3), acceleration = ref(0.5), jerk = ref(2), timeoutSeconds = ref(300)
|
||||
const speedRatio = ref(0.5), velocity = ref(0.3), acceleration = ref(0.5), jerk = ref(2), timeoutSeconds = ref(ARM_DEFAULT_WAIT_MS / 1000)
|
||||
const startFile = ref(''), startPosition = ref(null)
|
||||
let generation = 0, timer, active = true
|
||||
const common = () => ({ robotId: props.robotId, deviceId: props.deviceId })
|
||||
@ -103,7 +104,7 @@ onBeforeUnmount(() => { active = false; ++generation; clearTimeout(timer) })
|
||||
async function perform(operation) {
|
||||
if (!canControl.value) return
|
||||
if (['moveToTrajectoryStart', 'replayRecordedTrajectory'].includes(operation) && (!ready.value || !selectedFile.value || operation === 'replayRecordedTrajectory' && !atStart.value)) return
|
||||
const params = { ...common(), timeoutMs: 30000 }
|
||||
const params = { ...common(), timeoutMs: ARM_DEFAULT_WAIT_MS }
|
||||
const previousFile = listing.value?.recordingFile
|
||||
if (operation === 'startTrajectoryRecording') Object.assign(params, { fileName: recordName.value, samplingFrequencyHz: frequency.value })
|
||||
if (['moveToTrajectoryStart', 'replayRecordedTrajectory'].includes(operation)) Object.assign(params, { fileName: selectedFile.value, speedRatio: speedRatio.value, maxVelocity: velocity.value, maxAcceleration: acceleration.value, maxJerk: jerk.value, timeoutMs: timeoutSeconds.value * 1000 })
|
||||
@ -134,7 +135,7 @@ async function powerChanged(value) {
|
||||
async function stopMotion() {
|
||||
if (stopping.value || !props.robotId || !props.deviceId) return
|
||||
stopping.value = true; startFile.value = ''; startPosition.value = null
|
||||
try { await armTeachingRequest('stopMotion', { ...common(), timeoutMs: 30000 }); notice.value = '停止运动已返回;记录和示教模式需分别确认。'; await refresh() }
|
||||
try { await armTeachingRequest('stopMotion', { ...common(), timeoutMs: ARM_DEFAULT_WAIT_MS }); notice.value = '停止运动已返回;记录和示教模式需分别确认。'; await refresh() }
|
||||
catch (failure) { error.value = failure.message || '停止结果未确认,请核实现场' }
|
||||
finally { stopping.value = false }
|
||||
}
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
<template>
|
||||
<el-form label-position="top">
|
||||
<el-form label-position="top" :disabled="executing">
|
||||
<el-form-item label="机器人" required>
|
||||
<el-select v-model="robotId" filterable style="width: 100%" @change="loadDevices">
|
||||
<el-option v-for="item in robotOptions" :key="item.value" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="队列总超时(毫秒,自动计算)">
|
||||
<el-input :model-value="totalTimeoutMs == null ? '总超时超出范围,请调整步骤' : totalTimeoutMs === 0 ? '0(不限时)' : String(totalTimeoutMs)" readonly />
|
||||
<div class="single-queue-step__params">按步骤超时自动累加;0表示平台不限时,执行端需同时支持。</div>
|
||||
<el-input :model-value="totalTimeoutMs == null ? '总超时超出范围,请调整步骤' : totalTimeoutMs === 0 ? '0(执行端默认)' : String(totalTimeoutMs)" readonly />
|
||||
<div class="single-queue-step__params">默认每步60秒,自动累加;包含0时采用边端默认5分钟,总超时最多30分钟、最多100步。</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="动作标识(可选)">
|
||||
<el-input v-model="actionId" placeholder="留空时自动生成" />
|
||||
@ -44,28 +44,51 @@
|
||||
<el-input v-model="step.stepName" maxlength="50" show-word-limit placeholder="例如:移动到取料位" />
|
||||
</el-form-item>
|
||||
<el-form-item v-if="deviceKind(step.type)" label="执行设备" required>
|
||||
<el-select v-model="step.deviceId" filterable :loading="deviceLoading" style="width: 100%">
|
||||
<el-select v-model="step.deviceId" filterable :loading="deviceLoading" style="width: 100%" @change="assignStepDevice(step, $event)">
|
||||
<el-option v-for="device in devicesForStep(step)" :key="device.deviceId"
|
||||
:label="device.deviceName && device.deviceName !== device.deviceId ? `${device.deviceName} (${device.deviceId})` : device.deviceId"
|
||||
:value="device.deviceId" />
|
||||
</el-select>
|
||||
<div v-if="step.deviceSlotKey" class="single-queue-note">同一设备用途的步骤共用此选择。</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="步骤超时(毫秒,0表示不限时)"><el-input-number v-model="step.timeoutMs" :min="0" :max="2147483647" :precision="0" :step="1000" /></el-form-item>
|
||||
<template v-if="step.type === 'ARM_APPLY_USER_COORDINATE_SYSTEM'">
|
||||
<el-form-item label="应用坐标系" required>
|
||||
<div class="single-queue-coordinate">
|
||||
<el-select :model-value="step.params?.name || ''" filterable placeholder="读取当前机械臂已保存的坐标系" @update:model-value="selectCoordinate(step, $event)">
|
||||
<el-option v-for="row in coordinateState(step).rows" :key="row.name" :label="`${coordinateLabel(row.name)} · 版本 ${row.revision}`" :value="row.name" />
|
||||
<el-option v-if="step.params?.name && !coordinateState(step).rows.some(row => row.name === step.params.name)" :label="coordinateLabel(step.params.name)" :value="step.params.name" />
|
||||
</el-select>
|
||||
<el-button :loading="coordinateState(step).loading" :disabled="!robotId || !step.deviceId || deviceLoading" @click="loadCoordinates(step)">读取坐标系</el-button>
|
||||
</div>
|
||||
<div class="single-queue-note">仅查询当前执行机械臂,不会应用坐标系或执行运动。</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="坐标系版本">
|
||||
<el-checkbox :model-value="step.params?.expectedRevision === '0'" :disabled="isBuiltInCoordinate(step) || !coordinateState(step).rows.some(row => row.name === step.params?.name)" @update:model-value="selectLatestRevision(step, $event)">执行时使用最新版本</el-checkbox>
|
||||
<span class="single-queue-note">{{ step.params?.expectedRevision === '0' ? '运行时读取最新记录' : `固定版本 ${step.params?.expectedRevision || '未选择'}` }}</span>
|
||||
</el-form-item>
|
||||
<el-alert v-if="coordinateState(step).error" :title="coordinateState(step).error" type="warning" :closable="false" />
|
||||
</template>
|
||||
<el-form-item label="步骤超时(毫秒,0继承队列剩余时间)"><el-input-number v-model="step.timeoutMs" :min="0" :max="1800000" :precision="0" :step="1000" /></el-form-item>
|
||||
<div class="single-queue-step__params">{{ stepSummary(step) }}</div>
|
||||
<div v-if="armMotionUnitHint(step.type)" class="single-queue-step__params">{{ armMotionUnitHint(step.type) }}</div>
|
||||
<div v-if="isAppliedCoordinateMove(step)" class="single-queue-note">绝对目标沿用本队列前面的坐标系;单独执行时,会先应用同一机械臂最近的坐标系步骤。</div>
|
||||
</div>
|
||||
</el-form>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { computed, ref, watch, onBeforeUnmount } from 'vue'
|
||||
import { actionQueueTotalTimeout } from '@/cmvr/common/utils/actionQueueTimeout.mjs'
|
||||
import { armMotionUnitHint } from '@/cmvr/common/utils/armMotionUnits.mjs'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ArrowDown, ArrowUp, CopyDocument, VideoPlay } from '@element-plus/icons-vue'
|
||||
import { getRobotDevicesByRobotId } from '@/cmvr/common/api/resource/robot'
|
||||
import { DEVICE_KIND } from '@/cmvr/common/utils/robotDevice'
|
||||
import { copyActionQueueStep, getActionQueueStepName, moveActionQueueStep, toActionQueueExecutionSteps } from '@/cmvr/common/utils/actionQueue'
|
||||
import { armTeachingRequest } from '@/cmvr/common/api/device/armTeaching'
|
||||
import { userCoordinateCatalog } from '@/cmvr/common/utils/armCoordinateFrames.mjs'
|
||||
import { coordinateLabel } from '@/cmvr/common/utils/armUserCoordinates.mjs'
|
||||
import { copyActionQueueStep, getActionQueueStepName, moveActionQueueStep, toActionQueueExecutionSteps, validateActionQueueCoordinateParams, validateActionQueueCoordinateSequence, isAppliedCoordinateMove, actionQueueSingleExecutionSteps } from '@/cmvr/common/utils/actionQueue'
|
||||
import { requireStandaloneQueueSpeed } from '@/cmvr/common/utils/actionQueueSpeed.mjs'
|
||||
|
||||
/**
|
||||
* 组件输入配置,仅在当前单次动作队列运行表单内使用。
|
||||
@ -76,12 +99,13 @@ const props = defineProps({
|
||||
robotOptions: { type: Array, default: () => [] },
|
||||
initialRobotId: { type: String, default: '' },
|
||||
executingStepIndex: { type: Number, default: -1 },
|
||||
executing: { type: Boolean, default: false },
|
||||
})
|
||||
const emit = defineEmits(['execute-step'])
|
||||
|
||||
/** 动作类型到中文名称的映射,作用范围为当前组件的步骤标题展示。 */
|
||||
const labels = {
|
||||
DELAY: '等待', ARM_MOVE_J: '机械臂关节运动', ARM_MOVE_L: '机械臂直线运动',
|
||||
DELAY: '等待', ARM_MOVE_J: '机械臂关节运动', ARM_MOVE_L: '机械臂直线运动', ARM_MOVE_J_POSE: '机械臂末端位姿关节运动(MoveJ)', ARM_APPLY_USER_COORDINATE_SYSTEM: '应用坐标系',
|
||||
AGV_NAVIGATE_TO_POSE: '底盘导航到坐标', AGV_NAVIGATE_TO_STATION: '底盘导航到站点', AGV_FOLLOW_PATH: '底盘按路径导航',
|
||||
}
|
||||
/** 当前选中的机器人 ID,作用于设备查询、校验和最终运行请求。 */
|
||||
@ -96,6 +120,43 @@ const steps = ref([])
|
||||
const devices = ref([])
|
||||
/** 设备接口请求状态,仅控制当前组件设备选择框的加载效果。 */
|
||||
const deviceLoading = ref(false)
|
||||
const coordinateStates = ref({})
|
||||
let active = true
|
||||
let deviceGeneration = 0
|
||||
const coordinateState = (step) => coordinateStates.value[step.deviceId] || { rows: [], loading: false, error: '' }
|
||||
const assignStepDevice = (step, deviceId) => {
|
||||
step.deviceId = deviceId
|
||||
const binding = step.deviceSlotKey || step.deviceBindingKey
|
||||
if (binding) steps.value.forEach(item => {
|
||||
if ((item.deviceSlotKey || item.deviceBindingKey) === binding && deviceKind(item.type) === deviceKind(step.type)) item.deviceId = deviceId
|
||||
})
|
||||
}
|
||||
const isBuiltInCoordinate = (step) => ['__builtin_base__', '__builtin_tool__'].includes(step.params?.name)
|
||||
const selectCoordinate = (step, name) => {
|
||||
const record = coordinateState(step).rows.find(row => row.name === name)
|
||||
if (!record) return
|
||||
step.params = { name: record.name, expectedRevision: record.revision }
|
||||
}
|
||||
const selectLatestRevision = (step, latest) => {
|
||||
const record = coordinateState(step).rows.find(row => row.name === step.params?.name)
|
||||
if (record) step.params.expectedRevision = isBuiltInCoordinate(step) ? '1' : latest ? '0' : record.revision
|
||||
}
|
||||
const loadCoordinates = async (step) => {
|
||||
const currentRobot = robotId.value, currentDevice = step.deviceId
|
||||
if (!currentRobot || !currentDevice || coordinateState(step).loading) return
|
||||
coordinateStates.value[currentDevice] = { rows: [], loading: true, error: '' }
|
||||
const state = coordinateStates.value[currentDevice]
|
||||
try {
|
||||
const response = await armTeachingRequest('listUserCoordinateSystems', { robotId: currentRobot, deviceId: currentDevice }, { quiet: true })
|
||||
if (!active || currentRobot !== robotId.value || coordinateStates.value[currentDevice] !== state) return
|
||||
state.rows = userCoordinateCatalog(response.data).userCoordinates
|
||||
} catch (error) {
|
||||
if (active && currentRobot === robotId.value && coordinateStates.value[currentDevice] === state) state.error = error.message || '读取坐标系失败,请重试'
|
||||
} finally {
|
||||
state.loading = false
|
||||
}
|
||||
}
|
||||
onBeforeUnmount(() => { active = false; deviceGeneration += 1 })
|
||||
let runtimeKeySequence = 0
|
||||
const createRuntimeKey = () => `queue_runtime_${Date.now()}_${runtimeKeySequence += 1}`
|
||||
|
||||
@ -122,6 +183,7 @@ const devicesForStep = (step) => devices.value.filter((device) => Number(device.
|
||||
* 等待和站点导航使用易读文案,其余动作保留完整 JSON 信息。
|
||||
*/
|
||||
const stepSummary = (step) => {
|
||||
if (step.type === 'ARM_APPLY_USER_COORDINATE_SYSTEM') return `应用 ${coordinateLabel(step.params?.name || '未选择')} · ${step.params?.expectedRevision === '0' ? '执行时最新版本' : `固定版本 ${step.params?.expectedRevision || '未选择'}`}`
|
||||
if (step.type === 'DELAY') return `等待 ${step.params?.durationMs || 0} 毫秒`
|
||||
if (step.type === 'AGV_NAVIGATE_TO_STATION') return `站点 ${step.params?.stationId || '-'}`
|
||||
return JSON.stringify(step.params || {})
|
||||
@ -137,7 +199,7 @@ const initData = async () => {
|
||||
actionId.value = values.actionId || ''
|
||||
steps.value = JSON.parse(JSON.stringify(Array.isArray(values.steps) ? values.steps : [])).map((step, index) => ({
|
||||
...step,
|
||||
timeoutMs: Number(step.timeoutMs ?? 60000),
|
||||
timeoutMs: Number(step.timeoutMs ?? 120000),
|
||||
stepName: getActionQueueStepName(step, index),
|
||||
runtimeKey: createRuntimeKey(),
|
||||
}))
|
||||
@ -162,21 +224,25 @@ const copyStep = (index) => {
|
||||
* 接口返回后逐步按动作类型筛选设备,并默认选择第一个匹配项;finally 保证加载状态复位。
|
||||
*/
|
||||
const loadDevices = async (value) => {
|
||||
const generation = ++deviceGeneration
|
||||
// 机器人发生变化时,旧设备可能属于另一台机器人,必须整体清除以避免误提交。
|
||||
devices.value = []
|
||||
coordinateStates.value = {}
|
||||
deviceLoading.value = false
|
||||
steps.value.forEach((step) => { step.deviceId = '' })
|
||||
if (!value) return
|
||||
deviceLoading.value = true
|
||||
try {
|
||||
const response = await getRobotDevicesByRobotId(value)
|
||||
if (!active || generation !== deviceGeneration || value !== robotId.value) return
|
||||
devices.value = Array.isArray(response.data) ? response.data : []
|
||||
// 每个步骤独立按设备类型匹配;有候选项时预选首项,减少单一设备场景下的重复操作。
|
||||
steps.value.forEach((step) => {
|
||||
const options = devicesForStep(step)
|
||||
if (options.length) step.deviceId = options[0].deviceId
|
||||
if (options.length === 1) step.deviceId = options[0].deviceId
|
||||
})
|
||||
} finally {
|
||||
deviceLoading.value = false
|
||||
if (active && generation === deviceGeneration) deviceLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
@ -185,6 +251,7 @@ const loadDevices = async (value) => {
|
||||
* 依次检查机器人、队列非空及每个需要设备的步骤;首次失败即提示并终止,全部通过返回 true。
|
||||
*/
|
||||
const validate = () => {
|
||||
if (props.executing || deviceLoading.value) return false
|
||||
if (!robotId.value) return ElMessage.warning('请选择机器人'), false
|
||||
if (!steps.value.length) return ElMessage.warning('动作队列不能为空'), false
|
||||
try { actionQueueTotalTimeout(steps.value) } catch (e) { ElMessage.warning(e.message); return false }
|
||||
@ -195,11 +262,21 @@ const validate = () => {
|
||||
ElMessage.warning(`步骤 ${index + 1} 没有可用的执行设备`)
|
||||
return false
|
||||
}
|
||||
try {
|
||||
requireStandaloneQueueSpeed(step)
|
||||
if (step.type === 'ARM_APPLY_USER_COORDINATE_SYSTEM') validateActionQueueCoordinateParams(step.params)
|
||||
if (isAppliedCoordinateMove(step)) actionQueueSingleExecutionSteps(steps.value, index)
|
||||
} catch (error) {
|
||||
ElMessage.warning(`步骤 ${index + 1}:${error.message}`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
try { validateActionQueueCoordinateSequence(steps.value) } catch (error) { ElMessage.warning(error.message); return false }
|
||||
return true
|
||||
}
|
||||
|
||||
const validateStep = (index) => {
|
||||
if (props.executing || deviceLoading.value) return false
|
||||
if (!robotId.value) return ElMessage.warning('请选择机器人'), false
|
||||
const step = steps.value[index]
|
||||
if (!step) return ElMessage.warning('未找到要执行的步骤'), false
|
||||
@ -207,6 +284,14 @@ const validateStep = (index) => {
|
||||
ElMessage.warning(`步骤 ${index + 1} 没有可用的执行设备`)
|
||||
return false
|
||||
}
|
||||
try {
|
||||
const selected = actionQueueSingleExecutionSteps(steps.value, index)
|
||||
actionQueueTotalTimeout(selected)
|
||||
for (const item of selected) if (item.type === 'ARM_APPLY_USER_COORDINATE_SYSTEM') validateActionQueueCoordinateParams(item.params)
|
||||
} catch (error) {
|
||||
ElMessage.warning(error.message)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@ -219,13 +304,13 @@ const getPayload = () => ({
|
||||
})
|
||||
|
||||
const getStepPayload = (index) => {
|
||||
const step = steps.value[index]
|
||||
const stepTimeoutMs = actionQueueTotalTimeout(step ? [step] : [])
|
||||
const selected = actionQueueSingleExecutionSteps(steps.value, index)
|
||||
const stepTimeoutMs = actionQueueTotalTimeout(selected)
|
||||
return {
|
||||
robotId: robotId.value,
|
||||
actionId: '',
|
||||
totalTimeoutMs: stepTimeoutMs,
|
||||
steps: toActionQueueExecutionSteps(step ? [step] : []),
|
||||
steps: toActionQueueExecutionSteps(selected),
|
||||
}
|
||||
}
|
||||
|
||||
@ -284,4 +369,7 @@ defineExpose({ validate, validateStep, getPayload, getStepPayload, getRobotId })
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.single-queue-coordinate { display: flex; width: 100%; gap: 8px; }
|
||||
.single-queue-coordinate .el-select { flex: 1; min-width: 0; }
|
||||
.single-queue-note { width: 100%; color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.6; white-space: normal; }
|
||||
</style>
|
||||
|
||||
@ -31,7 +31,7 @@
|
||||
|
||||
<div class="node-list">
|
||||
<div
|
||||
v-for="node in filterNodeList(item.nodeList)"
|
||||
v-for="node in item.nodeList"
|
||||
:key="`${node.type}-${node.action || node.name}`"
|
||||
class="node-item"
|
||||
draggable="true"
|
||||
@ -55,17 +55,17 @@
|
||||
<script setup>
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { Rank, Search } from "@element-plus/icons-vue";
|
||||
import { collapseList } from "../config";
|
||||
import { componentLibraryGroups } from "../config";
|
||||
|
||||
const props = defineProps({ flowId: String })
|
||||
|
||||
const keyword = ref("");
|
||||
const activeNames = ref(collapseList[0] ? [collapseList[0].collapseTitle] : []);
|
||||
const totalCount = computed(() => collapseList.reduce((total, group) => total + group.nodeList.length, 0));
|
||||
const activeNames = ref(componentLibraryGroups[0] ? [componentLibraryGroups[0].collapseTitle] : []);
|
||||
const totalCount = computed(() => componentLibraryGroups.reduce((total, group) => total + group.nodeList.length, 0));
|
||||
const filteredGroups = computed(() => {
|
||||
const query = keyword.value.trim().toLowerCase();
|
||||
if (!query) return collapseList;
|
||||
return collapseList
|
||||
if (!query) return componentLibraryGroups;
|
||||
return componentLibraryGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
nodeList: group.nodeList.filter((node) => (
|
||||
@ -81,13 +81,6 @@ watch(keyword, (value) => {
|
||||
if (value.trim()) activeNames.value = filteredGroups.value.map((group) => group.collapseTitle);
|
||||
});
|
||||
|
||||
const filterNodeList = (nodeList) => {
|
||||
return nodeList.filter((node) => {
|
||||
if (node.show === undefined) return true;
|
||||
return node.show;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 处理 handleDragCustom 对应的数据或交互;作用范围仅限当前组件或模块。
|
||||
* @param {*} event 触发操作的浏览器事件
|
||||
|
||||
@ -8,8 +8,8 @@
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="队列总超时(毫秒,自动计算)">
|
||||
<el-input :model-value="queueTimeoutMs == null ? '总超时超出范围,请调整步骤' : queueTimeoutMs === 0 ? '0(不限时)' : String(queueTimeoutMs)" readonly />
|
||||
<div class="queue-editor__hint">按各步骤超时自动累加;任一步为0时,平台不限时。执行端需同时支持0值不限时。</div>
|
||||
<el-input :model-value="queueTimeoutMs == null ? '总超时超出范围,请调整步骤' : queueTimeoutMs === 0 ? '0(边端默认超时)' : String(queueTimeoutMs)" readonly />
|
||||
<div class="queue-editor__hint">默认每步120秒并自动累加;包含0时采用边端默认5分钟,最多100步、总超时最多30分钟。队列完成后显示执行结果。</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="动作标识(可选)">
|
||||
<el-input v-model="formData.actionId" placeholder="留空时执行端自动生成" />
|
||||
@ -19,7 +19,7 @@
|
||||
<div class="queue-editor__toolbar">
|
||||
<div>
|
||||
<div class="queue-editor__heading">动作步骤</div>
|
||||
<div class="queue-editor__hint">步骤会在边缘端严格按顺序执行。</div>
|
||||
<div class="queue-editor__hint">步骤按顺序执行,失败即停止。可先应用坐标系,再填写该坐标系下的绝对目标位姿。</div>
|
||||
</div>
|
||||
<el-button type="primary" plain @click="addStep"><el-icon><Plus /></el-icon>添加步骤</el-button>
|
||||
</div>
|
||||
@ -83,21 +83,55 @@
|
||||
</el-select>
|
||||
<div v-if="!matchingSlots(step.type).length" class="queue-editor__warning">当前角色没有对应设备用途。</div>
|
||||
</el-form-item>
|
||||
<template v-if="step.type === QUEUE_APPLY_COORDINATE">
|
||||
<ArmWorkflowCoordinateSelect
|
||||
:model-value="{ name: step.params.name, revision: step.selectedRevision || step.params.expectedRevision }"
|
||||
@selected="(row) => selectCoordinate(step, row)"
|
||||
@read-target-change="step.readTarget = $event"
|
||||
/>
|
||||
<el-form-item v-if="step.params.name && !String(step.params.name).startsWith('__builtin_')" label="使用版本">
|
||||
<el-radio-group :model-value="step.params.expectedRevision === '0' ? 'latest' : 'fixed'" @update:model-value="(mode) => changeCoordinateVersion(step, mode)">
|
||||
<el-radio-button value="fixed" :disabled="!step.selectedRevision || step.selectedRevision === '0'">固定所选版本</el-radio-button>
|
||||
<el-radio-button value="latest">执行时取最新</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<p class="queue-editor__hint">仅应用已保存记录,不创建坐标系、不使能、不运动。应用计为一个步骤;队列结束后保持该坐标系,如需恢复请在末尾应用基座坐标系。</p>
|
||||
<p v-if="step.params.expectedRevision === '0' && step.params.name" class="queue-editor__warning">执行时使用最新记录;若坐标系被修改,后续绝对目标将按新记录解释。</p>
|
||||
</template>
|
||||
<template v-if="['ARM_MOVE_L','ARM_MOVE_J_POSE'].includes(step.type)">
|
||||
<p v-if="step.type === 'ARM_MOVE_J_POSE'" class="queue-editor__hint">{{ armMotionUnitHint(step.type) }}</p>
|
||||
<div v-if="isAppliedCoordinateMove(step)" class="queue-helper__tip">
|
||||
沿用同一机械臂前序已应用坐标系:{{ coordinateContextLabel(index) }}。目标为绝对位姿;RX/RY/RZ填0表示与参考系对齐,不表示保持姿态。
|
||||
</div>
|
||||
<div v-else class="queue-helper__tip">
|
||||
保留旧版单步参考系配置;目标值未转换。
|
||||
<el-button link type="primary" @click="useAppliedCoordinate(step)">改为沿用前序已应用坐标系</el-button>
|
||||
</div>
|
||||
</template>
|
||||
<div v-if="stepHelperLabel(step.type)" class="queue-step__helper">
|
||||
<el-button type="primary" plain :icon="Location" @click="openStepHelper(step)">
|
||||
{{ stepHelperLabel(step.type) }}
|
||||
</el-button>
|
||||
<el-button v-if="step.type === 'ARM_MOVE_L'" @click="openStepHelper(step, 'frames')">读取可用坐标系</el-button>
|
||||
<el-button v-if="step.type === 'ARM_MOVE_L' && !isAppliedCoordinateMove(step)" @click="openStepHelper(step, 'frames')">读取可用坐标系</el-button>
|
||||
</div>
|
||||
<p v-if="armMotionUnitHint(step.type)" class="queue-editor__hint">{{ armMotionUnitHint(step.type) }}</p>
|
||||
<el-form-item label="步骤超时(毫秒)">
|
||||
<el-input-number v-model="step.timeoutMs" :min="0" :max="2147483647" :precision="0" :step="1000" style="width: 100%" />
|
||||
<div class="queue-editor__hint">默认60000毫秒(60秒);0表示不限时。</div>
|
||||
<el-input-number v-model="step.timeoutMs" :min="0" :max="1800000" :precision="0" :step="1000" style="width: 100%" />
|
||||
<div class="queue-editor__hint">默认120000毫秒(120秒);0继承队列剩余总超时。</div>
|
||||
</el-form-item>
|
||||
<template v-for="field in fieldsForType(step)" :key="field.key">
|
||||
<el-form-item :label="field.label" :required="field.required !== false">
|
||||
<div v-if="field.key === 'velocity' && hasQueueArmSpeed(step.type)" class="queue-speed-source">
|
||||
<el-select v-model="step.speedSource.type" aria-label="速度来源" @change="step.speedSource.quote = []">
|
||||
<el-option label="输入" value="input" /><el-option label="引用" value="quote" />
|
||||
</el-select>
|
||||
<el-cascader v-if="step.speedSource.type === 'quote'" v-model="step.speedSource.quote"
|
||||
:options="quoteOptions" :props="{ checkStrictly: true }" placeholder="请选择上游速度"
|
||||
@visible-change="visibleChange" @change="value => cascaderChange(value, step.speedSource)" />
|
||||
<el-input-number v-else v-model="step.params.velocity" :min="field.min" :max="field.max ?? Infinity" :step="field.step || 0.01" />
|
||||
</div>
|
||||
<el-select
|
||||
v-if="field.key === 'stationId' && step.stationOptions?.length"
|
||||
v-else-if="field.key === 'stationId' && step.stationOptions?.length"
|
||||
v-model="step.params[field.key]"
|
||||
filterable
|
||||
style="width: 100%"
|
||||
@ -139,7 +173,8 @@
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<ArmFrameSelect v-if="helperStep?.type === 'ARM_MOVE_L'" v-model="helperFrames" :robot-id="helperForm.robotId" :device-id="helperForm.deviceId" @loaded="helperFrameCatalog = $event" />
|
||||
<ArmFrameSelect v-if="helperStep?.type === 'ARM_MOVE_L' && !isAppliedCoordinateMove(helperStep)" v-model="helperFrames" :robot-id="helperForm.robotId" :device-id="helperForm.deviceId" @loaded="helperFrameCatalog = $event" />
|
||||
<p v-if="isAppliedCoordinateMove(helperStep)" class="queue-helper__tip">读取前序坐标系 {{ coordinateContextLabel(formData.steps.indexOf(helperStep)) }} 下的实际TCP位姿,仅查询,不应用坐标系。</p>
|
||||
<template #footer>
|
||||
<el-button @click="helperDialogVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="helperSubmitting" @click="applyStepHelper">{{ helperMode === 'frames' ? '应用坐标系' : '确认读取' }}</el-button>
|
||||
@ -151,10 +186,14 @@
|
||||
<script setup>
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import { actionQueueTotalTimeout } from '@/cmvr/common/utils/actionQueueTimeout.mjs'
|
||||
import { useQuote } from './useQuote.js'
|
||||
import { hasQueueArmSpeed, queueSpeedSource, encodeQueueSpeed, queueSpeedValidationSteps, requireStandaloneQueueSpeed } from '@/cmvr/common/utils/actionQueueSpeed.mjs'
|
||||
import { armMotionParamLabel, armMotionUnitHint } from '@/cmvr/common/utils/armMotionUnits.mjs'
|
||||
import ArmFrameSelect from './ArmFrameSelect.vue'
|
||||
import { validateLinearCoordinate } from '@/cmvr/common/utils/armUserCoordinates.mjs'
|
||||
import { frameOptions, validateFrameChoice, poseFrameQuery } from '@/cmvr/common/utils/armCoordinateFrames.mjs'
|
||||
import ArmWorkflowCoordinateSelect from './ArmWorkflowCoordinateSelect.vue'
|
||||
import { coordinateLabel, validateLinearCoordinate } from '@/cmvr/common/utils/armUserCoordinates.mjs'
|
||||
import { armTeachingRequest } from '@/cmvr/common/api/device/armTeaching'
|
||||
import { frameOptions, validateFrameChoice, poseFrameQuery, poseFrameValues } from '@/cmvr/common/utils/armCoordinateFrames.mjs'
|
||||
import { ArrowDown, ArrowUp, CopyDocument, Delete, Location, MoreFilled, Plus, VideoPlay } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { getAgvStations, getAgvStatus, getArmJointState, getArmStatus } from '@/cmvr/common/api/flow/flow'
|
||||
@ -168,14 +207,22 @@ import {
|
||||
pruneUnusedNodeResources,
|
||||
} from '@/cmvr/common/utils/flowResources'
|
||||
import { DEVICE_KIND, toDeviceOptions } from '@/cmvr/common/utils/robotDevice'
|
||||
import { copyActionQueueStep, getActionQueueStepName, moveActionQueueStep } from '@/cmvr/common/utils/actionQueue'
|
||||
import {
|
||||
copyActionQueueStep, getActionQueueStepName, moveActionQueueStep,
|
||||
QUEUE_APPLY_COORDINATE, QUEUE_LEGACY_COORDINATE_FIELDS,
|
||||
isAppliedCoordinateMove, actionQueueCoordinateContext, actionQueueSingleExecutionSteps,
|
||||
validateActionQueueCoordinateParams, validateActionQueueCoordinateSequence,
|
||||
} from '@/cmvr/common/utils/actionQueue'
|
||||
|
||||
const props = defineProps({ data: { type: Object, required: true } })
|
||||
const emit = defineEmits(['save-success', 'save-error', 'extract-step'])
|
||||
const { quoteOptions, cascaderChange, visibleChange } = useQuote(props.data.id)
|
||||
|
||||
const actionTypes = [
|
||||
{ value: 'DELAY', label: '等待' },
|
||||
{ value: QUEUE_APPLY_COORDINATE, label: '应用坐标系' },
|
||||
{ value: 'ARM_MOVE_J', label: '机械臂关节运动' },
|
||||
{ value: 'ARM_MOVE_J_POSE', label: '机械臂末端位姿关节运动(MoveJ)' },
|
||||
{ value: 'ARM_MOVE_L', label: '机械臂直线运动' },
|
||||
{ value: 'AGV_NAVIGATE_TO_POSE', label: '底盘导航到坐标' },
|
||||
{ value: 'AGV_NAVIGATE_TO_STATION', label: '底盘导航到站点' },
|
||||
@ -189,6 +236,8 @@ const commonMotionFields = [
|
||||
const fieldsByType = {
|
||||
DELAY: [{ key: 'durationMs', label: '等待时长(毫秒)', number: true, min: 0 }],
|
||||
ARM_MOVE_J: [{ key: 'positions', label: '关节位置(JSON 数组)', multiline: true }, ...commonMotionFields],
|
||||
ARM_MOVE_J_POSE: [...['x','y','z','rx','ry','rz'].map(key=>({key,label:key.toUpperCase(),number:true})),
|
||||
...commonMotionFields.map(field=>({...field,required:true,min:0.000001}))],
|
||||
ARM_MOVE_L: [
|
||||
...['x', 'y', 'z', 'rx', 'ry', 'rz'].map((key) => ({ key, label: key.toUpperCase(), number: true })),
|
||||
{ key: 'frame', label: '坐标系', options: ['BASE', 'TOOL', 'WORLD', 'USER'].map((value) => ({ value, label: value })) },
|
||||
@ -217,19 +266,23 @@ const fieldsByType = {
|
||||
}
|
||||
const defaultParams = {
|
||||
DELAY: { durationMs: 1000 },
|
||||
[QUEUE_APPLY_COORDINATE]: { name: '', expectedRevision: '0' },
|
||||
ARM_MOVE_J: { positions: '[0, 0, 0, 0, 0, 0]', velocity: 0.1, acceleration: 0.2 },
|
||||
ARM_MOVE_L: { x: 0, y: 0, z: 0, rx: 0, ry: 0, rz: 0, frame: 'BASE', userCoordinateName:'',userCoordinateRevision:'',coordinateRelativeTranslation:false, velocity: 0.005, acceleration: 0.01 },
|
||||
AGV_NAVIGATE_TO_POSE: { x: 0, y: 0, theta: 0, maxSpeed: 0.5, blockedTimeoutMs: 60000 },
|
||||
AGV_NAVIGATE_TO_STATION: { stationId: '', maxSpeed: 0.5, blockedTimeoutMs: 60000 },
|
||||
AGV_FOLLOW_PATH: { path: '[]', maxSpeed: 0.5, blockedTimeoutMs: 60000 },
|
||||
ARM_MOVE_J_POSE: { x:null,y:null,z:null,rx:null,ry:null,rz:null,velocity:0.1,acceleration:0.5 },
|
||||
ARM_MOVE_L: { x: 0, y: 0, z: 0, rx: 0, ry: 0, rz: 0, velocity: 0.005, acceleration: 0.01 },
|
||||
AGV_NAVIGATE_TO_POSE: { x: 0, y: 0, theta: 0, maxSpeed: 0.5, blockedTimeoutMs: 120000 },
|
||||
AGV_NAVIGATE_TO_STATION: { stationId: '', maxSpeed: 0.5, blockedTimeoutMs: 120000 },
|
||||
AGV_FOLLOW_PATH: { path: '[]', maxSpeed: 0.5, blockedTimeoutMs: 120000 },
|
||||
}
|
||||
const defaultTimeoutByType = {
|
||||
DELAY: 60000,
|
||||
ARM_MOVE_J: 60000,
|
||||
ARM_MOVE_L: 60000,
|
||||
AGV_NAVIGATE_TO_POSE: 60000,
|
||||
AGV_NAVIGATE_TO_STATION: 60000,
|
||||
AGV_FOLLOW_PATH: 60000,
|
||||
DELAY: 120000,
|
||||
[QUEUE_APPLY_COORDINATE]: 120000,
|
||||
ARM_MOVE_J: 120000,
|
||||
ARM_MOVE_J_POSE: 120000,
|
||||
ARM_MOVE_L: 120000,
|
||||
AGV_NAVIGATE_TO_POSE: 120000,
|
||||
AGV_NAVIGATE_TO_STATION: 120000,
|
||||
AGV_FOLLOW_PATH: 120000,
|
||||
}
|
||||
|
||||
const roles = ref([])
|
||||
@ -245,6 +298,7 @@ const helperDeviceLoading = ref(false)
|
||||
const helperSubmitting = ref(false)
|
||||
const helperForm = reactive({ robotId: '', deviceId: '' })
|
||||
const fieldsForType = step => (fieldsByType[step.type] || [])
|
||||
.filter(field => !isAppliedCoordinateMove(step) || !QUEUE_LEGACY_COORDINATE_FIELDS.includes(field.key))
|
||||
.filter(field => field.key !== 'frame' || step.params.frame && step.params.frame !== 'BASE')
|
||||
.filter(field => !['baseFrame','tcpFrame'].includes(field.key) || Boolean(step.params[field.key]))
|
||||
.map(field => ({ ...field, label: armMotionParamLabel(step.type, field.key) || (field.key === 'frame' ? '参考系(旧版配置)' : field.label),
|
||||
@ -254,6 +308,7 @@ const deviceKindForType = (type) => type?.startsWith('ARM_') ? DEVICE_KIND.ARM :
|
||||
const stepHelperLabel = (type) => ({
|
||||
ARM_MOVE_J: '读取当前关节位置',
|
||||
ARM_MOVE_L: '读取当前末端位姿',
|
||||
ARM_MOVE_J_POSE: '读取所选坐标系当前位姿',
|
||||
AGV_NAVIGATE_TO_POSE: '读取底盘当前位置',
|
||||
AGV_NAVIGATE_TO_STATION: '加载底盘站点',
|
||||
}[type] || '')
|
||||
@ -270,6 +325,11 @@ const normalizeStep = (source = {}, index = 0) => {
|
||||
stepId: source.stepId || `step_${index + 1}`,
|
||||
stepName: String(source.stepName || '').trim() || `步骤 ${index + 1}`,
|
||||
type: source.type || 'DELAY',
|
||||
editingType: source.type || 'DELAY',
|
||||
motionLimits: {},
|
||||
speedSource: queueSpeedSource(source, props.data.properties?.nodeParams),
|
||||
...(source.coordinateMode ? { coordinateMode: source.coordinateMode } : {}),
|
||||
selectedRevision: source.params?.expectedRevision && source.params.expectedRevision !== '0' ? source.params.expectedRevision : '',
|
||||
timeoutMs: source.timeoutMs === undefined || source.timeoutMs === null
|
||||
? defaultTimeoutByType[source.type || 'DELAY']
|
||||
: Number(source.timeoutMs),
|
||||
@ -310,8 +370,8 @@ const ensureStepSlot = (step, createWhenMissing = true) => {
|
||||
if (!role) return
|
||||
const options = matchingSlots(step.type)
|
||||
if (options.some((slot) => slot.slotKey === step.deviceSlotKey)) return
|
||||
let slot = options[0]
|
||||
if (!slot && createWhenMissing) {
|
||||
let slot = options.length === 1 ? options[0] : null
|
||||
if (!slot && !options.length && createWhenMissing) {
|
||||
slot = createDeviceSlot(kind, role.deviceSlots || [])
|
||||
slot.managedBy = FLOW_NODE_RESOURCE_OWNER
|
||||
role.deviceSlots ||= []
|
||||
@ -346,13 +406,44 @@ const copyStep = (index) => {
|
||||
activeStepKeys.value = [...new Set([...activeStepKeys.value, copied.localKey])]
|
||||
}
|
||||
const handleStepTypeChange = (step) => {
|
||||
const previousType = step.editingType
|
||||
const previous = { ...step.params }
|
||||
step.motionLimits ||= {}
|
||||
if (['ARM_MOVE_L','ARM_MOVE_J_POSE'].includes(previousType))
|
||||
step.motionLimits[previousType] = { velocity:previous.velocity,acceleration:previous.acceleration }
|
||||
step.params = { ...(defaultParams[step.type] || {}) }
|
||||
step.speedSource = { type: 'input', quote: [] }
|
||||
if (['ARM_MOVE_L','ARM_MOVE_J_POSE'].includes(previousType) && ['ARM_MOVE_L','ARM_MOVE_J_POSE'].includes(step.type)) {
|
||||
for (const axis of ['x','y','z','rx','ry','rz']) step.params[axis] = previous[axis]
|
||||
Object.assign(step.params,step.motionLimits[step.type] || {})
|
||||
}
|
||||
step.editingType = step.type
|
||||
delete step.coordinateMode
|
||||
delete step.selectedRevision
|
||||
delete step.readTarget
|
||||
if (['ARM_MOVE_L','ARM_MOVE_J_POSE'].includes(step.type)) step.coordinateMode = 'APPLIED'
|
||||
step.timeoutMs = defaultTimeoutByType[step.type] || 0
|
||||
step.stationOptions = []
|
||||
ensureStepSlot(step)
|
||||
}
|
||||
const handleRoleChange = () => formData.steps.forEach((step) => ensureStepSlot(step))
|
||||
|
||||
const selectCoordinate = (step, row) => {
|
||||
step.params = validateActionQueueCoordinateParams({ name: row.name, expectedRevision: row.revision })
|
||||
step.selectedRevision = row.revision
|
||||
}
|
||||
const changeCoordinateVersion = (step, mode) => {
|
||||
step.params.expectedRevision = mode === 'latest' ? '0' : step.selectedRevision
|
||||
}
|
||||
const useAppliedCoordinate = (step) => {
|
||||
QUEUE_LEGACY_COORDINATE_FIELDS.forEach((key) => delete step.params[key])
|
||||
step.coordinateMode = 'APPLIED'
|
||||
}
|
||||
const coordinateContextLabel = (index) => {
|
||||
const context = actionQueueCoordinateContext(formData.steps, index)
|
||||
return context ? `${coordinateLabel(context.params.name)} · ${context.params.expectedRevision === '0' ? '执行时取最新' : `版本 ${context.params.expectedRevision}`}` : '尚未添加,请先为相同设备用途添加“应用坐标系”步骤'
|
||||
}
|
||||
|
||||
const loadHelperRobots = async () => {
|
||||
const response = await getRobotList({ pageNum: 1, pageSize: 1000, connectStatus: '1' })
|
||||
helperRobotOptions.value = (response.rows || []).map((robot) => ({
|
||||
@ -383,6 +474,12 @@ const openStepHelper = async (step, mode = 'position') => {
|
||||
helperMode.value = mode; helperFrameCatalog.value = null
|
||||
helperFrames.value = {baseFrame:step.params.baseFrame || '',tcpFrame:step.params.tcpFrame || '',userCoordinateName:step.params.userCoordinateName||'',userCoordinateRevision:step.params.userCoordinateRevision||'',coordinateRelativeTranslation:step.params.coordinateRelativeTranslation||false}
|
||||
helperStep.value = step
|
||||
const context = actionQueueCoordinateContext(formData.steps, formData.steps.indexOf(step))
|
||||
if (isAppliedCoordinateMove(step) && !context) {
|
||||
ElMessage.warning('请先为同一机械臂添加“应用坐标系”步骤')
|
||||
return
|
||||
}
|
||||
if (isAppliedCoordinateMove(step) && context?.readTarget?.robotId) helperForm.robotId = context.readTarget.robotId
|
||||
helperForm.deviceId = ''
|
||||
helperDialogVisible.value = true
|
||||
try {
|
||||
@ -413,7 +510,7 @@ const applyStepHelper = async () => {
|
||||
helperSubmitting.value = true
|
||||
try {
|
||||
const target = { robotId: helperForm.robotId, deviceId: helperForm.deviceId }
|
||||
if(step.type === 'ARM_MOVE_L') {
|
||||
if(step.type === 'ARM_MOVE_L' && !isAppliedCoordinateMove(step)) {
|
||||
validateFrameChoice(helperFrameCatalog.value,helperFrames.value,helperMode.value === 'frames')
|
||||
step.frameOptions = {baseFrame:frameOptions(helperFrameCatalog.value,'baseFrames'),tcpFrame:frameOptions(helperFrameCatalog.value,'tcpFrames')}
|
||||
if(helperMode.value === 'frames') {
|
||||
@ -426,15 +523,35 @@ const applyStepHelper = async () => {
|
||||
if (!Array.isArray(positions) || !positions.length) throw new Error('机械臂未返回有效的关节位置')
|
||||
step.params.positions = JSON.stringify(positions)
|
||||
ElMessage.success('已读取关节位置,单位为 rad')
|
||||
} else if (step.type === 'ARM_MOVE_L') {
|
||||
const response = await getArmStatus({...target,...poseFrameQuery(helperFrames.value,step.params.frame)})
|
||||
} else if (['ARM_MOVE_L','ARM_MOVE_J_POSE'].includes(step.type)) {
|
||||
const context = actionQueueCoordinateContext(formData.steps, formData.steps.indexOf(step))
|
||||
const inherited = isAppliedCoordinateMove(step)
|
||||
const coordinate = inherited ? validateActionQueueCoordinateParams(context?.params)
|
||||
: helperFrames.value.userCoordinateName ? { name: helperFrames.value.userCoordinateName, expectedRevision: helperFrames.value.userCoordinateRevision } : null
|
||||
const frameChoice = inherited ? { userCoordinateName: coordinate.name, userCoordinateRevision: coordinate.expectedRevision } : { ...helperFrames.value }
|
||||
const legacyFrame = inherited ? 'BASE' : step.params.frame
|
||||
const query = poseFrameQuery(frameChoice, legacyFrame)
|
||||
if (coordinate) {
|
||||
const record = await armTeachingRequest('getUserCoordinateSystem', {...target,...coordinate})
|
||||
if (record.data?.coordinate?.name !== coordinate.name || (coordinate.expectedRevision !== '0' && record.data.coordinate.revision !== coordinate.expectedRevision))
|
||||
throw new Error('前序坐标系名称或版本已变化,请重新选择')
|
||||
}
|
||||
const response = await getArmStatus({...target,...query})
|
||||
const pose = response?.data
|
||||
if (!pose) throw new Error('机械臂未返回当前末端位姿')
|
||||
Object.assign(step.params,helperFrames.value)
|
||||
if (helperStep.value !== step || helperForm.robotId !== target.robotId || helperForm.deviceId !== target.deviceId)
|
||||
throw new Error('读取来源已变化,请重新读取')
|
||||
if (inherited) {
|
||||
const current = actionQueueCoordinateContext(formData.steps, formData.steps.indexOf(step))
|
||||
if (JSON.stringify(coordinate) !== JSON.stringify(validateActionQueueCoordinateParams(current?.params)))
|
||||
throw new Error('前序坐标系已变化,请重新读取')
|
||||
} else if (JSON.stringify(frameChoice) !== JSON.stringify(helperFrames.value)) {
|
||||
throw new Error('所选坐标系已变化,请重新读取')
|
||||
}
|
||||
const values = poseFrameValues(pose, frameChoice, legacyFrame)
|
||||
if (!inherited) Object.assign(step.params, frameChoice)
|
||||
Object.assign(step.params, values)
|
||||
ElMessage.success('已读取末端位姿:X/Y/Z 为 m,RX/RY/RZ 为 rad')
|
||||
;['x', 'y', 'z', 'rx', 'ry', 'rz'].forEach((key) => {
|
||||
if (pose[key] !== undefined && pose[key] !== null) step.params[key] = Number(pose[key])
|
||||
})
|
||||
} else if (step.type === 'AGV_NAVIGATE_TO_POSE') {
|
||||
const response = await getAgvStatus(target)
|
||||
const pose = response?.data?.pose
|
||||
@ -472,10 +589,12 @@ const parseJsonFields = (step) => {
|
||||
}
|
||||
}
|
||||
if(step.type==='ARM_MOVE_L')validateLinearCoordinate(params)
|
||||
if(step.type===QUEUE_APPLY_COORDINATE)return validateActionQueueCoordinateParams(params)
|
||||
return params
|
||||
}
|
||||
|
||||
const buildStandaloneStep = (step, index) => {
|
||||
requireStandaloneQueueSpeed(step)
|
||||
if (!step?.type) throw new Error(`步骤 ${index + 1} 未选择动作`)
|
||||
const params = parseJsonFields(step)
|
||||
fieldsForType(step).filter((field) => field.required !== false).forEach((field) => {
|
||||
@ -487,6 +606,8 @@ const buildStandaloneStep = (step, index) => {
|
||||
stepId: 'step_1',
|
||||
stepName: getActionQueueStepName(step, index),
|
||||
type: step.type,
|
||||
...(step.coordinateMode ? { coordinateMode: step.coordinateMode } : {}),
|
||||
deviceSlotKey: step.deviceSlotKey,
|
||||
timeoutMs: Number(step.timeoutMs || 0),
|
||||
params,
|
||||
}
|
||||
@ -495,8 +616,9 @@ const buildStandaloneStep = (step, index) => {
|
||||
const runStep = (index) => {
|
||||
try {
|
||||
const step = formData.steps[index]
|
||||
const executionStep = buildStandaloneStep(step, index)
|
||||
const stepTimeoutMs = actionQueueTotalTimeout([executionStep])
|
||||
const contextSteps = actionQueueSingleExecutionSteps(formData.steps, index)
|
||||
const executionSteps = contextSteps.map((item) => buildStandaloneStep(item, formData.steps.indexOf(step)))
|
||||
const stepTimeoutMs = actionQueueTotalTimeout(executionSteps)
|
||||
document.dispatchEvent(new CustomEvent('singleNodeExecution', {
|
||||
bubbles: false,
|
||||
cancelable: false,
|
||||
@ -508,7 +630,7 @@ const runStep = (index) => {
|
||||
nodeParams: [
|
||||
{ name: 'actionId', type: 'input', input: '', required: false },
|
||||
{ name: 'totalTimeoutMs', type: 'input', componentType: 'number', input: stepTimeoutMs, required: true },
|
||||
{ name: 'steps', type: 'input', input: [executionStep], required: true },
|
||||
{ name: 'steps', type: 'input', input: executionSteps, required: true },
|
||||
],
|
||||
},
|
||||
}))
|
||||
@ -520,6 +642,7 @@ const runStep = (index) => {
|
||||
const buildQueueDefinition = () => {
|
||||
if (!formData.executionTarget.roleKey) throw new Error('请选择执行机器人角色')
|
||||
if (!formData.steps.length) throw new Error('请添加至少一个动作步骤')
|
||||
const speedParameters = []
|
||||
const steps = formData.steps.map((step, index) => {
|
||||
if (!step.type) throw new Error(`步骤 ${index + 1} 未选择动作`)
|
||||
if (deviceKindForType(step.type) && !step.deviceSlotKey) throw new Error(`步骤 ${index + 1} 未选择设备用途`)
|
||||
@ -527,21 +650,27 @@ const buildQueueDefinition = () => {
|
||||
fieldsForType(step).filter((field) => field.required !== false).forEach((field) => {
|
||||
if (params[field.key] === '' || params[field.key] == null) throw new Error(`步骤 ${index + 1} 的${field.label}不能为空`)
|
||||
})
|
||||
const speed = encodeQueueSpeed(step, params)
|
||||
if (speed.parameter) speedParameters.push(speed.parameter)
|
||||
return {
|
||||
stepId: `step_${index + 1}`,
|
||||
stepName: String(step.stepName || '').trim() || `步骤 ${index + 1}`,
|
||||
type: step.type,
|
||||
...(step.coordinateMode ? { coordinateMode: step.coordinateMode } : {}),
|
||||
timeoutMs: Number(step.timeoutMs || 0),
|
||||
...(deviceKindForType(step.type) ? {
|
||||
deviceBindingKey: step.deviceBindingKey,
|
||||
deviceSlotKey: step.deviceSlotKey,
|
||||
} : {}),
|
||||
...(step.sourceNode ? { sourceNode: JSON.parse(JSON.stringify(step.sourceNode)) } : {}),
|
||||
params,
|
||||
params: speed.params,
|
||||
...(speed.paramBindings ? { paramBindings: speed.paramBindings } : {}),
|
||||
}
|
||||
})
|
||||
validateActionQueueCoordinateSequence(queueSpeedValidationSteps(steps))
|
||||
return {
|
||||
steps,
|
||||
speedParameters,
|
||||
executionTarget: {
|
||||
roleKey: formData.executionTarget.roleKey,
|
||||
dispatchPolicy: 'ONE',
|
||||
@ -553,7 +682,7 @@ const buildQueueDefinition = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const persistQueueDefinition = ({ steps, executionTarget }) => {
|
||||
const persistQueueDefinition = ({ steps, executionTarget, speedParameters }) => {
|
||||
lf.setProperties(props.data.id, {
|
||||
...props.data.properties,
|
||||
executionTarget,
|
||||
@ -561,6 +690,7 @@ const persistQueueDefinition = ({ steps, executionTarget }) => {
|
||||
{ name: 'actionId', type: 'input', input: formData.actionId, required: false },
|
||||
{ name: 'totalTimeoutMs', type: 'input', componentType: 'number', input: actionQueueTotalTimeout(steps), required: true },
|
||||
{ name: 'steps', type: 'input', input: steps, required: true },
|
||||
...speedParameters,
|
||||
],
|
||||
})
|
||||
}
|
||||
@ -597,6 +727,9 @@ defineExpose({ validateAndSave })
|
||||
|
||||
<style scoped lang="scss">
|
||||
.queue-editor { padding-top: 16px; }
|
||||
.queue-speed-source { display: flex; gap: 8px; width: 100%; }
|
||||
.queue-speed-source > .el-select { width: 90px; flex-shrink: 0; }
|
||||
.queue-speed-source > :last-child { flex: 1; min-width: 0; }
|
||||
.queue-editor__heading { color: var(--el-text-color-regular); font-size: 14px; font-weight: 650; }
|
||||
.queue-editor__hint { margin-top: 3px; color: var(--el-text-color-secondary); font-size: 12px; }
|
||||
.queue-editor__toolbar { display: flex; margin: 14px 0 12px; align-items: center; justify-content: space-between; }
|
||||
|
||||
@ -1,17 +1,17 @@
|
||||
<template>
|
||||
<div class="arm-frame-select">
|
||||
<p class="frame-tip"
|
||||
>仅使用新版用户坐标系记录;先选择,再在运动前连接“应用用户坐标系”节点。此处不会调用旧命名坐标系接口。</p
|
||||
>选择读取当前TCP位姿时使用的参考坐标系。这里只查询,不会应用坐标系或执行运动;运行前仍需通过“应用用户坐标系”节点应用同一记录。</p
|
||||
>
|
||||
<el-form label-position="top">
|
||||
<el-form-item label="服务端用户坐标系(仅选择,不自动应用)"
|
||||
<el-form-item label="参考坐标系(仅选择,不自动应用)"
|
||||
><el-select
|
||||
:model-value="modelValue.userCoordinateName || ''"
|
||||
:empty-values="[null, undefined]"
|
||||
:disabled="loading || !catalog?.userCoordinates"
|
||||
:disabled="disabled || loading || !catalog?.userCoordinates"
|
||||
style="width: 100%"
|
||||
@update:model-value="selectCoordinate"
|
||||
><el-option value="" label="不指定,沿用边端当前参考系(旧用例兼容)" /><el-option
|
||||
><el-option value="" label="未选择,按基座坐标读取(旧用例兼容)" /><el-option
|
||||
v-for="c in catalog?.userCoordinates || []"
|
||||
:key="c.name"
|
||||
:value="c.name"
|
||||
@ -21,8 +21,9 @@
|
||||
>已选择版本
|
||||
{{
|
||||
modelValue.userCoordinateRevision
|
||||
}}。请在运动前连接“应用用户坐标系”节点;版本变化或服务重连后重新查询并应用。获取实际位姿始终返回基座下TCP;当前工具坐标系的绝对目标分支仍按当前TCP下的位姿增量解释。</p
|
||||
}}。读取结果为该参考系下的实际TCP位姿(位置m、姿态rad),不是坐标系定义或位移增量。版本变化或服务重连后,需重新查询并应用后再运行。</p
|
||||
>
|
||||
<p v-if="modelValue.userCoordinateName === '__builtin_tool__'" class="frame-tip">工具参考系使用最近一次应用时冻结的TCP坐标系;需先应用该记录,读取操作不会自动应用。</p>
|
||||
</el-form>
|
||||
<el-alert
|
||||
v-if="modelValue.baseFrame || modelValue.tcpFrame"
|
||||
@ -34,7 +35,7 @@
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
:disabled="!robotId || !deviceId"
|
||||
:disabled="disabled || !robotId || !deviceId"
|
||||
:loading="loading"
|
||||
@click="load"
|
||||
>重新读取坐标系</el-button
|
||||
@ -48,6 +49,7 @@ import { armTeachingRequest } from '@/cmvr/common/api/device/armTeaching'
|
||||
const props = defineProps({
|
||||
robotId: String,
|
||||
deviceId: String,
|
||||
disabled: { type: Boolean, default: false },
|
||||
modelValue: { type: Object, default: () => ({}) }
|
||||
})
|
||||
const emit = defineEmits(['update:modelValue', 'loaded'])
|
||||
@ -57,7 +59,9 @@ const catalog = ref(null),
|
||||
const coordinateLabel = (name) =>
|
||||
name === '__builtin_base__' ? '内置基座' : name === '__builtin_tool__' ? '内置工具' : name
|
||||
function selectCoordinate(name) {
|
||||
if (props.disabled || loading.value) return
|
||||
const c = catalog.value?.userCoordinates?.find((c) => c.name === name)
|
||||
if (name && !c) return
|
||||
emit('update:modelValue', {
|
||||
...props.modelValue,
|
||||
userCoordinateName: name,
|
||||
@ -68,6 +72,7 @@ function selectCoordinate(name) {
|
||||
let generation = 0,
|
||||
active = true
|
||||
async function load() {
|
||||
if (props.disabled) return
|
||||
const token = ++generation
|
||||
catalog.value = null
|
||||
emit('loaded', null)
|
||||
@ -92,7 +97,24 @@ async function load() {
|
||||
if (active && token === generation) loading.value = false
|
||||
}
|
||||
}
|
||||
watch(() => [props.robotId, props.deviceId], load, { immediate: true })
|
||||
watch(() => [props.robotId, props.deviceId], () => {
|
||||
if (props.disabled) {
|
||||
++generation
|
||||
catalog.value = null
|
||||
loading.value = false
|
||||
emit('loaded', null)
|
||||
return
|
||||
}
|
||||
load()
|
||||
}, { immediate: true })
|
||||
watch(() => props.disabled, (disabled) => {
|
||||
if (disabled) {
|
||||
++generation
|
||||
loading.value = false
|
||||
} else if (!catalog.value) {
|
||||
load()
|
||||
}
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
active = false
|
||||
++generation
|
||||
|
||||
@ -39,7 +39,7 @@
|
||||
>
|
||||
<div class="teaching-field">
|
||||
<el-select
|
||||
v-if="data.properties?.action !== COORDINATE_STEP_ACTION"
|
||||
v-if="canReferenceArmParameter(data.properties?.action, param.name)"
|
||||
v-model="param.type"
|
||||
class="source"
|
||||
@change="() => handleTypeChange(param)"
|
||||
@ -128,6 +128,7 @@ import {
|
||||
COORDINATE_STEP_ACTION,
|
||||
usesCoordinateSelection,
|
||||
coordinateSelectionField,
|
||||
canReferenceArmParameter,
|
||||
setCoordinateSelection,
|
||||
normalizeWorkflowStepParams,
|
||||
absolutePoseInputs
|
||||
@ -147,7 +148,7 @@ const props = defineProps({ data: { type: Object, required: true } })
|
||||
const emit = defineEmits(['save-success', 'save-error', 'cancel'])
|
||||
const validateRequest = inject('armWorkflowValidate', validateArmTeachingRequest)
|
||||
const poseReader = inject('armWorkflowPoseReader', (params) =>
|
||||
request.get('/api/arm/getPose', { params, timeout: 30000 })
|
||||
request.get('/api/arm/getPose', { params, timeout: 130000 })
|
||||
)
|
||||
const coordinateReader = inject('armWorkflowCoordinateApi', armTeachingRequest)
|
||||
const readTarget = ref({}),
|
||||
|
||||
@ -22,8 +22,10 @@
|
||||
<div class="form__container">
|
||||
<p v-if="armMotionUnitHint(data.properties.action)" class="arm-unit-hint">{{ armMotionUnitHint(data.properties.action) }}</p>
|
||||
<el-button type="primary" v-if="hasDeviceDebugAction" size="small" @click="openRobotForm(props.data.properties.action)">{{ robotActionButtonText }}</el-button>
|
||||
<el-button v-if="isLinearArmAction(data.properties.action)" size="small" @click="openRobotForm(data.properties.action, 'frames')">选择机器人并读取坐标系</el-button>
|
||||
<ArmWorkflowCoordinateSelect v-if="isLinearArmAction(data.properties.action)" :key="data.id" :model-value="linearCoordinateChoice" @selected="selectLinearCoordinate" />
|
||||
<div v-if="isLinearArmAction(data.properties.action)" class="arm-coordinate-summary" role="note" aria-label="位姿坐标系">
|
||||
<span>位姿坐标系:</span><strong>{{ poseCoordinateSummary }}</strong>
|
||||
</div>
|
||||
<p v-if="isLinearArmAction(data.properties.action)" class="arm-unit-hint">通过上方按钮读取所选坐标系下的TCP位姿,仅查询,不会应用坐标系或执行运动。</p>
|
||||
<el-form :inline="true" :model="formData" :rules="rules" ref="dynamicFormRef" label-position="top"
|
||||
label-width="auto">
|
||||
<div v-for="(property, index) in formData.nodeParams" :key="index" v-show="!isLinearArmAction(data.properties.action) || !['baseFrame','tcpFrame','userCoordinateName','userCoordinateRevision'].includes(property.name)">
|
||||
@ -105,7 +107,7 @@
|
||||
<p v-if="armMotionUnitHint(robotFormAction)" class="arm-unit-hint">{{ armMotionUnitHint(robotFormAction) }}</p>
|
||||
<el-form ref="robotFormRef" :model="robotForm" :rules="robotFormRules" label-width="90px">
|
||||
<el-form-item label="机器人" prop="robotId">
|
||||
<el-select v-model="robotForm.robotId" filterable placeholder="请选择在线机器人"
|
||||
<el-select v-model="robotForm.robotId" filterable :disabled="positionReadBusy" placeholder="请选择在线机器人"
|
||||
style="width: 100%" @change="loadRobotDevices">
|
||||
<el-option v-for="item in robotOptions" :key="item.value"
|
||||
:label="item.label" :value="item.value" />
|
||||
@ -113,17 +115,17 @@
|
||||
</el-form-item>
|
||||
<el-form-item label="执行设备" prop="deviceId">
|
||||
<el-select v-model="robotForm.deviceId" filterable :loading="deviceLoading"
|
||||
:disabled="deviceOptions.length === 1" placeholder="请先选择机器人" style="width: 100%">
|
||||
:disabled="deviceOptions.length === 1 || positionReadBusy" placeholder="请先选择机器人" style="width: 100%">
|
||||
<el-option v-for="item in deviceOptions" :key="item.value"
|
||||
:label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
<div v-if="deviceOptions.length === 1" class="device-auto-hint">已自动匹配并锁定</div>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<ArmFrameSelect v-if="isLinearArmAction(robotFormAction)" v-model="helperFrames" :robot-id="robotForm.robotId" :device-id="robotForm.deviceId" @loaded="helperFrameCatalog = $event" />
|
||||
<ArmFrameSelect v-if="isLinearArmAction(robotFormAction)" v-model="helperFrames" :robot-id="robotForm.robotId" :device-id="robotForm.deviceId" :disabled="positionReadBusy" @loaded="helperFrameCatalog = $event" />
|
||||
<template #footer>
|
||||
<el-button @click="dialogVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="stationListLoading" @click="submitRobotForm">{{ helperMode === 'frames' ? '应用坐标系' : '确认读取' }}</el-button>
|
||||
<el-button type="primary" :loading="stationListLoading || positionReadBusy" :disabled="deviceLoading || positionReadBusy" @click="submitRobotForm">{{ helperMode === 'frames' ? '采用坐标系选择' : '确认读取' }}</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
@ -135,6 +137,7 @@ import FormItemRecursive from '../FormItemRecursive.vue'
|
||||
import RobotExecutionTarget from './RobotExecutionTarget.vue'
|
||||
import { useQuote } from './useQuote.js'
|
||||
import { getArmStatus, getArmJointState, getAgvStatus, getAgvStations } from '@/cmvr/common/api/flow/flow'
|
||||
import { armTeachingRequest } from '@/cmvr/common/api/device/armTeaching'
|
||||
import { getRobotList, getRobotDevicesByRobotId } from '@/cmvr/common/api/resource/robot'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { getDeviceKindForAction, toDeviceOptions } from '@/cmvr/common/utils/robotDevice'
|
||||
@ -142,22 +145,14 @@ import { actionRequiresDevice } from '@/cmvr/common/utils/flowResources'
|
||||
import { isWorkcellAction, validateWorkcellLiterals } from '@/cmvr/common/utils/scanMotorNodes.mjs'
|
||||
import { withArmMotionUnits, armMotionUnitHint } from '@/cmvr/common/utils/armMotionUnits.mjs'
|
||||
import ArmFrameSelect from './ArmFrameSelect.vue'
|
||||
import ArmWorkflowCoordinateSelect from './ArmWorkflowCoordinateSelect.vue'
|
||||
import { validateLinearCoordinate } from '@/cmvr/common/utils/armUserCoordinates.mjs'
|
||||
import { isLinearArmAction, withArmFrameParams, frameOptions, validateFrameChoice, poseFrameQuery } from '@/cmvr/common/utils/armCoordinateFrames.mjs'
|
||||
import { coordinateLabel, validateLinearCoordinate } from '@/cmvr/common/utils/armUserCoordinates.mjs'
|
||||
import { isLinearArmAction, withArmFrameParams, frameOptions, validateFrameChoice, poseFrameQuery, poseFrameValues } from '@/cmvr/common/utils/armCoordinateFrames.mjs'
|
||||
|
||||
const props = defineProps({
|
||||
data: Object
|
||||
})
|
||||
|
||||
const emit = defineEmits(['save-success', 'save-error'])
|
||||
const linearCoordinateChoice = computed(() => ({ name: formData.nodeParams.find(p=>p.name==='userCoordinateName' && p.type==='input')?.input || '', revision: formData.nodeParams.find(p=>p.name==='userCoordinateRevision' && p.type==='input')?.input || '' }))
|
||||
function selectLinearCoordinate(row) {
|
||||
for (const [name,input] of Object.entries({userCoordinateName:row.name,userCoordinateRevision:row.revision,baseFrame:'',tcpFrame:''})) {
|
||||
const param=formData.nodeParams.find(p=>p.name===name)
|
||||
if(param)Object.assign(param,{type:'input',input,quote:[],quoteType:undefined})
|
||||
}
|
||||
}
|
||||
|
||||
const formData = reactive({
|
||||
nodeParams: [],
|
||||
@ -165,6 +160,20 @@ const formData = reactive({
|
||||
executionTarget: {}
|
||||
})
|
||||
|
||||
// Show the frame saved with these target values, without querying or applying a device frame.
|
||||
const poseCoordinateSummary = computed(() => {
|
||||
const field = (name) => formData.nodeParams.find(param => param.name === name)
|
||||
const coordinate = field('userCoordinateName')
|
||||
if (coordinate?.type === 'quote') return '运行时引用,当前尚未确定'
|
||||
if (typeof coordinate?.input === 'string' && coordinate.input.trim()) {
|
||||
const revision = field('userCoordinateRevision')
|
||||
const version = revision?.type === 'quote' ? '版本由运行时引用确定'
|
||||
: revision?.input != null && revision.input !== '' ? `版本 ${revision.input}` : '版本未指定'
|
||||
return `${coordinateLabel(coordinate.input)} · ${version}`
|
||||
}
|
||||
return '未指定(沿用边端当前参考系)'
|
||||
})
|
||||
|
||||
const rules = reactive({})
|
||||
const outputRules = reactive({})
|
||||
const dynamicFormRef = ref()
|
||||
@ -358,6 +367,7 @@ const testRule = (property) => {
|
||||
return [
|
||||
{ required: true, message: '请输入参数值', trigger: 'blur' },
|
||||
{ validator: () => {
|
||||
if (formData.nodeParams.find(param => param.name === 'velocity')?.type === 'quote') return Promise.resolve()
|
||||
if (formData.nodeParams.find(param => param.name === 'acceleration')?.input > formData.nodeParams.find(param => param.name === 'velocity')?.input) {
|
||||
return Promise.resolve()
|
||||
} else {
|
||||
@ -372,6 +382,7 @@ const testRule = (property) => {
|
||||
return [
|
||||
{ required: true, message: '请输入参数值', trigger: 'blur' },
|
||||
{ validator: () => {
|
||||
if (formData.nodeParams.find(param => param.name === 'acceleration')?.type === 'quote') return Promise.resolve()
|
||||
if (formData.nodeParams.find(param => param.name === 'acceleration')?.input > formData.nodeParams.find(param => param.name === 'velocity')?.input) {
|
||||
return Promise.resolve()
|
||||
} else {
|
||||
@ -395,6 +406,7 @@ function applyFrameSelection() {
|
||||
}
|
||||
}
|
||||
const stationListLoading = ref(false)
|
||||
const positionReadBusy = ref(false)
|
||||
const POSITION_ACTIONS = ['AGV_MOVE_TO_POINT', 'ARM_MOVE_TO_POINT', 'ARM_MOVE_TO_J']
|
||||
const isRobotNode = computed(() => props.data.properties?.nodeType === 'EDGE')
|
||||
const hasDeviceDebugAction = computed(() => (
|
||||
@ -417,6 +429,7 @@ const robotDialogTitle = computed(() => {
|
||||
* 处理 submitRobotForm 对应的数据或交互;作用范围仅限当前组件或模块。
|
||||
*/
|
||||
const submitRobotForm = () => {
|
||||
if (positionReadBusy.value || stationListLoading.value) return
|
||||
if (isLinearArmAction(robotFormAction.value)) {
|
||||
if(helperMode.value !== 'frames' && formData.nodeParams.some(p => ['baseFrame','tcpFrame','userCoordinateName','userCoordinateRevision','coordinateRelativeTranslation'].includes(p.name) && p.type === 'quote')) {
|
||||
ElMessage.warning('坐标系正在引用上游,读取当前位置前请先明确本次使用的坐标系'); return
|
||||
@ -487,36 +500,7 @@ const submitRobotForm = () => {
|
||||
}
|
||||
})
|
||||
} else if (robotFormAction.value === 'ARM_MOVE_TO_POINT') {
|
||||
robotFormRef.value.validate(async (valid) => {
|
||||
if (valid) {
|
||||
try {
|
||||
const legacy = formData.nodeParams.find(p => p.name === 'frame')?.input || 'BASE'
|
||||
const response = await getArmStatus({ deviceId: robotForm.deviceId, robotId: robotForm.robotId, ...poseFrameQuery(helperFrames.value,legacy) })
|
||||
if (response && response.data) {
|
||||
applyFrameSelection()
|
||||
ElMessage.success('已读取末端位姿:X/Y/Z 为 m,RX/RY/RZ 为 rad')
|
||||
dialogVisible.value = false
|
||||
const { x, y, z, rx, ry, rz } = response.data
|
||||
const testMap = {
|
||||
x: x,
|
||||
y: y,
|
||||
z: z,
|
||||
rx: rx,
|
||||
ry: ry,
|
||||
rz: rz,
|
||||
}
|
||||
// 将获取到的位置信息设置到 formData 中
|
||||
formData.nodeParams.forEach(param => {
|
||||
if (testMap.hasOwnProperty(param.name)) {
|
||||
param.input = testMap[param.name]
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取位置信息失败:', error)
|
||||
}
|
||||
}
|
||||
})
|
||||
return readArmPosition()
|
||||
} else if (robotFormAction.value === 'ARM_MOVE_TO_J') {
|
||||
robotFormRef.value.validate(async (valid) => {
|
||||
if (valid) {
|
||||
@ -543,6 +527,42 @@ const submitRobotForm = () => {
|
||||
}
|
||||
}
|
||||
|
||||
async function readArmPosition() {
|
||||
if (positionReadBusy.value) return
|
||||
const nodeId = props.data.id
|
||||
const target = { robotId: robotForm.robotId, deviceId: robotForm.deviceId }
|
||||
const choice = { ...helperFrames.value }
|
||||
const legacy = formData.nodeParams.find(p => p.name === 'frame')?.input || 'BASE'
|
||||
positionReadBusy.value = true
|
||||
try {
|
||||
const valid = await robotFormRef.value.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
if (choice.userCoordinateName) {
|
||||
const record = await armTeachingRequest('getUserCoordinateSystem', {
|
||||
...target, name: choice.userCoordinateName, expectedRevision: choice.userCoordinateRevision
|
||||
}, { quiet: true })
|
||||
if (record.data?.coordinate?.name !== choice.userCoordinateName || record.data.coordinate.revision !== choice.userCoordinateRevision)
|
||||
throw new Error('坐标系名称或版本已变化,请重新读取列表并选择')
|
||||
}
|
||||
const response = await getArmStatus({ ...target, ...poseFrameQuery(choice, legacy) })
|
||||
if (!dialogVisible.value || nodeId !== props.data.id || robotFormAction.value !== props.data.properties.action
|
||||
|| target.robotId !== robotForm.robotId || target.deviceId !== robotForm.deviceId
|
||||
|| JSON.stringify(choice) !== JSON.stringify(helperFrames.value))
|
||||
throw new Error('读取来源或坐标系已变化,请重新读取;原目标未改变')
|
||||
const values = poseFrameValues(response?.data, choice, legacy)
|
||||
applyFrameSelection()
|
||||
formData.nodeParams.forEach(param => {
|
||||
if (Object.hasOwn(values, param.name)) Object.assign(param, { type: 'input', input: values[param.name], quote: [], quoteType: undefined })
|
||||
})
|
||||
dialogVisible.value = false
|
||||
ElMessage.success('已读取所选坐标系下的TCP位姿:X/Y/Z 为 m,RX/RY/RZ 为 rad;未执行运动')
|
||||
} catch (error) {
|
||||
ElMessage.error(error.message || '获取位置信息失败,原目标未改变')
|
||||
} finally {
|
||||
positionReadBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 toStationOptions 对应的数据或交互;作用范围仅限当前组件或模块。
|
||||
* @param {*} stations 站点集合
|
||||
@ -666,4 +686,6 @@ defineExpose({ validateAndSave })
|
||||
font-size: 12px;
|
||||
}
|
||||
.arm-unit-hint { margin: 10px 0 16px; color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.7; }
|
||||
.arm-coordinate-summary { display: flex; flex-wrap: wrap; gap: 4px; margin: 12px 0 6px; font-size: 12px; line-height: 1.7; color: var(--el-text-color-secondary); }
|
||||
.arm-coordinate-summary strong { color: var(--el-text-color-primary); font-weight: 600; overflow-wrap: anywhere; }
|
||||
</style>
|
||||
|
||||
@ -51,7 +51,7 @@
|
||||
<el-input v-if="task.type === 'input'" v-model="task.input" placeholder="32位设备任务编号" />
|
||||
<el-cascader v-else v-model="task.quote" :options="quoteOptions" :props="{ checkStrictly: true }" @visible-change="refreshQuoteOptions" @change="value => cascaderChange(value, task)" />
|
||||
</el-form-item>
|
||||
<el-form-item label="等待超时(毫秒)" required><el-input-number v-model="timeout.input" :min="1" :max="3600000" :precision="0" :disabled="!!operation?.waitTimeoutMs" /></el-form-item>
|
||||
<el-form-item label="等待超时(毫秒)" required><el-input-number v-model="timeout.input" :min="1" :max="3600000" :precision="0" /></el-form-item>
|
||||
</el-form>
|
||||
<el-alert v-if="operation?.note" :title="operation.note" type="info" :closable="false" />
|
||||
<div class="field-note">{{ operation?.key === 'SCAN_START' ? '本节点等待启动命令完成,随后设备持续采集;结束采集需要“暂停采集”节点。' : '控制操作会等待设备任务终态;等待超时不会撤销已受理的设备动作。' }}</div>
|
||||
@ -148,7 +148,6 @@ watch(() => [props.data.id, props.data.properties?.action], async () => {
|
||||
Object.assign(request, { type: 'input', input: JSON.stringify(operation.value?.defaultBody || {}, null, 2), quote: [] }, clone(parameters.find(p => p.name === 'requestJson') || {}))
|
||||
Object.assign(task, { type: 'input', input: '', quote: [] }, clone(parameters.find(p => p.name === 'taskId') || {}))
|
||||
Object.assign(timeout, { input: 120000 }, clone(parameters.find(p => p.name === 'timeoutMs') || {}))
|
||||
if (operation.value?.waitTimeoutMs) Object.assign(timeout, { type: 'input', input: operation.value.waitTimeoutMs, quote: [] })
|
||||
fieldBindings.value = clone(parameters.find(p => p.name === 'requestFields')?.children || []).filter(field => field.name !== 'confirm')
|
||||
legacy.value = parameters.some(p => ['planCode', 'jobId', 'format'].includes(p.name))
|
||||
rawMode.value = false
|
||||
|
||||
@ -126,7 +126,7 @@ const corpus_type = () => {
|
||||
}]
|
||||
}
|
||||
|
||||
export const collapseList = [
|
||||
const componentGroups = [
|
||||
...createWorkcellNodeGroups({ SCANNER: scannerSvg, MOTOR: motorSvg }),
|
||||
createArmTeachingGroup(videoSvg),
|
||||
{
|
||||
@ -386,7 +386,7 @@ function handler(params) {
|
||||
{ name: "x", type: "input", input: "", disabled: true },
|
||||
{ name: "y", type: "input", input: "", disabled: true },
|
||||
{ name: "theta", type: "input", input: "", disabled: true },
|
||||
{ name: "blockedTimeoutMs", type: "input", componentType: "number", input: 60000, min: 1, required: true, disabled: true },
|
||||
{ name: "blockedTimeoutMs", type: "input", componentType: "number", input: 120000, min: 1, required: true, disabled: true },
|
||||
],
|
||||
outputType: 'json'
|
||||
},
|
||||
@ -399,7 +399,8 @@ function handler(params) {
|
||||
nodeType: 'EDGE',
|
||||
nodeParams: [
|
||||
{ name: "stationId", type: "input", input: "", componentType: 'select', selectOptions: [], forceSelect: true, disabled: true },
|
||||
{ name: "blockedTimeoutMs", type: "input", componentType: "number", input: 60000, min: 1, required: true, disabled: true }
|
||||
{ name: "blockedTimeoutMs", type: "input", componentType: "number", input: 120000, min: 1, required: true, disabled: true },
|
||||
{ name: "waitTimeoutMs", label: "导航完成等待(毫秒)", type: "input", componentType: "number", input: 120000, min: 1, required: true, disabled: true }
|
||||
],
|
||||
outputType: 'json'
|
||||
},
|
||||
@ -429,7 +430,7 @@ function handler(params) {
|
||||
nodeType: 'EDGE',
|
||||
nodeParams: [
|
||||
{ name: "actionId", type: "input", input: "", required: false },
|
||||
{ name: "totalTimeoutMs", type: "input", componentType: 'number', input: 60000, required: true },
|
||||
{ name: "totalTimeoutMs", type: "input", componentType: 'number', input: 120000, required: true },
|
||||
{ name: "steps", type: "input", input: [], required: true },
|
||||
],
|
||||
outputParams: [
|
||||
@ -987,6 +988,30 @@ function handler(params) {
|
||||
},
|
||||
]
|
||||
|
||||
// 爱玛扫描项目仅调整组件库入口;完整定义保留供旧流程编辑、身份识别和图标恢复。
|
||||
if (__PROJECT_NAME__ === 'aima') {
|
||||
const arm = componentGroups.find((group) => group.collapseTitle === '机械臂示教与轨迹')
|
||||
const robot = componentGroups.find((group) => group.collapseTitle === '机器人')
|
||||
const utilities = componentGroups.find((group) => group.collapseTitle === '功能')
|
||||
arm.collapseTitle = arm.name = '机械臂'
|
||||
const isArmComponent = (node) => node.action?.startsWith('ARM_')
|
||||
|| ['VISION_LOCATE_TARGET', 'SYSTEM_EXECUTE_ACTION_QUEUE'].includes(node.action)
|
||||
arm.nodeList.unshift(...robot.nodeList.filter(isArmComponent))
|
||||
utilities.nodeList.push(...robot.nodeList.filter((node) => node.action === 'DEVICE_EXECUTE_JSON_COMMAND'))
|
||||
robot.nodeList = robot.nodeList.filter((node) => !isArmComponent(node) && node.action !== 'DEVICE_EXECUTE_JSON_COMMAND')
|
||||
robot.collapseTitle = robot.name = 'AGV'
|
||||
for (const node of robot.nodeList) if (!node.action?.startsWith('AGV_')) node.show = false
|
||||
const hiddenGroups = new Set(['相机', '音频', '大模型', '语音交互', '触控交互', 'AI评估', '闲聊'])
|
||||
for (const group of componentGroups) if (hiddenGroups.has(group.collapseTitle)) group.show = false
|
||||
}
|
||||
|
||||
export const collapseList = componentGroups
|
||||
// 搜索、数量和拖拽统一使用可见定义,避免隐藏分组仍出现或计入组件数量。
|
||||
export const componentLibraryGroups = collapseList
|
||||
.filter((group) => group.show !== false)
|
||||
.map((group) => ({ ...group, nodeList: group.nodeList.filter((node) => node.show !== false) }))
|
||||
.filter((group) => group.nodeList.length > 0)
|
||||
|
||||
// 自定义名称不覆盖组件身份,旧流程也按稳定动作标识识别组件库定义。
|
||||
for (const group of collapseList) for (const node of group.nodeList) {
|
||||
if (node.nodeParams) node.nodeParams = withArmFrameParams(node.action, withArmMotionUnits(node.action, node.nodeParams))
|
||||
|
||||
@ -248,6 +248,7 @@
|
||||
:robot-options="singleNodeRobotOptions"
|
||||
:initial-robot-id="singleNodeInitialRobotId"
|
||||
:executing-step-index="singleQueueStepExecutingIndex"
|
||||
:executing="singleNodeExecuting"
|
||||
@execute-step="executeActionQueueStep"
|
||||
/>
|
||||
<el-form
|
||||
@ -2349,6 +2350,7 @@ const execute = async () => {
|
||||
};
|
||||
|
||||
const executeActionQueueStep = async (index) => {
|
||||
if (singleNodeExecuting.value) return;
|
||||
if (!actionQueueSingleRunRef.value?.validateStep?.(index)) return;
|
||||
rememberSingleNodeRobot();
|
||||
singleNodeExecuting.value = true;
|
||||
|
||||
@ -1,33 +1,43 @@
|
||||
import axios from 'axios'
|
||||
import { rejectRequestFailure } from '@/config/axios/requestFailure.mjs'
|
||||
import { markAuthRequest, canRefreshRequest, isPlatformUnauthorized, replayAuthenticatedRequest, responseErrorEnvelope } from '@/config/axios/authReplay'
|
||||
export { isRelogin } from '@/config/axios/sessionExpired'
|
||||
import { ElLoading, ElMessage } from 'element-plus'
|
||||
import { saveAs } from 'file-saver'
|
||||
import { getAccessToken, getTenantId, getVisitTenantId } from '@/utils/auth'
|
||||
|
||||
/** CMVR keeps its AjaxResult/table contracts while sharing FreeScan authentication. */
|
||||
export const cmvrApiBase = `${import.meta.env.VITE_BASE_URL}/admin-api/cmvr`
|
||||
export const isRelogin = { show: false }
|
||||
const request = axios.create({ baseURL: cmvrApiBase, timeout: 60000 })
|
||||
const request = axios.create({ baseURL: cmvrApiBase, timeout: 130000 })
|
||||
request.interceptors.request.use((config) => {
|
||||
const token = getAccessToken()
|
||||
if (token) config.headers.Authorization = `Bearer ${token}`
|
||||
config.headers['tenant-id'] = getTenantId() ?? 1
|
||||
const visitTenantId = getVisitTenantId()
|
||||
if (visitTenantId) config.headers['visit-tenant-id'] = visitTenantId
|
||||
return config
|
||||
return markAuthRequest(config)
|
||||
})
|
||||
request.interceptors.response.use((response) => {
|
||||
if (response.config.responseType === 'blob' || response.config.responseType === 'arraybuffer') return response.data
|
||||
const result = response.data
|
||||
request.interceptors.response.use(async (response) => {
|
||||
const binary = response.config.responseType === 'blob' || response.config.responseType === 'arraybuffer'
|
||||
const envelope = binary ? await responseErrorEnvelope(response) : null
|
||||
const result = envelope ?? response.data
|
||||
if (isPlatformUnauthorized(result) && canRefreshRequest(response.config)) return replayAuthenticatedRequest(request, response.config)
|
||||
if (binary && (!envelope || envelope.code === 0 || envelope.code === 200)) return response.data
|
||||
if (result?.code != null && result.code !== 200 && result.code !== 0) {
|
||||
const error = new Error(result.msg || result.message || '请求失败')
|
||||
if (!(response.config as any).silentError) ElMessage.error(error.message)
|
||||
return Promise.reject(error)
|
||||
}
|
||||
return result
|
||||
}, (error) => rejectRequestFailure(error, (error) => {
|
||||
if (!error.config?.silentError) ElMessage.error(error.response?.data?.msg || error.message || 'CMVR 服务连接失败')
|
||||
}))
|
||||
}, async (error) => {
|
||||
if (error.response && canRefreshRequest(error.config)) {
|
||||
const envelope = await responseErrorEnvelope(error.response)
|
||||
if (isPlatformUnauthorized(envelope ?? error.response.data, error.response.status)) return replayAuthenticatedRequest(request, error.config)
|
||||
}
|
||||
return rejectRequestFailure(error, (error) => {
|
||||
if (!error.config?.silentError) ElMessage.error(error.response?.data?.msg || error.message || 'CMVR 服务连接失败')
|
||||
})
|
||||
})
|
||||
export async function download(url: string, params: Record<string, any>, filename: string, config = {}) {
|
||||
const loading = ElLoading.service({ text: '正在下载数据,请稍候' })
|
||||
try {
|
||||
|
||||
89
am-web/src/config/axios/authRefresh.ts
Normal file
89
am-web/src/config/axios/authRefresh.ts
Normal file
@ -0,0 +1,89 @@
|
||||
import axios from 'axios'
|
||||
import { config } from './config'
|
||||
import { AuthRefreshError, createAuthRefreshCoordinator } from './authRefreshCore.mjs'
|
||||
import { createIndexedDbLeaseStore, createRefreshLeaseLock } from './authRefreshLock.mjs'
|
||||
import {
|
||||
getAccessToken, getRefreshToken, getAuthSessionId, getTenantId, getVisitTenantId, setToken
|
||||
} from '@/utils/auth'
|
||||
import type { TokenType } from '@/api/login/types'
|
||||
|
||||
export { AuthRefreshError }
|
||||
export type AuthRefreshErrorCode = 'SESSION_CHANGED' | 'SESSION_EXPIRED' | 'REFRESH_FAILED'
|
||||
export type AuthSessionSnapshot = {
|
||||
sessionId: string | null
|
||||
tenantId: string | number | null
|
||||
visitTenantId: string | number | null
|
||||
accessToken: string | undefined
|
||||
refreshToken: string | undefined
|
||||
}
|
||||
|
||||
const tokenValue = (input: unknown) => typeof input === 'string' && input.trim() ? input : undefined
|
||||
export const getSessionSnapshot = (): AuthSessionSnapshot => ({
|
||||
sessionId: getAuthSessionId(),
|
||||
tenantId: getTenantId() ?? null,
|
||||
visitTenantId: getVisitTenantId() ?? null,
|
||||
accessToken: tokenValue(getAccessToken()),
|
||||
refreshToken: tokenValue(getRefreshToken())
|
||||
})
|
||||
|
||||
// No application response interceptor here: a failed renewal must never renew itself.
|
||||
const refreshHttp = axios.create({
|
||||
baseURL: config.base_url,
|
||||
timeout: config.request_timeout,
|
||||
withCredentials: false
|
||||
})
|
||||
const expiredMessages = new Set(['无效的刷新令牌', '刷新令牌已过期', '刷新令牌的客户端编号不正确'])
|
||||
|
||||
async function renew(snapshot: AuthSessionSnapshot): Promise<TokenType> {
|
||||
try {
|
||||
// Spring @RequestParam accepts form data; keep the refresh credential out of the URL.
|
||||
const response = await refreshHttp.post('/system/auth/refresh-token',
|
||||
new URLSearchParams({ refreshToken: snapshot.refreshToken! }), {
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'tenant-id': String(snapshot.tenantId ?? 1)
|
||||
}
|
||||
})
|
||||
const body = response.data
|
||||
if (body?.code === 401 || expiredMessages.has(body?.msg)) {
|
||||
throw new AuthRefreshError('SESSION_EXPIRED', '登录状态已过期,请重新登录')
|
||||
}
|
||||
if (body?.code !== 0) throw new AuthRefreshError('REFRESH_FAILED', '登录状态续期失败,请稍后重试')
|
||||
return body.data
|
||||
} catch (error) {
|
||||
if (error instanceof AuthRefreshError) throw error
|
||||
if (axios.isAxiosError(error)
|
||||
&& (error.response?.status === 401 || expiredMessages.has(error.response?.data?.msg))) {
|
||||
throw new AuthRefreshError('SESSION_EXPIRED', '登录状态已过期,请重新登录')
|
||||
}
|
||||
throw new AuthRefreshError('REFRESH_FAILED', '登录状态续期失败,请稍后重试')
|
||||
}
|
||||
}
|
||||
|
||||
const withLease = createRefreshLeaseLock({
|
||||
store: createIndexedDbLeaseStore(),
|
||||
waitMs: config.request_timeout,
|
||||
leaseMs: config.request_timeout + 15000
|
||||
})
|
||||
|
||||
async function runExclusive(snapshot: AuthSessionSnapshot, task: () => Promise<string>): Promise<string> {
|
||||
const key = `am-freescan:auth-refresh:${snapshot.tenantId ?? 1}:${snapshot.sessionId ?? 'legacy'}`
|
||||
if (typeof navigator === 'undefined' || !navigator.locks?.request) return withLease(key, task)
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), config.request_timeout)
|
||||
try {
|
||||
return await navigator.locks.request(key, { signal: controller.signal }, () => {
|
||||
clearTimeout(timer)
|
||||
return task()
|
||||
})
|
||||
} finally { clearTimeout(timer) }
|
||||
}
|
||||
|
||||
const coordinator = createAuthRefreshCoordinator({
|
||||
getSnapshot: getSessionSnapshot,
|
||||
refresh: renew,
|
||||
setTokens: (tokens: TokenType) => setToken(tokens, { refresh: true }),
|
||||
runExclusive
|
||||
})
|
||||
export const isSessionCurrent = (snapshot: AuthSessionSnapshot): boolean => coordinator.isSessionCurrent(snapshot)
|
||||
export const refreshAccessToken = (snapshot: AuthSessionSnapshot): Promise<string> => coordinator.refreshAccessToken(snapshot)
|
||||
84
am-web/src/config/axios/authRefreshCore.mjs
Normal file
84
am-web/src/config/axios/authRefreshCore.mjs
Normal file
@ -0,0 +1,84 @@
|
||||
export class AuthRefreshError extends Error {
|
||||
constructor(code, message) {
|
||||
super(message)
|
||||
this.name = 'AuthRefreshError'
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
const changed = () => new AuthRefreshError('SESSION_CHANGED', '登录账号或租户已变化,请重新提交本次操作')
|
||||
const expired = () => new AuthRefreshError('SESSION_EXPIRED', '登录状态已过期,请重新登录')
|
||||
const failed = () => new AuthRefreshError('REFRESH_FAILED', '登录状态续期失败,请稍后重试')
|
||||
const value = (input) => input == null ? '' : String(input)
|
||||
const present = (input) => typeof input === 'string' && input.trim().length > 0
|
||||
|
||||
/** Shared by both HTTP clients; only an explicit authentication rejection enters this coordinator. */
|
||||
export function createAuthRefreshCoordinator({ getSnapshot, refresh, setTokens, runExclusive = (_snapshot, task) => task() }) {
|
||||
let activeFlight = null
|
||||
const read = () => ({ ...getSnapshot() })
|
||||
const sameSession = (left, right) => Boolean(left && right
|
||||
&& value(left.sessionId) === value(right.sessionId)
|
||||
&& value(left.tenantId) === value(right.tenantId)
|
||||
&& value(left.visitTenantId) === value(right.visitTenantId))
|
||||
const isSessionCurrent = (snapshot) => sameSession(snapshot, read())
|
||||
const currentFor = (snapshot) => {
|
||||
const current = read()
|
||||
if (!sameSession(snapshot, current)) throw changed()
|
||||
if (!present(current.refreshToken)) throw expired()
|
||||
return current
|
||||
}
|
||||
const newerToken = (snapshot, current) => present(current.accessToken)
|
||||
&& current.accessToken !== snapshot.accessToken
|
||||
const assertTokens = (tokens) => {
|
||||
if (!tokens || !present(tokens.accessToken) || !present(tokens.refreshToken)) throw failed()
|
||||
}
|
||||
|
||||
const perform = async (snapshot) => {
|
||||
const attempt = currentFor(snapshot)
|
||||
if (newerToken(snapshot, attempt)) return attempt.accessToken
|
||||
try {
|
||||
const tokens = await refresh(attempt)
|
||||
const latest = currentFor(attempt)
|
||||
// Another tab may already have renewed this session. Never overwrite its credentials.
|
||||
if (latest.accessToken !== attempt.accessToken || latest.refreshToken !== attempt.refreshToken) {
|
||||
if (present(latest.accessToken)) return latest.accessToken
|
||||
throw changed()
|
||||
}
|
||||
assertTokens(tokens)
|
||||
setTokens(tokens)
|
||||
const saved = currentFor(attempt)
|
||||
if (saved.accessToken !== tokens.accessToken || saved.refreshToken !== tokens.refreshToken) throw changed()
|
||||
return saved.accessToken
|
||||
} catch (error) {
|
||||
const latest = currentFor(snapshot)
|
||||
if (newerToken(snapshot, latest)) return latest.accessToken
|
||||
if (error instanceof AuthRefreshError) throw error
|
||||
throw failed()
|
||||
}
|
||||
}
|
||||
|
||||
const refreshAccessToken = async (snapshot) => {
|
||||
const current = currentFor(snapshot)
|
||||
// A late 401 may belong to a request issued before the other client refreshed.
|
||||
if (newerToken(snapshot, current)) return current.accessToken
|
||||
if (!activeFlight || !sameSession(activeFlight.snapshot, snapshot)) {
|
||||
const flight = { snapshot: { ...snapshot }, promise: null }
|
||||
activeFlight = flight
|
||||
flight.promise = Promise.resolve()
|
||||
.then(() => runExclusive(flight.snapshot, () => perform(flight.snapshot)))
|
||||
.catch((error) => {
|
||||
// Lock acquisition errors and transport failures must reject every waiter too.
|
||||
if (error instanceof AuthRefreshError) throw error
|
||||
throw failed()
|
||||
})
|
||||
.finally(() => { if (activeFlight === flight) activeFlight = null })
|
||||
}
|
||||
const token = await activeFlight.promise
|
||||
const latest = currentFor(snapshot)
|
||||
if (present(latest.accessToken)) return latest.accessToken
|
||||
if (!present(token)) throw failed()
|
||||
return token
|
||||
}
|
||||
|
||||
return { isSessionCurrent, refreshAccessToken }
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user