fix(扫描): 修复连续停稳样本交接并减少工具Z摆扫停顿

循环按精确迭代导出指定直接子节点结果,拒绝停止、中断和旧缓存。
车架方案使用同一对严格通过的停稳回读,保留20微米精度要求。
工具Z摆扫细分由10度改为45度,减少额外同步目标,保留原XYZ和安全动作。
补充现有循环回归测试及中文发布说明,平台更新后发布独立方案V3。
This commit is contained in:
Codex 2026-11-27 15:12:19 +08:00
parent aca071e806
commit e2f13df7d1
7 changed files with 696 additions and 2 deletions

View File

@ -2,6 +2,7 @@ package com.cmvr.test.flow.runtime.dispatcher;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.common.utils.spring.SpringUtils;
import com.cmvr.test.flow.builder.FlowGraph;
import com.cmvr.test.flow.builder.FlowNodeWrapper;
@ -18,6 +19,7 @@ import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
@Slf4j
@Component("LOOP")
@ -41,18 +43,23 @@ public class FlowLoopNodeHandler implements FlowNodeTypeHandler {
FlowNodeWrapper nodeWrapper = graph.getNode(nodeId);
int loopCount = inputParams.getIntValue("loopNum"); // 获取循环次数
Object loopArray = inputParams.get("loopArray"); // 获取循环次数
FlowGraph template = nodeWrapper.getSubGraph();
String resultNodeId = FlowLoopResultExporter.configuredNode(nodeWrapper, inputParams, template);
// 如果没有设置循环次数或者循环次数为 0,则跳过处理
if (loopCount <= 0) {
if (resultNodeId != null) throw new GlobalException("循环尚无已完成迭代,不能导出结果");
log.warn("循环节点 {} 没有有效的 loopCount 参数,跳过处理", nodeId);
return TaskNodeExecuteResult.success(inputParams);
}
FlowGraph template = nodeWrapper.getSubGraph();
FlowGraph subGraph = null;
List<Integer> lastCompletedIterations = null;
TaskContext lastCompletedContext = null;
// 循环执行子图
for (int i = loopStartNum; i <= loopCount; i++) {
TaskContext context = taskInstHolder.getContext(instId);
if (resultNodeId != null) FlowLoopResultExporter.requireActive(context);
if (context == null || context.isStopped()) {
log.info("任务已结束,退出循环:instId={}, nodeId={}, nextIteration={}", instId, nodeId, i);
break;
@ -80,19 +87,41 @@ public class FlowLoopNodeHandler implements FlowNodeTypeHandler {
subGraph = template.copyForIteration();
subGraph.setSub(true);
flowItemExecutor.executeSubGraph(subGraph, subMessage, latch::countDown, newIterations);
AtomicBoolean completed = new AtomicBoolean();
try {
if (resultNodeId != null) FlowLoopResultExporter.clearIteration(context, resultNodeId, newIterations);
flowItemExecutor.executeSubGraph(subGraph, subMessage, resultNodeId == null ? latch::countDown : () -> {
completed.set(true);
latch.countDown();
}, newIterations);
latch.await(); // 等待子图执行完毕后再进行下一轮
if (resultNodeId != null) {
FlowLoopResultExporter.requireActive(context);
if (!completed.get() || taskInstHolder.getContext(instId) != context)
throw new GlobalException("循环子图尚未完成或执行上下文已变化,不能导出结果");
lastCompletedIterations = new ArrayList<>(newIterations);
lastCompletedContext = context;
}
} catch (InterruptedException e) {
log.error("循环第 {} 次等待中断", i, e);
Thread.currentThread().interrupt(); // 保留中断标志
if (resultNodeId != null) throw new GlobalException("循环等待已中断,不能导出结果", e);
break;
} finally {
taskThreadRegistry.releaseLatch(instId, nodeId);
}
}
if (resultNodeId != null) {
TaskContext context = taskInstHolder.getContext(instId);
if (context != lastCompletedContext) throw new GlobalException("循环执行上下文已变化,不能导出结果");
JSONObject exported = FlowLoopResultExporter.export(context, resultNodeId, lastCompletedIterations);
if (taskInstHolder.getContext(instId) != context) throw new GlobalException("循环执行上下文已变化,不能导出结果");
JSONObject output = new JSONObject(inputParams);
output.put("result", exported);
return TaskNodeExecuteResult.success(output);
}
// 返回执行结果
return TaskNodeExecuteResult.success(inputParams);
}

View File

@ -0,0 +1,54 @@
package com.cmvr.test.flow.runtime.dispatcher;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.test.enums.TaskStatusEnum;
import com.cmvr.test.flow.builder.FlowGraph;
import com.cmvr.test.flow.builder.FlowNodeWrapper;
import com.cmvr.test.flow.builder.FlowParamDef;
import com.cmvr.test.flow.builder.TaskKeyBuilder;
import com.cmvr.test.flow.context.TaskContext;
import java.util.List;
/** Explicit export of one direct child result, never an ancestor/previous iteration fallback. */
final class FlowLoopResultExporter {
private FlowLoopResultExporter() {}
static String configuredNode(FlowNodeWrapper loop, JSONObject input, FlowGraph template) {
List<FlowParamDef> definitions = loop.getNodeParams() == null ? List.of() : loop.getNodeParams();
List<FlowParamDef> exports = definitions.stream().filter(value -> "resultNodeId".equals(value.getName())).toList();
if (exports.isEmpty() && !input.containsKey("resultNodeId")) return null;
if (exports.size() != 1 || !"input".equals(exports.get(0).getType())
|| !(exports.get(0).getInput() instanceof String id) || id.isBlank()
|| !id.equals(input.get("resultNodeId")))
throw new GlobalException("循环结果节点resultNodeId必须为非空静态输入");
if (template == null || template.getNode(id) == null)
throw new GlobalException("循环结果节点必须属于当前循环的直接子图");
return id;
}
static void requireActive(TaskContext context) {
if (context == null || context.isStopped() || context.isPaused() || Thread.currentThread().isInterrupted()
|| context.getStatus() != null && context.getStatus() != TaskStatusEnum.RUNNING)
throw new GlobalException("循环已停止、暂停或中断,不能导出结果");
}
static void clearIteration(TaskContext context, String nodeId, List<Integer> iterations) {
requireActive(context);
context.getNodeOutputs().remove(TaskKeyBuilder.buildKey(nodeId, iterations));
}
static JSONObject export(TaskContext context, String nodeId, List<Integer> completedIterations) {
requireActive(context);
if (completedIterations == null || completedIterations.isEmpty())
throw new GlobalException("循环尚无已完成迭代,不能导出结果");
// getNodeOutput intentionally supports ancestor fallback; exports must not use it.
JSONObject output = context.getNodeOutputs().get(TaskKeyBuilder.buildKey(nodeId, completedIterations));
if (output == null) throw new GlobalException("循环最后已完成迭代缺少指定节点结果,禁止复用旧结果");
JSONObject copy = JSON.parseObject(JSON.toJSONString(output));
requireActive(context);
return copy;
}
}

View File

@ -1,9 +1,11 @@
package com.cmvr.test.flow.runtime.dispatcher;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.test.enums.NodeTypeEnum;
import com.cmvr.test.flow.builder.FlowGraph;
import com.cmvr.test.flow.builder.FlowNodeWrapper;
import com.cmvr.test.flow.builder.FlowParamDef;
import com.cmvr.test.flow.context.TaskContext;
import com.cmvr.test.flow.context.TaskContextManager;
import com.cmvr.test.flow.context.TaskInstHolder;
@ -18,6 +20,11 @@ import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class FlowLoopNodeHandlerTest {
@ -69,4 +76,190 @@ public class FlowLoopNodeHandlerTest {
assertEquals(1, executions.get());
}
@Test
public void legacyLoopReturnsTheOriginalInputObjectWithoutAnExport() {
Fixture fixture = new Fixture();
fixture.loop.setNodeParams(List.of());
fixture.message.getInputParams().remove("resultNodeId");
assertSame(fixture.message.getInputParams(), fixture.handler.handle(fixture.message).getOutputParams());
assertFalse(fixture.message.getInputParams().containsKey("result"));
}
@Test
public void exportsTheExactLastCompletedNestedIterationAfterStopLoopAndDeepCopiesIt() {
Fixture fixture = new Fixture();
fixture.message.setIterations(List.of(7));
JSONObject last = JSONObject.of("result", JSONObject.of("ready", true,
"state", JSONObject.of("marker", "last", "values", List.of(1, 2))));
fixture.body = (graph, message, finished, path) -> {
fixture.context.setNodeOutput("proof", path, path.get(1) == 2 ? last : JSONObject.of("result", "first"));
if (path.get(1) == 2) graph.setStopLoop(true);
finished.run();
};
JSONObject output = fixture.handler.handle(fixture.message).getOutputParams();
assertEquals("last", output.getJSONObject("result").getJSONObject("result").getJSONObject("state").getString("marker"));
assertEquals(2, fixture.executions.get());
assertNotSame(last, output.getJSONObject("result"));
output.getJSONObject("result").getJSONObject("result").getJSONObject("state").put("marker", "edited");
assertEquals("last", last.getJSONObject("result").getJSONObject("state").getString("marker"));
assertFalse(fixture.message.getInputParams().containsKey("result"));
}
@Test
public void normalCompletionExportsTheLastIterationWithoutRequiringStopLoop() {
Fixture fixture = new Fixture();
fixture.body = (graph, message, finished, path) -> {
fixture.context.setNodeOutput("proof", path, JSONObject.of("result", JSONObject.of("iteration", path.get(0))));
finished.run();
};
assertEquals(3, fixture.handler.handle(fixture.message).getOutputParams().getJSONObject("result").getJSONObject("result").getIntValue("iteration"));
}
@Test
public void missingFinalOutputCannotFallBackToAnEarlierIterationOrAncestorScope() {
Fixture fixture = new Fixture();
fixture.context.setNodeOutput("proof", List.of(), JSONObject.of("result", "ancestor"));
fixture.body = (graph, message, finished, path) -> {
if (path.get(0) < 3) fixture.context.setNodeOutput("proof", path, JSONObject.of("result", "older"));
finished.run();
};
assertThrows(GlobalException.class, () -> fixture.handler.handle(fixture.message));
}
@Test
public void resumedIterationCannotExportAnOutputLeftByAnEarlierAttempt() {
Fixture fixture = new Fixture();
fixture.message.setLoopNum(3);
fixture.context.setNodeOutput("proof", List.of(3), JSONObject.of("result", "stale"));
assertThrows(GlobalException.class, () -> fixture.handler.handle(fixture.message));
}
@Test
public void exportedNodeMustBeAStaticNonemptyDirectChild() {
for (Object invalid : new Object[]{"", " ", 42, "outside", "nested"}) {
Fixture fixture = new Fixture();
fixture.loop.setNodeParams(List.of(definition(invalid, "input")));
fixture.message.getInputParams().put("resultNodeId", invalid);
FlowNodeWrapper outside = node("outside", NodeTypeEnum.CODE);
fixture.message.getGraph().getNodeMap().put("outside", outside);
FlowNodeWrapper nestedLoop = node("nested-loop", NodeTypeEnum.LOOP);
nestedLoop.setSubGraph(new FlowGraph());
nestedLoop.getSubGraph().getNodeMap().put("nested", node("nested", NodeTypeEnum.CODE));
fixture.loop.getSubGraph().getNodeMap().put("nested-loop", nestedLoop);
assertThrows(GlobalException.class, () -> fixture.handler.handle(fixture.message));
assertEquals(0, fixture.executions.get());
}
Fixture quoted = new Fixture();
quoted.loop.setNodeParams(List.of(definition("proof", "quote")));
assertThrows(GlobalException.class, () -> quoted.handler.handle(quoted.message));
Fixture duplicate = new Fixture();
duplicate.loop.setNodeParams(List.of(definition("proof", "input"), definition("proof", "input")));
assertThrows(GlobalException.class, () -> duplicate.handler.handle(duplicate.message));
Fixture replaced = new Fixture();
replaced.message.getInputParams().put("resultNodeId", "different");
assertThrows(GlobalException.class, () -> replaced.handler.handle(replaced.message));
Fixture undeclared = new Fixture();
undeclared.loop.setNodeParams(List.of());
assertThrows(GlobalException.class, () -> undeclared.handler.handle(undeclared.message));
}
@Test
public void enabledExportRejectsNoCompletedIteration() {
Fixture zero = new Fixture();
zero.message.getInputParams().put("loopNum", 0);
assertThrows(GlobalException.class, () -> zero.handler.handle(zero.message));
Fixture beyondEnd = new Fixture();
beyondEnd.message.setLoopNum(4);
assertThrows(GlobalException.class, () -> beyondEnd.handler.handle(beyondEnd.message));
}
@Test
public void releasingALatchDoesNotPretendTheSubgraphCompleted() {
Fixture fixture = new Fixture();
fixture.body = (graph, message, finished, path) -> {
fixture.context.setNodeOutput("proof", path, JSONObject.of("result", "not-completed"));
fixture.registry.releaseLatch(message.getInstId(), message.getNodeId());
};
assertThrows(GlobalException.class, () -> fixture.handler.handle(fixture.message));
}
@Test
public void cancelledPausedOrRemovedContextsCannotExportEvenAfterTheCallback() {
for (int cancellation = 0; cancellation < 3; cancellation++) {
Fixture fixture = new Fixture();
int kind = cancellation;
fixture.body = (graph, message, finished, path) -> {
fixture.context.setNodeOutput("proof", path, JSONObject.of("result", "cancelled"));
if (kind == 0) fixture.context.setStopped(true);
if (kind == 1) fixture.context.setPaused(true);
if (kind == 2) fixture.holder.unRegister(message.getInstId());
finished.run();
};
assertThrows(GlobalException.class, () -> fixture.handler.handle(fixture.message));
}
}
@Test
public void anInterruptedWaitPreservesTheInterruptAndCannotExport() {
Fixture fixture = new Fixture();
fixture.body = (graph, message, finished, path) -> {
fixture.context.setNodeOutput("proof", path, JSONObject.of("result", "interrupted"));
Thread.currentThread().interrupt();
};
try {
assertThrows(GlobalException.class, () -> fixture.handler.handle(fixture.message));
assertTrue(Thread.currentThread().isInterrupted());
} finally {
Thread.interrupted();
}
}
private static FlowParamDef definition(Object value, String type) {
FlowParamDef field = new FlowParamDef();
field.setName("resultNodeId"); field.setType(type); field.setInput(value);
return field;
}
private static FlowNodeWrapper node(String id, NodeTypeEnum type) {
FlowNodeWrapper node = new FlowNodeWrapper();
node.setNodeId(id); node.setNodeType(type);
return node;
}
@FunctionalInterface
private interface IterationBody {
void execute(FlowGraph graph, TaskNodeExecuteMessage message, Runnable finished, List<Integer> iterations);
}
private static final class Fixture {
final TaskInstHolder holder = new TaskInstHolder(null, new TaskContextManager(), null, null);
final TaskContext context = new TaskContext();
final TaskThreadRegistry registry = new TaskThreadRegistry();
final FlowNodeWrapper loop = node("loop", NodeTypeEnum.LOOP);
final TaskNodeExecuteMessage message = new TaskNodeExecuteMessage();
final AtomicInteger executions = new AtomicInteger();
IterationBody body = (graph, message, finished, path) -> finished.run();
final FlowItemExecutor executor = new FlowItemExecutor(null, List.of(), null, holder, null, null, null, null) {
@Override
public void executeSubGraph(FlowGraph graph, TaskNodeExecuteMessage message, Runnable finished, List<Integer> iterations) {
executions.incrementAndGet(); body.execute(graph, message, finished, iterations);
}
};
final FlowLoopNodeHandler handler = new FlowLoopNodeHandler(registry, holder) {
@Override
protected FlowItemExecutor getFlowItemExecutor() { return executor; }
};
Fixture() {
context.setInstId("export-inst"); holder.register(context);
FlowGraph template = new FlowGraph();
template.getNodeMap().put("proof", node("proof", NodeTypeEnum.CODE));
loop.setSubGraph(template); loop.setNodeParams(List.of(definition("proof", "input")));
FlowGraph graph = new FlowGraph(); graph.getNodeMap().put(loop.getNodeId(), loop);
message.setInstId(context.getInstId()); message.setNodeId(loop.getNodeId()); message.setGraph(graph);
message.setIterations(new ArrayList<>());
message.setInputParams(JSONObject.of("loopNum", 3, "resultNodeId", "proof"));
}
}
}

View File

@ -0,0 +1,27 @@
# 车架工具Z摆扫停稳交接修复与提速(V3)
目标方法:车架扫描方案-参数化自动路径 - RX-2优先工具Z摆扫版。方法ID `a3d44bacd1be4a9b97a6315bcca86f50`,流程ID `5e2bddeeb05fb181296b4721ba6dd9bc`。本次更新平台后发布此方法的V3草稿(291节点);原方案、冻结V1/V2及既有执行保持。
## 错误原因与修复
真实失败执行EX-20261127-0006中,停稳循环的一对回读漂移13.27µm,通过20µm标准;循环结束后又采了另一对回读,漂移32.58µm,规划器立即报“连续回读的TCP位姿仍在漂移”,尽管120秒期限还剩117秒。停稳门与规划器还分别使用Euler分量和四元数总角标准,存在交接不一致。
新增循环静态输入resultNodeId,输出最后真正完成迭代的指定直接子节点完整结果。精确匹配嵌套迭代键、清理本轮旧缓存、深拷贝,停止/暂停/中断/上下文更换/缺失结果均拒绝导出。未配置此输入的旧循环保持原输出。
8组停稳循环将同一对严格通过的样本直接交给规划器,删除24个额外回读及等待节点。共同采用位置20µm、四元数总角0.0001rad、关节及TCP速度/漂移标准。未停稳时在原120秒期限内继续检查,不放宽阈值或伪造成功。
## 减少额外姿态目标
保留每站RX=-2优先,再RX=-1.1,末端工具自身Z轴随原XYZ路径0→120°→0;工具局部旋转仍为R_reference * Rz(theta)。保留原路径顶点、直线边、转角及摆角峰值;短于2mm的段仍不分配转角。
附加共线姿态点最大物理角间隔由10°改为45°。真实14顶点示例从35个目标/34次MoveL降至15个目标/14次MoveL,减少平台逐点同步开销;原转角、反向处仍可能减速。这是减少额外目标,并非控制器整轨迹预规划或已验收的全程连续运动。未改动作队列或SDK协议。长边/顶面80、短边100mm/s及原加速度、安全入场/退让、8对扫描采集保持。
## 验证与升级顺序
- 23项后端回归通过:循环导出11项、分支迭代2项、引用解析6项、参数准备4项。
- 真实失败日志回放及阈值/安全/超时等19项检查通过。
- 87组轨迹检查、5657点通过,工具轴、原XYZ、转角、峰值、短段和速度保持。
- 实际流程构建器接受291节点;独立复核483个引用、8组同样本交接及28份规划源码一致。
- 无新依赖、配置或表结构迁移。保留正式私有配置、证书和业务数据;不自动执行设备动作。
必须先经正式platform.ps1 Update流程安装本次后端并核对部署提交、程序哈希和健康状态,再发布V3。旧后端没有循环结果导出能力,不能先发布V3。新建或复制任务时选择本方法最新发布版;已冻结任务不会自动切换。离线检查不等于整条真机逆解、碰撞、奇异点及实际流畅度验收。

View File

@ -0,0 +1,52 @@
import fs from 'node:fs'
import assert from 'node:assert/strict'
import crypto from 'node:crypto'
// Requires loop resultNodeId support in the installed platform; never deploys or moves equipment.
const [sourcePath,outputPath,summaryPath]=process.argv.slice(2)
if(!sourcePath||!outputPath)throw new Error('Usage: node build_settle_update.mjs <published-tool-z-snapshot.json> <flow.json> [summary.json]')
const source=JSON.parse(fs.readFileSync(sourcePath,'utf8').replace(/^\uFEFF/,''))
const before=JSON.parse(source.published?.flowData||source.flowData||JSON.stringify(source)),graph=structuredClone(before)
assert.equal(graph.nodes.length,315,'Review the source before applying a different layout')
const byId=new Map(graph.nodes.map(node=>[node.id,node])),order=[]
for(let n=graph.nodes.find(n=>n.type==='start');n;){assert(!order.includes(n));order.push(n);const edges=graph.edges.filter(e=>e.sourceNodeId===n.id);assert(edges.length<=1);n=edges.length?byId.get(edges[0].targetNodeId):null}
const params=node=>node.properties.nodeParams||[],mode=node=>params(node).find(p=>p.name==='mode')?.input
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,'output',...path],quoteType:'output',required:true,disabled:true})
const field=(name,type,children=[])=>({name,type,children,required:true})
function set(node,name,value){const index=params(node).findIndex(p=>p.name===name);if(index<0)node.properties.nodeParams.push(value);else node.properties.nodeParams[index]=value}
const helper=fs.readFileSync(new URL('./settle-probe.js',import.meta.url),'utf8'),removed=new Set(),gates=[]
const smooth=fs.readFileSync(new URL('./tool-z-sweep-smooth-planner.js',import.meta.url),'utf8')
assert(smooth.includes('// TOOL_Z_RIGHT_MULTIPLY'),'Tool-local Z implementation required')
for(const planner of order.filter(node=>mode(node)==='scan')){
const index=order.indexOf(planner),loop=order[index-4],extra=order.slice(index-3,index)
assert(loop.type==='loop'&&loop.properties.name.includes('连续停稳'))
assert.deepEqual(extra.map(node=>node.type),['serviceNode','sleep','serviceNode'])
const probe=loop.children.map(id=>byId.get(id)).find(node=>node.type==='code')
assert(probe&&params(probe).some(p=>p.name==='previousState')&&params(probe).some(p=>p.name==='state'))
const first=byId.get(params(probe).find(p=>p.name==='previousState').quote[0])
const stateDef=structuredClone(first.properties.outputParams.find(p=>p.name==='state'))
const exportedFields=[field('ready','boolean'),field('reason','string'),{...stateDef,name:'previousState'},{...structuredClone(stateDef),name:'state'},field('deadlineMs','number'),field('observedAt','number')]
set(probe,'code',input('code',helper))
probe.properties.outputParams=[field('result','object',exportedFields)]
set(loop,'resultNodeId',input('resultNodeId',probe.id))
loop.properties.outputParams=loop.properties.outputParams.filter(p=>p.name!=='result').concat(field('result','object',[field('result','object',structuredClone(exportedFields))]))
loop.properties.name=loop.properties.name.replace('等待连续停稳','等待并交付同一对连续停稳回读')
set(planner,'previousState',quote('previousState',loop,'result','result','previousState'))
set(planner,'state',quote('state',loop,'result','result','state'))
extra.forEach(node=>removed.add(node.id))
gates.push({loopId:loop.id,probeId:probe.id,plannerId:planner.id})
}
assert.equal(gates.length,8)
graph.nodes=graph.nodes.filter(node=>!removed.has(node.id))
for(const node of graph.nodes)if(mode(node))set(node,'code',input('code',smooth))
const main=order.filter(node=>!removed.has(node.id)),mainIds=new Set(order.map(node=>node.id))
graph.edges=graph.edges.filter(edge=>!mainIds.has(edge.sourceNodeId)&&!mainIds.has(edge.targetNodeId))
graph.edges.push(...main.slice(0,-1).map((node,i)=>({id:crypto.randomUUID().replaceAll('-',''),type:'bezier',sourceNodeId:node.id,targetNodeId:main[i+1].id,sourceAnchorId:node.id+'_1',targetAnchorId:main[i+1].id+'_3'})))
main.forEach((node,index)=>{node.x=index*320;node.y=220})
for(const node of graph.nodes)for(const p of params(node))if(p.quote)assert(!removed.has(p.quote[0]),'Removed sample node is still referenced')
assert.equal(graph.nodes.filter(node=>node.properties.action==='SCANNER_START').length,8)
fs.writeFileSync(outputPath,JSON.stringify(graph,null,2))
const summary={nodes:graph.nodes.length,removedDuplicateSampleNodes:removed.size,gates,strictPositionDriftMetres:0.00002,strictOrientationDriftRadians:0.0001,maxToolAngleStepDegrees:45,requiresLoopResultExport:true,deviceCommandsSent:0}
if(summaryPath)fs.writeFileSync(summaryPath,JSON.stringify(summary,null,2))
console.log(JSON.stringify({...summary,gates:gates.length}))

View File

@ -0,0 +1,47 @@
// Read-only stationary gate. The exact passing pair is exported by the loop.
function handler(params) {
function finite(value) { return typeof value === 'number' && isFinite(value); }
function fail(message) { throw new Error(message); }
var now = Date.now(), deadline = params.deadlineMs;
if (!finite(deadline) || deadline <= now || deadline > now + 120000)
fail('等待机械臂连续停稳超时(120秒),未发送后续动作');
if (!finite(params.index) || params.index < 0 || params.index !== Math.floor(params.index))
fail('停稳复核循环次数无效');
function snapshot(s) {
if (!s || s.connected !== true || s.poweredOn !== true || s.brakeReleased !== true ||
s.protectiveStopped !== false || s.emergencyStopped !== false || s.fault !== false ||
s.safetyMode !== 'ARM_SAFETY_MODE_NORMAL' || s.controlMode !== 'ARM_CONTROL_MODE_POSITION')
fail('停稳复核发现连接、上电、制动或安全状态异常');
if (!finite(s.timestamp) || Math.abs(now / 1000 - s.timestamp) > 10) fail('停稳复核状态已过期');
if (typeof s.moving !== 'boolean' || typeof s.programRunning !== 'boolean' ||
typeof s.robotMode !== 'string' || !s.robotMode || s.robotMode === 'ARM_ROBOT_MODE_UNKNOWN')
fail('停稳复核缺少有效运动状态');
var q = s.actualJointState, p = s.actualTcpPose, velocity = s.actualTcpVelocity;
if (!q || !Array.isArray(q.position) || q.position.length !== 6 || !Array.isArray(q.velocity) || q.velocity.length !== 6 || !p || !velocity)
fail('停稳复核缺少实际关节、TCP位姿或速度');
var stopped = s.moving === false && s.programRunning === false && s.robotMode === 'ARM_ROBOT_MODE_IDLE';
var axes = ['x','y','z','rx','ry','rz'], speeds = ['vx','vy','vz','wx','wy','wz'];
for (var i = 0; i < 6; i++) {
if (!finite(q.position[i]) || !finite(q.velocity[i]) || !finite(p[axes[i]]) || !finite(velocity[speeds[i]]))
fail('停稳复核关节或TCP数值无效');
if (Math.abs(q.velocity[i]) > 0.001 || Math.abs(velocity[speeds[i]]) > 0.0001) stopped = false;
}
return stopped;
}
function quaternion(p) {
var x=p.rx/2,y=p.ry/2,z=p.rz/2,cx=Math.cos(x),sx=Math.sin(x),cy=Math.cos(y),sy=Math.sin(y),cz=Math.cos(z),sz=Math.sin(z);
return [sx*cy*cz-cx*sy*sz,cx*sy*cz+sx*cy*sz,cx*cy*sz-sx*sy*cz,cx*cy*cz+sx*sy*sz];
}
function angle(a,b) {
var qa=quaternion(a),qb=quaternion(b),minus=0,plus=0;
for(var i=0;i<4;i++){minus+=(qa[i]-qb[i])*(qa[i]-qb[i]);plus+=(qa[i]+qb[i])*(qa[i]+qb[i]);}
return 4*Math.asin(Math.min(1,Math.sqrt(Math.min(minus,plus))/2));
}
var first=params.previousState,second=params.state,firstStopped=snapshot(first),secondStopped=snapshot(second);
var dt=second.timestamp-first.timestamp,ready=firstStopped&&secondStopped&&dt>=0.2&&dt<=2;
var a=first.actualTcpPose,b=second.actualTcpPose,dx=b.x-a.x,dy=b.y-a.y,dz=b.z-a.z;
if(Math.sqrt(dx*dx+dy*dy+dz*dz)>0.00002||angle(a,b)>0.0001)ready=false;
for(var i=0;i<6;i++)if(!(dt>0)||Math.abs(second.actualJointState.position[i]-first.actualJointState.position[i])/dt>0.001)ready=false;
if(!ready&&params.index>=479)fail('等待机械臂连续停稳超时(120秒),未发送后续动作');
return {ready:ready,reason:ready?'同一对回读已通过连续停稳':'尚未满足连续停稳,继续只读等待',previousState:first,state:second,deadlineMs:deadline,observedAt:now};
}

View File

@ -0,0 +1,292 @@
// TOOL_Z_RIGHT_MULTIPLY
// Fewer artificial orientation waypoints. Synchronous original corners and the
// exact sweep peak remain; this does not provide a continuous-motion RPC.
// Pure planning/checks for an independent sweep about the tool's own Z axis.
// Absolute Base/TCP poses use metres/radians. This code sends no device command.
// R_target = R_reference * Rz(theta). Base RX/RY/RZ may all change: forcing
// Base RX/RY to stay fixed would rotate about the wrong axis. XYZ remain Base
// absolute targets; this is not a relative move or a changing user coordinate.
function handler(params) {
var MIN_EDGE = 0.002, EPS = 1e-10, MAX_POINTS = 4096;
var AMPLITUDE = 2 * Math.PI / 3, MAX_ANGLE_STEP = Math.PI / 4;
function fail(message) { throw new Error(message); }
function finite(value) { return typeof value === 'number' && isFinite(value); }
function joints(value) {
if (typeof value === 'string') {
try { value = JSON.parse(value); } catch (error) { fail('关节目标不是有效数组'); }
}
if (!Array.isArray(value) || value.length !== 6) fail('实际关节角必须为六个数值');
for (var i = 0; i < 6; i++) if (!finite(value[i])) fail('关节角数值无效');
return value;
}
function requiredPose(value, label) {
var keys = ['x', 'y', 'z', 'rx', 'ry', 'rz'];
if (!value) fail(label + '缺少完整TCP位姿');
for (var i = 0; i < keys.length; i++) if (!finite(value[keys[i]])) fail(label + '的TCP位姿数值无效');
return value;
}
function distance(a, b) {
var x = a.x - b.x, y = a.y - b.y, z = a.z - b.z;
return Math.sqrt(x * x + y * y + z * z);
}
function quaternion(p) {
var x = p.rx / 2, y = p.ry / 2, z = p.rz / 2;
var cx = Math.cos(x), sx = Math.sin(x), cy = Math.cos(y), sy = Math.sin(y), cz = Math.cos(z), sz = Math.sin(z);
return [sx * cy * cz - cx * sy * sz, cx * sy * cz + sx * cy * sz, cx * cy * sz - sx * sy * cz, cx * cy * cz + sx * sy * sz];
}
function angle(a, b) {
var qa = quaternion(a), qb = quaternion(b), minus = 0, plus = 0;
for (var i = 0; i < 4; i++) {
minus += (qa[i] - qb[i]) * (qa[i] - qb[i]);
plus += (qa[i] + qb[i]) * (qa[i] + qb[i]);
}
return 4 * Math.asin(Math.min(1, Math.sqrt(Math.min(minus, plus)) / 2));
}
function product(a, b) {
return [a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],
a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],
a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],
a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2]];
}
function matrix(q) {
var x = q[0], y = q[1], z = q[2], w = q[3];
return [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w),
2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w),
2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)];
}
function nearest(value, previous) {
return value + 2 * Math.PI * Math.round((previous - value) / (2 * Math.PI));
}
function chooseEuler(first, second, previous) {
function candidate(value) {
return { rx: nearest(value.rx, previous.rx), ry: nearest(value.ry, previous.ry), rz: nearest(value.rz, previous.rz) };
}
function cost(value) {
var x = value.rx - previous.rx, y = value.ry - previous.ry, z = value.rz - previous.rz;
return x * x + y * y + z * z;
}
var a = candidate(first), b = candidate(second);
return cost(a) <= cost(b) ? a : b;
}
function euler(q, previous, reference) {
var r = matrix(q), cp = Math.sqrt(r[0] * r[0] + r[3] * r[3]);
if (cp <= 1e-12) {
// At pitch +/-pi/2 only rx-sign(pitch)*rz is observable. Choose its
// nearest equivalent and share the adjustment between rx and rz.
// This singular tolerance only absorbs floating-point round-off.
var sign = r[6] < 0 ? 1 : -1, prior = previous.rx - sign * previous.rz;
var combined = nearest(Math.atan2(-r[5], r[4]), prior), change = combined - prior;
return { rx: previous.rx + change / 2, ry: nearest(sign * Math.PI / 2, previous.ry), rz: previous.rz - sign * change / 2 };
}
if (reference) return chooseEuler(reference, { rx: reference.rx + Math.PI, ry: Math.PI - reference.ry, rz: reference.rz + Math.PI }, previous);
var primary = { rx: Math.atan2(r[7], r[8]), ry: Math.atan2(-r[6], cp), rz: Math.atan2(r[3], r[0]) };
return chooseEuler(primary, { rx: primary.rx + Math.PI, ry: Math.PI - primary.ry, rz: primary.rz + Math.PI }, previous);
}
function toolOrientation(reference, theta, previous, first) {
if (first) return { rx: reference.rx, ry: reference.ry, rz: reference.rz };
var wanted = product(quaternion(reference), [0, 0, Math.sin(theta / 2), Math.cos(theta / 2)]);
var result = euler(wanted, previous, theta === 0 ? reference : null);
var actual = quaternion(result), minus = 0, plus = 0;
for (var i = 0; i < 4; i++) {
minus += (wanted[i] - actual[i]) * (wanted[i] - actual[i]);
plus += (wanted[i] + actual[i]) * (wanted[i] + actual[i]);
}
if (Math.sqrt(Math.min(minus, plus)) > 1e-9) fail('工具Z轴姿态转换误差超出范围');
return result;
}
function state(s) {
if (!s || s.connected !== true || s.poweredOn !== true || s.brakeReleased !== true ||
s.protectiveStopped !== false || s.emergencyStopped !== false || s.fault !== false ||
s.safetyMode !== 'ARM_SAFETY_MODE_NORMAL' || s.controlMode !== 'ARM_CONTROL_MODE_POSITION')
fail('机械臂连接、上电、制动或安全状态未确认正常');
if (!finite(s.timestamp) || Math.abs(Date.now() / 1000 - s.timestamp) > 10) fail('机械臂实际回读状态已过期');
if (s.moving !== false || s.programRunning !== false || s.robotMode !== 'ARM_ROBOT_MODE_IDLE') fail('机械臂尚未确认停稳');
var q = joints(s.actualJointState && s.actualJointState.position);
var v = s.actualJointState.velocity, t = s.actualTcpVelocity;
if (!Array.isArray(v) || v.length !== 6 || !t) fail('停稳复核缺少关节或TCP速度');
var keys = ['vx', 'vy', 'vz', 'wx', 'wy', 'wz'];
for (var i = 0; i < 6; i++) {
if (!finite(v[i]) || Math.abs(v[i]) > 0.001) fail('机械臂关节尚未连续停稳');
if (!finite(t[keys[i]]) || Math.abs(t[keys[i]]) > 0.0001) fail('机械臂末端尚未连续停稳');
}
requiredPose(s.actualTcpPose, '实际回读');
return s.actualTcpPose;
}
function continuous() {
var before = params.previousState, after = params.state;
var a = state(before), b = state(after), dt = after.timestamp - before.timestamp;
if (dt < 0.2 || dt > 2) fail('连续停稳复核的两帧间隔必须为0.2至2秒');
if (distance(a, b) > 0.00002 || angle(a, b) > 0.0001) fail('连续回读的TCP位姿仍在漂移');
var qa = joints(before.actualJointState.position), qb = joints(after.actualJointState.position);
for (var i = 0; i < 6; i++) if (Math.abs(qb[i] - qa[i]) / dt > 0.001) fail('连续关节回读尚未停稳');
}
function pose(p, speed) { return { x: p.x, y: p.y, z: p.z, rx: p.rx, ry: p.ry, rz: p.rz, velocity: speed }; }
function poseMatch(actual, target) {
requiredPose(target, '规划目标');
if (distance(actual, target) > 0.003 || angle(actual, target) > 0.015) fail('未到指定扫描末点、退让位置或姿态,停止后续动作');
}
function jointMatch(actual, target) {
actual = joints(actual); target = joints(target);
for (var i = 0; i < 6; i++) if (Math.abs(actual[i] - target[i]) > 0.015) fail('未到原初始关节目标');
}
function stamp(reference, now) {
if (!reference || !finite(reference.stamp) || now < reference.stamp) fail('实际回读时间与本阶段准备记录不一致');
}
function confirmedMoves(target, actual) {
if (distance(actual, target) > 0.00005 || angle(actual, target) > 0.0001) return [target];
continuous();
if (distance(params.previousState.actualTcpPose, target) > 0.00005 || angle(params.previousState.actualTcpPose, target) > 0.0001)
fail('重复衔接点缺少连续到位回读,停止发送空移动');
return [];
}
function pointList(points, original) {
var limit = original ? 202 : MAX_POINTS;
if (!Array.isArray(points) || points.length < 2 || points.length > limit || (original && points.length % 2 !== 0))
fail(original ? '原扫描条带必须为2至202个偶数点' : '扫描点集必须为2至4096个点');
for (var i = 0; i < points.length; i++) {
var p = requiredPose(points[i], '扫描点');
if (!finite(p.velocity) || !(p.velocity > 0) || p.y < 0.456 || p.z < -0.3 - EPS) fail('扫描点速度或XYZ范围无效');
if (original && i % 2 === 1 && (Math.abs(p.y - points[i - 1].y) > EPS || Math.abs(p.z - points[i - 1].z) > EPS))
fail('原横扫条带两端不在同一Y/Z');
if (i && distance(points[i - 1], p) <= 1e-12) fail('原扫描路径存在零距离重复点');
}
return points;
}
function copy(p) {
var result = {};
for (var key in p) if (Object.prototype.hasOwnProperty.call(p, key)) result[key] = p[key];
return result;
}
function ordered(points, actual) {
var candidates = [], best = null, bestCost = Infinity;
for (var flip = 0; flip < 2; flip++) {
var list = [];
for (var i = 0; i < points.length; i++) list.push(points[flip ? (i % 2 === 0 ? i + 1 : i - 1) : i]);
candidates.push(list); candidates.push(list.slice(0).reverse());
}
for (var i = 0; i < candidates.length; i++) {
var first = candidates[i][0], x = first.x - actual.x, z = first.z - actual.z, cost = x * x + z * z;
if (cost < bestCost) { bestCost = cost; best = candidates[i]; }
}
return best;
}
function sweep(input, orientation) {
var cumulative = [0], lengths = [], total = 0;
for (var i = 1; i < input.length; i++) {
var length = distance(input[i - 1], input[i]);
lengths.push(length);
if (length >= MIN_EDGE) total += length;
cumulative.push(total);
}
if (!(total > 2 * MIN_EDGE)) fail('有效扫描路径过短,不能在保持XYZ路径的同时完成工具Z轴往复');
var peak = total / 2, closest = MIN_EDGE;
// A nearby original interior vertex is the peak; short edges there become a plateau.
for (var i = 1; i < cumulative.length - 1; i++) {
var delta = Math.abs(cumulative[i] - total / 2);
if (cumulative[i] > 0 && cumulative[i] < total && delta < closest) { closest = delta; peak = cumulative[i]; }
}
function offset(w) {
if (w <= 0 || w >= total) return 0;
if (w === peak) return AMPLITUDE;
return w < peak ? AMPLITUDE * w / peak : AMPLITUDE * (total - w) / (total - peak);
}
var result = [], thetaValues = [];
function append(p, w) {
var theta = offset(w), target = copy(p);
var converted = toolOrientation(orientation, theta, result.length ? result[result.length - 1] : orientation, result.length === 0);
target.rx = converted.rx; target.ry = converted.ry; target.rz = converted.rz;
result.push(target); thetaValues.push(theta);
}
append(input[0], 0);
for (var edge = 0; edge < lengths.length; edge++) {
var a = input[edge], b = input[edge + 1], start = cumulative[edge], end = cumulative[edge + 1];
var cuts = [0];
if (start < peak && peak < end) cuts.push((peak - start) / (end - start));
cuts.push(1);
for (var part = 1; part < cuts.length; part++) {
var from = cuts[part - 1], to = cuts[part];
var startW = start + (end - start) * from, endW = start + (end - start) * to;
var change = Math.abs(offset(endW) - offset(startW));
var steps = Math.max(1, Math.ceil(change / MAX_ANGLE_STEP - 1e-10));
if (change > EPS && lengths[edge] * (to - from) / steps < MIN_EDGE - EPS)
fail('工具Z轴关键帧间距不足2mm,不能安全表达本次摆扫');
for (var step = 1; step <= steps; step++) {
var t = step === steps ? to : from + (to - from) * step / steps;
var point = copy(b);
if (t !== 1) {
point.x = a.x + (b.x - a.x) * t;
point.y = a.y + (b.y - a.y) * t;
point.z = a.z + (b.z - a.z) * t;
}
append(point, t === 1 ? end : start + (end - start) * t);
if (result.length > MAX_POINTS) fail('工具Z轴摆扫细分点超过4096个');
}
}
}
var maximum = 0, variation = 0, descending = false;
var referenceQ = quaternion(orientation), inverse = [-referenceQ[0], -referenceQ[1], -referenceQ[2], referenceQ[3]];
var referenceMatrix = matrix(referenceQ);
for (var i = 0; i < result.length; i++) {
// Check the intrinsic phase and physical relative axis, not the Base
// rz difference: all three Base Euler components may change together.
var value = thetaValues[i], actualQ = quaternion(result[i]), relative = product(inverse, actualQ);
var expectedRelative = [0, 0, Math.sin(value / 2), Math.cos(value / 2)], minus = 0, plus = 0;
for (var j = 0; j < 4; j++) {
minus += (relative[j] - expectedRelative[j]) * (relative[j] - expectedRelative[j]);
plus += (relative[j] + expectedRelative[j]) * (relative[j] + expectedRelative[j]);
}
if (Math.sqrt(Math.min(minus, plus)) > 1e-9) fail('姿态偏离工具自身Z轴旋转');
var actualMatrix = matrix(actualQ);
for (var j = 2; j < 9; j += 3) if (Math.abs(actualMatrix[j] - referenceMatrix[j]) > 1e-9) fail('工具Z轴在Base中的方向发生变化');
if (value < -EPS || value > AMPLITUDE + EPS) fail('工具Z轴摆角超出本次往复范围');
maximum = Math.max(maximum, value);
if (i) {
var difference = value - thetaValues[i - 1];
if (Math.abs(difference) > MAX_ANGLE_STEP + EPS || angle(result[i - 1], result[i]) > MAX_ANGLE_STEP + EPS) fail('相邻工具姿态关键帧超过45度');
if (Math.abs(difference) > EPS && distance(result[i - 1], result[i]) < MIN_EDGE - EPS) fail('工具转角变化段XYZ间距不足2mm');
if (difference < -EPS) descending = true;
if (descending && difference > EPS) fail('工具Z轴摆扫出现额外往复');
variation += Math.abs(difference);
}
}
if (thetaValues[0] !== 0 || thetaValues[thetaValues.length - 1] !== 0 || angle(result[0], orientation) > 1e-9 || angle(result[result.length - 1], orientation) > 1e-9 ||
Math.abs(maximum - AMPLITUDE) > EPS || Math.abs(variation - 2 * AMPLITUDE) > EPS) fail('工具Z轴摆扫未完成初始到120度再回初始的一次往复');
return result;
}
var actual = state(params.state), now = params.state.timestamp;
if (params.mode === 'offset_initial') {
jointMatch(params.state.actualJointState.position, params.initialJoints);
var initialRetreat = pose(actual, 0.15); initialRetreat.y -= 0.2;
return { retreatPose: initialRetreat, stamp: now };
}
if (params.mode === 'rx_target') {
stamp(params.offset, now); stamp(params.reference, now);
poseMatch(actual, requiredPose(params.offset.retreatPose, '当前退让位置'));
var reference = requiredPose(params.reference.retreatPose, '本站最初姿态基准');
if (params.rx !== -2 && params.rx !== -1.1) fail('RX目标必须为-2或-1.1rad');
var target = pose(actual, 0.06); target.rx = params.rx; target.ry = reference.ry; target.rz = reference.rz;
return { targetPose: target, stamp: now };
}
if (params.mode === 'scan') {
continuous(); stamp(params.rotation, now);
var rotation = requiredPose(params.rotation.targetPose, '本组原RX姿态');
poseMatch(actual, rotation);
var original = pointList(params.points, true), lo = params.minZMm / 1000, hi = params.maxZMm / 1000;
if (!finite(lo) || !finite(hi) || hi < lo || (rotation.rx !== -2 && rotation.rx !== -1.1) ||
Math.abs(lo - (rotation.rx === -2 ? -0.15 : -0.3)) > EPS) fail('RX扫描Z范围无效');
for (var i = 0; i < original.length; i++)
if (Math.abs(original[i].rx - rotation.rx) > EPS || original[i].z < lo - EPS || original[i].z > hi + EPS)
fail('原扫描点超出本组RX或Z范围');
var points = sweep(ordered(original, actual), rotation);
var entry = pose(points[0], 0.15), hover = pose(points[0], 0.15); hover.y -= 0.2;
return { points: points, scanPoints: points.slice(1), hover: hover, hoverMoves: confirmedMoves(hover, actual), entry: entry, count: points.length, stamp: now };
}
if (params.mode === 'offset') {
var completed = pointList(params.completedPoints, false), last = completed[completed.length - 1];
poseMatch(actual, last);
var retreat = pose(last, 0.15); retreat.y -= 0.2;
retreat.rx = actual.rx; retreat.ry = actual.ry; retreat.rz = actual.rz;
return { retreatPose: retreat, stamp: now };
}
fail('工具Z轴摆扫规划模式无效');
}