feat(扫描): 新增独立手持流程与逐段人工结束控制

新增夹具八段和车架单段手持流程维护入口,机械臂均不运动,车架AGV不移动;保留为未发布草稿。
增加本段采集结束按钮和后端等待门,核对任务样件归属、工程、当前运行上下文和随机段编号,阻止旧点击与重复提交误放行。
暂停恢复重新建门,超时中断不自动进入换面或后续采集;修复恢复节点派发前状态竞态并保留停止确认。
后端真实编译及64项离线验证通过,前端18项验证和Vue脚本模板编译通过,新增临时验证文件已清理。
This commit is contained in:
Codex 2026-11-28 16:20:59 +08:00
parent 3b6e44ee1b
commit eaf29b8209
17 changed files with 755 additions and 6 deletions

View File

@ -0,0 +1,83 @@
package com.cmvr.scanner;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import com.cmvr.test.flow.runtime.operator.edge.WorkcellDeviceAdapter;
import com.cmvr.test.flow.runtime.operator.edge.WorkcellNodeContract;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
/** A per-segment human finish gate. START and confirmed STOP remain separate nodes. */
@Service
@RequiredArgsConstructor
public class ScannerManualScanAdapter implements WorkcellDeviceAdapter {
private final ScannerWorkflowAdapter driver;
private final ScannerMonitoringService monitoring;
private final ScannerManualScanSignals signals;
@Override public boolean supports(ActionEnum action) { return action == ActionEnum.SCANNER_MANUAL_WAIT; }
@Override public void validateConfiguration(String robot, String device) { driver.validateConfiguration(robot, device); }
@Override public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) {
JSONObject input = message.getInputParams();
WorkcellNodeContract.validate(ActionEnum.SCANNER_MANUAL_WAIT, input);
validateConfiguration(message.getRobotId(), input.getString("deviceId"));
JsonNode binding = currentBinding(message).deepCopy();
requireCollecting(monitoring.status(binding));
ScannerManualScanSignals.Gate gate = signals.enter(message, input.getString("label"), input.getLongValue("timeoutMs"));
try {
while (!signals.finishRequested(gate)) {
try { Thread.sleep(200); }
catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new ScannerException("interrupted", "手持采集等待已中断;需继续确认设备停止", 409);
}
}
JsonNode latest = currentBinding(message);
for (String field : List.of("instId", "robotId", "deviceId", "endpoint", "sessionId", "projectId", "commandKey", "itemOrder", "itemOccurrence")) {
if (!binding.path(field).equals(latest.path(field))) {
throw new ScannerException("project_changed", "手持采集期间工程、会话或采集关联已变化,不能完成本段", 409);
}
}
requireCollecting(monitoring.status(binding));
signals.processing(gate);
return TaskNodeExecuteResult.success(JSONObject.of("gateId", gate.gateId(), "nodeId", gate.nodeId(),
"label", gate.label(), "projectId", binding.path("projectId").asText(),
"manualFinishRequested", true, "phase", "PROCESSING"));
} finally {
signals.close(gate);
}
}
private JsonNode currentBinding(TaskNodeExecuteMessage message) {
String instId = message.getInstId();
if (instId == null || instId.isBlank()) throw new ScannerException("runtime_pending", "手持采集必须由任务工作台启动", 409);
JsonNode binding = monitoring.binding(instId);
if (binding == null || !instId.equals(binding.path("instId").asText())
|| !message.getRobotId().equals(binding.path("robotId").asText())
|| !message.getInputParams().getString("deviceId").equals(binding.path("deviceId").asText())
|| !binding.path("itemOrder").isIntegralNumber() || binding.path("itemOrder").asInt() != message.getItemOrder()
|| !binding.path("itemOccurrence").isIntegralNumber() || binding.path("itemOccurrence").asInt() != message.getItemOccurrence()) {
throw new ScannerException("project_not_bound", "本段尚未建立属于本次执行的扫描工程关联,不能进入手持采集", 409);
}
return binding;
}
private void requireCollecting(JsonNode status) {
for (String field : List.of("initialized", "deviceOnline", "scanning")) {
if (!status.path(field).isBoolean() || !status.path(field).booleanValue()) {
throw new ScannerException("scanner_not_collecting", "扫描仪未确认在线并正在采集,不能完成手持采集段", 409);
}
}
for (String field : List.of("busy", "stateUncertain", "restartRequired")) {
if (!status.path(field).isBoolean() || status.path(field).booleanValue()) {
throw new ScannerException("scanner_not_ready", "扫描仪状态待确认,不能完成手持采集段", 409);
}
}
}
}

View File

@ -0,0 +1,159 @@
package com.cmvr.scanner;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.test.enums.TaskStatusEnum;
import com.cmvr.test.flow.context.TaskContext;
import com.cmvr.test.flow.context.TaskInstHolder;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
/**
* A finish intent belongs to one live wait invocation, never to a whole task or a
* future station. Runtime contexts are local to this process; after a restart no
* old nonce can become actionable. This does not acknowledge physical scan stop.
*/
@Service
public class ScannerManualScanSignals {
private final TaskInstHolder tasks;
private final Map<String, Gate> gates = new ConcurrentHashMap<>();
public ScannerManualScanSignals(@Lazy TaskInstHolder tasks) { this.tasks = tasks; }
public Gate enter(TaskNodeExecuteMessage message, String label, long timeoutMs) {
String instId = required(message.getInstId());
required(message.getTaskId()); required(message.getItemId()); required(message.getNodeId());
TaskContext context = tasks.getContext(instId);
if (!running(context) || !instId.equals(context.getInstId())
|| !message.getTaskId().equals(context.getTaskId()) || Thread.currentThread().isInterrupted()) {
throw unavailable();
}
if (label == null || label.isBlank() || label.trim().length() > 200 || timeoutMs < 1 || timeoutMs > 3600000) {
throw new ScannerException("invalid_manual_gate", "手持采集段名称或等待期限无效", 400);
}
// Include item occurrence, nested invocation and the complete iteration path.
String scope = JSONObject.toJSONString(Arrays.asList(instId, message.getItemId(), message.getItemOrder(),
message.getItemOccurrence(), message.getNodeId(), message.getIterations(), message.getSubFlowExecutionId()));
Gate gate = new Gate(UUID.randomUUID().toString().replace("-", ""), instId,
message.getNodeId(), label.trim(), scope, timeoutMs, context, Thread.currentThread());
gates.compute(instId, (key, previous) -> {
if (previous != null && live(previous) && !expired(previous)) {
throw new ScannerException("manual_gate_active", "本次执行已有手持采集段等待结束,不能并行进入另一段", 409);
}
return gate;
});
return gate;
}
/** Platform state only: this endpoint must not poll the scanner SDK. */
public Map<String, Object> state(String instId) {
Gate gate = instId == null ? null : gates.get(instId);
if (gate == null) return emptyState();
synchronized (gate) {
String phase = gate.phase;
if (!live(gate)) phase = "ABORTED";
else if (expired(gate)) phase = "TIMED_OUT";
boolean collecting = "COLLECTING".equals(phase);
Map<String, Object> state = new LinkedHashMap<>();
state.put("available", collecting); state.put("collecting", collecting);
state.put("gateId", gate.gateId); state.put("nodeId", gate.nodeId);
state.put("label", gate.label); state.put("phase", phase); state.put("timeoutAt", gate.timeoutAt);
return state;
}
}
/** Called only after the task aggregate has verified ownership and RUNNING state. */
public void finish(String instId, String gateId) {
Gate gate = instId == null ? null : gates.get(instId);
if (gate == null || gateId == null || !gate.gateId.equals(gateId)) throw stale();
synchronized (gate) {
if (gates.get(instId) != gate || !live(gate) || expired(gate)
|| !"COLLECTING".equals(gate.phase)) throw stale();
gate.phase = "FINISH_REQUESTED";
}
}
public boolean finishRequested(Gate gate) {
synchronized (gate) {
requireLiveWait(gate);
return "FINISH_REQUESTED".equals(gate.phase);
}
}
public void processing(Gate gate) {
synchronized (gate) {
requireLiveWait(gate);
if (!"FINISH_REQUESTED".equals(gate.phase)) throw stale();
gate.phase = "PROCESSING";
}
}
public void close(Gate gate) {
// Identity removal cannot erase a newer invocation's gate.
if (gate != null) gates.remove(gate.instId, gate);
}
private void requireLiveWait(Gate gate) {
if (gate == null || gates.get(gate.instId) != gate || Thread.currentThread() != gate.thread || !live(gate)) throw unavailable();
if (expired(gate)) {
throw new ScannerException("manual_scan_timeout", "手持采集等待人工结束超时;本段未完成,请确认设备停止后处理", 504);
}
}
private boolean live(Gate gate) {
return tasks.getContext(gate.instId) == gate.context && running(gate.context)
&& gate.thread.isAlive() && !gate.thread.isInterrupted();
}
private static boolean running(TaskContext context) {
return context != null && context.getStatus() == TaskStatusEnum.RUNNING && !context.isPaused() && !context.isStopped();
}
private static boolean expired(Gate gate) { return System.nanoTime() - gate.deadlineNanos >= 0; }
public static Map<String, Object> emptyState() {
Map<String, Object> state = new LinkedHashMap<>();
state.put("available", false); state.put("collecting", false); state.put("gateId", "");
state.put("nodeId", ""); state.put("label", ""); state.put("phase", "NONE");
return state;
}
private static String required(String value) {
if (value == null || value.isBlank()) throw unavailable();
return value;
}
private static ScannerException unavailable() {
return new ScannerException("manual_scan_unavailable", "手持采集执行已暂停、停止或本段等待已失效,请刷新状态", 409);
}
private static ScannerException stale() {
return new ScannerException("manual_scan_gate_changed", "当前手持采集段已变更、已结束或已超时,请刷新状态", 409);
}
public static final class Gate {
private final String gateId, instId, nodeId, label, scope;
private final long timeoutAt, deadlineNanos;
private final TaskContext context;
private final Thread thread;
private String phase = "COLLECTING";
private Gate(String gateId, String instId, String nodeId, String label, String scope,
long timeoutMs, TaskContext context, Thread thread) {
this.gateId = gateId; this.instId = instId; this.nodeId = nodeId; this.label = label;
this.scope = scope; this.timeoutAt = System.currentTimeMillis() + timeoutMs;
this.deadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMs);
this.context = context; this.thread = thread;
}
public String gateId() { return gateId; }
public String nodeId() { return nodeId; }
public String label() { return label; }
public String scope() { return scope; }
}
}

View File

@ -82,6 +82,7 @@ public enum ActionEnum {
SCANNER_BATTERY("EDGE", "SCANNER_BATTERY", "读取扫描仪和跟踪仪电量"),
SCANNER_SUPPLEMENT_PREPARE("EDGE", "SCANNER_SUPPLEMENT_PREPARE", "核对原工程并准备补扫"),
SCANNER_SUPPLEMENT_WAIT("EDGE", "SCANNER_SUPPLEMENT_WAIT", "补扫采集,等待结束或到时"),
SCANNER_MANUAL_WAIT("EDGE", "SCANNER_MANUAL_WAIT", "手持采集,等待人工结束"),
MOTOR_SET_MODE("EDGE", "MOTOR_SET_MODE", "设置模式"),
MOTOR_VELOCITY("EDGE", "MOTOR_VELOCITY", "轮廓速度控制"),
MOTOR_ENABLE("EDGE", "MOTOR_ENABLE", "使能"),

View File

@ -268,7 +268,13 @@ public class FlowControlService {
for (TaskNodeExecuteContext discarded : discardedSubFlowNodes) {
nodeInstService.delete(instId, discarded.getNode().getNodeId(), discarded.getIterations());
}
// Publish a coherent live state before any resumed worker can run.
// A worker may start immediately inside executor.execute().
ctx.setTerminalStatus(TerminalStatusEnum.RUNNING);
ctx.setStatus(TaskStatusEnum.RUNNING);
ctx.updateTimestamp();
ctx.setPaused(false);
try {
List<TaskNodeExecuteContext> pendingNodes = taskThreadRegistry.getPendingNodes(instId);
List<TaskNodeExecuteContext> pendingLoops = pendingNodes.stream()
.filter(node -> node.getNode().getNodeType().equals(NodeTypeEnum.LOOP))
@ -348,13 +354,22 @@ public class FlowControlService {
}
}
// 最终设置上下文和数据库状态为 RUNNING
ctx.setTerminalStatus(TerminalStatusEnum.RUNNING);
ctx.setStatus(TaskStatusEnum.RUNNING);
ctx.updateTimestamp();
// A fast worker may already have completed or failed; do not overwrite its terminal state.
if (taskInstHolder.getContext(instId) != ctx || ctx.isStopped() || ctx.isPaused()
|| ctx.getStatus() != TaskStatusEnum.RUNNING) return;
taskInstHolder.syncStatus(instId, TaskStatusEnum.RUNNING);
// 发布任务恢复事件
taskInstHolder.syncStatusAsResumed(instId);
} catch (RuntimeException dispatchFailure) {
// Acquisition may already have resumed and earlier workers may have started.
// Use the existing blocking pause/StopAll confirmation path; never leave a
// rejected dispatch reported as RUNNING or retry a device operation here.
if (taskInstHolder.getContext(instId) == ctx && !ctx.isStopped() && !ctx.isPaused()) {
try { pause(instId); }
catch (RuntimeException cleanupFailure) { dispatchFailure.addSuppressed(cleanupFailure); }
}
throw new GlobalException("恢复节点调度失败,已请求重新暂停并确认设备停止,请刷新状态后处理", dispatchFailure);
}
}
private List<String> robotIds(TaskContext context) {

View File

@ -23,12 +23,12 @@ public final class WorkcellNodeContract {
}
public static boolean supports(ActionEnum action) {
return action != null && (supplement(action) || ScannerOperation.forAction(action.getAction()) != null || MOTOR.contains(action) || com.cmvr.rotarybase.RotaryBaseParameters.ACTIONS.contains(action));
return action != null && (action == ActionEnum.SCANNER_MANUAL_WAIT || supplement(action) || ScannerOperation.forAction(action.getAction()) != null || MOTOR.contains(action) || com.cmvr.rotarybase.RotaryBaseParameters.ACTIONS.contains(action));
}
public static int deviceKind(ActionEnum action) {
if (!supports(action)) throw new GlobalException("不是扫描仪或电机节点");
return supplement(action) || ScannerOperation.forAction(action.getAction()) != null ? 14 : 10;
return action == ActionEnum.SCANNER_MANUAL_WAIT || supplement(action) || ScannerOperation.forAction(action.getAction()) != null ? 14 : 10;
}
public static void validate(ActionEnum action, JSONObject input) {
@ -38,6 +38,10 @@ public final class WorkcellNodeContract {
throw new GlobalException("timeoutMs 必须是 1 至 3600000 的整数毫秒");
}
ScannerOperation scanner = ScannerOperation.forAction(action.getAction());
if (action == ActionEnum.SCANNER_MANUAL_WAIT) {
validateManualLabel(input);
return;
}
if (supplement(action)) {
var context = ScannerRequestValidator.parse(required(input,"expectedContextJson"));
for (String name : java.util.List.of("sessionId","projectId","robotId","deviceId","endpoint"))
@ -90,6 +94,12 @@ public final class WorkcellNodeContract {
throw new GlobalException("timeoutMs 必须是 1 至 3600000 的整数毫秒");
}
ScannerOperation scanner = ScannerOperation.forAction(action.getAction());
if (action == ActionEnum.SCANNER_MANUAL_WAIT) {
if (dynamic.contains("label")) throw new GlobalException("手持采集段名称必须是固定文本");
validateManualLabel(literals);
if (names.contains("expectedContextJson")) throw new GlobalException("手持采集门必须使用本次执行的实时工程关联");
return;
}
if (scanner != null) {
if (names.stream().anyMatch(Set.of("planCode", "jobId", "format")::contains))
throw new GlobalException("旧扫描组件参数与真实接口不一致,请重新配置节点");
@ -112,6 +122,11 @@ public final class WorkcellNodeContract {
}
}
private static void validateManualLabel(JSONObject input) {
if (required(input, "label").length() > 200) throw new GlobalException("手持采集段名称不能超过200字");
if (input.containsKey("expectedContextJson")) throw new GlobalException("手持采集门必须使用本次执行的实时工程关联");
}
private static String required(JSONObject input, String key) {
Object value = input.get(key);
if (!(value instanceof String text) || text.isBlank()) throw new GlobalException(key + " 不能为空");

View File

@ -20,6 +20,9 @@ import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.*;
public class FlowControlServiceTest {
@ -132,6 +135,64 @@ public class FlowControlServiceTest {
assertTrue(unfinishedNodesStopped.get());
}
@Test
public void resumedWorkerSeesRunningBeforeItCanOpenAnInteractiveGate() {
TaskContext context = pausedContext();
TaskInstHolder holder = mock(TaskInstHolder.class);
when(holder.getContext("manual-inst")).thenReturn(context);
var registry = mock(TaskThreadRegistry.class);
var pending = pendingResumeNode();
when(registry.getPendingNodes("manual-inst")).thenReturn(List.of(pending));
var executor = mock(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.class);
doAnswer(call -> {
assertFalse(context.isPaused());
assertEquals(TaskStatusEnum.RUNNING, context.getStatus());
return null;
}).when(executor).execute(org.mockito.ArgumentMatchers.any(Runnable.class));
FlowControlService service = new FlowControlService(executor, holder, mock(ITeNodeInstService.class), registry,
mock(com.cmvr.test.flow.runtime.engine.FlowItemExecutor.class), null, null, null, null);
service.resume("manual-inst");
verify(executor).execute(org.mockito.ArgumentMatchers.any(Runnable.class));
verify(holder).syncStatus("manual-inst", TaskStatusEnum.RUNNING);
verify(holder).syncStatusAsResumed("manual-inst");
}
@Test
public void rejectedResumeDispatchUsesConfirmedPauseInsteadOfLeavingRunningAcquisition() {
TaskContext context = pausedContext();
TaskInstHolder holder = mock(TaskInstHolder.class);
when(holder.getContext("manual-inst")).thenReturn(context);
var registry = mock(TaskThreadRegistry.class);
var pending = pendingResumeNode(); pending.markExecutionFinished();
when(registry.getPendingNodes("manual-inst")).thenReturn(List.of(pending));
var executor = mock(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.class);
doThrow(new java.util.concurrent.RejectedExecutionException("offline rejection"))
.when(executor).execute(org.mockito.ArgumentMatchers.any(Runnable.class));
FlowControlService service = new FlowControlService(executor, holder, mock(ITeNodeInstService.class), registry,
mock(com.cmvr.test.flow.runtime.engine.FlowItemExecutor.class), null, null, null, null);
assertThrows(com.cmvr.common.exception.GlobalException.class, () -> service.resume("manual-inst"));
assertTrue(context.isPaused()); assertTrue(context.isPauseSettled());
assertEquals(TaskStatusEnum.PAUSED, context.getStatus());
verify(registry).interruptAll("manual-inst");
verify(holder).syncStatus("manual-inst", TaskStatusEnum.PAUSED);
verify(holder, never()).syncStatus("manual-inst", TaskStatusEnum.RUNNING);
verify(holder, never()).syncStatusAsResumed("manual-inst");
}
private TaskContext pausedContext() {
TaskContext context = new TaskContext(); context.setInstId("manual-inst"); context.setTaskId("manual-task");
context.setStatus(TaskStatusEnum.PAUSED); context.setPaused(true); context.setPauseSettled(true); context.setRobotIds(List.of());
return context;
}
private com.cmvr.test.flow.runtime.message.TaskNodeExecuteContext pendingResumeNode() {
var pending = new com.cmvr.test.flow.runtime.message.TaskNodeExecuteContext();
var node = new com.cmvr.test.flow.builder.FlowNodeWrapper(); node.setNodeId("manual-node"); node.setNodeType(com.cmvr.test.enums.NodeTypeEnum.FUNCTION);
pending.setNode(node); pending.setGraph(mock(com.cmvr.test.flow.builder.FlowGraph.class));
pending.setRootMessage(new com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage());
return pending;
}
private ITeTaskInstService taskInstService(String status) {
return (ITeTaskInstService) Proxy.newProxyInstance(
ITeTaskInstService.class.getClassLoader(),

View File

@ -43,6 +43,10 @@ public class ScanOnlyTaskController {
public CommonResult<Long> supplement(@Valid @RequestBody ScanTaskRequests.Supplement request){return success(service.startSupplement(request));}
@PostMapping("/finish-supplement") @PreAuthorize("@ss.hasPermission('lab:execution:control')")
public CommonResult<Boolean> finishSupplement(@Valid @RequestBody ScanTaskRequests.FinishSupplement request){service.finishSupplement(request);return success(true);}
@GetMapping("/manual-scan-state") @PreAuthorize("@ss.hasPermission('lab:task:query')")
public CommonResult<Map<String,Object>> manualScanState(@RequestParam Long taskId,@RequestParam Long executionId){return success(service.manualScanState(taskId,executionId));}
@PostMapping("/finish-manual-scan") @PreAuthorize("@ss.hasPermission('lab:execution:control')")
public CommonResult<Boolean> finishManualScan(@Valid @RequestBody ScanTaskRequests.FinishManualScan request){service.finishManualScan(request);return success(true);}
@PostMapping("/cancel") @PreAuthorize("@ss.hasPermission('lab:execution:cancel')")
public CommonResult<Boolean> cancel(@Valid @RequestBody ScanTaskRequests.Task request) { service.cancel(request.getTaskId(),request.getReason()); return success(true); }
@PostMapping("/confirm-stop") @PreAuthorize("@ss.hasPermission('lab:execution:cancel')")

View File

@ -22,6 +22,8 @@ public interface ScanOnlyTaskService {
Map<String,Object> supplementOption(Long taskId,Long unitId);
Long startSupplement(ScanTaskRequests.Supplement request);
void finishSupplement(ScanTaskRequests.FinishSupplement request);
Map<String,Object> manualScanState(Long taskId,Long executionId);
void finishManualScan(ScanTaskRequests.FinishManualScan request);
void cancel(Long taskId,String reason);
/** Internal emergency-stop observer only; never exposed as a user cancellation endpoint. */
void emergencyStop(Long taskId,List<Long> expectedLeaseIds,String source);

View File

@ -84,6 +84,7 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService {
@Resource private LabBizProperties properties;
@Resource private LabArtifactService artifacts;
@Resource private ScanSupplementWorkflow supplements;
@Resource private com.cmvr.scanner.ScannerManualScanSignals manualScans;
@Resource @Lazy private ScanOnlyTaskServiceImpl self;
@Override public boolean isScanTask(Long taskId) {
@ -372,6 +373,39 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService {
supplements.finish(execution.getId());audit(task,"SCAN_SUPPLEMENT_FINISH_REQUESTED",map("executionId",execution.getId()));
}
@Override @Transactional(rollbackFor=Exception.class)
public Map<String,Object> manualScanState(Long taskId,Long executionId){
LabTestTaskDO task=owned(taskId,false);var c=config(taskId);
LabExecutionDO execution=manualScanExecution(task,executionId);
if(!manualScanActive(c,execution))return com.cmvr.scanner.ScannerManualScanSignals.emptyState();
var link=bindings.selectById(executionId);
if(link==null||link.getCmvrInstId()==null||link.getCmvrInstId().isBlank())return com.cmvr.scanner.ScannerManualScanSignals.emptyState();
return manualScans.state(link.getCmvrInstId());
}
@Override @Transactional(rollbackFor=Exception.class)
public void finishManualScan(ScanTaskRequests.FinishManualScan request){
LabTestTaskDO task=owned(request.getTaskId(),false);var c=config(task.getId());
LabExecutionDO execution=manualScanExecution(task,request.getExecutionId());
if(!manualScanActive(c,execution))throw invalidParamException("当前没有可结束的手持采集段,请刷新状态");
var link=bindings.selectById(execution.getId());
if(link==null||link.getCmvrInstId()==null||link.getCmvrInstId().isBlank())throw invalidParamException("手持采集尚未启动,请等待或刷新状态");
manualScans.finish(link.getCmvrInstId(),request.getGateId());
audit(task,"SCAN_MANUAL_FINISH_REQUESTED",map("executionId",execution.getId(),"gateId",request.getGateId()));
}
private LabExecutionDO manualScanExecution(LabTestTaskDO task,Long executionId){
var execution=executions.selectById(executionId);
if(execution==null||!Objects.equals(execution.getTaskId(),task.getId()))throw invalidParamException("执行记录不属于当前扫描任务");
return execution;
}
private boolean manualScanActive(ScanTaskConfigDO config,LabExecutionDO execution){
if(!"RUNNING".equals(execution.getStatus())||execution.getSampleUnitId()==null||Boolean.TRUE.equals(config.getStopPending())||Boolean.TRUE.equals(config.getCancelRequested()))return false;
var unit=units.selectById(execution.getSampleUnitId());
return unit!=null&&Objects.equals(unit.getCurrentExecutionId(),execution.getId())&&"RUNNING".equals(unit.getStatus());
}
@Override @Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED)
public void onExecutionFinished(Long executionId,boolean success,String outputJson,String error) {
LabExecutionDO reference=executions.selectById(executionId);if(reference==null||!isScanTask(reference.getTaskId()))return;

View File

@ -57,6 +57,10 @@ public final class ScanTaskRequests {
@NotNull @Min(1) @Max(1800) private Integer durationSeconds;
}
@Data public static class FinishSupplement { @NotNull private Long taskId,executionId; }
@Data public static class FinishManualScan {
@NotNull private Long taskId,executionId;
@NotBlank @Pattern(regexp="[a-f0-9]{32}") private String gateId;
}
@Data public static class FixtureRange {
@NotNull private Long fixtureId;
@NotNull @DecimalMin("0.001") private BigDecimal maxLengthMm,maxWidthMm,maxHeightMm;

View File

@ -39,6 +39,8 @@ class ScanOnlyTaskServiceTest {
private ScanRobotOccupationMapper occupations;
private ScanResourceService resources;
private ScanSupplementWorkflow supplements;
private com.cmvr.scanner.ScannerManualScanSignals manualScans;
private cn.iocoder.yudao.module.lab.dal.mysql.execution.LabCmvrExecutionMapper bindings;
@BeforeEach void setup() {
service=new ScanOnlyTaskServiceImpl(); tasks=mock(LabTestTaskMapper.class); configs=mock(ScanTaskConfigMapper.class);
executions=mock(LabExecutionMapper.class);
@ -48,6 +50,8 @@ class ScanOnlyTaskServiceTest {
ReflectionTestUtils.setField(service,"units",units);ReflectionTestUtils.setField(service,"occupations",occupations);
resources=mock(ScanResourceService.class);ReflectionTestUtils.setField(service,"resources",resources);
supplements=mock(ScanSupplementWorkflow.class);ReflectionTestUtils.setField(service,"supplements",supplements);
manualScans=mock(com.cmvr.scanner.ScannerManualScanSignals.class);ReflectionTestUtils.setField(service,"manualScans",manualScans);
bindings=mock(cn.iocoder.yudao.module.lab.dal.mysql.execution.LabCmvrExecutionMapper.class);ReflectionTestUtils.setField(service,"bindings",bindings);
ReflectionTestUtils.setField(service,"timeline",mock(LabTaskTimelineMapper.class));ReflectionTestUtils.setField(service,"events",mock(LabExecutionEventMapper.class));
TenantContextHolder.setTenantId(1L); identity=mockStatic(SecurityFrameworkUtils.class); identity.when(SecurityFrameworkUtils::getLoginUserId).thenReturn(7L);
}
@ -235,5 +239,61 @@ class ScanOnlyTaskServiceTest {
service.onExecutionFinished(2L,true,"{}",null);
assertEquals("FAILED",execution.getStatus());assertEquals("FAILED",unit.getStatus());assertNotEquals("COMPLETED",task.getStatus());assertTrue(execution.getFailureReason().contains("archive disk full"));
}
@Test void ordinaryHandheldExecutionCanRequestOnlyItsCurrentManualGateWithoutCompletingTheExecution() {
var request=manualRequest();
when(manualScans.state("manual-inst")).thenReturn(Map.of("available",true,"collecting",true,"gateId",request.getGateId(),"phase","COLLECTING"));
assertEquals(true,service.manualScanState(1L,2L).get("available"));
service.finishManualScan(request);verify(manualScans).finish("manual-inst",request.getGateId());
verify(executions,never()).updateById(any(LabExecutionDO.class));verifyNoInteractions(resources,supplements);
}
@Test void manualGateRejectsForeignTaskAndOwnerBeforeWritingAFinishIntent() {
var request=manualRequest();var execution=executions.selectById(2L);execution.setTaskId(9L);
assertThrows(ServiceException.class,()->service.manualScanState(1L,2L));
assertThrows(ServiceException.class,()->service.finishManualScan(request));verifyNoInteractions(manualScans);
execution.setTaskId(1L);var task=tasks.selectById(1L);task.setOwnerId(9L);
assertThrows(ServiceException.class,()->service.manualScanState(1L,2L));
assertThrows(ServiceException.class,()->service.finishManualScan(request));verifyNoInteractions(manualScans);
}
@Test void pausedCancelledAndStopPendingManualExecutionsCannotFinishOrExposeAnAvailableGate() {
var request=manualRequest();var execution=executions.selectById(2L);var c=configs.byTask(1L);
execution.setStatus("PAUSED");assertEquals(false,service.manualScanState(1L,2L).get("available"));
assertThrows(ServiceException.class,()->service.finishManualScan(request));
execution.setStatus("RUNNING");c.setCancelRequested(true);assertEquals(false,service.manualScanState(1L,2L).get("available"));
assertThrows(ServiceException.class,()->service.finishManualScan(request));
c.setCancelRequested(false);c.setStopPending(true);assertEquals(false,service.manualScanState(1L,2L).get("available"));
assertThrows(ServiceException.class,()->service.finishManualScan(request));verifyNoInteractions(manualScans);
}
@Test void historicalOrUnboundManualAttemptCannotFinishTheCurrentSample() {
var request=manualRequest();var unit=units.selectById(3L);unit.setCurrentExecutionId(22L);
assertEquals(false,service.manualScanState(1L,2L).get("available"));
assertThrows(ServiceException.class,()->service.finishManualScan(request));verifyNoInteractions(manualScans);
unit.setCurrentExecutionId(2L);when(bindings.selectById(2L)).thenReturn(null);
assertEquals(false,service.manualScanState(1L,2L).get("available"));
assertThrows(ServiceException.class,()->service.finishManualScan(request));verifyNoInteractions(manualScans);
}
@Test void staleManualNonceIsPropagatedWithoutACompletionOrAuditSuccess() {
var request=manualRequest();
doThrow(new com.cmvr.scanner.ScannerException("manual_scan_gate_changed","采集段已变更",409)).when(manualScans).finish("manual-inst",request.getGateId());
assertThrows(com.cmvr.scanner.ScannerException.class,()->service.finishManualScan(request));
verify(executions,never()).updateById(any(LabExecutionDO.class));
verifyNoInteractions(resources,supplements);
}
@Test void actualStartedControlEventMovesTheUnitFromQueuedToRunningBeforeManualStateIsExposed() {
manualRequest();var execution=executions.selectById(2L);var unit=units.selectById(3L);
execution.setStatus("QUEUED");unit.setStatus("QUEUED");when(executions.selectByIdForUpdate(2L)).thenReturn(execution);
when(manualScans.state("manual-inst")).thenReturn(Map.of("available",true,"collecting",true,"phase","COLLECTING"));
assertEquals(false,service.manualScanState(1L,2L).get("available"));
service.onControl(2L,"RUNNING");
assertEquals("RUNNING",execution.getStatus());assertEquals("RUNNING",unit.getStatus());
assertEquals(true,service.manualScanState(1L,2L).get("available"));
}
private ScanTaskRequests.FinishManualScan manualRequest(){
task();config();
var execution=LabExecutionDO.builder().id(2L).taskId(1L).sampleUnitId(3L).executionType("INITIAL").status("RUNNING").build();
when(executions.selectById(2L)).thenReturn(execution);
var unit=new ScanSampleUnitDO();unit.setId(3L);unit.setCurrentExecutionId(2L);unit.setStatus("RUNNING");when(units.selectById(3L)).thenReturn(unit);
var link=new cn.iocoder.yudao.module.lab.dal.dataobject.execution.LabCmvrExecutionDO();link.setExecutionId(2L);link.setCmvrInstId("manual-inst");when(bindings.selectById(2L)).thenReturn(link);
var request=new ScanTaskRequests.FinishManualScan();request.setTaskId(1L);request.setExecutionId(2L);request.setGateId("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");return request;
}
private ScanTaskConfigDO config(){ScanTaskConfigDO c=new ScanTaskConfigDO();c.setTaskId(1L);c.setRuntimeAssignments(List.of());when(configs.byTask(1L)).thenReturn(c);return c;}
}

View File

@ -125,6 +125,19 @@ export interface SupplementOption { available: boolean; parentExecutionId?: Id;
export const getSupplementOption = (taskId: Id, unitId: Id) => request.get<SupplementOption>({ url: base + '/supplement-option', params: { taskId, unitId } })
export const startSupplement = (data: { taskId: Id; unitId: Id; parentExecutionId: Id; expectedRevision: number; durationSeconds: number; reason: string; idempotencyKey: string; sampleConfirmed: boolean; fixtureConfirmed: boolean; loadedConfirmed: boolean }) => request.post<Id>({ url: base + '/supplement', data })
export const finishSupplement = (taskId: Id, executionId: Id) => request.post({ url: base + '/finish-supplement', data: { taskId, executionId } })
export interface ManualScanState {
available: boolean
collecting: boolean
gateId: string
nodeId: string
label: string
phase: 'NONE' | 'COLLECTING' | 'FINISH_REQUESTED' | 'PROCESSING' | 'TIMED_OUT' | 'ABORTED' | 'FAILED'
timeoutAt?: number
}
export const getManualScanState = (taskId: Id, executionId: Id) =>
request.get<ManualScanState>({ url: base + '/manual-scan-state', params: { taskId, executionId }, silentError: true })
export const finishManualScan = (taskId: Id, executionId: Id, gateId: string) =>
request.post<boolean>({ url: base + '/finish-manual-scan', data: { taskId, executionId, gateId }, silentError: true })
export const acquireResources = (taskId: Id, expectedRevision: number) =>
request.post<ScanConfig>({ url: base + '/acquire-resources', data: { taskId, expectedRevision }, silentError: true })
export const releaseResources = (taskId: Id, reason: string) =>

View File

@ -0,0 +1,92 @@
<template>
<div v-if="target && (state.gate?.nodeId || state.error)" class="manual-scan-actions" role="group" aria-label="当前手持补扫">
<span v-if="state.gate?.label" class="manual-scan-label">当前补扫:{{ state.gate.label }}</span>
<el-button
v-if="state.gate?.phase === 'COLLECTING'"
type="primary"
v-hasPermi="['lab:execution:control']"
:disabled="!canFinish"
:loading="state.finishing"
@click="finish"
>结束本段补扫并继续</el-button>
<span v-if="waitingForStop" role="status">已请求结束本段,等待停止确认</span>
<span v-else-if="expired" class="manual-scan-warning" role="status">本段等待已超时,请查看任务处理结果。</span>
<span v-if="state.error" class="manual-scan-warning" role="status">{{ state.error }}</span>
</div>
</template>
<script setup lang="ts">
import * as ScanApi from '@/api/lab/scan-task'
import type { LabExecutionVO } from '@/api/lab/execution'
import { createManualScanControl, manualScanCollecting, manualScanTarget } from './manualScan.mjs'
const props = withDefaults(defineProps<{
detail: ScanApi.ScanTaskDetail
unit?: ScanApi.ScanUnit
execution?: Partial<LabExecutionVO>
active?: boolean
disabled?: boolean
}>(), { active: true, disabled: false })
const emit = defineEmits<{ changed: [] }>()
const message = useMessage()
const state = shallowRef<{
gate?: ScanApi.ManualScanState
checking: boolean
finishing: boolean
submitted: boolean
error: string
}>({ checking: false, finishing: false, submitted: false, error: '' })
const mountedActive = ref(true), visible = ref(!document.hidden), now = ref(Date.now())
const target = computed(() => manualScanTarget(props.detail, props.unit, props.execution,
props.active && !props.disabled && mountedActive.value && visible.value))
const control = createManualScanControl(ScanApi.getManualScanState, ScanApi.finishManualScan,
value => { state.value = value })
const canFinish = computed(() => !!target.value && !state.value.finishing && !state.value.submitted
&& manualScanCollecting(state.value.gate, now.value))
const waitingForStop = computed(() => ['FINISH_REQUESTED', 'PROCESSING'].includes(state.value.gate?.phase || '')
|| (state.value.submitted && !state.value.error))
const expired = computed(() => state.value.gate?.phase === 'TIMED_OUT'
|| (state.value.gate?.timeoutAt != null && state.value.gate.timeoutAt <= now.value))
watch(target, value => {
control.select(value)
if (value) void control.refresh()
}, { immediate: true })
let timer: ReturnType<typeof setInterval> | undefined
const checkVisibility = () => { visible.value = !document.hidden; now.value = Date.now() }
const checkFocus = () => { checkVisibility(); if (target.value) void control.refresh() }
onMounted(() => {
let lastChecked = 0
timer = setInterval(() => {
now.value = Date.now()
if (target.value && !state.value.finishing && now.value - lastChecked >= 2000) {
lastChecked = now.value
void control.refresh()
}
}, 1000)
document.addEventListener('visibilitychange', checkVisibility)
window.addEventListener('focus', checkFocus)
})
onActivated(() => { mountedActive.value = true; checkFocus() })
onDeactivated(() => { mountedActive.value = false })
onUnmounted(() => {
mountedActive.value = false
control.select(undefined)
if (timer) clearInterval(timer)
document.removeEventListener('visibilitychange', checkVisibility)
window.removeEventListener('focus', checkFocus)
})
async function finish() {
if (!canFinish.value) return
if (await control.finishCurrent()) {
message.success('已请求结束本段,等待停止确认')
emit('changed')
}
}
</script>
<style scoped>
.manual-scan-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
.manual-scan-label { color: var(--el-text-color-regular); }
.manual-scan-warning { color: var(--el-color-warning); font-size: 12px; }
</style>

View File

@ -503,6 +503,8 @@
>{{ selectedUnit.attemptNo ? '重新装夹并重试' : '确认装夹并开始' }}</el-button
>
<ScanSupplementActions :detail="detail" :unit="selectedUnit" :execution="selectedExecution" @changed="supplementChanged" />
<ManualScanActions :detail="detail" :unit="selectedUnit" :execution="selectedExecution"
:active="props.active && activeTab === 'units' && !logVisible" :disabled="busy" @changed="supplementChanged" />
</div>
</div>
<div v-if="selectedExecution" class="execution-record-context">
@ -694,6 +696,7 @@ import { generateUUID } from '@/utils'
import { scannerTaskParameters, validateScannerParameters, SCANNER_PARAMETER_DEFAULTS, SCANNER_PARAMETER_RUN_KEY } from '@/cmvr/common/utils/scannerParameters.mjs'
import * as ScanApi from '@/api/lab/scan-task'
import ScanSupplementActions from './ScanSupplementActions.vue'
import ManualScanActions from './ManualScanActions.vue'
import ExecutionPlanSetup from './ExecutionPlanSetup.vue'
import * as FileApi from '@/api/infra/file'
import type { LabExecutionVO } from '@/api/lab/execution'

View File

@ -0,0 +1,83 @@
const identity = target => target ? `${target.taskId}\u0000${target.executionId}` : ''
const present = value => value != null && String(value).trim() !== ''
export function manualScanTarget(detail, unit, execution, active = true) {
if (!active || !present(detail?.task?.id) || !unit || !present(execution?.id)
|| execution.status !== 'RUNNING' || detail.config?.stopPending || detail.config?.cancelRequested
|| String(unit.currentExecutionId) !== String(execution.id)
|| (present(execution.taskId) && String(execution.taskId) !== String(detail.task.id))) return undefined
return { taskId: detail.task.id, executionId: execution.id }
}
export function manualScanCollecting(gate, now = Date.now()) {
return !!gate && gate.available === true && gate.collecting === true && gate.phase === 'COLLECTING'
&& typeof gate.gateId === 'string' && !!gate.gateId.trim()
&& typeof gate.nodeId === 'string' && !!gate.nodeId.trim()
&& (gate.timeoutAt == null || (typeof gate.timeoutAt === 'number' && Number.isFinite(gate.timeoutAt) && gate.timeoutAt > now))
}
// A click owns one current gate. Later responses can never finish a new sample or stage.
export function createManualScanControl(load, finish, publish) {
let generation = 0, target, gate, pending, checking = false, finishing = false, error = ''
const submitted = new Set()
const gateKey = (selection, value) => `${identity(selection)}\u0000${value?.gateId || ''}`
const notify = () => publish({ gate, checking, finishing, error, submitted: submitted.has(gateKey(target, gate)) })
const current = (version, selection) => version === generation && identity(selection) === identity(target)
const control = {
select(next) {
if (identity(next) === identity(target)) return
generation++; target = next ? { ...next } : undefined
gate = undefined; pending = undefined; checking = false; finishing = false; error = ''
notify()
},
refresh() {
if (!target) return Promise.resolve()
if (pending) return pending
const version = generation, selection = { ...target }
checking = true; notify()
pending = Promise.resolve().then(() => load(selection.taskId, selection.executionId)).then(value => {
if (!current(version, selection)) return
gate = value; error = ''
}, failure => {
if (!current(version, selection)) return
gate = undefined; error = failure?.message || '当前补扫状态暂时无法确认,请刷新任务。'
}).finally(() => {
if (!current(version, selection)) return
pending = undefined; checking = false; notify()
})
return pending
},
async finishCurrent() {
if (!target || finishing || !manualScanCollecting(gate) || submitted.has(gateKey(target, gate))) return false
const version = generation, selection = { ...target }, chosen = { ...gate }
finishing = true; error = ''; notify()
try {
// Recheck the chosen gate; never silently apply this click to a later gate.
await control.refresh()
if (!current(version, selection)) return false
if (gate?.gateId !== chosen.gateId || !manualScanCollecting(gate)) {
error = '当前补扫段已变更或已结束,请核对后再操作。'
return false
}
submitted.add(gateKey(selection, chosen)); notify()
const accepted = await finish(selection.taskId, selection.executionId, chosen.gateId)
if (accepted !== true) throw new Error('结束请求尚未被确认,请刷新任务核对当前补扫状态。')
if (!current(version, selection)) return false
if (gate?.gateId === chosen.gateId) gate = { ...gate, available: false, collecting: false, phase: 'FINISH_REQUESTED' }
error = ''
return true
} catch (failure) {
if (current(version, selection)) {
error = failure?.message || '结束请求尚未确认,请刷新任务核对当前补扫状态。'
// A response may be lost after acceptance. Never resend this click automatically.
await control.refresh()
if (current(version, selection)) error = failure?.message || '结束请求尚未确认,请刷新任务核对当前补扫状态。'
}
return false
} finally {
if (current(version, selection)) { finishing = false; notify() }
}
}
}
return control
}

View File

@ -0,0 +1,30 @@
# 夹具与车架手持扫描(待发布)
按用户确认新建两条独立流程,机械臂均不运动,人工在任务扫描执行页点击“结束本段补扫并继续”。原大型夹具和车架自动路径不修改;这两条是新工程采集流程,不复用已完成任务的原扫描工程。
| 流程 | 方法ID | 流程ID | 当前状态 |
| --- | --- | --- | --- |
| 夹具手持扫描 | `23a289807b6549b2b11de2e0e659c4ac` | `bc109935a9e67cef87988436b569bc66` | 草稿修订1,57节点,8段人工采集 |
| 车架手持扫描 | `eaa03eee97bf43a49d3dc4d10d1e2efa` | `0632aabf9ba743b06a6f7e06e538f95b` | 草稿修订1,16节点,1段人工采集 |
## 流程和操作
夹具源为“大型夹具全流程”V8 `8946d6a8bfcbb1ca252b9bd26ccfcb1a`。保留LM202停靠、转台使能与原角度换面、扫描仪连接/工程/框架/参数/采集/网格及导出。去除机械臂动作和自动轨迹计算,每段采集后等待人工结束。确认扫描仪停止成功后,才能继续原转台换面及下一段采集。末尾仍按原流程回转台0位。操作前由现场人员确认机械臂已停止并处于适合手持扫描、AGV停靠和转台换面的安全位置。
车架源为Y退50低位版V1 `a02ccea8e279e8c9caf0acb6d6cb1dc9`。按用户最后确认去除全部AGV、转台和机械臂操作,保留一段手持采集和扫描仪工程、框架、网格、导出操作。框架输入继续由任务夹具配置提供。两条流程扫描参数默认亮度17、点间距0.7,仍尊重任务的参数覆盖。
每段最大人工等待默认120秒,可在任务输入中设置1至3600整数秒。只有当前段的人工结束请求能推进流程;超时按失败处理并进入既有设备停止确认,不能自动进入换面、下一段或网格。人工按钮发出的是结束意图,实际停止仍由后续SCANNER_STOP完成并确认。
## 运行实现
新增独立动作 `SCANNER_MANUAL_WAIT`,不修改原 `SCANNER_SUPPLEMENT_WAIT` 的冻结流程语义。等待门使用运行上下文、当前节点/调用/迭代身份和每次进入的新随机标识;旧点击、已结束段、暂停或终止的运行、其他任务和其他样件均不能放行当前段。按钮只查询平台本地门状态,不持续查询扫描仪SDK。进入和结束等待时核对本次扫描工程及实际采集状态。
暂停恢复依照现有扫描仪暂停扩展,在同会话同工程下确认恢复采集,再重新进入人工等待并产生新标识。恢复节点可能立即执行,因此在派发前统一设置RUNNING;派发失败仍走原阻塞暂停及设备停止确认,不重发运动。
维护入口 `scripts/build_handheld_scan.mjs` 仅从以上固定发布源离线生成派生图,检查人工段数量、资源契约、引用完整性、机械臂零动作、车架AGV零动作,以及保留设备节点参数与源相等。
离线验证已完成:后端20模块真实编译成功,CMVR 30项与LAB 34项共64项测试全部通过,包含两份实际流程的FlowModelBuilder解析、设备角色与动态参数契约、暂停恢复和旧补扫回归;11个后端实现/原测试文件与实际编译副本逐项哈希相同。前端10项当前段控制与8项原补扫测试通过,两个Vue文件脚本及模板编译通过。新增临时测试、日志、来源快照和隔离编译树按项目约定清理;原有回归测试中的必要扩展保留。
## 发布顺序
2026-11-28用户已授权检查当前修改并上传Git,本批实现和验证说明随之提交入库。手持流程仍为未发布草稿,本次车架夹具默认关联的正式更新不包含手持运行代码。用户另行确认手持流程发布时,须先通过正式更新脚本安装本批后端和前端、完成健康及安装指纹检查,再通过平台正常发布接口发布两条草稿;旧平台不支持新增动作,不能先发布流程。无新增配置、依赖、数据库表或菜单权限;沿用 `lab:task:query`、`lab:execution:control` 权限。保留现场配置、证书、冻结版本和任务历史,不执行实际设备采集或运动作为自动验证。

View File

@ -0,0 +1,90 @@
import fs from 'node:fs'
import assert from 'node:assert/strict'
import crypto from 'node:crypto'
// Offline derivative only. Never publishes or runs a scanner, motor, AGV or arm.
const [kind, sourcePath, outputPath, summaryPath] = process.argv.slice(2)
if (!['fixture','frame'].includes(kind) || !sourcePath || !outputPath) throw new Error('Usage: node build_handheld_scan.mjs <fixture|frame> <source-snapshot.json> <flow.json> [summary.json]')
const source=JSON.parse(fs.readFileSync(sourcePath,'utf8').replace(/^\uFEFF/,''))
assert.equal(source.published.id,kind==='fixture'?'8946d6a8bfcbb1ca252b9bd26ccfcb1a':'a02ccea8e279e8c9caf0acb6d6cb1dc9','Review a different source before deriving')
const original=JSON.parse(source.published.flowData),byId=new Map(original.nodes.map(n=>[n.id,n])),order=[]
for(let n=original.nodes.find(n=>n.type==='start');n;){
assert(!order.includes(n),'Unexpected source cycle');order.push(n)
const edges=original.edges.filter(e=>e.sourceNodeId===n.id);assert(edges.length<=1,'Review source branching')
n=edges.length?byId.get(edges[0].targetNodeId):null
}
let generatedId=0
const uid=()=>crypto.createHash('sha256').update(source.published.id+':handheld:'+kind+':'+(++generatedId)).digest('hex').slice(0,32),clone=v=>structuredClone(v)
const action=n=>(n.properties.action||'').toUpperCase(),params=n=>n.properties.nodeParams||[]
const input=(name,value)=>({name,type:'input',input:value,required:true,disabled:true})
const quote=(name,node,...path)=>({name,type:'quote',input:'',quote:[node.id,...path],quoteType:path[0],required:true,disabled:true})
const start=clone(order[0]),end=clone(order.at(-1))
assert.equal(start.type,'start');assert.equal(end.type,'end')
const name=kind==='fixture'?'夹具手持扫描':'车架手持扫描'
let retained
if(kind==='fixture'){
retained=order.slice(1,-1).filter(n=>/^(AGV_|MOTOR_|SCANNER_)/.test(action(n))||action(n)==='SLEEP').map(clone)
assert.equal(retained.filter(n=>action(n)==='AGV_MOVE_TO_STATION').length,1)
assert.equal(retained.filter(n=>action(n)==='MOTOR_MOVE').length,8)
assert.equal(retained.filter(n=>action(n)==='SCANNER_START').length,8)
}else{
const first=order.findIndex(n=>action(n)==='SCANNER_START')
const stop=order.findIndex((n,i)=>i>first&&action(n)==='SCANNER_STOP')
const mesh=order.findIndex(n=>action(n)==='SCANNER_MESH')
assert(first>0&&stop>first&&mesh>stop)
retained=[...order.slice(1,first).filter(n=>action(n).startsWith('SCANNER_')),order[first],order[stop],...order.slice(mesh,-1).filter(n=>action(n).startsWith('SCANNER_'))].map(clone)
retained.find(n=>action(n)==='SCANNER_START').properties.name='开始车架手持采集'
retained.find(n=>action(n)==='SCANNER_STOP').properties.name='结束车架手持采集并保留工程'
assert(!retained.some(n=>/^(AGV_|ARM_|MOTOR_)/.test(action(n))))
}
const usedInputs=new Set()
function inspect(v){
if(Array.isArray(v)){v.forEach(inspect);return}
if(!v||typeof v!=='object')return
if(v.type==='quote'&&v.quote?.[0]===start.id&&v.quote[1]==='input')usedInputs.add(v.quote[2])
Object.values(v).forEach(inspect)
}
retained.forEach(inspect)
start.properties.inputParams=(start.properties.inputParams||[]).filter(p=>usedInputs.has(p.name))
start.properties.inputParams.push({name:'manualScanSeconds',type:'number',input:120,children:[],required:true,desc:'每段手持采集最长等待秒数,默认120,可输入1至3600整数;只有点击结束本段才能继续,超时将停止并阻断后续步骤。'})
start.properties.name=name+'开始'
const options={id:uid(),type:'code',x:0,y:0,properties:{name:'检查人工采集等待时长',action:'CODE',nodeParams:[quote('seconds',start,'input','manualScanSeconds'),input('code','function handler(params){var s=params.seconds;if(typeof s!=="number"||!isFinite(s)||s!==Math.floor(s)||s<1||s>3600)throw new Error("每段人工等待时长必须为1至3600整数秒");return {timeoutMs:s*1000};}')],outputType:'json',outputParams:[{name:'result',type:'object',required:true,children:[{name:'timeoutMs',type:'number',children:[],required:true}]}]}}
const sequence=[start,options],labels=[]
let collecting=false,segment=''
for(const n of retained){
const a=action(n)
if(a==='SCANNER_START'){assert(!collecting,'Nested capture');collecting=true;segment=n.properties.name}
if(a==='MOTOR_MOVE'||a==='AGV_MOVE_TO_STATION')assert(!collecting,'Source moves a platform during active hand-held collection; review explicitly')
if(a==='SCANNER_STOP'&&collecting){
const label=kind==='frame'?'车架手持采集':'第'+(labels.length+1)+'/8段:'+segment
labels.push(label)
sequence.push({id:uid(),type:'serviceNode',x:0,y:0,properties:{name:'等待人工结束:'+label,action:'SCANNER_MANUAL_WAIT',nodeType:'EDGE',executionTarget:{roleKey:'scanner',deviceSlotKey:'scanner'},nodeParams:[quote('timeoutMs',options,'output','result','timeoutMs'),input('label',label)],outputType:'json',outputParams:[]}})
collecting=false
}
sequence.push(n)
}
assert(!collecting,'Missing stop after manual collection')
sequence.push(end)
assert.equal(labels.length,kind==='fixture'?8:1)
const targets=new Map()
for(const n of sequence){const t=n.properties.executionTarget;if(t?.roleKey&&t.deviceSlotKey){if(!targets.has(t.roleKey))targets.set(t.roleKey,new Set());targets.get(t.roleKey).add(t.deviceSlotKey)}}
start.properties.resourceRoles=(start.properties.resourceRoles||[]).filter(r=>targets.has(r.roleKey)).map(r=>({...r,deviceSlots:r.deviceSlots.filter(s=>targets.get(r.roleKey).has(s.slotKey))}))
for(const [key,slots] of targets)for(const slot of slots)assert(start.properties.resourceRoles.find(r=>r.roleKey===key)?.deviceSlots.some(s=>s.slotKey===slot),'Resource role missing')
const graph={...clone(original),nodes:sequence,edges:sequence.slice(0,-1).map((n,i)=>({id:uid(),type:'bezier',sourceNodeId:n.id,targetNodeId:sequence[i+1].id,sourceAnchorId:n.id+'_1',targetAnchorId:sequence[i+1].id+'_3'}))}
sequence.forEach((n,i)=>{n.x=i*320;n.y=220;delete n.properties.parentId})
const present=new Set(sequence.map(n=>n.id))
function check(v){
if(Array.isArray(v)){v.forEach(check);return}
if(!v||typeof v!=='object')return
if(v.type==='quote')assert(present.has(v.quote[0]),'Dangling parameter reference')
Object.values(v).forEach(check)
}
sequence.forEach(check)
assert(!sequence.some(n=>action(n).startsWith('ARM_')))
assert(!start.properties.resourceRoles.some(r=>r.deviceSlots.some(s=>s.deviceKind===2)))
for(const n of retained)assert.deepEqual(n.properties.nodeParams,byId.get(n.id).properties.nodeParams,'Retained device parameters changed')
if(kind==='fixture')assert.deepEqual(retained.filter(n=>action(n).startsWith('SCANNER_')).map(n=>action(n)),order.filter(n=>action(n).startsWith('SCANNER_')).map(n=>action(n)))
fs.writeFileSync(outputPath,JSON.stringify(graph,null,2))
const summary={kind,name,nodes:sequence.length,manualSegments:labels.length,labels,armActions:0,agvMoves:sequence.filter(n=>action(n).startsWith('AGV_')).length,motorMoves:sequence.filter(n=>action(n)==='MOTOR_MOVE').length,inputCount:start.properties.inputParams.length,requiresManualWaitRuntime:true,published:false,deviceCommandsSent:0}
if(summaryPath)fs.writeFileSync(summaryPath,JSON.stringify(summary,null,2))
console.log(JSON.stringify(summary))