feat: 结束标定并恢复

This commit is contained in:
zhanghao 2026-11-07 21:55:32 +08:00
parent ba0f749d40
commit 2ee35c4739
46 changed files with 1331 additions and 397 deletions

View File

@ -1,5 +1,12 @@
# AM FreeScan 开发约定
- 2026-11-06 用户要求移除扫描仪流程节点“已核对本次操作的目标和影响”及框架导入同类勾选项和对应的用户确认校验;已有流程中的 `confirm` 字段兼容忽略。供应商接口必需的固定 `confirm:true` 仅由 HTTP 适配层补齐,不再作为表单、发布或执行门槛;工程/会话、设备状态、停止回执和资源释放校验保持。
- 2026-11-06 用户进一步明确:本次及今后每次任务完成并验证通过后,主动删除该任务新增的测试源码(包括 `test.mjs`)、专用验证脚本、测试输入输出、验证报告、测试日志、测试编译产物及临时目录,不因属于自动化回归测试而默认永久保留,只保留任务实现、运行和维护所需的文件。项目原有回归测试、运行配置、凭据、来源指纹及明确要求保留的真实或演示数据不清理。当前进程占用的临时文件在进程正常退出后再清理,不为删除文件中断服务。
- 待释放文件:`.local/idea-launch-20261106/am-idea-bridge.jar`、`.local/idea-launch-20261106/am-idea-console-20261107.jar`、`.local/idea-launch-20261106/am-idea-console2-20261107.jar` 被当前 IDEA 加载并锁定,IDEA 正常退出、文件不再占用后删除,同时移除本条待清理记录。后两个文件用于本次重启后的 IDEA 控制台只读诊断。
- 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-10-29 用户明确要求机械臂示教/轨迹组件名及操作按钮使用中文;内部动作标识与RPC方法保留协议定义。组件使用原有QUIC发现的机器人和机械臂用途,不将文档示例IP自动登记为现场设备。真实录制、使能、运动仍不在自动验证中执行。
@ -10,12 +17,12 @@
- 2026-10-27 用户要求组件名称沿用提供的接口文档;旋转底座分组保持不变,五个组件为“设置模式、使能、去使能、轮廓位置控制、轮廓速度控制”。用户已授权必要时自动重启本项目前后端,包括 IDEA 启动的后端;优先保留其原有启动方式和环境配置,重启前核对活动执行,不中断正在进行的实体采集或运动。
- 只修改本项目。CMVR-AIMA、cmvr-iot-common、CMVR-IOT 来源项目保持只读。
- 用户要求:自动化回归测试代码保留;开发验证成功后,清理本次生成的业务测试用例、任务、执行日志、导入文件、输出文件和临时文件,不能留在业务页面中。
- 用户要求:项目原有自动化回归测试代码保留;每次任务新增的测试源码及专用验证脚本按上述要求清理;开发验证成功后,清理本次生成的业务测试用例、任务、执行日志、导入文件、输出文件和临时文件,不能留在业务页面中。
- 通过明确的验证批次前缀登记测试数据。优先执行 `scripts/cleanup_verification.py --prefix <本次前缀> --apply`,先结束运行中的任务并确认资源释放。不要用“名称包含 test”、创建时间或清空整表来判断测试数据。
- 若验证失败,保留必要诊断信息;修复并通过后必须完成清理。最终核对没有本轮测试数据及机器人占用残留。
- 用户明确要求的永久在线模拟机器人 `am-freescan-sim-robot` 和模拟设备 `am-freescan-sim-agv` 继续保留,除非用户另行要求删除。
- 2026-10-22 用户另行要求创建并保留两条全流程演示数据:前缀 `DEMO-20261022-091650`,任务 `T-20261022-0005`、`T-20261022-0006`,导入批次 `IB-20261022-0009`。对应测试用例、样品、夹具、技术资料、执行日志和输出均供用户查看,不纳入开发验证自动清理;清单见 `docs/full-flow-demo-20261022.json`。
- 不删除运行配置、凭据、来源指纹、实际业务数据或回归测试代码。不要输出 `.local/runtime.json` 中的敏感信息。
- 不删除运行配置、凭据、来源指纹、实际业务数据或项目原有回归测试代码。不要输出 `.local/runtime.json` 中的敏感信息。
- 2026-10-27 用户要求集成真实旋转底座,工位 `am-freescan-rotary-base-station-001` 已通过正常接口登记;设备永久标识 `aima_motor`,服务配置为 `192.168.0.203:50052`。该工位不是验证样例,不自动清理;不得用传输可达替代机械状态反馈,不在开发验证中自动使能或移动真实底座。
- 2026-10-23 用户要求保留真实扫描待运行数据:前缀 `REAL-SCAN-20261023-001`,任务 `T-20261023-0001`,导入批次 `IB-20261023-0001`;清单见 `docs/real-scan-ready-20261023.json`。对应样品、夹具预设、用例、流程版本及真实扫描工位 `am-freescan-station-001` / 设备 `am-freescan-scanner-001` 不纳入验证数据清理。准备脚本不能自动执行扫描,也不能代替用户确认实物与装夹。
- 上述真实任务的用户首次运行在 SDK 三维快照报 `scene_data_unavailable`,失败执行 `2113504832933294082` 保留;旧任务已停止并取消以释放占用。修正版为 `T-20261023-0002`(`REAL-SCAN-20261023-001-R1`,批次 `IB-20261023-0002`,流程 V3),增加独立 Trak 工程并在停止采集前请求快照,同样保留且不纳入验证清理。新任务必须重新由操作人确认收样与装夹,不能复制这些物理确认状态。

View File

@ -40,6 +40,10 @@
修改 Java 后执行 `./scripts/start-backend.ps1 -Build`。本机预启动的后台实例可先用 `./scripts/stop-backend.ps1` 停止;自行在终端启动的实例用 Ctrl+C 停止,避免端口占用。日志、凭据和成果位于 Git 忽略的 `.local/`;前端源码和后端源码分别位于 `am-web/`、`am-backend/`。
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` 配置继续保留。
本机已启用可删除的“模拟测试机器人(永久在线)”及“模拟AGV底盘(测试设备)”,用于验证原版流程与设备分配。测试用例为“【模拟测试】AGV导航流程”。启动、能力范围和删除方法见 [模拟机器人说明](docs/simulated-robot.md)。
### 新环境初始化
@ -70,6 +74,32 @@ cd ..
MySQL 开发账号为 `root`,Redis 当前使用逻辑库 `15`。开发环境账号密码已按用户要求保存为 `application-dev.yaml` 和 `application-local.yaml` 的默认值,仍可通过环境变量覆盖。迁移环境时先分配空闲 Redis 库,再修改本地配置;运行配置生成脚本仍通过环境变量提供密码,重新生成后如需保留默认值,应核对两个环境配置。
## 生产配置
`resources/application.yaml` 和 `application-prod.yaml` 是可提交、随 JAR 打包的配置模板;`${变量名}` 读取启动进程的环境变量,`${变量名:默认值}` 在未提供变量时使用默认值。`.local` 是本机覆盖、凭据、证书及运行文件目录,不上传 Git,也不会自动进入 JAR 或 Docker 镜像。部署新服务器时需要单独提供实际配置及证书;已有业务文件、数据库和 Redis 数据也需要单独持久化或迁移。
生产启动前,向 Java 进程或容器注入以下变量,密钥由部署系统提供,不写入可提交文件:
| 用途 | 环境变量 |
| --- | --- |
| MySQL(必填) | `AM_FREESCAN_DB_URL`(完整 JDBC URL)、`AM_FREESCAN_DB_USER`、`AM_FREESCAN_DB_PASSWORD` |
| Redis(必填) | `AM_FREESCAN_REDIS_HOST`、`AM_FREESCAN_REDIS_DATABASE`、`AM_FREESCAN_REDIS_PASSWORD`;`AM_FREESCAN_REDIS_PORT` 默认 `6379` |
| 扫描仪(使用时填写) | `AM_FREESCAN_SCANNER_HOST`、`AM_FREESCAN_SCANNER_PORT`、`AM_FREESCAN_SCANNER_API_KEY`(Bearer Token)、`AM_FREESCAN_SCANNER_ROBOT_ID`、`AM_FREESCAN_SCANNER_DEVICE_ID` |
| QUIC(使用时填写) | `CMVR_QUIC_ENABLED=true`、`CMVR_QUIC_TLS_CERTIFICATE`、`CMVR_QUIC_TLS_PRIVATE_KEY`;`CMVR_QUIC_PORT` 默认 UDP `4433`,`CMVR_QUIC_ALLOWED_NODE_IDS` 为逗号分隔的节点白名单 |
| QUIC 双向认证(可选) | `CMVR_QUIC_TLS_REQUIRE_CLIENT_CERTIFICATE=true`、`CMVR_QUIC_TLS_CLIENT_CA` |
| 对外地址 | `AM_FREESCAN_ADMIN_UI_URL` 为前端地址;`AM_FREESCAN_PUBLIC_BASE_URL` 为设备可访问的完整 `/open-api/lab/v1` 地址 |
| 文件持久化 | `LAB_ARTIFACT_NAS_ROOT` 为成果存储目录(默认 `./artifacts`);`LOGGING_FILE_NAME` 为后端日志文件(默认 `./logs/backend.log`) |
注入变量后,从任意部署目录启动:
```shell
java -jar yudao-server.jar --spring.profiles.active=prod
```
`prod` 不会自动读取 `.local`,也不会继承 `application-local.yaml` / `application-dev.yaml` 的开发数据库配置。扫描仪未配置时保持未配置状态;QUIC 默认关闭,启用后会校验证书与私钥文件。证书必须匹配生产地址,并将证书和私钥作为服务器文件或容器只读挂载文件提供,环境变量中填写路径,容器内路径以挂载目标为准。
也可以由部署系统生成外部 YAML(结构与上述模板一致),使用 `--spring.config.additional-location=file:/etc/am-freescan/application-private.yaml` 显式加载;该文件含密钥时不提交 Git。现有 `am-backend/docker-compose.yml` 用于本地环境,设置的是 `local` profile;生产容器应显式设置 `SPRING_PROFILES_ACTIVE=prod`,并注入上述变量、挂载证书及持久化目录。工作目录中存在 `.local` 时,单独使用 `prod` 也不会导入它。
## 验证
```powershell

View File

@ -7,7 +7,7 @@ public final class ScannerFixtureFrameworkBinding {
public static JSONObject apply(JSONObject input,JSONObject runParams){
if(runParams==null||!runParams.containsKey(PARAM))return input;
ScannerFrameworkReferences.sources(runParams.get(PARAM));
var result=new JSONObject(input);result.put("frameworkUrls",runParams.get(PARAM));result.put("requestJson","{\"confirm\":true}");
var result=new JSONObject(input);result.put("frameworkUrls",runParams.get(PARAM));result.put("requestJson","{}");
result.remove("requestFields");result.put("fixtureFrameworkVersion",runParams.get("fixtureFrameworkVersion"));return result;
}
}

View File

@ -65,7 +65,7 @@ public class ScannerFrameworkReferenceService {
files.addObject().put("sourceUrl",source.url()).put("sourceFileId",source.fileId()).put("fileId",receipt.path("fileId").asText())
.put("name",name).put("bytes",bytes.length).put("sha256",contentHash).put("reused",reused);
}
ObjectNode body=ScannerRequestValidator.JSON.createObjectNode().put("confirm",true);body.set("fileIds",ids);
ObjectNode body=ScannerRequestValidator.JSON.createObjectNode();body.set("fileIds",ids);
ScannerRequestValidator.validate(ScannerOperation.FRAMEWORK_IMPORT,body);
ObjectNode result=ScannerRequestValidator.JSON.createObjectNode();result.set("body",body);result.set("context",context);result.set("files",files);
journal.ready(planKey,result.toString());return prepared(result);

View File

@ -12,9 +12,8 @@ public final class ScannerFrameworkReferences {
private ScannerFrameworkReferences() {}
public static boolean usesReferences(JSONObject input) {return input.containsKey("frameworkUrls");}
public static void validate(JSONObject input,boolean sourceKnown) {
var body=ScannerRequestValidator.parse(input.getString("requestJson")==null?"{}":input.getString("requestJson"));
if(body.size()!=1||!body.path("confirm").isBoolean()||!body.path("confirm").asBoolean())
throw bad("请确认导入框架;URL引用模式只接受confirm,不要同时填写旧fileIds");
var body=ScannerRequestValidator.withoutConfirmation(ScannerRequestValidator.parse(input.getString("requestJson")==null?"{}":input.getString("requestJson")));
if(!body.isEmpty())throw bad("URL引用模式不接受旧fileIds或其他操作参数");
if(sourceKnown)sources(input.get("frameworkUrls"));
}
public static List<Source> sources(Object value) {

View File

@ -44,7 +44,7 @@ public class ScannerHttpClient {
.header("Accept",op.binary()?"*/*":"application/json");
if(op!=ScannerOperation.METADATA)builder.header("Authorization","Bearer "+settings.getApiKey());
if(op.control())builder.header("Content-Type","application/json; charset=utf-8")
.POST(HttpRequest.BodyPublishers.ofString(body,StandardCharsets.UTF_8));
.POST(HttpRequest.BodyPublishers.ofString(supplierBody(op,body),StandardCharsets.UTF_8));
else builder.GET();
return builder.build();
}catch(ScannerException e){throw e;}catch(Exception e){throw new ScannerException("invalid_config","扫描服务地址配置无效",400);}
@ -53,6 +53,18 @@ public class ScannerHttpClient {
if(op.upload())throw new ScannerException("invalid_request","框架上传必须使用原始文件上传通道",400);
return json(request(op,id,body,timeoutMs),op.control()?202:200,timeoutMs);
}
private static String supplierBody(ScannerOperation op,String source) {
var body=ScannerRequestValidator.withoutConfirmation(ScannerRequestValidator.parse(source));
// Supplier API compatibility only; flow configuration has no confirmation switch.
switch(op) {
case DISCONNECT,RECONNECT,SCAN_TYPE,FRAMEWORK_IMPORT,ALIGN,EDIT,CLIP_PLANE,
CALIBRATION_START,CALIBRATION_TRAK,CALIBRATION_SYSTEM,CALIBRATION_FREE,
CALIBRATION_CAPTURE,CALIBRATION_COMPUTE,CALIBRATION_ADVANCED,CALIBRATION_APPLY_LAST,
CALIBRATION_RECOVER -> body.put("confirm",true);
default -> { }
}
return body.toString();
}
public JsonNode uploadFramework(String encodedName,byte[] bytes,long timeoutMs) {
requireConfigured();
try {

View File

@ -39,6 +39,7 @@ public enum ScannerOperation {
CALIBRATION_COMPUTE("POST", "/api/v1/calibration/compute", "计算自由标定结果", "SCANNER_CALIBRATION_COMPUTE"),
CALIBRATION_ADVANCED("POST", "/api/v1/calibration/setAdvanced", "设置精细标定开关", "SCANNER_CALIBRATION_ADVANCED"),
CALIBRATION_APPLY_LAST("POST", "/api/v1/calibration/applyLast", "应用上次标定结果", "SCANNER_CALIBRATION_APPLY_LAST"),
CALIBRATION_RECOVER("POST", "/api/v1/calibration/recover", "结束标定并恢复设备", "SCANNER_CALIBRATION_RECOVER"),
METADATA("GET", "/", "查询公开服务元数据", "SCANNER_METADATA"),
HEALTH("GET", "/api/v1/health", "健康检查", "SCANNER_HEALTH"),
STATUS("GET", "/api/v1/status", "读取设备和工程状态", "SCANNER_STATUS"),
@ -54,7 +55,7 @@ public enum ScannerOperation {
public boolean upload() { return this==FRAMEWORK_UPLOAD; }
public boolean control() { return method.equals("POST")&&!upload(); }
public boolean binary() { return this==FILE || this==PREVIEW_IMAGE || this==PREVIEW_STREAM; }
public boolean usableWithoutDevice() {return !control()||this==CONNECT||this==DISCONNECT||this==RECONNECT||this==SCAN_STOP;}
public boolean usableWithoutDevice() {return !control()||this==CONNECT||this==DISCONNECT||this==RECONNECT||this==SCAN_STOP||this==CALIBRATION_RECOVER;}
public static ScannerOperation forAction(String action) {
return Arrays.stream(values()).filter(op -> op.action!=null && op.action.equals(action)).findFirst().orElse(null);
}

View File

@ -17,6 +17,7 @@ public final class ScannerRequestComposer {
ObjectNode body=ScannerRequestValidator.parse(input.getString("requestJson")==null?"{}":input.getString("requestJson"));
Set<String> keys=keys(op);
for(var entry:values.entrySet()) {
if("confirm".equals(entry.getKey()))continue;
if(!(entry.getKey() instanceof String key)||!keys.contains(key))throw bad("此接口不接受请求字段:"+entry.getKey());
JsonNode value=ScannerRequestValidator.JSON.valueToTree(entry.getValue());
if(JSON_FIELDS.contains(key)&&value.isTextual()) {
@ -36,7 +37,10 @@ public final class ScannerRequestComposer {
public static Set<String> names(ScannerOperation op,JsonNode list) {
if(list==null||!list.isArray()||list.size()>64)throw bad("请求字段列表无效");
Set<String> names=new LinkedHashSet<>();
for(JsonNode item:list)if(!item.isTextual()||!keys(op).contains(item.asText())||!names.add(item.asText()))throw bad("请求字段为空、重复或不受此接口支持");
for(JsonNode item:list) {
if(item.isTextual()&&item.asText().equals("confirm"))continue;
if(!item.isTextual()||!keys(op).contains(item.asText())||!names.add(item.asText()))throw bad("请求字段为空、重复或不受此接口支持");
}
return names;
}
public static void validateTemplate(ScannerOperation op,String body,JsonNode names) {
@ -57,6 +61,7 @@ public final class ScannerRequestComposer {
Set<String> all=new HashSet<>(),dynamic=new LinkedHashSet<>();JSONObject values=new JSONObject();
for(int i=0;i<children.size();i++) {
var child=children.getJSONObject(i);String key=child.getString("name");
if("confirm".equals(key))continue;
Object nested=child.get("children");
if(!keys(op).contains(key==null?"":key)||!all.add(key)||nested!=null&&(!(nested instanceof List<?> list)||!list.isEmpty()))throw bad("请求字段为空、重复或包含不支持的嵌套");
if("quote".equals(child.getString("type"))) {

View File

@ -13,22 +13,22 @@ public class ScannerRequestValidator {
return switch(op) {
case CONNECT -> "deviceType";
case CREATE_PROJECT -> "name mode";
case DISCONNECT -> "confirm discardProject expectedProjectId expectedSessionId";
case RECONNECT -> "confirm discardProject expectedProjectId expectedSessionId deviceType";
case SCAN_TYPE -> "scanType device confirm";
case FRAMEWORK_IMPORT -> "fileIds confirm";
case DISCONNECT -> "discardProject expectedProjectId expectedSessionId";
case RECONNECT -> "discardProject expectedProjectId expectedSessionId deviceType";
case SCAN_TYPE -> "scanType device";
case FRAMEWORK_IMPORT -> "fileIds";
case PARAMETERS -> "pointDistance brightness lightSourceMode scanFrameRate highSpeedMode addMarkerMode viewLock localEnlargedView qualityColor strongLight preScanMode markerDiameters";
case MESH -> "filterLevel smoothLevel removeSmallFloatingParts cutMeshEdgeOptimization cutMeshEdgeValue holeOptimization boundaryOptimization maxTriangles fillSmallHole removeSpikes fillMarkerHoles rememberChoice";
case EXPORT -> "name formats";
case SNAPSHOT -> "maxPoints include pauseAcquisition";
case ALIGN -> "action mode fixedProjectUuid movingProjectUuid confirm fixedPoints movingPoints fixedMarkerPoints movingMarkerPoints fixedMarkerIds movingMarkerIds";
case EDIT -> "projectUuid cloudUuid pointIds markerIds points normals confirm";
case CLIP_PLANE -> "center normal deleteBelowPoints deleteBelowMarkers confirm";
case ALIGN -> "action mode fixedProjectUuid movingProjectUuid fixedPoints movingPoints fixedMarkerPoints movingMarkerPoints fixedMarkerIds movingMarkerIds";
case EDIT -> "projectUuid cloudUuid pointIds markerIds points normals";
case CLIP_PLANE -> "center normal deleteBelowPoints deleteBelowMarkers";
case CALIBRATION_MODE -> "mode";
case CALIBRATION_TRAK -> "trakType confirm";
case CALIBRATION_APPLY_LAST -> "mode confirm";
case CALIBRATION_FREE,CALIBRATION_ADVANCED -> "enabled confirm";
case CALIBRATION_START,CALIBRATION_SYSTEM,CALIBRATION_CAPTURE,CALIBRATION_COMPUTE -> "confirm";
case CALIBRATION_TRAK -> "trakType";
case CALIBRATION_APPLY_LAST -> "mode";
case CALIBRATION_RECOVER -> "force expectedSessionId";
case CALIBRATION_FREE,CALIBRATION_ADVANCED -> "enabled";
default -> "";
};
}
@ -42,7 +42,12 @@ public class ScannerRequestValidator {
depth(object,1);return object;
}catch(ScannerException error){throw error;}catch(Exception error){throw bad("JSON请求体格式无效");}
}
/** Old saved flows may still contain this removed editor field. */
static ObjectNode withoutConfirmation(ObjectNode body) {
ObjectNode result=body.deepCopy();result.remove("confirm");return result;
}
public static void validate(ScannerOperation op,ObjectNode b) {
b=withoutConfirmation(b);
int limit=op==ScannerOperation.ALIGN||op==ScannerOperation.EDIT?1048576:16384;
if(b.toString().getBytes(StandardCharsets.UTF_8).length>limit)throw bad("请求体超过设备接口大小限制");
depth(b,1);
@ -50,20 +55,21 @@ public class ScannerRequestValidator {
switch(op) {
case FRAMEWORK_UPLOAD -> throw bad("框架上传必须发送文件原始字节,不能发送JSON或作为异步控制命令");
case SCAN_TYPE -> {
fields(b,"scanType device confirm");choice(b,"scanType",true,"photogrammetry","mesh","markers");
choice(b,"device",false,"tracker","scanner");bool(b,"confirm");
fields(b,"scanType device");choice(b,"scanType",true,"photogrammetry","mesh","markers");
choice(b,"device",false,"tracker","scanner");
}
case FRAMEWORK_IMPORT -> {
fields(b,"fileIds confirm");confirmed(b);strings(b,"fileIds",true);
fields(b,"fileIds");strings(b,"fileIds",true);
if(b.get("fileIds").size()>8)throw bad("一次只能导入1至8个已上传框架文件");
for(JsonNode id:b.get("fileIds"))if(!id.asText().matches("[a-fA-F0-9]{32}"))throw bad("框架上传编号必须为32位十六进制,不能填写文件路径");
}
case CONNECT -> {fields(b,"deviceType");deviceType(b);}
case CREATE_PROJECT -> {fields(b,"name mode");name(b);choice(b,"mode",false,"trak","laser");}
case DISCONNECT,RECONNECT -> {
fields(b,op==ScannerOperation.RECONNECT?"confirm discardProject expectedProjectId expectedSessionId deviceType":"confirm discardProject expectedProjectId expectedSessionId");
confirmed(b);bool(b,"discardProject");nullableText(b,"expectedProjectId");nullableText(b,"expectedSessionId");deviceType(b);
fields(b,op==ScannerOperation.RECONNECT?"discardProject expectedProjectId expectedSessionId deviceType":"discardProject expectedProjectId expectedSessionId");
bool(b,"discardProject");nullableText(b,"expectedProjectId");nullableText(b,"expectedSessionId");deviceType(b);
}
case CALIBRATION_RECOVER -> {bool(b,"force");nullableText(b,"expectedSessionId");}
case PARAMETERS -> {
fields(b,"pointDistance brightness lightSourceMode scanFrameRate highSpeedMode addMarkerMode viewLock localEnlargedView qualityColor strongLight preScanMode markerDiameters");
if(b.isEmpty())throw bad("至少设置一项扫描参数");
@ -90,7 +96,7 @@ public class ScannerRequestValidator {
}
case ALIGN -> align(b);
case EDIT -> {
fields(b,"projectUuid cloudUuid pointIds markerIds points normals confirm");confirmed(b);text(b,"projectUuid",true);
fields(b,"projectUuid cloudUuid pointIds markerIds points normals");text(b,"projectUuid",true);
for(String k:List.of("pointIds","markerIds"))if(b.has(k))integerArray(b,k);
int points=size(b,"pointIds"),markers=size(b,"markerIds");
if(points+markers==0)throw bad("pointIds和markerIds至少一组非空");
@ -98,29 +104,30 @@ public class ScannerRequestValidator {
for(String k:List.of("points","normals"))if(b.has(k)){vectors(b,k);if(size(b,k)>0&&size(b,k)!=points)throw bad(k+"数量必须与pointIds一致");}
}
case CLIP_PLANE -> {
fields(b,"center normal deleteBelowPoints deleteBelowMarkers confirm");confirmed(b);vector(b.get("center"));vector(b.get("normal"));
fields(b,"center normal deleteBelowPoints deleteBelowMarkers");vector(b.get("center"));vector(b.get("normal"));
boolean nonzero=false;for(JsonNode item:b.get("normal"))nonzero|=(float)item.asDouble()!=0f;
if(!nonzero)throw bad("裁剪法向量不能为零");bool(b,"deleteBelowPoints");bool(b,"deleteBelowMarkers");
if(!b.path("deleteBelowPoints").asBoolean()&&!b.path("deleteBelowMarkers").asBoolean())throw bad("至少选择一种裁剪对象");
}
case CALIBRATION_MODE -> {fields(b,"mode");range(b,"mode",0,3);}
case CALIBRATION_TRAK -> {fields(b,"trakType confirm");confirmed(b);range(b,"trakType",0,3);}
case CALIBRATION_APPLY_LAST -> {fields(b,"mode confirm");confirmed(b);range(b,"mode",0,3);}
case CALIBRATION_FREE,CALIBRATION_ADVANCED -> {fields(b,"enabled confirm");confirmed(b);if(!b.has("enabled"))throw bad("enabled不能为空");bool(b,"enabled");}
case CALIBRATION_START,CALIBRATION_SYSTEM,CALIBRATION_CAPTURE,CALIBRATION_COMPUTE -> {fields(b,"confirm");confirmed(b);}
case CALIBRATION_TRAK -> {fields(b,"trakType");range(b,"trakType",0,3);}
case CALIBRATION_APPLY_LAST -> {fields(b,"mode");range(b,"mode",0,3);}
case CALIBRATION_FREE,CALIBRATION_ADVANCED -> {fields(b,"enabled");if(!b.has("enabled"))throw bad("enabled不能为空");bool(b,"enabled");}
default -> fields(b,"");
}
}
/** Check known fields now; combinations involving upstream values are checked after resolution. */
public static void validateTemplate(ScannerOperation op,ObjectNode body,Set<String> referenced) {
if(!op.control())throw bad("此组件不接收请求字段引用");
body=withoutConfirmation(body);
referenced=new LinkedHashSet<>(referenced);referenced.remove("confirm");
ObjectNode all=body.deepCopy();referenced.forEach(k->all.putNull(k));fields(all,fieldKeys(op));
if(referenced.isEmpty()){validate(op,body);return;}
ObjectNode known=body.deepCopy();referenced.forEach(known::remove);depth(known,1);
for(var it=known.fieldNames();it.hasNext();) {
String key=it.next();
switch(key) {
case "confirm","discardProject","highSpeedMode","addMarkerMode","viewLock","localEnlargedView","qualityColor","strongLight","preScanMode","cutMeshEdgeOptimization","holeOptimization","boundaryOptimization","removeSpikes","fillMarkerHoles","rememberChoice","pauseAcquisition","deleteBelowPoints","deleteBelowMarkers","enabled" -> bool(known,key);
case "discardProject","force","highSpeedMode","addMarkerMode","viewLock","localEnlargedView","qualityColor","strongLight","preScanMode","cutMeshEdgeOptimization","holeOptimization","boundaryOptimization","removeSpikes","fillMarkerHoles","rememberChoice","pauseAcquisition","deleteBelowPoints","deleteBelowMarkers","enabled" -> bool(known,key);
case "expectedProjectId","expectedSessionId" -> nullableText(known,key);
case "name" -> name(known);
case "deviceType" -> range(known,key,3,4);
@ -142,10 +149,8 @@ public class ScannerRequestValidator {
default -> text(known,key,true);
}
}
boolean confirms=switch(op){case DISCONNECT,RECONNECT,FRAMEWORK_IMPORT,EDIT,CLIP_PLANE,CALIBRATION_TRAK,CALIBRATION_APPLY_LAST,CALIBRATION_FREE,CALIBRATION_ADVANCED,CALIBRATION_START,CALIBRATION_SYSTEM,CALIBRATION_CAPTURE,CALIBRATION_COMPUTE -> true;case ALIGN -> "exit".equals(known.path("action").asText());default -> false;};
if(confirms&&!referenced.contains("confirm"))confirmed(known);
if(op==ScannerOperation.ALIGN&&known.has("action")&&!known.path("action").asText().equals("apply"))fields(all,"action confirm");
String required=switch(op){case SCAN_TYPE -> "scanType";case FRAMEWORK_IMPORT -> "fileIds confirm";case EXPORT -> "formats";case EDIT -> "projectUuid confirm";case CLIP_PLANE -> "center normal confirm";case CALIBRATION_MODE -> "mode";case CALIBRATION_TRAK -> "trakType confirm";case CALIBRATION_APPLY_LAST -> "mode confirm";case CALIBRATION_FREE,CALIBRATION_ADVANCED -> "enabled confirm";case DISCONNECT,RECONNECT,CALIBRATION_START,CALIBRATION_SYSTEM,CALIBRATION_CAPTURE,CALIBRATION_COMPUTE -> "confirm";case ALIGN -> "action";default -> "";};
if(op==ScannerOperation.ALIGN&&known.has("action")&&!known.path("action").asText().equals("apply"))fields(all,"action");
String required=switch(op){case SCAN_TYPE -> "scanType";case FRAMEWORK_IMPORT -> "fileIds";case EXPORT -> "formats";case EDIT -> "projectUuid";case CLIP_PLANE -> "center normal";case CALIBRATION_MODE -> "mode";case CALIBRATION_TRAK -> "trakType";case CALIBRATION_APPLY_LAST -> "mode";case CALIBRATION_FREE,CALIBRATION_ADVANCED -> "enabled";case ALIGN -> "action";default -> "";};
for(String key:required.split(" "))if(!key.isEmpty()&&!known.has(key)&&!referenced.contains(key))throw bad(key+"为必填参数,请填写或引用上游");
if(op==ScannerOperation.EDIT) {
if(!referenced.contains("pointIds")&&!referenced.contains("markerIds")&&size(known,"pointIds")+size(known,"markerIds")==0)throw bad("pointIds和markerIds至少一组非空");
@ -159,9 +164,9 @@ public class ScannerRequestValidator {
}
private static void align(ObjectNode b) {
choice(b,"action",true,"enter","next","cancel","exit","apply");String action=b.path("action").asText();
if(!action.equals("apply")){fields(b,"action confirm");bool(b,"confirm");if(action.equals("exit"))confirmed(b);return;}
fields(b,"action mode fixedProjectUuid movingProjectUuid confirm fixedPoints movingPoints fixedMarkerPoints movingMarkerPoints fixedMarkerIds movingMarkerIds");
choice(b,"mode",true,"featureAuto","markerAuto","featureManual","markerManual");bool(b,"confirm");
if(!action.equals("apply")){fields(b,"action");return;}
fields(b,"action mode fixedProjectUuid movingProjectUuid fixedPoints movingPoints fixedMarkerPoints movingMarkerPoints fixedMarkerIds movingMarkerIds");
choice(b,"mode",true,"featureAuto","markerAuto","featureManual","markerManual");
text(b,"fixedProjectUuid",true);text(b,"movingProjectUuid",true);
if(b.get("fixedProjectUuid").asText().equals(b.get("movingProjectUuid").asText()))throw bad("固定与移动工程不能相同");
for(String k:List.of("fixedPoints","movingPoints","fixedMarkerPoints","movingMarkerPoints"))if(b.has(k))vectors(b,k);
@ -177,7 +182,6 @@ public class ScannerRequestValidator {
private static void text(ObjectNode b,String k,boolean required){if(!b.has(k)&&!required)return;if(!b.path(k).isTextual()||b.path(k).asText().isBlank())throw bad(k+"必须是非空字符串");}
private static void nullableText(ObjectNode b,String k){if(b.hasNonNull(k))text(b,k,true);}
private static void bool(ObjectNode b,String k){if(b.has(k)&&!b.get(k).isBoolean())throw bad(k+"必须是布尔值");}
private static void confirmed(ObjectNode b){if(!b.path("confirm").isBoolean()||!b.path("confirm").asBoolean())throw bad("请明确确认本次操作的目标和影响");}
private static void number(ObjectNode b,String k,boolean required){if(!b.has(k)&&!required)return;if(!b.path(k).isNumber()||!Double.isFinite(b.path(k).asDouble()))throw bad(k+"必须是有限数值");}
private static void integer(ObjectNode b,String k,boolean required){if(!b.has(k)&&!required)return;if(!b.path(k).isIntegralNumber())throw bad(k+"必须使用JSON整数字面量");}
private static void range(ObjectNode b,String k,int min,int max){integer(b,k,true);var v=b.path(k).bigIntegerValue();if(v.compareTo(java.math.BigInteger.valueOf(min))<0||v.compareTo(java.math.BigInteger.valueOf(max))>0)throw bad(k+"超出枚举范围");}

View File

@ -11,6 +11,8 @@ import java.util.concurrent.locks.ReentrantLock;
@Service
@RequiredArgsConstructor
public class ScannerService {
public static final long CALIBRATION_FREE_TIMEOUT_MS=5000;
private static final long CALIBRATION_FREE_POLL_INTERVAL_MS=1000;
private final ScannerProperties settings;
private final ScannerHttpClient client;
private final ScannerCommandJournal journal;
@ -69,8 +71,11 @@ public class ScannerService {
if(active!=null){requireKnown(active);refresh(active,deadline);if(journal.active(client.endpointKey())!=null)throw new ScannerException("command_busy","上一控制任务尚未结束,请先等待任务终态",409);}
JsonNode status=query(ScannerOperation.STATUS,null,deadline);
if(expectedContext!=null&&(!expectedContext.path("endpoint").asText(client.endpointKey()).equals(client.endpointKey())||!expectedContext.path("sessionId").asText().equals(status.path("sessionId").asText())||!expectedContext.path("projectId").asText().equals(status.path("projectId").asText())))throw new ScannerException("project_changed","扫描会话或工程已切换,不能继续原工程操作",409);
if(status.path("restartRequired").asBoolean())throw new ScannerException("restart_required","设备服务要求正常重启,禁止自动重连",409);
if(status.path("stateUncertain").asBoolean())throw new ScannerException("state_uncertain","设备状态不确定,请先核对任务和现场状态",409);
// Recovery is explicit and session-bound; it cannot bypass an active command or occupation.
if(op==ScannerOperation.CALIBRATION_RECOVER)body=prepareCalibrationRecovery(body,status);
boolean forcedRecovery=op==ScannerOperation.CALIBRATION_RECOVER&&body.path("force").asBoolean(false);
if(!forcedRecovery&&status.path("restartRequired").asBoolean())throw new ScannerException("restart_required","设备服务要求正常重启,禁止自动重连",409);
if(!forcedRecovery&&status.path("stateUncertain").asBoolean())throw new ScannerException("state_uncertain","设备状态不确定,请先核对任务和现场状态",409);
if(status.path("busy").asBoolean())throw new ScannerException("device_busy","扫描设备正在处理其他控制任务",409);
requestBudget(deadline);
journal.intent(key,client.endpointKey(),op,hash,body.toString(),owner);
@ -104,12 +109,29 @@ public class ScannerService {
public JsonNode executeAndWait(ScannerOperation op,ObjectNode body,String key,String owner,long timeoutMs) {
return executeBoundAndWait(op,body,key,owner,timeoutMs,null);
}
private ObjectNode prepareCalibrationRecovery(ObjectNode body,JsonNode status) {
if(status.path("scanning").asBoolean())
throw new ScannerException("scan_active","请先暂停采集,再结束标定并恢复设备",409);
JsonNode current=status.get("sessionId");
if(current==null||!current.isNull()&&(!current.isTextual()||current.asText().isBlank()))
throw new ScannerException("session_unconfirmed","扫描服务未返回可核对的设备会话,暂不能恢复设备",409);
String actual=current.isNull()?null:current.asText();
String expected=body.hasNonNull("expectedSessionId")?body.get("expectedSessionId").asText():actual;
if(!Objects.equals(expected,actual))
throw new ScannerException("session_mismatch","设备会话编号不匹配,请读取当前状态并更新 expectedSessionId 后重试",409);
// Resolve from this command's fresh status without changing the caller's
// template or its replay hash; explicit session bindings still must match.
ObjectNode request=body.deepCopy();
request.set("expectedSessionId",current);
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){
try {accepted=submit(op,body,key,owner,expectedContext,deadline);break;}
catch(ScannerException error){if(!Set.of("command_busy","device_busy").contains(error.scannerCode))throw error;sleep(deadline);}
catch(ScannerException error){if(!Set.of("command_busy","device_busy").contains(error.scannerCode))throw error;sleep(deadline,op==ScannerOperation.CALIBRATION_FREE?CALIBRATION_FREE_POLL_INTERVAL_MS:settings.getPollIntervalMs());}
}
return waitCommandUntil(accepted.path("commandKey").asText(),deadline);
}
@ -117,18 +139,23 @@ 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("FAILED"))throw taskFailure(entry);
try {refresh(entry,deadline);}catch(ScannerException error){if(!transientQuery(error))throw error;}
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("FAILED"))throw taskFailure(entry);
sleep(deadline);
sleep(deadline,free?CALIBRATION_FREE_POLL_INTERVAL_MS:settings.getPollIntervalMs());
}
}
public JsonNode waitRemoteTask(String id,long timeoutMs) {
@ -155,8 +182,9 @@ public class ScannerService {
if(!entry.taskId().equals(task.path("taskId").asText())){
journal.uncertain(entry.key(),"任务响应编号不匹配");throw new ScannerException("task_mismatch","任务响应编号不匹配,禁止重发",409);
}
String state=task.path("state").asText();
String state=task.path("state").asText("");
if(state.equals("succeeded")||state.equals("failed"))journal.finish(entry.key(),state.equals("succeeded"),task,state.equals("failed")?task.path("error").toString():null);
else if(state.isBlank()&&ScannerOperation.CALIBRATION_FREE.name().equals(entry.operation()))return;
else if(!Set.of("queued","running").contains(state))throw new ScannerException("invalid_task_state","设备任务状态无效",502);
}
private long deadline(long timeoutMs) {
@ -198,7 +226,8 @@ public class ScannerService {
private ScannerException failure(JsonNode task){return new ScannerException(task.path("error").path("code").asText("task_failed"),task.path("error").path("message").asText("设备任务失败"),task.path("error").path("httpStatus").asInt(502));}
private void requireKnown(ScannerCommandJournal.Entry entry){if(Set.of("INTENT","UNKNOWN").contains(entry.state()))throw new ScannerException("command_uncertain","命令"+entry.key()+"结果未确认,禁止重复发送,请人工核对",409);}
private ObjectNode accepted(ScannerCommandJournal.Entry entry){ObjectNode result=ScannerRequestValidator.JSON.createObjectNode();result.put("commandKey",entry.key());result.put("taskId",entry.taskId());result.put("state",entry.state());result.put("statusUrl",entry.taskId()==null?null:"/admin-api/cmvr/scanner/tasks/"+entry.taskId());return result;}
private void sleep(long deadline){long remaining=deadline-System.nanoTime();if(remaining<=0)throw new ScannerException("task_wait_timeout","等待超时;已受理任务仍可能执行,可按原命令记录继续查询",504);try{Thread.sleep(Math.min(java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(remaining)+1,Math.max(10,settings.getPollIntervalMs())));}catch(InterruptedException e){Thread.currentThread().interrupt();throw new ScannerException("interrupted","等待被中断;不会撤销设备动作",504);}}
private void sleep(long deadline){sleep(deadline,settings.getPollIntervalMs());}
private void sleep(long deadline,long intervalMs){long remaining=deadline-System.nanoTime();if(remaining<=0)throw waitTimeout();try{Thread.sleep(Math.min(java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(remaining)+1,Math.max(10,intervalMs)));}catch(InterruptedException e){Thread.currentThread().interrupt();throw new ScannerException("interrupted","等待被中断;不会撤销设备动作",504);}}
public static String key(String key){if(key==null||!key.matches("[A-Za-z0-9_-]{8,64}"))throw new ScannerException("invalid_command_key","需要8至64位命令标识",400);return key;}
public static String hash(String source){return cn.hutool.crypto.digest.DigestUtil.sha256Hex(source);}
private String canonical(JsonNode node){if(node.isObject()){var sorted=new TreeMap<String,JsonNode>();node.fields().forEachRemaining(e->sorted.put(e.getKey(),e.getValue()));return sorted.entrySet().stream().map(e->e.getKey()+":"+canonical(e.getValue())).collect(java.util.stream.Collectors.joining(",","{","}"));}if(node.isArray()){List<String> items=new ArrayList<>();node.forEach(n->items.add(canonical(n)));return "["+String.join(",",items)+"]";}return node.toString();}

View File

@ -27,7 +27,8 @@ 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"));
long timeout=input.getLongValue("timeoutMs");
// 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");
ScannerFrameworkReferenceService.Prepared prepared=null;
com.fasterxml.jackson.databind.JsonNode result;
if(op==ScannerOperation.TASK){result=service.waitRemoteTask(input.getString("taskId"),timeout);}
@ -56,6 +57,8 @@ public class ScannerWorkflowAdapter implements WorkcellDeviceAdapter {
}else if(prepared!=null)result=service.executeBoundAndWait(op,prepared.body(),commandKey,"workflow:"+message.getInstId(),timeout,prepared.context());
else result=service.executeAndWait(op,ScannerRequestValidator.parse(body),commandKey,"workflow:"+message.getInstId(),timeout);
}
if(op==ScannerOperation.CALIBRATION_FREE&&(result==null||!"succeeded".equals(result.path("state").asText())))
throw new ScannerException("task_not_confirmed","设置自由标定开关未取得厂家任务成功终态",502);
// A control's terminal acknowledgement can precede the next periodic status
// refresh. Refresh now so the next node sees measured post-command readiness.
if(op.control())resources.refresh();

View File

@ -72,6 +72,7 @@ public enum ActionEnum {
SCANNER_CALIBRATION_COMPUTE("EDGE", "SCANNER_CALIBRATION_COMPUTE", "计算自由标定结果"),
SCANNER_CALIBRATION_ADVANCED("EDGE", "SCANNER_CALIBRATION_ADVANCED", "设置精细标定开关"),
SCANNER_CALIBRATION_APPLY_LAST("EDGE", "SCANNER_CALIBRATION_APPLY_LAST", "应用上次标定结果"),
SCANNER_CALIBRATION_RECOVER("EDGE", "SCANNER_CALIBRATION_RECOVER", "结束标定并恢复设备"),
SCANNER_METADATA("EDGE", "SCANNER_METADATA", "查询公开服务元数据"),
SCANNER_HEALTH("EDGE", "SCANNER_HEALTH", "健康检查"),
SCANNER_STATUS("EDGE", "SCANNER_STATUS", "读取设备和工程状态"),

View File

@ -279,6 +279,13 @@ public class ScannerController extends BaseController {
return success(access.submit(ScannerOperation.CALIBRATION_APPLY_LAST, body, commandKey));
}
@ApiOperation("结束标定并恢复设备")
@PostMapping("/calibration/recover")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postCalibrationRecover(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.CALIBRATION_RECOVER, body, commandKey));
}
@ApiOperation("查询公开服务元数据")
@GetMapping("/metadata")
public AjaxResult getMetadata() { return success(scanner.get(ScannerOperation.METADATA, null)); }

View File

@ -3,6 +3,7 @@ package com.cmvr.web.controller.test;
import com.cmvr.common.core.controller.BaseController;
import com.cmvr.common.core.page.TableDataInfo;
import com.cmvr.test.model.domain.TeNodeInst;
import com.cmvr.test.model.domain.TeTaskInst;
import com.cmvr.test.model.vo.TeQueryTaskInstVO;
import com.cmvr.test.model.vo.TeTaskInstVO;
import com.cmvr.test.service.ITeTaskInstService;
@ -39,6 +40,28 @@ public class TeTaskInstController extends BaseController {
return getDataTable(list);
}
@ApiOperation("查询单次执行状态,不返回流程配置")
@PreAuthorize("@cmvrSs.hasPermi('test:config:execute') or @cmvrSs.hasPermi('test:inst:list') or @ss.hasPermission('lab:execution:dispatch')")
@GetMapping("/status/{id}")
public AjaxResult status(@PathVariable String id) {
TeTaskInst instance = teTaskInstService.getById(id);
if (instance == null) return AjaxResult.error("执行实例不存在或已被删除");
String message = null;
if ("2".equals(instance.getStatus())) {
List<TeNodeInst> logs = teTaskInstService.detail(id);
if (logs != null) {
message = logs.stream()
.filter(log -> "FAILED".equalsIgnoreCase(log.getStatus()))
.map(TeNodeInst::getMessage)
.filter(value -> value != null && !value.isBlank())
.reduce((previous, latest) -> latest).orElse(null);
}
}
return AjaxResult.success(new ExecutionStatus(instance.getId(), instance.getStatus(), message));
}
public record ExecutionStatus(String instId, String status, String message) { }
@ApiOperation("查询节点执行日志")
@GetMapping("/log/detail")
public TableDataInfo detail(@RequestParam String instId, @RequestParam(required = false) Long afterId) {

View File

@ -46,19 +46,23 @@ public class ScannerComponentProtocolTest {
input.put("deviceId","scanner");input.put("timeoutMs",5000);
var m=new TaskNodeExecuteMessage();m.setAction(ActionEnum.fromAction(op.action));m.setRobotId("station");m.setInstId("component-protocol");m.setNodeId(op.name());m.setItemId("case");m.setInputParams(input);return m;
}
@Test public void allThirtyControlComponentsComposeFieldsAndReachDocumentedHttpTasks() throws Exception {
@Test public void allThirtyOneControlComponentsComposeFieldsAndReachDocumentedHttpTasks() throws Exception {
var fixture=ScannerRequestValidator.JSON.readTree(Files.readString(Path.of("../../scripts/fixtures/scanner-supplier-contract.json")));
Map<ScannerOperation,String> examples=new EnumMap<>(ScannerOperation.class);
for(var row:fixture.path("operations"))examples.put(ScannerOperation.valueOf(row.path("operation").asText()),row.path("request").toString());
examples.put(ScannerOperation.CALIBRATION_RECOVER,"{\"confirm\":true,\"force\":true,\"expectedSessionId\":\"S1\"}");
int count=0;
for(var op:ScannerOperation.values())if(op.control()) {
var input=JSONObject.of("requestJson","{}","requestFields",JSONObject.parseObject(examples.get(op)));
var result=adapter.execute(message(op,input));assertTrue(op.name(),result.isSuccess());count++;
assertEquals(op.name(),ScannerRequestValidator.parse(examples.get(op)),ScannerRequestValidator.parse(requests.get(op.path)));
assertEquals(ScannerRequestValidator.parse(examples.get(op)),ScannerRequestValidator.parse(result.getOutputParams().getString("requestJson")));
var expected=ScannerRequestValidator.parse(examples.get(op));
if(op==ScannerOperation.ALIGN)expected.put("confirm",true);
assertEquals(op.name(),expected,ScannerRequestValidator.parse(requests.get(op.path)));
expected.remove("confirm");
assertEquals(expected,ScannerRequestValidator.parse(result.getOutputParams().getString("requestJson")));
if(op==ScannerOperation.CALIBRATION_MODE||op==ScannerOperation.CALIBRATION_APPLY_LAST){assertEquals(2,result.getOutputParams().getJSONObject("result").getIntValue("mode"));assertEquals("探针标定",result.getOutputParams().getJSONObject("result").getString("modeName"));}
}
assertEquals(30,count);assertEquals(30,requests.size());
assertEquals(31,count);assertEquals(31,requests.size());
}
@Test public void allEightQueryComponentsReturnSupplierFieldsWithoutAControlPost() {
int count=0;

View File

@ -103,11 +103,11 @@ public class ScannerFrameworkIntegrationTest {
@Test public void newJsonRequestsUseStrictTypesAllowDocumentedDefaultsAndRejectPaths() {
for(String body:List.of("{\"scanType\":\"mesh\"}","{\"scanType\":\"photogrammetry\",\"device\":\"tracker\",\"confirm\":true}","{\"scanType\":\"markers\",\"confirm\":false}"))
ScannerRequestValidator.validate(ScannerOperation.SCAN_TYPE,ScannerRequestValidator.parse(body));
for(String body:List.of("{}","{\"scanType\":\"invalid\"}","{\"scanType\":\"mesh\",\"device\":3}","{\"scanType\":\"mesh\",\"confirm\":\"true\"}","{\"scanType\":\"mesh\",\"unknown\":1}"))
for(String body:List.of("{}","{\"scanType\":\"invalid\"}","{\"scanType\":\"mesh\",\"device\":3}","{\"scanType\":\"mesh\",\"unknown\":1}"))
assertThrows(ScannerException.class,()->ScannerRequestValidator.validate(ScannerOperation.SCAN_TYPE,ScannerRequestValidator.parse(body)));
var valid=ScannerRequestValidator.parse("{\"fileIds\":[\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"],\"confirm\":true}");
ScannerRequestValidator.validate(ScannerOperation.FRAMEWORK_IMPORT,valid);
for(String body:List.of("{\"fileIds\":[],\"confirm\":true}","{\"fileIds\":[\"C:/frame.p3\"],\"confirm\":true}","{\"fileIds\":[\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"],\"confirm\":false}","{\"fileIds\":[1],\"confirm\":true}"))
for(String body:List.of("{\"fileIds\":[],\"confirm\":true}","{\"fileIds\":[\"C:/frame.p3\"],\"confirm\":true}","{\"fileIds\":[1],\"confirm\":true}"))
assertThrows(ScannerException.class,()->ScannerRequestValidator.validate(ScannerOperation.FRAMEWORK_IMPORT,ScannerRequestValidator.parse(body)));
for(int i=1;i<8;i++)valid.withArray("fileIds").add("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
ScannerRequestValidator.validate(ScannerOperation.FRAMEWORK_IMPORT,valid);valid.withArray("fileIds").add("cccccccccccccccccccccccccccccccc");

View File

@ -110,8 +110,7 @@ public class ScannerFrameworkReferenceTest {
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());
}
@Test public void unconfirmedOrWrongScanModeFailsBeforeDownload() {
var input=input(url());input.put("requestJson","{\"confirm\":false}");assertThrows(ScannerException.class,()->transfer.prepare("framework-confirm","run",input,5000));
@Test public void wrongScanModeFailsBeforeDownload() {
mode.set("photogrammetry");assertEquals("framework_import_not_ready",assertThrows(ScannerException.class,()->prepare("framework-mode",url())).scannerCode);assertEquals(0,downloads.get());
}
@Test public void projectChangeBetweenUploadAndImportBlocksSdkAction() {

View File

@ -240,8 +240,8 @@ public class ScannerIntegrationTest {
assertTrue("Stalled body must be aborted before it arrives",java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-start)<1000);
}
@Test public void all42SupplierRoutesUseTheirExactMethodPathAndHeader() throws Exception {
assertEquals(42,ScannerOperation.values().length);
@Test public void all43SupplierRoutesUseTheirExactMethodPathAndHeader() throws Exception {
assertEquals(43,ScannerOperation.values().length);
for(var op:ScannerOperation.values()) {
String id=op==ScannerOperation.TASK||op==ScannerOperation.FILE?taskId:null;
if(op.upload())client.uploadFramework("Frame.p3",new byte[]{1,2,3,4},3000);
@ -249,7 +249,7 @@ public class ScannerIntegrationTest {
else client.json(op,id,op.control()?"{}":null,3000);
assertTrue(seen.contains(op.method+" "+op.route(id)));
}
assertEquals(31,submissions.get());
assertEquals(32,submissions.get());
}
@Test public void acceptedTaskIsPolledAndReplayAfterServiceRecreationDoesNotResubmit(){
var body=ScannerRequestValidator.parse("{\"mode\":\"trak\"}");

View File

@ -26,6 +26,7 @@ public class ScannerRequestComposerTest {
JSONObject values=JSONObject.parseObject(expected.toString());var original=input("{}",values);
var resolved=ScannerRequestComposer.resolve(op,original);
var body=ScannerRequestValidator.parse(resolved.getString("requestJson"));ScannerRequestValidator.validate(op,body);
expected.remove("confirm");
assertEquals(op.name(),expected,body);assertFalse(resolved.containsKey("requestFields"));assertEquals("{}",original.getString("requestJson"));
for(String key:values.keySet()) {
var fields=JSONArray.of(JSONObject.of("name","requestJson","type","input","input",expected.toString()),
@ -33,7 +34,7 @@ public class ScannerRequestComposerTest {
WorkcellNodeContract.validateLiterals(ActionEnum.fromAction(op.action),fields);
}
}
assertEquals(30,controls);
assertEquals(31,controls);
}
@Test public void arrayJsonTextPreservesIdsBeyondJavaScriptAndSignedLongPrecision() {
String ids="[9007199254740993,18446744073709551615]";
@ -50,7 +51,7 @@ public class ScannerRequestComposerTest {
@Test public void staticErrorsAndWrongFieldsCannotHideBehindDynamicReferences() {
var def=definition("brightness","upstream","value");
assertThrows(ScannerException.class,()->ScannerRequestComposer.validateDefinition(ScannerOperation.PARAMETERS,def,JSONObject.of("requestJson","{\"pointDistance\":0.01}"),false));
assertThrows(ScannerException.class,()->ScannerRequestComposer.validateDefinition(ScannerOperation.EDIT,definition("projectUuid","scene","projectUuid"),JSONObject.of("requestJson","{\"markerIds\":[1],\"confirm\":false}"),false));
ScannerRequestComposer.validateDefinition(ScannerOperation.EDIT,definition("projectUuid","scene","projectUuid"),JSONObject.of("requestJson","{\"markerIds\":[1],\"confirm\":false}"),false);
assertThrows(ScannerException.class,()->ScannerRequestComposer.resolve(ScannerOperation.EXPORT,input("{}",JSONObject.of("projectId","wrong"))));
assertThrows(ScannerException.class,()->ScannerRequestComposer.resolve(ScannerOperation.STATUS,input("{}",new JSONObject())));
var duplicate=definition("name","source","name");duplicate.getJSONArray("children").add(duplicate.getJSONArray("children").getJSONObject(0));

View File

@ -31,7 +31,18 @@ public class ScanExpiredScannerRecovery {
void recoverPending() {
if(!settings.configured()||settings.getRobotId()==null||settings.getRobotId().isBlank())return;
var candidates=jdbc.queryForList("SELECT DISTINCT o.owner_key,t.id FROM lab_resource_occupation o JOIN te_task_inst t ON t.id=SUBSTRING(o.owner_key,8) WHERE o.tenant_id=1 AND o.deleted=0 AND o.status='STOP_PENDING' AND o.resource_type='ROBOT' AND o.resource_id=? AND o.owner_key LIKE 'NATIVE:%' AND t.status IN ('2','4') ORDER BY o.owner_key LIMIT 5",settings.getRobotId());
// Preserve all 128 utf8mb4 characters when comparing IDs across table collations.
// An explicit binary width is also needed by H2; byte lengths exclude padding matches.
var candidates=jdbc.queryForList("""
SELECT DISTINCT o.owner_key,t.id
FROM lab_resource_occupation o JOIN te_task_inst t
ON OCTET_LENGTH(t.id)=OCTET_LENGTH(SUBSTRING(o.owner_key,8))
AND CAST(t.id AS BINARY(512))=CAST(SUBSTRING(o.owner_key,8) AS BINARY(512))
WHERE o.tenant_id=1 AND o.deleted=0 AND o.status='STOP_PENDING'
AND o.resource_type='ROBOT' AND o.resource_id=?
AND o.owner_key LIKE 'NATIVE:%' AND t.status IN ('2','4')
ORDER BY o.owner_key LIMIT 5
""",settings.getRobotId());
Set<String> owners=new HashSet<>();
for(var row:candidates) {
String owner=Objects.toString(row.get("owner_key")),inst=Objects.toString(row.get("id"));owners.add(owner);

View File

@ -2,6 +2,8 @@
server:
port: 48090
spring:
config:
import: ${cmvr.scanner.config-location:optional:file:./.local/scanner-private.yaml}
application:
name: am-freescan
autoconfigure:

View File

@ -2,6 +2,8 @@
server:
port: 48090
spring:
config:
import: ${cmvr.scanner.config-location:optional:file:./.local/scanner-private.yaml}
application:
name: am-freescan
autoconfigure:

View File

@ -0,0 +1,95 @@
# 生产模板随 JAR 打包,不加载 .local;实际连接参数由部署环境提供。
server:
port: ${SERVER_PORT:48090}
spring:
autoconfigure:
exclude:
- org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration
- com.binarywang.spring.starter.wxjava.mp.config.WxMpAutoConfiguration
- com.binarywang.spring.starter.wxjava.miniapp.config.WxMaAutoConfiguration
datasource:
dynamic:
primary: master
strict: true
datasource:
master:
url: ${AM_FREESCAN_DB_URL}
username: ${AM_FREESCAN_DB_USER}
password: ${AM_FREESCAN_DB_PASSWORD}
data:
redis:
host: ${AM_FREESCAN_REDIS_HOST}
port: ${AM_FREESCAN_REDIS_PORT:6379}
database: ${AM_FREESCAN_REDIS_DATABASE}
password: ${AM_FREESCAN_REDIS_PASSWORD}
boot:
admin:
context-path: /admin
client:
enabled: false
cache:
redis:
key-prefix: '${spring.application.name}:'
cmvr:
quic:
# 启用时必须提供部署主机的证书和私钥文件路径。
enabled: ${CMVR_QUIC_ENABLED:false}
bind-host: ${CMVR_QUIC_BIND_HOST:0.0.0.0}
port: ${CMVR_QUIC_PORT:4433}
alpn: ${CMVR_QUIC_ALPN:cmvr-quic-edge/1}
allowed-node-ids: ${CMVR_QUIC_ALLOWED_NODE_IDS:}
tls:
certificate: ${CMVR_QUIC_TLS_CERTIFICATE:}
private-key: ${CMVR_QUIC_TLS_PRIVATE_KEY:}
client-ca: ${CMVR_QUIC_TLS_CLIENT_CA:}
require-client-certificate: ${CMVR_QUIC_TLS_REQUIRE_CLIENT_CERTIFICATE:false}
lab:
integration:
mock-enabled: false
mock-auto-callback: false
callback-base-url: http://127.0.0.1:${server.port}/open-api
public-base-url: ${AM_FREESCAN_PUBLIC_BASE_URL:}
task:
report-required: true
resource:
require-fixture: false
require-material: false
artifact:
nas-root: ${LAB_ARTIFACT_NAS_ROOT:./artifacts}
max-size-bytes: 10737418240
yudao:
captcha:
enable: false
security:
mock-enable: false
demo: false
api-encrypt:
enable: false
access-log:
enable: true
web:
admin-ui:
url: ${AM_FREESCAN_ADMIN_UI_URL:}
swagger:
title: AM FreeScan API
description: AM FreeScan 任务管理与检测配置
justauth:
enabled: false
management:
endpoints:
web:
base-path: /actuator
exposure:
include: health,info
logging:
file:
name: ${LOGGING_FILE_NAME:./logs/backend.log}
level:
cn.iocoder.yudao: INFO

View File

@ -13,20 +13,18 @@ cmvr:
external-robot-ids:
- ${AM_FREESCAN_ROTARY_BASE_ROBOT_ID:am-freescan-rotary-base-station-001}
scanner:
# 现场API地址;访问密钥待配置。18888为API端口,不能使用18890网页代理端口。
# 通用模板随应用打包;本地由私有 YAML 覆盖,生产从环境变量读取。
host: ${AM_FREESCAN_SCANNER_HOST:192.168.0.112}
port: ${AM_FREESCAN_SCANNER_PORT:18888}
api-key: ${AM_FREESCAN_SCANNER_API_KEY:}
robot-id: ${AM_FREESCAN_SCANNER_ROBOT_ID:}
device-id: ${AM_FREESCAN_SCANNER_DEVICE_ID:}
api-key: ${AM_FREESCAN_SCANNER_API_KEY:00da1ea59c601b3ed292879e75d22b41d9bbaeaa02c2fbc3f97f9e191fe0be2d}
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
operation-timeout-ms: 120000
poll-interval-ms: 500
spring:
config:
import: ${cmvr.scanner.config-location:optional:file:./.local/scanner-private.yaml}
application:
name: am-freescan
profiles:

View File

@ -0,0 +1,56 @@
import request from '@/cmvr/request'
import { loadMaintenanceDefinition } from '@/views/lab/dimension/maintenance.mjs'
interface NativeResult<T> {
code: number
msg?: string
data?: T
}
const read = async (url: string, signal?: AbortSignal) => {
const result = await request.get<never, NativeResult<any>>(url, {
signal,
timeout: 15000,
silentError: true
} as any)
return result.data
}
export async function getScannerStatus(signal?: AbortSignal) {
// The existing backend proxy calls the scanner's authenticated GET /api/v1/status.
const data = await read('/scanner/status', signal)
if (!data || typeof data !== 'object' || Array.isArray(data))
throw new Error('未取得有效的扫描仪状态')
return data as { lastCalibrationUtc?: string | null }
}
export function getMaintenanceDefinition(action: any, signal?: AbortSignal) {
return loadMaintenanceDefinition(action, {
readCase: (id: string) => read(`/aima/testcase/${encodeURIComponent(id)}`, signal),
readItem: (id: string) => read(`/test/detect/${encodeURIComponent(id)}`, signal),
readVersion: (id: string) => read(`/flow/version/${encodeURIComponent(id)}`, signal)
})
}
export async function startMaintenance(
_action: any,
signal: AbortSignal,
data: any
): Promise<string> {
if (!data?.itemId || !data?.flowData) throw new Error('请先填写本次执行配置')
signal.throwIfAborted()
// Once submitted, allow the acknowledgement to arrive even if the user leaves the page.
const result = await request.post<never, NativeResult<string>>('/flow/executeTrial', data, {
silentError: true
} as any)
const instId = result.data || result.msg
if (!instId || !/^[a-f\d]{32}$/i.test(instId))
throw new Error('未取得执行实例编号,请核对执行记录')
return instId
}
export async function getMaintenanceStatus(instId: string, signal: AbortSignal) {
const data = await read(`/test/inst/status/${encodeURIComponent(instId)}`, signal)
if (data?.instId !== instId) throw new Error('执行状态暂未同步')
return data
}

View File

@ -8,11 +8,13 @@ test('URLs and full export results select frameworks and filter large mesh outpu
assert.deepEqual(frameworkReferences({ result: { files: [{ name: 'frame.p3', downloadUrl: url }, { name: 'a.stl', downloadUrl: 'invalid' }] } }), [url])
for (const value of ['', [], '//evil' + url, url + '?x=1', 'file://' + url, '/api/v1/files/../' + 'a'.repeat(32), { name: 'a.stl', downloadUrl: url }]) assert.throws(() => frameworkReferences(value))
})
test('new import preset uses URL reference and explicit confirmation with export outputs available', () => {
test('new import preset uses URL reference with export outputs available', () => {
const nodes = createWorkcellNodeGroups()[0].nodeList
const importer = nodes.find(node => node.action === 'SCANNER_FRAMEWORK_IMPORT')
assert.equal(importer.nodeParams.find(p => p.name === 'frameworkUrls').type, 'quote')
assert.ok(validateWorkcellLiterals(importer.action, importer.nodeParams).some(e => e.includes('勾选')))
const params = structuredClone(importer.nodeParams)
Object.assign(params.find(p => p.name === 'frameworkUrls'), { type: 'input', input: url })
assert.deepEqual(validateWorkcellLiterals(importer.action, params), [])
assert.ok(nodes.find(node => node.action === 'SCANNER_EXPORT').outputParams.some(p => p.name === 'frameworkFiles'))
})
test('auto selection requires exactly one reachable export and supports legacy result.files', () => {

View File

@ -38,7 +38,7 @@ test('回执信息不完整或字节数不同,提示未确认,不发布虚
}
})
test('三个新增动作可拖入工作流,上传只有单独通道,状态引用包含新框架字段', () => {
assert.equal(SCANNER_OPERATIONS.length,42)
assert.equal(SCANNER_OPERATIONS.length,43)
const nodes = createWorkcellNodeGroups()[0].nodeList
for (const action of ['SCANNER_SCAN_TYPE','SCANNER_FRAMEWORK_IMPORT','SCANNER_FRAMEWORK_OPTIMIZE']) {
assert.ok(getScannerOperation(action));assert.ok(nodes.find(node => node.action===action))

View File

@ -129,10 +129,10 @@ export function createWorkcellNodeGroups(icons = {}) {
scannerOperation: op.key,
desc: op.note || (op.method === 'POST' ? '提交设备操作并等待任务结果' : op.key === 'TASK' ? '等待设备命令终态,不代表整件扫描完成' : '读取扫描服务数据'),
nodeParams: [
...(op.method === 'POST' ? [field('requestJson', '扫描操作参数', JSON.stringify(op.key === 'FRAMEWORK_IMPORT' ? { confirm: false } : op.defaultBody, null, 2))] : []),
...(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: 120000 },
{ ...timeout(), input: op.waitTimeoutMs || 120000 },
],
outputType: 'json',
outputParams: scannerOutputs(op),
@ -191,8 +191,7 @@ export function validateWorkcellLiterals(action, params = []) {
const known = { ...body }; bindings.forEach(field => delete known[field.name]); validateScannerParameters(known)
}
else if(scanner.key === 'FRAMEWORK_IMPORT' && params.some(p => p.name === 'frameworkUrls')) {
if(body.confirm !== true) errors.push('请先勾选已核对框架来源和目标扫描工程')
else if(Object.keys(body).length !== 1) errors.push('URL引用不能同时填写旧文件编号,请重新配置组件')
if(Object.keys(body).some(key => key !== 'confirm')) errors.push('URL引用不能同时填写旧文件编号,请重新配置组件')
}
} catch (error) { errors.push(error instanceof SyntaxError ? '扫描参数JSON格式无效' : error.message) }
}

View File

@ -65,12 +65,12 @@ test('各动作正确筛选设备,拖入多个节点时参数互不污染', ()
assert.equal(getDeviceKindForAction('DEVICE_EXECUTE_JSON_COMMAND'), 2)
})
test('42个接口映射38个工作流动作,上传、预览和下载由面板调用', () => {
assert.equal(SCANNER_OPERATIONS.length, 42)
assert.equal(SCANNER_OPERATIONS.filter(op => op.method === 'POST' && !op.upload).length, 30)
test('43个接口映射39个工作流动作,上传、预览和下载由面板调用', () => {
assert.equal(SCANNER_OPERATIONS.length, 43)
assert.equal(SCANNER_OPERATIONS.filter(op => op.method === 'POST' && !op.upload).length, 31)
const nodes = createWorkcellNodeGroups()[0].nodeList
assert.equal(nodes.length, 38)
assert.equal(new Set(nodes.map(node => node.action)).size, 38)
assert.equal(nodes.length, 39)
assert.equal(new Set(nodes.map(node => node.action)).size, 39)
assert.deepEqual(SCANNER_OPERATIONS.filter(op => !op.action).map(op => op.key), ['FRAMEWORK_UPLOAD', 'PREVIEW_IMAGE', 'PREVIEW_STREAM', 'FILE'])
const start = nodes.find(node => node.action === 'SCANNER_START')
assert.equal(start.nodeParams.find(param => param.name === 'requestJson').input, '{}')

View File

@ -120,20 +120,11 @@ export const SCANNER_OPERATIONS = [
"title": "断开设备会话",
"action": "SCANNER_DISCONNECT",
"defaultBody": {
"confirm": false,
"discardProject": false,
"expectedProjectId": null,
"expectedSessionId": null
},
"fields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
},
{
"key": "discardProject",
"label": "舍弃尚未导出的内存工程",
@ -160,13 +151,6 @@ export const SCANNER_OPERATIONS = [
}
],
"requestFields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"literalOnly": true
},
{
"key": "discardProject",
"label": "舍弃尚未导出的内存工程",
@ -197,21 +181,12 @@ export const SCANNER_OPERATIONS = [
"title": "结束旧会话并重新连接",
"action": "SCANNER_RECONNECT",
"defaultBody": {
"confirm": false,
"discardProject": false,
"expectedProjectId": null,
"expectedSessionId": null,
"deviceType": 3
},
"fields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
},
{
"key": "discardProject",
"label": "舍弃尚未导出的内存工程",
@ -255,13 +230,6 @@ export const SCANNER_OPERATIONS = [
}
],
"requestFields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"literalOnly": true
},
{
"key": "discardProject",
"label": "舍弃尚未导出的内存工程",
@ -360,8 +328,7 @@ export const SCANNER_OPERATIONS = [
"title": "选择采集类型或采集设备",
"action": "SCANNER_SCAN_TYPE",
"defaultBody": {
"scanType": "mesh",
"confirm": false
"scanType": "mesh"
},
"fields": [
{
@ -385,14 +352,6 @@ export const SCANNER_OPERATIONS = [
"optional": false,
"nullable": false
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
},
{
"key": "device",
"label": "采集设备",
@ -453,18 +412,11 @@ export const SCANNER_OPERATIONS = [
"label": "扫描头"
}
]
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"literalOnly": true
}
],
"advanced": false,
"upload": false,
"note": "在创建工程后、开始采集前设置。摄影测量使用Trak和跟踪仪,标志点采集使用Laser和扫描头;切换设备须明确确认。工程已采集或导入框架后不可切换设备,应先保存数据并新建工程。"
"note": "在创建工程后、开始采集前设置。摄影测量使用Trak和跟踪仪,标志点采集使用Laser和扫描头。工程已采集或导入框架后不可切换设备,应先保存数据并新建工程。"
},
{
"key": "FRAMEWORK_UPLOAD",
@ -486,8 +438,7 @@ export const SCANNER_OPERATIONS = [
"title": "导入已上传的标志点框架",
"action": "SCANNER_FRAMEWORK_IMPORT",
"defaultBody": {
"fileIds": [],
"confirm": false
"fileIds": []
},
"fields": [
{
@ -497,14 +448,6 @@ export const SCANNER_OPERATIONS = [
"options": null,
"optional": false,
"nullable": false
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"requestFields": [
@ -513,13 +456,6 @@ export const SCANNER_OPERATIONS = [
"label": "已上传框架编号",
"type": "json",
"options": null
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"literalOnly": true
}
],
"advanced": false,
@ -907,12 +843,6 @@ export const SCANNER_OPERATIONS = [
"label": "移动工程UUID",
"type": "text"
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"literalOnly": true
},
{
"key": "fixedPoints",
"label": "固定工程配对点",
@ -956,8 +886,7 @@ export const SCANNER_OPERATIONS = [
"action": "SCANNER_EDIT",
"defaultBody": {
"projectUuid": "",
"markerIds": [],
"confirm": false
"markerIds": []
},
"fields": [],
"requestFields": [
@ -990,12 +919,6 @@ export const SCANNER_OPERATIONS = [
"key": "normals",
"label": "法向量",
"type": "json"
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"literalOnly": true
}
],
"advanced": true,
@ -1020,8 +943,7 @@ export const SCANNER_OPERATIONS = [
1
],
"deleteBelowPoints": false,
"deleteBelowMarkers": false,
"confirm": false
"deleteBelowMarkers": false
},
"fields": [],
"requestFields": [
@ -1044,12 +966,6 @@ export const SCANNER_OPERATIONS = [
"key": "deleteBelowMarkers",
"label": "裁剪标志点",
"type": "boolean"
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"literalOnly": true
}
],
"advanced": true,
@ -1252,28 +1168,9 @@ export const SCANNER_OPERATIONS = [
"path": "/calibration/start",
"title": "开始当前标定",
"action": "SCANNER_CALIBRATION_START",
"defaultBody": {
"confirm": false
},
"fields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"requestFields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"literalOnly": true
}
],
"defaultBody": {},
"fields": [],
"requestFields": [],
"advanced": false,
"upload": false,
"note": "先进入标定并选择模式;启动命令成功不代表现场姿态采集与整个标定流程已经完成。"
@ -1285,8 +1182,7 @@ export const SCANNER_OPERATIONS = [
"title": "设置跟踪仪标定类型",
"action": "SCANNER_CALIBRATION_TRAK",
"defaultBody": {
"trakType": 1,
"confirm": false
"trakType": 1
},
"fields": [
{
@ -1313,14 +1209,6 @@ export const SCANNER_OPERATIONS = [
],
"optional": false,
"nullable": false
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"requestFields": [
@ -1347,13 +1235,6 @@ export const SCANNER_OPERATIONS = [
}
],
"integer": true
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"literalOnly": true
}
],
"advanced": false,
@ -1366,28 +1247,9 @@ export const SCANNER_OPERATIONS = [
"path": "/calibration/startSystem",
"title": "开始系统标定",
"action": "SCANNER_CALIBRATION_SYSTEM",
"defaultBody": {
"confirm": false
},
"fields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"requestFields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"literalOnly": true
}
],
"defaultBody": {},
"fields": [],
"requestFields": [],
"advanced": false,
"upload": false,
"note": "先进入并设置系统标定条件,需要现场设备与标定件就绪。"
@ -1399,8 +1261,7 @@ export const SCANNER_OPERATIONS = [
"title": "设置自由标定开关",
"action": "SCANNER_CALIBRATION_FREE",
"defaultBody": {
"enabled": true,
"confirm": false
"enabled": true
},
"fields": [
{
@ -1410,14 +1271,6 @@ export const SCANNER_OPERATIONS = [
"options": null,
"optional": false,
"nullable": false
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"requestFields": [
@ -1426,18 +1279,13 @@ export const SCANNER_OPERATIONS = [
"label": "启用",
"type": "boolean",
"options": null
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"literalOnly": true
}
],
"advanced": false,
"upload": false,
"note": ""
"note": "每1秒查询一次设备任务结果;仅 succeeded 判为成功,failed 立即失败。5秒内仍未取得明确终态则失败并结束流程,不重复提交开关命令。",
"waitTimeoutMs": 5000,
"pollIntervalMs": 1000
},
{
"key": "CALIBRATION_CAPTURE",
@ -1445,28 +1293,9 @@ export const SCANNER_OPERATIONS = [
"path": "/calibration/capturePose",
"title": "采集标定姿态",
"action": "SCANNER_CALIBRATION_CAPTURE",
"defaultBody": {
"confirm": false
},
"fields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"requestFields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"literalOnly": true
}
],
"defaultBody": {},
"fields": [],
"requestFields": [],
"advanced": false,
"upload": false,
"note": "需要已进入自由标定流程并准备好当前姿态;每次执行采集一次姿态,不能用普通扫描数据代替。"
@ -1477,28 +1306,9 @@ export const SCANNER_OPERATIONS = [
"path": "/calibration/compute",
"title": "计算自由标定结果",
"action": "SCANNER_CALIBRATION_COMPUTE",
"defaultBody": {
"confirm": false
},
"fields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"requestFields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"literalOnly": true
}
],
"defaultBody": {},
"fields": [],
"requestFields": [],
"advanced": false,
"upload": false,
"note": "先完成自由标定所需的姿态采集,再计算结果;具体有效姿态数量由SDK判断。"
@ -1510,8 +1320,7 @@ export const SCANNER_OPERATIONS = [
"title": "设置精细标定开关",
"action": "SCANNER_CALIBRATION_ADVANCED",
"defaultBody": {
"enabled": true,
"confirm": false
"enabled": true
},
"fields": [
{
@ -1521,14 +1330,6 @@ export const SCANNER_OPERATIONS = [
"options": null,
"optional": false,
"nullable": false
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"requestFields": [
@ -1537,13 +1338,6 @@ export const SCANNER_OPERATIONS = [
"label": "启用",
"type": "boolean",
"options": null
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"literalOnly": true
}
],
"advanced": false,
@ -1557,8 +1351,7 @@ export const SCANNER_OPERATIONS = [
"title": "应用上次标定结果",
"action": "SCANNER_CALIBRATION_APPLY_LAST",
"defaultBody": {
"mode": 0,
"confirm": false
"mode": 0
},
"fields": [
{
@ -1586,14 +1379,6 @@ export const SCANNER_OPERATIONS = [
"optional": false,
"nullable": false,
"hint": "标定类别与快速/标准/精细不同;实际硬件支持由设备服务确认。"
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"requestFields": [
@ -1620,19 +1405,61 @@ export const SCANNER_OPERATIONS = [
}
],
"integer": true
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"literalOnly": true
}
],
"advanced": false,
"upload": false,
"note": "选择历史标定结果所属的标定类别;需要厂家软件中存在可应用的结果,不能以本平台任务编号替代。"
},
{
"key": "CALIBRATION_RECOVER",
"method": "POST",
"path": "/calibration/recover",
"title": "结束标定并恢复设备",
"action": "SCANNER_CALIBRATION_RECOVER",
"defaultBody": {
"force": false,
"expectedSessionId": null
},
"fields": [
{
"key": "force",
"label": "强制恢复",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false,
"hint": "需要强制恢复时启用;仍检查设备占用、未结束任务及当前会话。"
},
{
"key": "expectedSessionId",
"label": "当前设备会话编号",
"type": "text",
"options": null,
"optional": true,
"nullable": true,
"hint": "留空时在恢复前自动读取 /api/v1/status 的 sessionId;手动填写或引用的编号须与当前会话一致。"
}
],
"requestFields": [
{
"key": "force",
"label": "强制恢复",
"type": "boolean",
"options": null
},
{
"key": "expectedSessionId",
"label": "当前设备会话编号",
"type": "text",
"options": null,
"nullable": true
}
],
"advanced": false,
"upload": false,
"note": "结束当前标定并恢复设备;先暂停采集。会话编号留空时,平台在恢复前自动读取 /api/v1/status 的 sessionId;手动填写或引用的编号必须匹配当前会话。强制恢复默认关闭,不跳过设备占用或未结束控制任务检查。"
},
{
"key": "METADATA",
"method": "GET",

View File

@ -1,16 +1,17 @@
export function requestFieldParameter(fields) {
fields = (fields || []).filter(field => field.name !== 'confirm')
if (!fields?.length) return undefined
return { name: 'requestFields', type: 'input', input: {}, disabled: true, children: JSON.parse(JSON.stringify(fields)) }
}
export function validateRequestBindings(operation, fields = []) {
fields = fields.filter(field => field.name !== 'confirm')
const seen = new Set()
for (const field of fields) {
const descriptor = operation?.requestFields?.find(item => item.key === field.name)
if (!descriptor || seen.has(field.name)) throw new Error('请求字段未选择、重复或不受此接口支持')
seen.add(field.name)
if (field.type === 'quote') {
if (descriptor.literalOnly) throw new Error('本次操作的确认需要明确勾选')
if (!Array.isArray(field.quote) || field.quote.length < 3 || field.quote.some(item => typeof item !== 'string' || !item.trim()) || !['input', 'output'].includes(field.quoteType)) throw new Error(`${descriptor.label}的上游引用不完整`)
} else if (field.type === 'input') {
const value = field.input
@ -33,11 +34,11 @@ export function validateRequestBindings(operation, fields = []) {
}
export function recommendedRequestBindings(operation, nodes, options) {
const action = ['DISCONNECT', 'RECONNECT'].includes(operation?.key) ? 'SCANNER_STATUS' : operation?.key === 'EDIT' ? 'SCANNER_SCENE' : null
const action = ['DISCONNECT', 'RECONNECT', 'CALIBRATION_RECOVER'].includes(operation?.key) ? 'SCANNER_STATUS' : operation?.key === 'EDIT' ? 'SCANNER_SCENE' : null
const sources = nodes.filter(node => node.properties?.action === action && options.some(option => String(option.value) === String(node.id)))
if (!action || sources.length !== 1) return []
const keys = action === 'SCANNER_STATUS' ? [['expectedProjectId', 'projectId'], ['expectedSessionId', 'sessionId']] : [['projectUuid', 'projectUuid'], ['cloudUuid', 'cloudUuid']]
return keys.filter(([, key]) => sources[0].properties.outputParams?.some(field => field.name === key))
return keys.filter(([name, key]) => operation.requestFields.some(field => field.key === name) && sources[0].properties.outputParams?.some(field => field.name === key))
.map(([name, key]) => ({ name, label: operation.requestFields.find(field => field.key === name)?.label || name, type: 'quote', input: '', quoteType: 'output', quote: [sources[0].id, 'output', key], disabled: true }))
}

View File

@ -7,7 +7,7 @@ import { normalizeFlowResourceSchema } from './flowResources.js'
const operation = key => SCANNER_OPERATIONS.find(op => op.key === key)
test('all scanner controls expose request fields and useful scene/status IDs can be selected downstream', () => {
const nodes = createWorkcellNodeGroups()[0].nodeList
assert.equal(nodes.length, 38)
assert.equal(nodes.length, 39)
assert.ok(operation('EDIT').requestFields.some(field => field.key === 'projectUuid'))
assert.ok(operation('ALIGN').requestFields.some(field => field.key === 'fixedMarkerIds'))
assert.ok(nodes.find(node => node.action === 'SCANNER_STATUS').outputParams.some(field => field.name === 'scanMode'))
@ -42,10 +42,10 @@ test('literal ID arrays remain raw text instead of rounding uint64 values', () =
validateRequestBindings(operation('EDIT'), fields)
assert.equal(requestFieldParameter(fields).children[0].input, source)
})
test('field references validate names, duplicates, completeness and explicit confirmation', () => {
test('field references validate names, duplicates and completeness', () => {
const valid = { name: 'projectUuid', type: 'quote', quoteType: 'output', quote: ['scene', 'output', 'projectUuid'] }
assert.equal(validateRequestBindings(operation('EDIT'), [valid]).length, 1)
for (const fields of [[valid, valid], [{ ...valid, name: 'projectId' }], [{ ...valid, quote: [] }], [{ ...valid, name: 'confirm' }]]) assert.throws(() => validateRequestBindings(operation('EDIT'), fields))
for (const fields of [[valid, valid], [{ ...valid, name: 'projectId' }], [{ ...valid, quote: [] }]]) assert.throws(() => validateRequestBindings(operation('EDIT'), fields))
assert.throws(() => validateRequestBindings(operation('PARAMETERS'), [{ name: 'brightness', type: 'input', input: 19 }]))
})
test('recommendations distinguish SDK UUIDs from directory IDs and never choose ambiguous sources', () => {

View File

@ -6,7 +6,7 @@
<div v-for="(field,index) in modelValue" :key="index" class="binding-row">
<div class="binding-controls">
<el-select v-model="field.name" placeholder="选择请求字段" @change="() => selectField(field)"><el-option v-for="item in operation.requestFields" :key="item.key" :label="`${item.label} · ${item.key}`" :value="item.key" /></el-select>
<el-select v-model="field.type" :disabled="descriptor(field).literalOnly" class="source"><el-option value="quote" label="引用上游" /><el-option value="input" label="填写" /></el-select>
<el-select v-model="field.type" class="source"><el-option value="quote" label="引用上游" /><el-option value="input" label="填写" /></el-select>
<el-button link type="danger" aria-label="移除字段" @click="remove(index)">移除</el-button>
</div>
<el-cascader v-if="field.type === 'quote'" v-model="field.quote" :options="quoteOptions" :props="{ checkStrictly: true }" placeholder="选择上游节点和字段" @visible-change="emit('refresh')" @change="value => field.quoteType = value?.[1] === 'input' ? 'input' : 'output'" />
@ -28,20 +28,57 @@ function selectField(field) {
const meta = descriptor(field)
field.label = meta.label
field.input = meta.type === 'boolean' ? false : meta.type === 'json' ? '[]' : meta.type === 'number' ? null : ''
if (meta.literalOnly) field.type = 'input'
}
function add() { emit('update:modelValue', [...props.modelValue, { name: '', type: 'quote', quote: [], quoteType: 'output', input: '', disabled: true }]); emit('refresh') }
function remove(index) { emit('update:modelValue', props.modelValue.filter((_, i) => i !== index)) }
function recommend() { emit('update:modelValue', [...props.modelValue, ...suggestions.value.filter(item => !props.modelValue.some(field => field.name === item.name))]) }
</script>
<style scoped>
.field-bindings { margin: 16px 0; padding: 14px 0; border-top: 1px solid var(--el-border-color-lighter); }
.binding-heading,.binding-controls { display: flex; align-items: center; gap: 8px; }
.binding-heading { justify-content: space-between; font-weight: 600; }
.binding-row { margin-top: 14px; }
.binding-controls { margin-bottom: 8px; }
.binding-controls > :first-child { flex: 1; min-width: 0; }
.source { width: 108px; flex-shrink: 0; }
.el-cascader,.el-input-number { width: 100%; }
.hint { color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.7; margin: 4px 0; }
.field-bindings {
padding: 14px 0;
margin: 16px 0;
border-top: 1px solid var(--el-border-color-lighter);
}
.binding-heading,
.binding-controls {
display: flex;
align-items: center;
gap: 8px;
}
.binding-heading {
justify-content: space-between;
font-weight: 600;
}
.binding-row {
margin-top: 14px;
}
.binding-controls {
margin-bottom: 8px;
}
.binding-controls > :first-child {
flex: 1;
min-width: 0;
}
.source {
width: 108px;
flex-shrink: 0;
}
.el-cascader,
.el-input-number {
width: 100%;
}
.hint {
margin: 4px 0;
font-size: 12px;
line-height: 1.7;
color: var(--el-text-color-secondary);
}
</style>

View File

@ -16,7 +16,8 @@
</el-form-item>
<el-alert v-if="sourceMode === 'fixture'" title="自动引用开始节点的夹具框架点URL。执行任务时选择夹具即可;未配置时任务预检会阻止开始,请先到夹具管理录入或导入文件。" type="info" :closable="false" />
<el-form-item v-if="sourceMode === 'quote'" label="上游框架文件" required>
<el-cascader v-model="source.quote" :options="quoteOptions" :props="{ checkStrictly: true }"
<el-cascader
v-model="source.quote" :options="quoteOptions" :props="{ checkStrictly: true }"
placeholder="选择导出节点 → 输出 → frameworkFiles" @visible-change="refreshQuoteOptions" @change="value => cascaderChange(value, source)" />
<div class="note">推荐 frameworkFiles;也支持 frameworkUrls、result.files 或完整导出结果。循环中读取本轮结果。</div>
</el-form-item>
@ -25,10 +26,6 @@
<div class="note">支持 P3 / TXT / ASC,1–8个文件,单个最大100MiB;URL必须来自当前扫描服务。</div>
</el-form-item>
<el-alert title="流程顺序:导出P3 → 创建用于扫描的新工程 → 选择 trak / mesh / scanner → 导入框架 → 开始采集。不会自动切换工程。" type="info" :closable="false" />
<el-form-item class="confirmation">
<el-checkbox v-model="confirmed">已核对框架来源和目标扫描工程,允许流程导入</el-checkbox>
<div class="note">保存一次后随流程执行,无需每次手动上传。登记或导入结果不明确时停止流程,防止重复操作。</div>
</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-collapse><el-collapse-item title="输出参数" name="outputs">
@ -50,7 +47,7 @@ import { validateScannerRequest } from '@/cmvr/common/api/scanner'
const props = defineProps({ data: { type: Object, required: true } })
const emit = defineEmits(['save-success', 'save-error', 'cancel'])
const clone = value => JSON.parse(JSON.stringify(value))
const target = ref({}), confirmed = ref(false), saving = ref(false), legacy = ref(false)
const target = ref({}), saving = ref(false), legacy = ref(false)
const sourceMode = ref('fixture')
const localFiles = ref([]), uploading = ref(false)
function fixtureSource() {
@ -78,8 +75,8 @@ watch(() => props.data.id, () => {
Object.assign(source, { type: 'quote', input: '', quote: [], quoteType: 'output' }, clone(params.find(p => p.name === 'frameworkUrls') || {}))
Object.assign(timeout, { input: 120000 }, clone(params.find(p => p.name === 'timeoutMs') || {}))
const request = params.find(p => p.name === 'requestJson')
try { const body = JSON.parse(request?.input || '{}'); confirmed.value = request?.type === 'input' && body.confirm === true; legacy.value = Object.hasOwn(body, 'fileIds') }
catch { confirmed.value = false; legacy.value = true }
try { const body = JSON.parse(request?.input || '{}'); legacy.value = Object.hasOwn(body, 'fileIds') }
catch { legacy.value = true }
refreshQuoteOptions()
if (!legacy.value && source.type === 'quote' && !source.quote?.length) source.quote = defaultFrameworkQuote(window.lf.getGraphData().nodes, quoteOptions.value)
sourceMode.value = source.type === 'quote' && (source.quote?.[2] === 'fixtureFrameworkUrls' || !source.quote?.length) ? 'fixture' : source.type
@ -96,7 +93,7 @@ async function save() {
if (sourceMode.value === 'local') source.input = JSON.stringify(localFrameworkFiles(localFiles.value))
if (!target.value.roleKey || !target.value.deviceSlotKey) throw new Error('请选择执行角色和扫描仪设备用途')
if (source.type === 'quote' && (!source.quote?.length || source.quote.length < 3)) throw new Error('请选择上游导出的框架文件参数')
const request = { name: 'requestJson', type: 'input', input: JSON.stringify({ confirm: confirmed.value }), required: true, disabled: true }
const request = { name: 'requestJson', type: 'input', input: '{}', required: true, disabled: true }
const savedSource = clone(source)
if (savedSource.type === 'input') { savedSource.quote = []; savedSource.quoteType = 'output' }
const params = [request, savedSource, clone(timeout)]
@ -120,10 +117,29 @@ async function save() {
}
</script>
<style scoped>
.framework-form { margin-top: 20px; }
.el-alert + .el-alert { margin-top: 12px; }
.el-cascader { width: 100%; }
.note { color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.7; margin-top: 6px; }
.confirmation { margin-top: 20px; }
.actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 20px; }
.framework-form {
margin-top: 20px;
}
.el-alert + .el-alert {
margin-top: 12px;
}
.el-cascader {
width: 100%;
}
.note {
margin-top: 6px;
font-size: 12px;
line-height: 1.7;
color: var(--el-text-color-secondary);
}
.actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 20px;
}
</style>

View File

@ -17,7 +17,8 @@
</el-select>
</el-form-item>
<el-form-item v-if="request.type === 'quote'" label="引用参数" required>
<el-cascader v-model="request.quote" :options="quoteOptions" :props="{ checkStrictly: true }"
<el-cascader
v-model="request.quote" :options="quoteOptions" :props="{ checkStrictly: true }"
@visible-change="refreshQuoteOptions" @change="value => cascaderChange(value, request)" />
</el-form-item>
<template v-else>
@ -50,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" /></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>
<el-alert v-if="operation?.note" :title="operation.note" type="info" :closable="false" />
<div class="field-note">{{ operation?.key === 'SCAN_START' ? '本节点等待启动命令完成,随后设备持续采集;结束采集需要“暂停采集”节点。' : '控制操作会等待设备任务终态;等待超时不会撤销已受理的设备动作。' }}</div>
@ -122,7 +123,7 @@ function syncBody() {
function loadForm() {
const value = JSON.parse(request.input)
if (!value || Array.isArray(value) || typeof value !== 'object') throw new Error('参数必须为JSON对象')
if (Object.keys(value).some(key => !operation.value.fields.some(field => field.key === key))) throw new Error('含有表单外的字段,请保留 JSON 编辑并核对参数')
if (Object.keys(value).some(key => key !== 'confirm' && !operation.value.fields.some(field => field.key === key))) throw new Error('含有表单外的字段,请保留 JSON 编辑并核对参数')
for (const field of operation.value.fields) included[field.key] = Object.hasOwn(value, field.key)
for (const field of operation.value.fields) form[field.key] = Object.hasOwn(value, field.key) ? value[field.key]
: operation.value.key === 'PARAMETERS' ? operation.value.defaultBody[field.key]
@ -147,7 +148,8 @@ 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') || {}))
fieldBindings.value = clone(parameters.find(p => p.name === 'requestFields')?.children || [])
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
try { loadForm() } catch { rawMode.value = true }
@ -190,14 +192,67 @@ defineExpose({ validateAndSave })
</script>
<style scoped>
.scanner-status { display: flex; align-items: center; gap: 12px; padding: 12px 0; flex-wrap: wrap; }
.scanner-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 20px; }
.field-note { color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.6; margin: 8px 0 12px; }
.form-control { width: 100%; }
.framework-upload { position: relative; padding: 7px 14px; border: 1px solid var(--el-color-primary); border-radius: 4px; color: var(--app-primary-text); cursor: pointer; }
.framework-upload input { position: absolute; inset: 0; width: 100%; opacity: 0; cursor: pointer; }
.framework-upload.is-disabled { opacity: .5; cursor: not-allowed; }
.upload-error { color: var(--el-color-danger); font-size: 12px; line-height: 1.6; }
.el-select, .el-cascader, .el-input-number { width: 100%; }
:deep(textarea) { font-family: Consolas, monospace; }
.scanner-status {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 0;
flex-wrap: wrap;
}
.scanner-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 20px;
}
.field-note {
margin: 8px 0 12px;
font-size: 12px;
line-height: 1.6;
color: var(--el-text-color-secondary);
}
.form-control {
width: 100%;
}
.framework-upload {
position: relative;
padding: 7px 14px;
color: var(--app-primary-text);
cursor: pointer;
border: 1px solid var(--el-color-primary);
border-radius: 4px;
}
.framework-upload input {
position: absolute;
width: 100%;
cursor: pointer;
opacity: 0;
inset: 0;
}
.framework-upload.is-disabled {
cursor: not-allowed;
opacity: 0.5;
}
.upload-error {
font-size: 12px;
line-height: 1.6;
color: var(--el-color-danger);
}
.el-select,
.el-cascader,
.el-input-number {
width: 100%;
}
:deep(textarea) {
font-family: Consolas, monospace;
}
</style>

View File

@ -0,0 +1,316 @@
<template>
<el-button
v-for="action in maintenanceActions"
:key="action.key"
v-hasPermi="['lab:execution:dispatch', 'test:config:execute']"
:loading="busy && state.actionKey === action.key"
:disabled="(busy && state.actionKey !== action.key) || dialogVisible"
@click="openAction(action)"
>{{ action.label }}{{ busy && state.actionKey === action.key ? '(正在执行)' : '' }}</el-button
>
<span class="calibration-time" role="status" aria-live="polite">
扫描仪最后标定时间:{{ calibrationDate }}
</span>
<span v-if="busy" class="maintenance-status" role="status" aria-live="polite">
{{
state.phase === 'paused'
? '执行已暂停,等待继续'
: state.phase === 'recovering'
? '正在执行,状态同步暂不可用,正在重新连接'
: '正在执行,请稍候…'
}}
</span>
<el-dialog
v-model="dialogVisible"
:title="`${currentAction?.label || ''} · 执行设置`"
width="min(860px, 96vw)"
append-to-body
destroy-on-close
:close-on-click-modal="false"
:close-on-press-escape="!busy"
:show-close="!busy"
:before-close="closeDialog"
>
<div
v-loading="definitionLoading || checkingVersion || busy"
:element-loading-text="busy ? '正在启动执行…' : '正在读取当前执行配置…'"
class="maintenance-form"
>
<template v-if="definition">
<p class="maintenance-definition">
用例:{{ definition.caseName }}
<span v-if="definition.versionNo != null"> · 发布版本 V{{ definition.versionNo }}</span>
</p>
<h4>本次执行设备</h4>
<RuntimeAssignmentsEditor
:key="`${definition.caseId}:${definition.versionId}`"
ref="assignmentsEditor"
v-model="runtimeAssignments"
:roles="definition.roles"
/>
<h4>本次运行参数</h4>
<el-form v-if="definition.fields.length" label-position="top">
<ParameterFields v-model="runParams" :fields="definition.fields" />
</el-form>
<el-empty v-else :image-size="52" description="没有需要填写的运行参数" />
</template>
<el-alert
v-if="definitionError"
:title="definitionError"
type="error"
:closable="false"
show-icon
/>
</div>
<template #footer>
<el-button :disabled="busy" @click="closeDialog">取消</el-button>
<el-button v-if="definitionError" @click="loadDefinition">重新加载</el-button>
<el-button
type="primary"
:loading="checkingVersion || busy"
:disabled="definitionLoading || !definition"
@click="confirmExecution"
>开始执行</el-button
>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import {
computed,
ref,
shallowRef,
onMounted,
onActivated,
onDeactivated,
onBeforeUnmount
} from 'vue'
import {
startMaintenance,
getMaintenanceDefinition,
getMaintenanceStatus,
getScannerStatus
} from '@/api/lab/maintenance'
import { useUserStore } from '@/store/modules/user'
import RuntimeAssignmentsEditor from '@/cmvr/common/views/flow/components/RuntimeAssignmentsEditor.vue'
import ParameterFields from '@/views/lab/scan-task/ParameterFields.vue'
import {
createMaintenanceExecution,
createMaintenanceForm,
prepareMaintenanceRequest,
maintenanceActions,
formatScannerCalibrationDate
} from './maintenance.mjs'
const message = useMessage()
const user = useUserStore()
const state = ref({ actionKey: '', phase: 'idle', instId: '', message: '' })
const busy = computed(() => state.value.phase !== 'idle')
const calibrationDate = ref('正在获取…')
const dialogVisible = ref(false)
const currentAction = shallowRef<any>()
const definition = shallowRef<any>()
const definitionLoading = ref(false)
const checkingVersion = ref(false)
const definitionError = ref('')
const runtimeAssignments = ref<any[]>([])
const runParams = ref<Record<string, any>>({})
const assignmentsEditor = ref<InstanceType<typeof RuntimeAssignmentsEditor>>()
const formCache = new Map<string, any>()
let definitionRequest: AbortController | undefined
let pageActive = false
let statusRequest: AbortController | undefined
const storageKey = `am-freescan:maintenance:${user.getUser.id}`
const execution = createMaintenanceExecution({
start: startMaintenance,
readStatus: getMaintenanceStatus,
onState: (value: typeof state.value) => {
state.value = value
if (value.instId) dialogVisible.value = false
},
onResult: ({ action, success, message: detail }: any) => {
if (success) message.success(`${action.label}执行成功`)
else message.error(`${action.label}执行失败${detail ? `:${detail}` : ''}`)
if (action.key === 'scanner-calibration') void refreshCalibrationDate()
},
readPending: () => {
try {
return JSON.parse(sessionStorage.getItem(storageKey) || 'null')
} catch {
return null
}
},
writePending: (pending: any) => {
try {
if (pending) sessionStorage.setItem(storageKey, JSON.stringify(pending))
else sessionStorage.removeItem(storageKey)
} catch {
/* Status tracking still works when browser storage is unavailable. */
}
}
})
function snapshotForm() {
return {
definition: definition.value,
runtimeAssignments: JSON.parse(JSON.stringify(runtimeAssignments.value)),
runParams: JSON.parse(JSON.stringify(runParams.value))
}
}
function applyDefinition(value: any, previous?: any) {
const form = createMaintenanceForm(value, previous)
runtimeAssignments.value = form.runtimeAssignments
runParams.value = form.runParams
definition.value = value
}
async function openAction(action: any) {
if (busy.value || dialogVisible.value) return
currentAction.value = action
definition.value = undefined
definitionError.value = ''
dialogVisible.value = true
await loadDefinition()
}
async function loadDefinition() {
if (!currentAction.value || busy.value) return
definitionRequest?.abort()
const request = new AbortController()
definitionRequest = request
definitionLoading.value = true
definitionError.value = ''
try {
const value = await getMaintenanceDefinition(currentAction.value, request.signal)
if (definitionRequest === request && !request.signal.aborted)
applyDefinition(value, formCache.get(currentAction.value.caseId))
} catch (error) {
if (definitionRequest === request && !request.signal.aborted)
definitionError.value = (error as Error).message || '读取用例执行配置失败'
} finally {
if (definitionRequest === request) {
definitionRequest = undefined
definitionLoading.value = false
}
}
}
function closeDialog(done?: unknown) {
if (busy.value) return
if (definition.value && currentAction.value)
formCache.set(currentAction.value.caseId, snapshotForm())
definitionRequest?.abort()
definitionRequest = undefined
definitionLoading.value = false
checkingVersion.value = false
dialogVisible.value = false
if (typeof done === 'function') done()
}
async function confirmExecution() {
if (busy.value || definitionLoading.value || checkingVersion.value || !definition.value) return
const assignmentError = assignmentsEditor.value?.validate()
if (assignmentError) {
message.warning(assignmentError)
return
}
let data: any
try {
data = prepareMaintenanceRequest(definition.value, {
runtimeAssignments: runtimeAssignments.value,
runParams: runParams.value
})
} catch (error) {
message.warning((error as Error).message)
return
}
const request = new AbortController()
definitionRequest = request
checkingVersion.value = true
try {
const latest = await getMaintenanceDefinition(currentAction.value, request.signal)
if (definitionRequest !== request || request.signal.aborted) return
if (
latest.versionId !== definition.value.versionId ||
latest.itemId !== definition.value.itemId
) {
applyDefinition(latest, snapshotForm())
message.warning('用例已更新,已刷新执行配置,请核对后再次点击“开始执行”')
return
}
formCache.set(currentAction.value.caseId, snapshotForm())
definitionRequest = undefined
checkingVersion.value = false
await execution.run(currentAction.value, data)
} catch (error) {
if (!request.signal.aborted) message.error((error as Error).message || '读取用例执行配置失败')
} finally {
if (definitionRequest === request) {
definitionRequest = undefined
checkingVersion.value = false
}
}
}
async function refreshCalibrationDate() {
if (!pageActive) return
statusRequest?.abort()
const request = new AbortController()
statusRequest = request
try {
const status = await getScannerStatus(request.signal)
if (statusRequest === request && !request.signal.aborted)
calibrationDate.value = formatScannerCalibrationDate(status.lastCalibrationUtc)
} catch {
if (statusRequest === request && !request.signal.aborted) calibrationDate.value = '暂无法获取'
} finally {
if (statusRequest === request) statusRequest = undefined
}
}
function activate() {
if (pageActive) return
pageActive = true
void execution.restore()
void refreshCalibrationDate()
}
function deactivate() {
pageActive = false
execution.dispose()
closeDialog()
dialogVisible.value = false
definitionRequest?.abort()
definitionRequest = undefined
statusRequest?.abort()
statusRequest = undefined
}
onMounted(activate)
onActivated(activate)
onDeactivated(deactivate)
onBeforeUnmount(deactivate)
</script>
<style scoped>
.maintenance-status,
.calibration-time {
display: inline-block;
margin-left: 12px;
font-size: 13px;
color: var(--el-text-color-secondary);
}
.calibration-time {
white-space: nowrap;
}
.maintenance-form {
min-height: 160px;
}
.maintenance-definition {
color: var(--el-text-color-secondary);
}
</style>

View File

@ -25,10 +25,9 @@
clearable
@keyup.enter="load" /></el-form-item
><el-button @click="load" :loading="loading">查询</el-button
><el-button v-if="!resultMode" @click="router.push('/lab/task/import')"
>批量导入</el-button
></el-form
>
><el-button v-if="!resultMode" @click="router.push('/lab/task/import')">批量导入</el-button
><MaintenanceActions v-if="mine && !resultMode"
/></el-form>
<el-table :data="rows" v-loading="loading">
<template v-if="resultMode" #empty>
<el-empty description="尚无尺寸比对返回的成套STL和PDF;扫描及补扫文件可在“文件查询”查看。">
@ -113,6 +112,7 @@
import * as Api from '@/api/lab/dimension'
import { deliveryStages, taskStates } from './presentation.mjs'
import ResultFilesDialog from './ResultFilesDialog.vue'
import MaintenanceActions from './MaintenanceActions.vue'
const resultFiles = ref<any>()
const router = useRouter(),
route = useRoute(),

View File

@ -0,0 +1,281 @@
import {
getResourceRoles,
validateFlowResources,
sanitizeFlowResourceDefinition
} from '../../../cmvr/common/utils/flowResources.js'
import { parameterFields, parameterDefaults, materializeParams } from '../scan-task/scanForm.mjs'
export const maintenanceActions = [
{
key: 'rotary-home',
label: '旋转底座回零',
caseId: 'ead3a87e968248718c2988bd23048d56'
},
{
key: 'scanner-calibration',
label: '扫描仪标定',
caseId: 'bedfaa6307c84141a72c9529d6232162'
}
]
export function formatScannerCalibrationDate(utc) {
if (utc == null || (typeof utc === 'string' && !utc.trim())) return '暂无记录'
if (typeof utc !== 'string') return '时间格式异常'
const value = utc.trim()
// The supplier field is UTC even when its ISO timestamp omits the timezone suffix.
const date = new Date(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value}Z`)
if (!Number.isFinite(date.getTime())) return '时间格式异常'
const parts = new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hourCycle: 'h23'
}).formatToParts(date)
const part = (type) => parts.find((item) => item.type === type)?.value
return `${part('year')}年${part('month')}月${part('day')}日${part('hour')}时${part('minute')}分${part('second')}秒`
}
/** Load the current published contract. Opening this form never dispatches a workflow. */
export async function loadMaintenanceDefinition(action, { readCase, readItem, readVersion }) {
const testCase = await readCase(action.caseId)
if (!testCase?.detectItemId) throw new Error('测试用例不存在或未关联流程')
if (String(testCase.enabled) === '1') throw new Error('测试用例已停用')
const item = await readItem(testCase.detectItemId)
if (!item?.publishedVersionId) throw new Error('用例流程尚未发布,请先在用例页面发布')
const version = await readVersion(item.publishedVersionId)
if (String(version?.detectionItemId) !== String(testCase.detectItemId)) {
throw new Error('发布版本不属于当前用例流程')
}
let source
try {
source = typeof version.flowData === 'string' ? JSON.parse(version.flowData) : version.flowData
} catch {
throw new Error('已发布的用例流程数据无效,请在用例页面检查后重新发布')
}
if (!source?.nodes?.some((node) => node.type === 'start'))
throw new Error('已发布的用例流程缺少开始节点')
const { graph, errors } = validateFlowResources(source)
if (errors.length) throw new Error(errors[0].message)
return {
caseId: action.caseId,
caseName: testCase.caseName || testCase.name || action.label,
itemId: testCase.detectItemId,
versionId: String(item.publishedVersionId),
versionNo: version.versionNo,
graph,
roles: getResourceRoles(graph),
fields: parameterFields(undefined, graph)
}
}
const clone = (value) => JSON.parse(JSON.stringify(value))
const compatibleValues = (fields, oldFields = [], values = {}) =>
Object.fromEntries(
fields.flatMap((field) => {
const previous = oldFields.find(
(item) => item.name === field.name && item.type === field.type
)
if (!previous || values[field.name] === undefined) return []
return [
[
field.name,
field.type === 'object' && field.children?.length
? compatibleValues(field.children, previous.children, values[field.name] || {})
: clone(values[field.name])
]
]
})
)
/** Keep only choices whose role, slot and parameter type still belong to this version. */
export function createMaintenanceForm(definition, previous = {}) {
return {
runtimeAssignments: definition.roles.map((role) => {
const oldRole = previous.definition?.roles.find((item) => item.roleKey === role.roleKey)
const member = previous.runtimeAssignments?.find((item) => item.roleKey === role.roleKey)
?.members?.[0]
return {
roleKey: role.roleKey,
members: [
{
memberKey: `${role.roleKey}_1`,
robotId: member?.robotId || role.legacyRobotId || '',
devices: Object.fromEntries(
(role.deviceSlots || []).map((slot) => {
const compatible = oldRole?.deviceSlots?.some(
(old) => old.slotKey === slot.slotKey && old.deviceKind === slot.deviceKind
)
return [
slot.slotKey,
(compatible && member?.devices?.[slot.slotKey]) || slot.legacyDeviceId || ''
]
})
)
}
]
}
}),
runParams: parameterDefaults(
definition.fields,
compatibleValues(definition.fields, previous.definition?.fields, previous.runParams)
)
}
}
export function prepareMaintenanceRequest(definition, { runtimeAssignments = [], runParams = {} }) {
const devicesUsed = new Map()
const assignments = definition.roles.flatMap((role) => {
const member = runtimeAssignments.find((item) => item.roleKey === role.roleKey)?.members?.[0]
if (!member?.robotId) {
if (role.required) throw new Error(`请为“${role.displayName}”选择机器人`)
return []
}
const devices = {}
for (const slot of role.deviceSlots || []) {
const deviceId = member.devices?.[slot.slotKey]
if (!deviceId) {
if (slot.required) throw new Error(`请为“${role.displayName}”选择“${slot.displayName}”`)
continue
}
const key = JSON.stringify([member.robotId, deviceId])
const existing = devicesUsed.get(key)
if (existing && (!existing.allowReuse || !slot.allowReuse))
throw new Error(`“${existing.roleName}”和“${role.displayName}”不能使用同一个设备`)
devicesUsed.set(key, { allowReuse: slot.allowReuse, roleName: role.displayName })
devices[slot.slotKey] = deviceId
}
return [
{
roleKey: role.roleKey,
members: [{ memberKey: `${role.roleKey}_1`, robotId: member.robotId, devices }]
}
]
})
return {
itemId: definition.itemId,
flowData: JSON.stringify(sanitizeFlowResourceDefinition(definition.graph)),
robotId: assignments[0]?.members[0]?.robotId || '',
runtimeAssignments: assignments,
runParams: materializeParams(definition.fields, runParams)
}
}
function delay(milliseconds, signal) {
return new Promise((resolve, reject) => {
const abort = () => {
clearTimeout(timer)
reject(new DOMException('aborted', 'AbortError'))
}
const timer = setTimeout(() => {
signal.removeEventListener('abort', abort)
resolve()
}, milliseconds)
if (signal.aborted) abort()
else signal.addEventListener('abort', abort, { once: true })
})
}
/** Submission is not completion. Poll only the returned instance until a persisted terminal status. */
export function createMaintenanceExecution({
start,
readStatus,
onState,
onResult,
readPending = () => null,
writePending = (_pending) => {},
wait = delay
}) {
let active = null
let monitoringEnabled = true
const emit = (action, phase, instId = '', message = '') =>
onState({ actionKey: action?.key || '', phase, instId, message })
const finish = (action, token, success, message = '') => {
if (active !== token || token.signal.aborted) return
active = null
writePending(null)
emit(null, 'idle')
onResult({ action, success, message })
}
const monitor = async (action, instId, token) => {
while (active === token && !token.signal.aborted) {
try {
const result = await readStatus(instId, token.signal)
if (active !== token || token.signal.aborted) return false
const status = String(result?.status)
if (status === '0') {
finish(action, token, true)
return true
}
if (status === '2' || status === '4') {
finish(
action,
token,
false,
result.message || (status === '4' ? '执行已终止' : '流程执行失败')
)
return false
}
if (!['1', '3'].includes(status)) throw new Error('暂未取得明确执行状态')
emit(action, status === '3' ? 'paused' : 'running', instId)
} catch (error) {
if (token.signal.aborted) return false
// A lost status response cannot prove that the physical workflow failed or stopped.
emit(action, 'recovering', instId, error?.message || '状态查询暂不可用')
}
await wait(1000, token.signal)
}
return false
}
const track = async (action, instId, token) => {
try {
return await monitor(action, instId, token)
} catch (error) {
if (!token.signal.aborted) throw error
return false
}
}
const restore = async () => {
monitoringEnabled = true
if (active) return false
const pending = readPending()
const action = maintenanceActions.find((item) => item.key === pending?.actionKey)
if (!action || typeof pending?.instId !== 'string' || !pending.instId) return false
const token = new AbortController()
active = token
emit(action, 'running', pending.instId)
return track(action, pending.instId, token)
}
return {
async run(action, request) {
if (active) return false
const token = new AbortController()
active = token
emit(action, 'starting')
try {
const instId = await start(action, token.signal, request)
if (!instId) throw new Error('未取得执行实例编号,请核对执行记录')
writePending({ actionKey: action.key, instId })
if (active !== token || token.signal.aborted) {
// Reactivation can precede the acknowledgement: resume only after its ID is known.
return monitoringEnabled && !active ? restore() : false
}
emit(action, 'running', instId)
return await track(action, instId, token)
} catch (error) {
if (!token.signal.aborted) finish(action, token, false, error?.message || '启动执行失败')
return false
}
},
restore,
dispose() {
monitoringEnabled = false
active?.abort()
active = null
// Keep the instance reference for refresh/return; never send a physical stop on navigation.
}
}
}

View File

@ -6037,3 +6037,27 @@ HTTP父进程监控SDK自动连接和异常重启。SDK工作进程可更换,H
|state|paused|
|state|blocked|
|state|session_active|
## POST 结束标定并恢复设备
POST /api/v1/calibration/recover
2026-11-07 补充:请求路径、标题和请求体由用户提供的接口示例确认,现场服务公开路由清单也包含此接口。平台按现有控制接口的异步任务协议接入:提交后取得 taskId,继续查询 GET /api/v1/tasks/{taskId},以任务终态判断成功或失败;HTTP 202 只表示受理。
> Body 请求参数
```json
{
"confirm": true,
"force": true,
"expectedSessionId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
```
|参数|类型|说明|
|---|---|---|
|confirm|boolean|厂家协议固定 true,由平台 HTTP 适配层补齐,不作为流程表单勾选项。|
|force|boolean|是否请求强制恢复;平台节点默认 false,操作人可显式开启或引用上游布尔值。|
|expectedSessionId|string 或 null|当前设备会话编号;省略或为 null 时,平台在恢复前自动读取 /api/v1/status 的 sessionId 并填入。显式填写或引用上游状态的编号仍须与当前会话匹配。|
平台保持设备身份、启用状态、执行占用、未结束控制任务、采集停止和会话匹配检查。仅显式 force=true 的本操作允许向厂家恢复接口提交 restartRequired/stateUncertain 状态,不放宽其他扫描控制接口。请求超时或回执不完整时保留未确认命令,禁止自动重发。

View File

@ -0,0 +1,29 @@
{
"date": "2026-11-06",
"request": "QUIC certificate: add 192.168.0.199; retain the original IP, CA and server private key",
"sourceProject": "E:\\workspace\\backend\\CMVR-IOT",
"previousIpAddresses": [
"192.168.0.222"
],
"currentIpAddresses": [
"192.168.0.222",
"192.168.0.199"
],
"subject": "CN=192.168.0.222",
"issuer": "CN=CMVR QUIC Local CA",
"notBefore": "2026-07-24 06:44:36+00:00",
"notAfter": "2028-10-26 06:44:36+00:00",
"originalCaRetained": true,
"serverPrivateKeyUnchanged": true,
"sourceFilesUnmodified": true,
"existingPrivateApplicationConfigurationUnmodified": true,
"caPrivateKeyCopied": false,
"privateConfiguration": ".local/scanner-private.yaml",
"certificate": ".local/quic-certs/quic-gateway.crt",
"originalCertificate": ".local/quic-certs/quic-gateway-original.crt",
"certificateSha256": "1e1115abc6a717bae5fd0f45d8365f4d7d024202ddf4b40e0db3121b3baa26f3",
"caCertificateSha256": "036244c4c877c579404960ebb654d6cd02cc1b582ab011d59601541efa7ea191",
"quicPort": 4433,
"httpPort": 48090,
"alpn": "cmvr-quic-edge/1"
}

View File

@ -26,6 +26,30 @@
## 接口与组件
### 设置自由标定开关的执行结果(2026-11-07)
`SCANNER_CALIBRATION_FREE` 提交 `/api/v1/calibration/setFree` 后,按返回的同一 taskId 查询 `/api/v1/tasks/{taskId}`,收到 202 仅表示受理。每 1000ms 查询一次,只有 `state=succeeded` 才成功;`state=failed` 立即令节点及流程失败。运行中、排队中或暂未返回状态时最多等待 5000ms,查询请求也受剩余时间限制,过期响应不能变为成功。超时停止轮询并令流程失败,仍保留尚未确认结束的原设备任务记录及占用检查,不能据此重发命令。
该策略同时适用于已有发布流程,不需要重新发布才能生效;此节点的等待超时在表单中固定显示为 5000ms,其他扫描仪节点的等待配置保持不变。
### 任务中心快捷执行(2026-11-07)
“我的任务”的“旋转底座回零”和“扫描仪标定”先打开执行设置窗口,读取对应测试用例当前已发布版本,按流程角色选择机器人、设备,并填写开始节点声明的运行参数。新增旋转底座等资源后不需要修改快捷按钮的设备类型配置。只有点击“开始执行”才会启动流程;取消、关闭或读取配置失败均不会执行设备动作。
窗口再次打开时复用当前页面中仍适用的上次选择,机器人及设备按实时资源列表重新匹配,失效或新增配置需要补选。弹窗期间若用例重新发布,开始前刷新配置并提示再次核对,不按旧版本静默启动。需要临时输入的业务参数应在开始节点声明,节点内部固定配置仍在用例页面维护。
沿用资源类型、身份、设备状态和占用校验;取得执行实例后关闭窗口,按钮保持 loading 并跟踪该实例的真实成功、失败或终止状态。扫描仪标定结束后重新获取最后标定时间。
### 结束标定并恢复设备(2026-11-07)
在“扫描仪”分组新增 `SCANNER_CALIBRATION_RECOVER`,复用扫描仪节点表单、角色与设备用途绑定以及命令执行适配器,后端请求配置的扫描服务 `POST /api/v1/calibration/recover`。不在节点中保存 IP、端口或 Token;Bearer 认证继续由后端配置提供。
表单包含“强制恢复”(默认关闭)、“当前设备会话编号”和等待超时。会话编号留空时,平台在恢复前自动读取 `/api/v1/status` 的 `sessionId` 并填入 `expectedSessionId`;也可填写当前会话编号、逐字段引用上游 `sessionId` 或引用整个请求对象,显式提供的编号仍须与当前会话匹配。字段 `confirm` 不进入表单,厂家要求的 `confirm:true` 仅由 HTTP 适配层补齐。
恢复操作允许使用已登记、已启用但设备状态异常或离线的本机 HTTP 扫描仪,仍验证身份和资源占用。执行前读取当前状态,拒绝采集中、会话不匹配或无法确认会话的请求。仅本操作显式设置 `force:true` 时可处理 restartRequired/stateUncertain;其他扫描操作的门禁保持。强制恢复不能越过尚未结束或结果不确定的控制命令。
沿用命令日志、幂等键和任务轮询:收到 202 后等待原 taskId 进入 succeeded/failed,超时保留原命令并禁止重发;节点成功后立即刷新真实资源状态,输出任务编号、终态、厂家结果和原始请求,供后续节点引用。本节点结束标定会话,不据此声明标定质量合格。
2026-10-27 接入用户提供的 API 1.3 文档,新增 `/scan/type`、`/framework/files`、`/framework/import`、`/framework/optimize`。文档顶部仍保留旧版接口数量,任务查询路径示例改成了具体编号;平台按实际路由清单比对,继续使用 `/tasks/{taskId}`,没有删除原有接口。
“选择采集类型与设备”“导入标志点框架”“优化摄影测量框架”已加入组件库。采集类型 `mesh` 是表面采集,不是后处理生成网格;摄影测量要求 Trak + tracker,标志点采集要求 Laser + scanner。工程已有采集数据或已导入框架时,SDK拒绝切换设备,平台保留 `project_data_present`,不自动新建工程或重试。
@ -147,7 +171,9 @@ FreeScan HTTP 工位不应配置 gRPC 地址。未加载工位绑定时,已登
原生试运行发生节点异常后,会停止关联设备并等待其他执行节点退出、清理设备会话。全部确认成功才释放原生试运行占用,执行状态和原始错误仍保留为失败;停止超时、旧节点尚未退出或会话清理失败时保留 `STOP_PENDING`,不能复用此前暂停取得的停止确认。批量扫描任务仍按原有工作台生命周期管理资源。
手动恢复入口位于“资源中心 → 设备预约 / 场地预约”顶部的“实际资源占用”:原生试运行及人工控制使用“停止并确认释放”,正式扫描任务进入对应“任务工作台”取消或确认停止。重启后端不会直接清空数据库中的占用记录。改变采集设备所需的 `confirm:true` 仍由操作人确认,平台不自动勾选或修改用户流程。
手动恢复入口位于“资源中心 → 设备预约 / 场地预约”顶部的“实际资源占用”:原生试运行及人工控制使用“停止并确认释放”,正式扫描任务进入对应“任务工作台”取消或确认停止。重启后端不会直接清空数据库中的占用记录。
2026-11-06 按用户要求移除扫描仪节点“已核对本次操作的目标和影响”及框架导入同类勾选项,保存、发布和执行均不再校验用户配置的 `confirm`。新节点不再提供或保存该参数,已有流程中的旧值及旧请求字段配置兼容忽略。供应商 API 要求的 `confirm:true` 由 HTTP 适配层自动补齐,不作为流程参数。工程、会话、数据类型、设备状态、停止回执和资源释放校验继续生效;“确认网格”等实际协议动作保留。
### 激光亮度与点间距

View File

@ -22,6 +22,7 @@ def main():
public = {
'server': {'port': 48090},
'spring': {
'config': {'import': '${cmvr.scanner.config-location:optional:file:./.local/scanner-private.yaml}'},
'application': {'name': 'am-freescan'},
'autoconfigure': {'exclude': ['org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration',
'com.binarywang.spring.starter.wxjava.mp.config.WxMpAutoConfiguration',

View File

@ -1,6 +1,12 @@
{
"document": "扫描设备api (4).md",
"sha256": "06cc3a1fe038215abf674eddad71a72ef2f519fc9f77c8027fcde9bd56604e11",
"document": "scanner-api.md",
"sha256": "8465fb73ddbbf336d4e3bda563cbebacfda8f62fea3394e4026dfc5e5d6f6223",
"sourceHistory": [
{
"document": "扫描设备api (4).md",
"sha256": "06cc3a1fe038215abf674eddad71a72ef2f519fc9f77c8027fcde9bd56604e11"
}
],
"operations": [
{
"operation": "CONNECT",
@ -390,6 +396,17 @@
"path": "/api/v1/framework/files",
"request": null,
"upload": true
},
{
"operation": "CALIBRATION_RECOVER",
"method": "POST",
"path": "/api/v1/calibration/recover",
"request": {
"confirm": true,
"force": true,
"expectedSessionId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
},
"upload": false
}
]
}

View File

@ -18,23 +18,25 @@ def field_options(operation,key):
templates={
'CONNECT':{'deviceType':3}, 'CREATE_PROJECT':{'mode':'trak'},
'SCAN_TYPE':{'scanType':'mesh','confirm':False},
'FRAMEWORK_IMPORT':{'fileIds':[],'confirm':False},
'DISCONNECT':{'confirm':False,'discardProject':False,'expectedProjectId':None,'expectedSessionId':None},
'RECONNECT':{'confirm':False,'discardProject':False,'expectedProjectId':None,'expectedSessionId':None,'deviceType':3},
'SCAN_TYPE':{'scanType':'mesh'},
'FRAMEWORK_IMPORT':{'fileIds':[]},
'DISCONNECT':{'discardProject':False,'expectedProjectId':None,'expectedSessionId':None},
'RECONNECT':{'discardProject':False,'expectedProjectId':None,'expectedSessionId':None,'deviceType':3},
'PARAMETERS':{'pointDistance':0.2,'brightness':8}, 'MESH':{},
'EXPORT':{'formats':['PLY']}, 'SNAPSHOT':{'maxPoints':100000,'include':['points','markers','meshes']},
'ALIGN':{'action':'enter'}, 'EDIT':{'projectUuid':'','markerIds':[],'confirm':False},
'CLIP_PLANE':{'center':[0,0,0],'normal':[0,0,1],'deleteBelowPoints':False,'deleteBelowMarkers':False,'confirm':False},
'CALIBRATION_MODE':{'mode':0},'CALIBRATION_TRAK':{'trakType':1,'confirm':False},
'CALIBRATION_APPLY_LAST':{'mode':0,'confirm':False},
'CALIBRATION_FREE':{'enabled':True,'confirm':False},'CALIBRATION_ADVANCED':{'enabled':True,'confirm':False},
'ALIGN':{'action':'enter'}, 'EDIT':{'projectUuid':'','markerIds':[]},
'CLIP_PLANE':{'center':[0,0,0],'normal':[0,0,1],'deleteBelowPoints':False,'deleteBelowMarkers':False},
'CALIBRATION_MODE':{'mode':0},'CALIBRATION_TRAK':{'trakType':1},
'CALIBRATION_APPLY_LAST':{'mode':0},
'CALIBRATION_RECOVER':{'force':False,'expectedSessionId':None},
'CALIBRATION_FREE':{'enabled':True},'CALIBRATION_ADVANCED':{'enabled':True},
}
labels={'deviceType':'设备类型','mode':'工程或标定模式','name':'工程或导出名称','formats':'导出格式',
'confirm':'已核对本次操作的目标和影响','discardProject':'舍弃尚未导出的内存工程',
'discardProject':'舍弃尚未导出的内存工程',
'expectedProjectId':'已核对的工程目录编号','expectedSessionId':'已核对的设备会话编号',
'enabled':'启用','trakType':'跟踪仪标定类型','scanType':'采集内容','device':'采集设备','fileIds':'已上传框架编号'}
labels.update(brightness='激光亮度',pointDistance='点间距')
labels.update(force='强制恢复')
labels.update(projectUuid='SDK工程UUID',cloudUuid='SDK点云UUID',pointIds='SDK原始点号',markerIds='标志点编号',
fixedProjectUuid='固定工程UUID',movingProjectUuid='移动工程UUID',fixedPoints='固定工程配对点',movingPoints='移动工程配对点',
fixedMarkerPoints='固定标志点坐标',movingMarkerPoints='移动标志点坐标',fixedMarkerIds='固定标志点编号',movingMarkerIds='移动标志点编号',
@ -47,7 +49,7 @@ labels.update(projectUuid='SDK工程UUID',cloudUuid='SDK点云UUID',pointIds='SD
deleteBelowPoints='裁剪点云',deleteBelowMarkers='裁剪标志点')
notes={
'SNAPSHOT':'原始场景快照依赖SDK实际场景数据。新文档示例支持pauseAcquisition布尔字段,参数表尚未列出;默认不发送此字段,需使用时在JSON中显式配置并核对设备支持。',
'SCAN_TYPE':'在创建工程后、开始采集前设置。摄影测量使用Trak和跟踪仪,标志点采集使用Laser和扫描头;切换设备须明确确认。工程已采集或导入框架后不可切换设备,应先保存数据并新建工程。',
'SCAN_TYPE':'在创建工程后、开始采集前设置。摄影测量使用Trak和跟踪仪,标志点采集使用Laser和扫描头。工程已采集或导入框架后不可切换设备,应先保存数据并新建工程。',
'FRAMEWORK_IMPORT':'引用上游P3/TXT/ASC下载结果,运行时自动读取、登记及导入,无需手动上传。要求Trak模式、表面采集、扫描头、已暂停且未生成网格。厂家服务重启后旧URL可能失效,需重新导出。',
'FRAMEWORK_OPTIMIZE':'暂停摄影测量采集后优化框架,要求Trak和跟踪仪,且当前工程已进行摄影测量采集。优化完成后使用“导出文件”仅选择P3;再次采集会使框架需要重新优化。',
'EXPORT':'普通成果须暂停采集并确认网格。摄影测量框架须暂停且已优化,仅选择P3可直接保存,无需生成表面网格;混合格式仍要求已确认网格。',
@ -60,9 +62,11 @@ notes={
'CALIBRATION_START':'先进入标定并选择模式;启动命令成功不代表现场姿态采集与整个标定流程已经完成。',
'CALIBRATION_TRAK':'先进入对应跟踪仪标定流程,再选择标定类型。类型编号可填写或引用上游。',
'CALIBRATION_SYSTEM':'先进入并设置系统标定条件,需要现场设备与标定件就绪。',
'CALIBRATION_FREE':'每1秒查询一次设备任务结果;仅 succeeded 判为成功,failed 立即失败。5秒内仍未取得明确终态则失败并结束流程,不重复提交开关命令。',
'CALIBRATION_CAPTURE':'需要已进入自由标定流程并准备好当前姿态;每次执行采集一次姿态,不能用普通扫描数据代替。',
'CALIBRATION_COMPUTE':'先完成自由标定所需的姿态采集,再计算结果;具体有效姿态数量由SDK判断。',
'CALIBRATION_APPLY_LAST':'选择历史标定结果所属的标定类别;需要厂家软件中存在可应用的结果,不能以本平台任务编号替代。',
'CALIBRATION_RECOVER':'结束当前标定并恢复设备;先暂停采集。会话编号留空时,平台在恢复前自动读取 /api/v1/status 的 sessionId;手动填写或引用的编号必须匹配当前会话。强制恢复默认关闭,不跳过设备占用或未结束控制任务检查。',
}
def request_keys():
@ -72,12 +76,13 @@ def request_keys():
def reference_field(operation,key,fields):
json_keys=set('fileIds formats include markerDiameters pointIds markerIds points normals center normal fixedPoints movingPoints fixedMarkerPoints movingMarkerPoints fixedMarkerIds movingMarkerIds'.split())
bool_keys=set('confirm discardProject highSpeedMode addMarkerMode viewLock localEnlargedView qualityColor strongLight preScanMode cutMeshEdgeOptimization holeOptimization boundaryOptimization removeSpikes fillMarkerHoles rememberChoice pauseAcquisition deleteBelowPoints deleteBelowMarkers enabled'.split())
bool_keys=set('discardProject force highSpeedMode addMarkerMode viewLock localEnlargedView qualityColor strongLight preScanMode cutMeshEdgeOptimization holeOptimization boundaryOptimization removeSpikes fillMarkerHoles rememberChoice pauseAcquisition deleteBelowPoints deleteBelowMarkers enabled'.split())
number_keys=set('deviceType brightness pointDistance lightSourceMode scanFrameRate filterLevel smoothLevel removeSmallFloatingParts cutMeshEdgeValue maxTriangles fillSmallHole maxPoints trakType'.split())
kind='json' if key in json_keys else 'boolean' if key in bool_keys else 'number' if key in number_keys or key=='mode' and operation not in ('CREATE_PROJECT','ALIGN') else 'text'
field=dict(key=key,label=labels.get(key,key),type=kind)
old=next((f for f in fields if f['key']==key),{})
field.update({k:old[k] for k in ('options','min','max','integer','precision') if k in old})
if operation=='CALIBRATION_RECOVER' and key=='expectedSessionId':field.update(label='当前设备会话编号',nullable=True)
options=field_options(operation,key)
if options is not None:field['options']=options
if key=='mode' and operation in ('CALIBRATION_MODE','CALIBRATION_APPLY_LAST'):field['label']='标定类别'
@ -85,7 +90,6 @@ def reference_field(operation,key,fields):
if kind=='number' and key not in ('pointDistance','cutMeshEdgeValue'):field['integer']=True
if operation=='ALIGN' and key=='action':field['options']=[dict(value=v,label=label) for v,label in [('enter','进入拼接'),('apply','应用配对参数'),('next','应用当前变换并继续'),('cancel','撤销当前变换'),('exit','确认并退出')]]
if operation=='ALIGN' and key=='mode':field['options']=[dict(value=v,label=label) for v,label in [('featureAuto','自动特征'),('markerAuto','自动标志点'),('featureManual','手动特征'),('markerManual','手动标志点')]]
if key=='confirm':field['literalOnly']=True
if operation=='MESH' and key in ('maxTriangles','fillSmallHole'):field['nullable']=True
return field
@ -94,7 +98,6 @@ def main():
bindings=request_keys()
for name,method,path,title,action in operations():
default=templates.get(name,{})
if name in ('CALIBRATION_START','CALIBRATION_SYSTEM','CALIBRATION_CAPTURE','CALIBRATION_COMPUTE'):default={'confirm':False}
fields=[]
if name not in ('MESH','SNAPSHOT','ALIGN','EDIT','CLIP_PLANE'):
for key in dict.fromkeys(list(default)+(['name'] if name in ('CREATE_PROJECT','EXPORT') else ['device'] if name=='SCAN_TYPE' else [])):
@ -113,11 +116,14 @@ def main():
if key=='mode' and name=='CREATE_PROJECT':fields[-1]['label']='工程模式'
if name=='PARAMETERS' and key=='brightness':fields[-1].update(min=1,max=18,step=1,precision=0,integer=True,hint='1–18,整数;默认8')
if name=='PARAMETERS' and key=='pointDistance':fields[-1].update(min=0.05,max=10,step=0.05,hint='0.05–10;默认0.2')
if name=='CALIBRATION_RECOVER' and key=='force':fields[-1].update(hint='需要强制恢复时启用;仍检查设备占用、未结束任务及当前会话。')
if name=='CALIBRATION_RECOVER' and key=='expectedSessionId':fields[-1].update(label='当前设备会话编号',optional=True,hint='留空时在恢复前自动读取 /api/v1/status 的 sessionId;手动填写或引用的编号须与当前会话一致。')
records.append(dict(key=name,method=method,path='/metadata' if path=='/' else path.removeprefix('/api/v1'),
title=title,action=action or None,defaultBody=default,fields=fields,
requestFields=[reference_field(name,key,fields) for key in bindings.get(name,[])],
advanced=name in ('MESH','SNAPSHOT','ALIGN','EDIT','CLIP_PLANE'),
upload=name=='FRAMEWORK_UPLOAD',note=notes.get(name,'')))
if name=='CALIBRATION_FREE':records[-1].update(waitTimeoutMs=5000,pollIntervalMs=1000)
target=ROOT/'am-web/src/cmvr/common/utils/scannerOperations.mjs'
target.write_text('// Generated from ScannerOperation.java by scripts/generate_scanner_frontend.py.\n'
+'export const SCANNER_OPERATIONS = '+json.dumps(records,ensure_ascii=False,indent=2)+'\n'

View File

@ -14,11 +14,11 @@ class ScannerContractTest(unittest.TestCase):
target=Path(folder)/'contract.json'
with patch.object(contract,'FIXTURE',target):contract.extract(contract.ROOT/'docs/integrations/scanner-api.md')
rows={row['operation']:row for row in json.loads(target.read_text(encoding='utf-8'))['operations']}
self.assertEqual(len(rows),42)
self.assertEqual(len(rows),43)
self.assertIsNone(rows['FRAMEWORK_UPLOAD']['request']);self.assertTrue(rows['FRAMEWORK_UPLOAD']['upload'])
self.assertEqual(rows['TASK']['path'],'/api/v1/tasks/{taskId}')
self.assertIn('METADATA',rows);self.assertEqual(rows['SCAN_TYPE']['request']['scanType'],'photogrammetry')
self.assertEqual(sum(row['method']=='POST' and not row['upload'] for row in rows.values()),30)
self.assertEqual(sum(row['method']=='POST' and not row['upload'] for row in rows.values()),31)
self.assertEqual(rows['CREATE_PROJECT']['request'],{'mode':'trak','name':'Part001'})
self.assertEqual(rows['CALIBRATION_MODE']['request'],{'mode':0})
self.assertEqual(rows['CALIBRATION_APPLY_LAST']['request'],{'mode':0,'confirm':True})

View File

@ -45,8 +45,16 @@ def extract(source):
operations.append(dict(operation=names[('GET','/')],method='GET',path='/',request=None,upload=False))
require(len(operations) == len(routes) and len({row['operation'] for row in operations}) == len(routes),
'Supplier route inventory is incomplete or duplicated')
fingerprint = dict(document=source.name, sha256=hashlib.sha256(raw).hexdigest())
history = []
if FIXTURE.exists():
previous = json.loads(FIXTURE.read_text(encoding='utf-8'))
history = previous.get('sourceHistory', [])
original = {key: previous[key] for key in ('document', 'sha256')}
if original != fingerprint and original not in history:
history = [*history, original]
FIXTURE.parent.mkdir(parents=True, exist_ok=True)
FIXTURE.write_text(json.dumps(dict(document=source.name, sha256=hashlib.sha256(raw).hexdigest(),
FIXTURE.write_text(json.dumps(dict(**fingerprint, sourceHistory=history,
operations=operations), ensure_ascii=False, indent=2), encoding='utf-8')