feat(scanner): integrate scanner workflows and real-time preview

Add scanner API integration, workflow components, execution-bound live images and 3D model viewing. Harden task control, parameters, resource protection and reports, with automated regressions and detailed verification records.
This commit is contained in:
lixiaolong 2026-10-23 09:03:27 +08:00
parent 7884e5ad49
commit cfff7295a6
144 changed files with 28691 additions and 70 deletions

View File

@ -0,0 +1,17 @@
CREATE TABLE IF NOT EXISTS `lab_scanner_command` (
`command_key` varchar(64) NOT NULL,
`active_endpoint` varchar(64) DEFAULT NULL,
`endpoint_key` varchar(64) NOT NULL,
`operation` varchar(64) NOT NULL,
`request_hash` varchar(64) NOT NULL,
`state` varchar(16) NOT NULL,
`remote_task_id` varchar(32) DEFAULT NULL,
`request_json` longtext NOT NULL,
`result_json` longtext,
`error_message` text,
`owner_ref` varchar(255) DEFAULT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`command_key`),
UNIQUE KEY `uk_scanner_active_endpoint` (`active_endpoint`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Scanner command acceptance journal; no supplier credentials';

View File

@ -0,0 +1,2 @@
ALTER TABLE `lab_scanner_command` ADD COLUMN `context_json` longtext COMMENT 'Immutable scanner session/project captured for a workflow command';
ALTER TABLE `lab_scanner_command` ADD INDEX `idx_scanner_command_owner` (`owner_ref`, `created_at`);

View File

@ -0,0 +1,8 @@
package com.cmvr.edge.client.service;
/** Additional transports that must acknowledge stop before a robot can be released. */
public interface RobotStopExtension {
boolean handles(String robotId);
/** Returns true only when this extension stopped all enabled devices on this robot. */
boolean stop(String robotId);
}

View File

@ -36,6 +36,8 @@ public class EdgeSystemServiceImpl implements EdgeSystemService {
private static final Logger logger = LoggerFactory.getLogger(EdgeSystemServiceImpl.class);
private final GrpcServiceManager grpcServiceManager;
@org.springframework.beans.factory.annotation.Autowired(required = false)
private java.util.List<com.cmvr.edge.client.service.RobotStopExtension> stopExtensions = java.util.List.of();
@Override
public SystemCommand.GetSystemInfoCommand.Feedback getSystemInfo(String robotId) {
@ -212,6 +214,9 @@ public class EdgeSystemServiceImpl implements EdgeSystemService {
@Override
public String stopAll(String robotId) {
boolean exclusive = false;
for (var extension : stopExtensions) if (extension.handles(robotId)) exclusive |= extension.stop(robotId);
if (exclusive) return "ACKNOWLEDGED";
SystemServiceGrpc.SystemServiceBlockingStub stub = grpcServiceManager.getGrpcClient(
robotId, SystemServiceGrpc.SystemServiceBlockingStub.class).withDeadlineAfter(10, TimeUnit.SECONDS);
SystemCommand.StopAllCommand.Feedback feedback = stub.stopAll(SystemCommand.StopAllCommand.Request.newBuilder()

View File

@ -0,0 +1,31 @@
package com.cmvr.scanner;
import com.cmvr.test.flow.runtime.engine.RobotTaskOccupationGuard;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Service;
import java.util.*;
/** Direct debugging uses the same occupation checks as existing edge controllers. */
@Service
@RequiredArgsConstructor
public class ScannerAccessService {
private final ScannerService scanner;
private final ScannerProperties settings;
private final ObjectProvider<RobotTaskOccupationGuard> guards;
private final com.cmvr.test.flow.runtime.engine.RobotDeviceAssignmentValidator deviceValidator;
@org.springframework.security.access.prepost.PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public ObjectNode submit(ScannerOperation op,String body,String key) {
if(!settings.configured())throw new ScannerException("not_configured","请先配置扫描服务的地址、端口和访问密钥",503);
if(settings.getRobotId().isBlank()||settings.getDeviceId().isBlank())throw new ScannerException("device_not_bound","请先配置扫描仪的永久robotId和deviceId,并登记运行设备",409);
ObjectNode request=ScannerRequestValidator.parse(body);ScannerRequestValidator.validate(op,request);ScannerService.key(key);
deviceValidator.validate(settings.getRobotId(),settings.getDeviceId(),14);
List<AutoCloseable> gates=new ArrayList<>();
try {
if(op!=ScannerOperation.SCAN_STOP)for(var guard:guards.orderedStream().toList())gates.add(guard.manual(settings.getRobotId()));
return scanner.submit(op,request,key,"manual:"+cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId());
}catch(RuntimeException e){throw e;}catch(Exception e){throw new ScannerException("occupation_error","设备占用检查失败",409);}
finally{for(int i=gates.size()-1;i>=0;i--)try{gates.get(i).close();}catch(Exception ignored){}}
}
}

View File

@ -0,0 +1,57 @@
package com.cmvr.scanner;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.*;
/** Committed before an external POST. No application transaction spans a device operation. */
@Repository
@RequiredArgsConstructor
@org.springframework.transaction.annotation.Transactional(propagation = org.springframework.transaction.annotation.Propagation.REQUIRES_NEW)
public class ScannerCommandJournal {
private final JdbcTemplate jdbc;
public record Entry(String key,String operation,String requestHash,String state,String taskId,String result,String endpoint,String error) {}
public Entry get(String key) {
var rows=jdbc.query("SELECT command_key,operation,request_hash,state,remote_task_id,result_json,endpoint_key,error_message FROM lab_scanner_command WHERE command_key=?",
(r,n)->new Entry(r.getString(1),r.getString(2),r.getString(3),r.getString(4),r.getString(5),r.getString(6),r.getString(7),r.getString(8)),key);
return rows.isEmpty()?null:rows.get(0);
}
public Entry active(String endpoint) {
var keys=jdbc.queryForList("SELECT command_key FROM lab_scanner_command WHERE active_endpoint=?",String.class,endpoint);
return keys.isEmpty()?null:get(keys.get(0));
}
public JsonNode context(String key) {
var rows=jdbc.queryForList("SELECT context_json FROM lab_scanner_command WHERE command_key=? AND context_json IS NOT NULL",String.class,key);
return rows.isEmpty()?null:parseContext(rows.get(0));
}
public JsonNode latestContext(String instId) {
return jdbc.queryForList("SELECT context_json FROM lab_scanner_command WHERE owner_ref=? AND context_json IS NOT NULL AND state='SUCCEEDED' AND operation IN ('CREATE_PROJECT','SCAN_START')",String.class,"workflow:"+instId)
.stream().map(this::parseContext).max(Comparator.comparingLong(node->node.path("capturedAt").asLong())).orElse(null);
}
public void bindContext(String key,String instId,JsonNode context) {
jdbc.update("UPDATE lab_scanner_command SET context_json=? WHERE command_key=? AND owner_ref=? AND state='SUCCEEDED' AND context_json IS NULL",context.toString(),key,"workflow:"+instId);
}
public boolean ownedBy(String key,String instId) {
return jdbc.queryForObject("SELECT COUNT(*) FROM lab_scanner_command WHERE command_key=? AND owner_ref=?",Integer.class,key,"workflow:"+instId)>0;
}
public void bindSnapshot(String key,String instId,JsonNode context) {
jdbc.update("UPDATE lab_scanner_command SET context_json=? WHERE command_key=? AND owner_ref=? AND operation='SNAPSHOT' AND state IN ('ACCEPTED','SUCCEEDED') AND context_json IS NULL",context.toString(),key,"workflow:"+instId);
}
public List<JsonNode> assetResults(String instId) {
return jdbc.query("SELECT command_key,result_json,context_json FROM lab_scanner_command WHERE owner_ref=? AND operation IN ('SNAPSHOT','EXPORT') AND state='SUCCEEDED' AND context_json IS NOT NULL",
(row,n)->{var value=ScannerRequestValidator.JSON.createObjectNode();value.put("commandKey",row.getString(1));value.set("task",parseContext(row.getString(2)));value.set("context",parseContext(row.getString(3)));return (JsonNode)value;},"workflow:"+instId);
}
private JsonNode parseContext(String source) {
try {return ScannerRequestValidator.JSON.readTree(source);}
catch(Exception error){throw new ScannerException("binding_invalid","扫描工程关联记录无效",500);}
}
public void intent(String key,String endpoint,ScannerOperation op,String hash,String request,String actor) {
try{jdbc.update("INSERT INTO lab_scanner_command(command_key,active_endpoint,endpoint_key,operation,request_hash,state,request_json,owner_ref,created_at,updated_at) VALUES(?,?,?,?,?,'INTENT',?,?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",key,endpoint,endpoint,op.name(),hash,request,actor);}
catch(org.springframework.dao.DuplicateKeyException e){throw new ScannerException("command_busy","存在未确认的设备命令,请先查询记录",409);}
}
public void accepted(String key,String taskId){jdbc.update("UPDATE lab_scanner_command SET state='ACCEPTED',remote_task_id=?,updated_at=CURRENT_TIMESTAMP WHERE command_key=? AND state='INTENT'",taskId,key);}
public void uncertain(String key,String message){jdbc.update("UPDATE lab_scanner_command SET state='UNKNOWN',error_message=?,updated_at=CURRENT_TIMESTAMP WHERE command_key=? AND state IN ('INTENT','ACCEPTED')",message,key);}
public void finish(String key,boolean success,JsonNode result,String error){jdbc.update("UPDATE lab_scanner_command SET state=?,result_json=?,error_message=?,active_endpoint=NULL,updated_at=CURRENT_TIMESTAMP WHERE command_key=? AND state IN ('INTENT','ACCEPTED')",success?"SUCCEEDED":"FAILED",result==null?null:result.toString(),error,key);}
}

View File

@ -0,0 +1,20 @@
package com.cmvr.scanner;
import com.cmvr.test.flow.control.FlowDeviceLifecycleExtension;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.List;
/** A completed workflow must not release a scanner that is still acquiring. */
@Component
@RequiredArgsConstructor
public class ScannerCompletionExtension implements FlowDeviceLifecycleExtension {
private final ScannerStopExtension stop;
private final ScannerPauseExtension pauses;
@Override public void beforePause(String instId, List<String> robots) {}
@Override public void beforeResume(String instId, List<String> robots) {}
@Override public void beforeComplete(String instId, List<String> robots) {
robots.stream().filter(stop::handles).distinct().forEach(stop::stop);
pauses.afterStop(instId);
}
}

View File

@ -0,0 +1,11 @@
package com.cmvr.scanner;
import com.cmvr.common.exception.GlobalException;
public class ScannerException extends GlobalException {
public final String scannerCode;
public final int remoteStatus;
public ScannerException(String code,String message,int status) {
super("扫描设备["+code+"] "+message); scannerCode=code; remoteStatus=status;
}
}

View File

@ -0,0 +1,113 @@
package com.cmvr.scanner;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.io.InputStream;
import java.net.URI;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.*;
@Component
@RequiredArgsConstructor
public class ScannerHttpClient {
private final ScannerProperties settings;
private volatile HttpClient client;
private static final ScheduledThreadPoolExecutor STREAM_TIMEOUTS = streamTimeouts();
private static ScheduledThreadPoolExecutor streamTimeouts() {
var pool=new ScheduledThreadPoolExecutor(1,r->{Thread thread=new Thread(r,"scanner-stream-timeout");thread.setDaemon(true);return thread;});
pool.setRemoveOnCancelPolicy(true);return pool;
}
public void requireConfigured() {
if(!settings.configured())throw new ScannerException("not_configured","请先配置扫描服务的地址、端口和访问密钥",503);
if(settings.getHost().contains("/")||settings.getHost().contains("@")||settings.getHost().contains("?"))throw new ScannerException("invalid_config","扫描服务地址仅填写主机名或IP",400);
}
public String endpointKey() {
requireConfigured(); return cn.hutool.crypto.digest.DigestUtil.sha256Hex(settings.getHost()+":"+settings.getPort());
}
private HttpClient client() {
if(client==null)synchronized(this){if(client==null)client=HttpClient.newBuilder()
.connectTimeout(Duration.ofMillis(Math.max(100,settings.getConnectTimeoutMs())))
.followRedirects(HttpClient.Redirect.NEVER).build();}
return client;
}
private HttpRequest request(ScannerOperation op,String id,String body,long timeoutMs) {
requireConfigured();
try {
URI uri=new URI("http",null,settings.getHost(),settings.getPort(),op.route(id),null,null);
HttpRequest.Builder builder=HttpRequest.newBuilder(uri).timeout(Duration.ofMillis(Math.max(1,timeoutMs)))
.header("Accept",op.binary()?"*/*":"application/json");
if(op!=ScannerOperation.METADATA)builder.header("X-Api-Key",settings.getApiKey());
if(op.control())builder.header("Content-Type","application/json; charset=utf-8")
.POST(HttpRequest.BodyPublishers.ofString(body,StandardCharsets.UTF_8));
else builder.GET();
return builder.build();
}catch(ScannerException e){throw e;}catch(Exception e){throw new ScannerException("invalid_config","扫描服务地址配置无效",400);}
}
public JsonNode json(ScannerOperation op,String id,String body,long timeoutMs) {
requireConfigured();
long deadline=System.nanoTime()+TimeUnit.MILLISECONDS.toNanos(Math.max(1,timeoutMs));
var future=client().sendAsync(request(op,id,body,timeoutMs),HttpResponse.BodyHandlers.ofInputStream());
try {
var response=future.get(Math.max(1,timeoutMs),TimeUnit.MILLISECONDS);
try(var stream=new TimedStream(response.body(),timeoutMs,deadline)) {
if(response.statusCode()!=(op.control()?202:200)) {
if(op.control()&&response.statusCode()>=200&&response.statusCode()<300)throw new ScannerException("invalid_response","控制接口未返回202,执行结果未确认",502);
throw remote(response.statusCode(),stream.readNBytes(65536));
}
byte[] bytes=stream.readNBytes(4*1024*1024+1);
if(bytes.length>4*1024*1024)throw new ScannerException("response_too_large","扫描服务JSON响应过大",502);
JsonNode value=ScannerRequestValidator.JSON.readTree(bytes);
if(value==null||!value.isObject())throw new ScannerException("invalid_response","扫描服务未返回JSON对象",502);
return value;
}
}catch(ScannerException e){throw e;}
catch(InterruptedException e){future.cancel(true);Thread.currentThread().interrupt();throw new ScannerException("interrupted","等待被中断;设备动作可能仍在执行",504);}
catch(Exception e){future.cancel(true);throw new ScannerException("transport_uncertain","连接中断或超时;先核对任务和设备状态,不得直接重发",504);}
}
public record Binary(InputStream stream,Map<String,java.util.List<String>> headers) implements AutoCloseable {
@Override public void close() throws java.io.IOException{stream.close();}
}
public Binary binary(ScannerOperation op,String id) {
requireConfigured();
if(!op.binary())throw new IllegalArgumentException("not binary");
var future=client().sendAsync(request(op,id,null,settings.getRequestTimeoutMs()),HttpResponse.BodyHandlers.ofInputStream());
try {
var response=future.get(Math.max(1,settings.getRequestTimeoutMs()),TimeUnit.MILLISECONDS);
var body=new TimedStream(response.body(),settings.getRequestTimeoutMs(),0);
if(response.statusCode()!=200){try(body){throw remote(response.statusCode(),body.readNBytes(65536));}}
return new Binary(body,response.headers().map());
}catch(ScannerException e){throw e;}catch(InterruptedException e){future.cancel(true);Thread.currentThread().interrupt();throw new ScannerException("interrupted","下载已中断",504);}
catch(Exception e){future.cancel(true);throw new ScannerException("stream_unavailable","扫描图像或文件暂不可用",503);}
}
/** Bound JSON by an absolute deadline and downloads/MJPEG by idle time.
* HttpRequest.timeout stops protecting the body after ofInputStream headers.
*/
private static final class TimedStream extends java.io.FilterInputStream {
private final long idleNanos,deadline;
private final java.util.concurrent.atomic.AtomicBoolean expired=new java.util.concurrent.atomic.AtomicBoolean();
TimedStream(InputStream source,long timeoutMs,long deadline){super(source);this.idleNanos=TimeUnit.MILLISECONDS.toNanos(Math.max(1,timeoutMs));this.deadline=deadline;}
@FunctionalInterface private interface Read {int run() throws java.io.IOException;}
private int readTimed(Read read) throws java.io.IOException {
long remaining=deadline==0?idleNanos:Math.min(idleNanos,deadline-System.nanoTime());
if(expired.get()||remaining<=0)throw new java.net.SocketTimeoutException("Scanner response body timed out");
var timer=STREAM_TIMEOUTS.schedule(()->{expired.set(true);try{in.close();}catch(java.io.IOException ignored){}},remaining,TimeUnit.NANOSECONDS);
try {
int result=read.run();
if(expired.get())throw new java.net.SocketTimeoutException("Scanner response body timed out");
return result;
} finally {timer.cancel(false);}
}
@Override public int read() throws java.io.IOException{return readTimed(in::read);}
@Override public int read(byte[] bytes,int offset,int length)throws java.io.IOException{return readTimed(()->in.read(bytes,offset,length));}
}
private ScannerException remote(int status,byte[] bytes) {
try {
JsonNode value=ScannerRequestValidator.JSON.readTree(bytes).path("error");
return new ScannerException(value.path("code").asText("remote_error"),value.path("message").asText("设备请求失败"),status);
}catch(Exception ignored){return new ScannerException("remote_error","设备返回HTTP "+status,status);}
}
}

View File

@ -0,0 +1,136 @@
package com.cmvr.scanner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.*;
/** Read-only monitoring bound to an immutable workflow command, scanner session and project. */
@Service
@RequiredArgsConstructor
public class ScannerMonitoringService {
private final ScannerService scanner;
private final ScannerProperties settings;
private final ScannerHttpClient client;
private final ScannerCommandJournal journal;
public JsonNode capture(ScannerOperation operation,String commandKey,String instId,String robot,String device) {
if(operation!=ScannerOperation.CREATE_PROJECT && operation!=ScannerOperation.SCAN_START) {
JsonNode context=journal.latestContext(instId);
if(context!=null&&(operation==ScannerOperation.SNAPSHOT||operation==ScannerOperation.EXPORT)) {
ObjectNode recorded=context.deepCopy();recorded.put("assetCreatedAt",System.currentTimeMillis());journal.bindContext(commandKey,instId,recorded);
}
return context;
}
JsonNode existing=journal.context(commandKey);
if(existing!=null)return existing;
var command=journal.get(commandKey);
if(command==null || !command.state().equals("SUCCEEDED"))return null;
JsonNode status=scanner.get(ScannerOperation.STATUS,null);
requireProject(status);
if(operation==ScannerOperation.CREATE_PROJECT) {
try {
String expected=ScannerRequestValidator.JSON.readTree(command.result()).path("result").path("projectId").asText();
if(!expected.equals(status.path("projectId").asText()))throw new ScannerException("project_changed","创建工程的结果与当前工程不同,不能自动关联画面",409);
}catch(ScannerException error){throw error;}catch(Exception error){throw new ScannerException("binding_invalid","创建工程结果缺少可核对的工程编号",409);}
}
JsonNode metrics=scanner.get(ScannerOperation.METRICS,null);
if(!metrics.path("latestSequence").canConvertToLong())throw new ScannerException("frame_sequence_unavailable","暂时无法建立扫描画面的帧边界",503);
ObjectNode context=ScannerRequestValidator.JSON.createObjectNode();
context.put("instId",instId);context.put("robotId",robot);context.put("deviceId",device);
context.put("endpoint",client.endpointKey());context.put("sessionId",status.path("sessionId").asText());
context.put("projectId",status.path("projectId").asText());context.put("commandKey",commandKey);
context.put("baselineSequence",metrics.path("latestSequence").asLong());context.put("capturedAt",System.currentTimeMillis());
journal.bindContext(commandKey,instId,context);
return journal.context(commandKey);
}
public JsonNode binding(String instId){return journal.latestContext(instId);}
public ObjectNode snapshot(String instId,String requestedKey) {
String key=ScannerService.hash("view-snapshot:"+instId+":"+ScannerService.key(requestedKey));
JsonNode context=binding(instId);status(context);
ObjectNode accepted;
try {accepted=scanner.submitBound(ScannerOperation.SNAPSHOT,ScannerRequestValidator.parse("{\"maxPoints\":100000,\"include\":[\"points\",\"markers\",\"meshes\"]}"),key,"workflow:"+instId,context);}
catch(ScannerException error) {
var entry=journal.get(key);if(entry==null)throw error;
accepted=ScannerRequestValidator.JSON.createObjectNode();accepted.put("commandKey",key);accepted.put("state",entry.state());accepted.put("error",entry.error());
}
ObjectNode recorded=context.deepCopy();recorded.put("assetCreatedAt",System.currentTimeMillis());
journal.bindSnapshot(key,instId,recorded);
return accepted;
}
public ScannerCommandJournal.Entry snapshotCommand(String instId,String key) {
if(!journal.ownedBy(ScannerService.key(key),instId))throw new ScannerException("command_not_found","本次执行没有该快照命令",404);
var entry=scanner.command(key);
if(!entry.operation().equals("SNAPSHOT"))throw new ScannerException("invalid_command","该命令不是三维快照",400);
return entry;
}
public List<JsonNode> assets(String instId) {
if(settings.configured()) {
var active=journal.active(client.endpointKey());
if(active!=null&&active.operation().equals("SNAPSHOT")&&journal.ownedBy(active.key(),instId)) {
try {scanner.command(active.key());}catch(ScannerException ignored){/* Keep the journal and previously completed files visible. */}
}
}
List<JsonNode> files=new ArrayList<>();
for(JsonNode record:journal.assetResults(instId))for(JsonNode file:record.path("task").path("result").path("files")) {
if(!file.isObject())continue;
String id=file.path("fileId").asText();if(!id.matches("[a-fA-F0-9]{32}"))continue;
ObjectNode item=file.deepCopy();item.put("commandKey",record.path("commandKey").asText());
item.put("capturedAt",record.path("context").path("assetCreatedAt").asLong(record.path("context").path("capturedAt").asLong()));
item.put("projectId",record.path("context").path("projectId").asText());
item.set("binding",record.path("context"));files.add(item);
}
files.sort(Comparator.comparingLong((JsonNode file)->file.path("capturedAt").asLong()).reversed());
return files;
}
public ScannerHttpClient.Binary asset(String instId,String fileId) {
ScannerOperation.FILE.route(fileId);
JsonNode file=assets(instId).stream().filter(item->fileId.equals(item.path("fileId").asText())).findFirst()
.orElseThrow(()->new ScannerException("file_not_owned","文件不属于本次执行",404));
if(!file.path("binding").path("endpoint").asText().equals(client.endpointKey()))throw new ScannerException("endpoint_changed","扫描服务已变更,原文件不能从当前地址读取",409);
if(file.path("bytes").asLong()>100L*1024*1024)throw new ScannerException("model_too_large","文件超过在线三维查看的100MiB限制,请使用原始成果下载",413);
return scanner.binary(ScannerOperation.FILE,fileId);
}
public JsonNode status(JsonNode binding) {
if(binding==null)throw new ScannerException("project_not_bound","等待本次执行建立扫描工程关联",409);
client.requireConfigured();
if(!binding.path("endpoint").asText().equals(client.endpointKey())
||!binding.path("robotId").asText().equals(settings.getRobotId())
||!binding.path("deviceId").asText().equals(settings.getDeviceId()))throw new ScannerException("device_changed","扫描服务或设备身份已变更,暂停展示画面",409);
JsonNode status=scanner.get(ScannerOperation.STATUS,null);
requireProject(status);
if(!binding.path("sessionId").asText().equals(status.path("sessionId").asText())
||!binding.path("projectId").asText().equals(status.path("projectId").asText()))throw new ScannerException("project_changed","扫描会话或工程已切换,当前画面不属于这次执行",409);
return status;
}
public record Frame(byte[] bytes,Map<String,List<String>> headers) {}
public Frame image(JsonNode binding) {
status(binding);
try(var binary=scanner.binary(ScannerOperation.PREVIEW_IMAGE,null)) {
String type=header(binary.headers(),"content-type");
if(type==null||!type.toLowerCase(Locale.ROOT).startsWith("image/jpeg"))throw new ScannerException("invalid_frame","扫描服务未返回JPEG画面",502);
String sequence=header(binary.headers(),"x-frame-sequence");
long number;
try {number=Long.parseLong(sequence);}catch(Exception error){throw new ScannerException("invalid_frame","扫描画面缺少有效帧编号",502);}
byte[] bytes=binary.stream().readNBytes(8*1024*1024+1);
if(bytes.length>8*1024*1024)throw new ScannerException("frame_too_large","扫描画面超过大小限制",502);
if(bytes.length<4||(bytes[0]&255)!=255||(bytes[1]&255)!=216)throw new ScannerException("invalid_frame","扫描画面内容无效",502);
status(binding); // The project must still match after reading the complete frame.
if(number<=binding.path("baselineSequence").asLong())throw new ScannerException("frame_pending","等待本次工程的新画面",503);
return new Frame(bytes,binary.headers());
}catch(IOException error){throw new ScannerException("frame_unavailable","扫描画面读取失败,请稍后重试",503);}
}
private String header(Map<String,List<String>> headers,String name) {
return headers.entrySet().stream().filter(e->e.getKey().equalsIgnoreCase(name))
.filter(e->!e.getValue().isEmpty()).map(e->e.getValue().get(0)).findFirst().orElse(null);
}
private void requireProject(JsonNode status) {
if(status.path("stateUncertain").asBoolean()||status.path("restartRequired").asBoolean())throw new ScannerException("state_uncertain","扫描设备状态待确认,暂停展示画面",409);
if(!status.path("projectReady").asBoolean()||!status.path("sessionId").isTextual()||status.path("sessionId").asText().isBlank()
||!status.path("projectId").isTextual()||status.path("projectId").asText().isBlank())throw new ScannerException("project_not_ready","扫描工程尚未就绪",409);
}
}

View File

@ -0,0 +1,59 @@
package com.cmvr.scanner;
import java.util.Arrays;
/** Routes transcribed from the supplier's 2026-10-22 API 1.2 document. */
public enum ScannerOperation {
CONNECT("POST", "/api/v1/device/connect", "连接扫描仪", "SCANNER_INITIALIZE"),
CREATE_PROJECT("POST", "/api/v1/projects", "创建扫描工程", "SCANNER_CREATE_PROJECT"),
DISCONNECT("POST", "/api/v1/device/disconnect", "断开扫描会话", "SCANNER_DISCONNECT"),
RECONNECT("POST", "/api/v1/device/reconnect", "重新连接扫描仪", "SCANNER_RECONNECT"),
PREVIEW_START("POST", "/api/v1/preview/start", "开启扫描预览", "SCANNER_PREVIEW_START"),
PREVIEW_STOP("POST", "/api/v1/preview/stop", "关闭扫描预览", "SCANNER_PREVIEW_STOP"),
SCAN_START("POST", "/api/v1/scan/start", "开始或继续采集", "SCANNER_START"),
SCAN_STOP("POST", "/api/v1/scan/stop", "暂停采集", "SCANNER_STOP"),
PREVIEW_IMAGE("GET", "/api/v1/preview/image", "扫描预览图像", null),
PREVIEW_STREAM("GET", "/api/v1/preview/stream", "扫描实时预览", null),
PARAMETERS("POST", "/api/v1/parameters", "配置扫描参数", "SCANNER_PARAMETERS"),
MESH("POST", "/api/v1/mesh", "生成网格预览", "SCANNER_MESH"),
MESH_CONFIRM("POST", "/api/v1/mesh/confirm", "确认扫描网格", "SCANNER_MESH_CONFIRM"),
MESH_UNDO("POST", "/api/v1/mesh/undo", "撤销扫描网格", "SCANNER_MESH_UNDO"),
ALIGN("POST", "/api/v1/align", "扫描工程拼接", "SCANNER_ALIGN"),
EDIT("POST", "/api/v1/edit", "删除扫描点或标志点", "SCANNER_EDIT"),
CLIP_PLANE("POST", "/api/v1/clip-plane", "平面裁剪", "SCANNER_CLIP_PLANE"),
EXPORT("POST", "/api/v1/exports", "导出扫描成果", "SCANNER_EXPORT"),
SNAPSHOT("POST", "/api/v1/data/snapshots", "保存原始场景快照", "SCANNER_SNAPSHOT"),
SCENE("GET", "/api/v1/data/scene", "读取扫描场景摘要", "SCANNER_SCENE"),
FILE("GET", "/api/v1/files/{fileId}", "下载扫描成果文件", null),
CALIBRATION_ENTER("POST", "/api/v1/calibration/enter", "进入扫描标定", "SCANNER_CALIBRATION_ENTER"),
CALIBRATION_MODE("POST", "/api/v1/calibration/setMode", "设置标定模式", "SCANNER_CALIBRATION_MODE"),
CALIBRATION_START("POST", "/api/v1/calibration/start", "开始扫描标定", "SCANNER_CALIBRATION_START"),
CALIBRATION_TRAK("POST", "/api/v1/calibration/setTrakType", "设置跟踪仪标定类型", "SCANNER_CALIBRATION_TRAK"),
CALIBRATION_SYSTEM("POST", "/api/v1/calibration/startSystem", "开始系统标定", "SCANNER_CALIBRATION_SYSTEM"),
CALIBRATION_FREE("POST", "/api/v1/calibration/setFree", "设置自由标定", "SCANNER_CALIBRATION_FREE"),
CALIBRATION_CAPTURE("POST", "/api/v1/calibration/capturePose", "采集标定姿态", "SCANNER_CALIBRATION_CAPTURE"),
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"),
METADATA("GET", "/", "读取扫描服务信息", "SCANNER_METADATA"),
HEALTH("GET", "/api/v1/health", "检查扫描服务", "SCANNER_HEALTH"),
STATUS("GET", "/api/v1/status", "读取扫描仪状态", "SCANNER_STATUS"),
CAPABILITIES("GET", "/api/v1/capabilities", "读取扫描能力", "SCANNER_CAPABILITIES"),
METRICS("GET", "/api/v1/preview/metrics", "读取预览指标", "SCANNER_METRICS"),
TASK("GET", "/api/v1/tasks/{taskId}", "等待扫描设备任务", "SCANNER_WAIT");
public final String method, path, title, action;
ScannerOperation(String method, String path, String title, String action) {
this.method=method; this.path=path; this.title=title; this.action=action;
}
public boolean control() { return method.equals("POST"); }
public boolean binary() { return this==FILE || this==PREVIEW_IMAGE || this==PREVIEW_STREAM; }
public static ScannerOperation forAction(String action) {
return Arrays.stream(values()).filter(op -> op.action!=null && op.action.equals(action)).findFirst().orElse(null);
}
public String route(String id) {
if(this!=FILE && this!=TASK)return path;
if(id==null || !id.matches("[a-fA-F0-9]{32}"))throw new ScannerException("invalid_id","任务或文件编号必须为32位十六进制",400);
return path.replace(this==FILE?"{fileId}":"{taskId}",id);
}
}

View File

@ -0,0 +1,56 @@
package com.cmvr.scanner;
import com.cmvr.test.flow.control.FlowDeviceLifecycleExtension;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/** Restores acquisition only in the same scanner session and project captured before pause. */
@Component
@RequiredArgsConstructor
public class ScannerPauseExtension implements FlowDeviceLifecycleExtension {
private final ScannerProperties settings;
private final ScannerService scanner;
private final ScannerHttpClient client;
private final ScannerCommandJournal journal;
private final Map<String, Pause> pauses = new ConcurrentHashMap<>();
private record Pause(boolean scanning, String session, String project, String endpoint, String commandKey, String error) {}
private boolean handles(List<String> robots) { return !settings.getRobotId().isBlank() && robots.contains(settings.getRobotId()); }
@Override public void beforePause(String instId, List<String> robots) {
if (!handles(robots)) return;
pauses.put(instId, new Pause(false, null, null, null, null, "未能确认暂停前的扫描状态,请终止任务并核对现场后重新执行"));
var active = journal.active(client.endpointKey());
if (active != null) scanner.waitCommand(active.key(), settings.getOperationTimeoutMs());
JsonNode status = scanner.get(ScannerOperation.STATUS, null);
known(status);
boolean scanning = status.path("scanning").asBoolean();
String session = status.path("sessionId").asText(), project = status.path("projectId").asText();
if (scanning && (session.isBlank() || project.isBlank())) throw new ScannerException("pause_unconfirmed", "采集中设备缺少会话或工程身份", 409);
pauses.put(instId, new Pause(scanning, session, project, client.endpointKey(), UUID.randomUUID().toString(), null));
}
@Override public void beforeResume(String instId, List<String> robots) {
if (!handles(robots)) return;
Pause pause = pauses.get(instId);
if (pause == null || pause.error != null) throw new ScannerException("pause_unconfirmed", pause == null ? "扫描暂停状态已丢失,请终止后重新执行" : pause.error, 409);
if (!pause.endpoint.equals(client.endpointKey())) throw new ScannerException("endpoint_changed", "扫描服务地址已变更,不能自动恢复采集", 409);
var active = journal.active(client.endpointKey());
if (active != null) scanner.waitCommand(active.key(), settings.getOperationTimeoutMs());
JsonNode status = scanner.get(ScannerOperation.STATUS, null);
known(status);
if (!pause.session.equals(status.path("sessionId").asText()) || !pause.project.equals(status.path("projectId").asText())) throw new ScannerException("session_changed", "扫描会话或工程已改变,不能自动恢复采集", 409);
if (!pause.scanning) return;
if (!status.path("scanning").asBoolean()) {
scanner.executeAndWait(ScannerOperation.SCAN_START, ScannerRequestValidator.parse("{}"), pause.commandKey, "resume:" + instId, settings.getOperationTimeoutMs());
status = scanner.get(ScannerOperation.STATUS, null);
known(status);
if (!status.path("scanning").asBoolean()) throw new ScannerException("resume_unconfirmed", "尚未确认扫描恢复,工作流保持暂停", 409);
}
}
private void known(JsonNode status) {
if (!status.path("scanning").isBoolean() || status.path("busy").asBoolean() || status.path("stateUncertain").asBoolean() || status.path("restartRequired").asBoolean()) throw new ScannerException("pause_unconfirmed", "设备状态尚未确认,工作流不能自动恢复", 409);
}
@Override public void afterStop(String instId) { pauses.remove(instId); }
}

View File

@ -0,0 +1,21 @@
package com.cmvr.scanner;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "cmvr.scanner")
public class ScannerProperties {
private String host = "";
private Integer port;
private String apiKey = "";
private String robotId = "";
private String deviceId = "";
private int connectTimeoutMs = 5000;
private int requestTimeoutMs = 15000;
private int pollIntervalMs = 500;
private int operationTimeoutMs = 120000;
public boolean configured() { return host != null && !host.isBlank() && port != null && port > 0 && port <= 65535 && apiKey != null && !apiKey.isBlank(); }
}

View File

@ -0,0 +1,107 @@
package com.cmvr.scanner;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.nio.charset.StandardCharsets;
import java.util.*;
/** Documented shape/lexical types; unknown SDK limits remain device-side validations. */
public class ScannerRequestValidator {
public static final ObjectMapper JSON=new ObjectMapper().enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
public static ObjectNode parse(String source) {
if(source==null||source.getBytes(StandardCharsets.UTF_8).length>1048576)throw bad("请求体不能为空或超过1MiB");
try {
JsonNode node=JSON.readTree(source);
if(!(node instanceof ObjectNode object))throw bad("请求体必须是JSON对象");
depth(object,1);return object;
}catch(ScannerException error){throw error;}catch(Exception error){throw bad("JSON请求体格式无效");}
}
public static void validate(ScannerOperation op,ObjectNode 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);
switch(op) {
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);
}
case PARAMETERS -> {
fields(b,"pointDistance brightness lightSourceMode scanFrameRate highSpeedMode addMarkerMode viewLock localEnlargedView qualityColor strongLight preScanMode markerDiameters");
if(b.isEmpty())throw bad("至少设置一项扫描参数");
number(b,"pointDistance",false);integer(b,"brightness",false);integer(b,"scanFrameRate",false);
if(b.has("lightSourceMode"))range(b,"lightSourceMode",0,2);
for(String k:List.of("highSpeedMode","addMarkerMode","viewLock","localEnlargedView","qualityColor","strongLight","preScanMode"))bool(b,k);
if(b.has("markerDiameters"))integerArray(b,"markerDiameters");
}
case MESH -> {
fields(b,"filterLevel smoothLevel removeSmallFloatingParts cutMeshEdgeOptimization cutMeshEdgeValue holeOptimization boundaryOptimization maxTriangles fillSmallHole removeSpikes fillMarkerHoles rememberChoice");
for(String k:List.of("filterLevel","smoothLevel"))if(b.has(k))range(b,k,0,3);
integer(b,"removeSmallFloatingParts",false);number(b,"cutMeshEdgeValue",false);
for(String k:List.of("maxTriangles","fillSmallHole"))if(b.hasNonNull(k)){integer(b,k,true);if(b.get(k).bigIntegerValue().signum()<=0)throw bad(k+"必须为正整数或null");}
for(String k:List.of("cutMeshEdgeOptimization","holeOptimization","boundaryOptimization","removeSpikes","fillMarkerHoles","rememberChoice"))bool(b,k);
}
case EXPORT -> {fields(b,"name formats");name(b);strings(b,"formats",true);}
case SNAPSHOT -> {
fields(b,"maxPoints include");integer(b,"maxPoints",false);
if(b.has("maxPoints")&&b.get("maxPoints").bigIntegerValue().signum()<=0)throw bad("maxPoints必须为正整数");
if(b.has("include")){strings(b,"include",true);for(JsonNode item:b.get("include"))if(!Set.of("points","markers","meshes").contains(item.asText()))throw bad("不支持的快照数据类别");}
}
case ALIGN -> align(b);
case EDIT -> {
fields(b,"projectUuid cloudUuid pointIds markerIds points normals confirm");confirmed(b);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至少一组非空");
text(b,"cloudUuid",points>0);
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"));
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);}
default -> fields(b,"");
}
}
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");
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);
for(String k:List.of("fixedMarkerIds","movingMarkerIds"))if(b.has(k))integerArray(b,k);
for(String[] pair:List.of(new String[]{"fixedPoints","movingPoints"},new String[]{"fixedMarkerPoints","movingMarkerPoints"},new String[]{"fixedMarkerIds","movingMarkerIds"}))if(size(b,pair[0])!=size(b,pair[1]))throw bad("拼接配对数量不一致");
if(b.path("mode").asText().equals("featureManual")&&size(b,"fixedPoints")<3)throw bad("手动特征拼接至少需要三对点");
if(b.path("mode").asText().equals("markerManual")){int count=size(b,"fixedMarkerPoints");if(count<3||count!=size(b,"fixedMarkerIds"))throw bad("手动标志点拼接四组数量必须一致且至少为三");}
}
private static void deviceType(ObjectNode b){if(b.has("deviceType"))range(b,"deviceType",3,4);}
private static void name(ObjectNode b){if(!b.has("name"))return;text(b,"name",true);String n=b.get("name").asText();if(!n.matches("[\\p{L}\\p{Nd}_-]+")||n.chars().anyMatch(c->Character.isSurrogate((char)c)))throw bad("名称仅支持BMP字母、数字、下划线和短横线");}
private static void fields(ObjectNode b,String keys){Set<String> allowed=keys.isEmpty()?Set.of():Set.of(keys.split(" "));b.fieldNames().forEachRemaining(k->{if(!allowed.contains(k))throw bad("接口不接受字段:"+k);});}
private static void choice(ObjectNode b,String k,boolean required,String...choices){if(!b.has(k)&&!required)return;text(b,k,true);if(!Set.of(choices).contains(b.get(k).asText()))throw bad(k+"超出枚举范围");}
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+"超出枚举范围");}
private static void strings(ObjectNode b,String k,boolean required){if(!b.has(k)&&!required)return;if(!b.path(k).isArray()||b.path(k).isEmpty())throw bad(k+"必须是非空数组");for(JsonNode item:b.get(k))if(!item.isTextual()||item.asText().isBlank())throw bad(k+"必须为字符串数组");}
private static void integerArray(ObjectNode b,String k){if(!b.path(k).isArray())throw bad(k+"必须是整数数组");for(JsonNode item:b.get(k))if(!item.isIntegralNumber())throw bad(k+"必须是整数数组");}
private static int size(ObjectNode b,String k){return b.path(k).isArray()?b.path(k).size():0;}
private static void vector(JsonNode n){if(n==null||!n.isArray()||n.size()!=3)throw bad("坐标必须包含三个数值");for(JsonNode item:n)if(!item.isNumber()||!Float.isFinite((float)item.asDouble()))throw bad("坐标超出SDK数值范围");}
private static void vectors(ObjectNode b,String k){if(!b.path(k).isArray())throw bad(k+"必须是坐标数组");for(JsonNode item:b.get(k))vector(item);}
private static void depth(JsonNode n,int d){if(d>32)throw bad("JSON嵌套超过32层");if(n.isContainerNode())n.forEach(child->depth(child,d+1));}
private static ScannerException bad(String m){return new ScannerException("invalid_request",m,400);}
}

View File

@ -0,0 +1,171 @@
package com.cmvr.scanner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
@Service
@RequiredArgsConstructor
public class ScannerService {
private final ScannerProperties settings;
private final ScannerHttpClient client;
private final ScannerCommandJournal journal;
private final ReentrantLock commandLock=new ReentrantLock();
public ObjectNode configuration() {
ObjectNode result=ScannerRequestValidator.JSON.createObjectNode();
result.put("configured",settings.configured());result.put("host",settings.getHost());
if(settings.getPort()!=null)result.put("port",settings.getPort());else result.putNull("port");
result.put("credentialConfigured",settings.getApiKey()!=null&&!settings.getApiKey().isBlank());
result.put("robotId",settings.getRobotId());result.put("deviceId",settings.getDeviceId());return result;
}
public JsonNode get(ScannerOperation op,String id) {
if(op.control()||op.binary())throw new IllegalArgumentException("not a JSON query");
return client.json(op,id,null,settings.getRequestTimeoutMs());
}
public ScannerHttpClient.Binary binary(ScannerOperation op,String id){return client.binary(op,id);}
public ScannerCommandJournal.Entry command(String key){var entry=journal.get(key(key));if(entry!=null&&entry.state().equals("ACCEPTED"))refresh(entry);return journal.get(key);}
public ObjectNode submit(ScannerOperation op,ObjectNode body,String commandKey,String owner) {
return submit(op,body,commandKey,owner,null,0);
}
public ObjectNode submitBound(ScannerOperation op,ObjectNode body,String commandKey,String owner,JsonNode expectedContext) {
return submit(op,body,commandKey,owner,expectedContext,0);
}
private ObjectNode submit(ScannerOperation op,ObjectNode body,String commandKey,String owner,JsonNode expectedContext,long deadline) {
client.requireConfigured();ScannerRequestValidator.validate(op,body);
if(!op.control())throw new IllegalArgumentException("not a control");
String key=key(commandKey),hash=hash(client.endpointKey()+":"+op.name()+":"+canonical(body));
lock(deadline);
try {
requestBudget(deadline);
ScannerCommandJournal.Entry previous=journal.get(key);
if(previous!=null){
if(!previous.operation().equals(op.name())||!previous.requestHash().equals(hash))throw new ScannerException("command_key_conflict","同一命令标识不能用于不同操作或参数",409);
requireKnown(previous);return accepted(previous);
}
ScannerCommandJournal.Entry active=journal.active(client.endpointKey());
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("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);
if(status.path("busy").asBoolean())throw new ScannerException("device_busy","扫描设备正在处理其他控制任务",409);
requestBudget(deadline);
journal.intent(key,client.endpointKey(),op,hash,body.toString(),owner);
JsonNode response;
try {response=client.json(op,null,body.toString(),requestBudget(deadline));}
catch(ScannerException error){
if(Set.of("transport_uncertain","interrupted","invalid_response","response_too_large").contains(error.scannerCode))journal.uncertain(key,error.getMessage());
else journal.finish(key,false,null,error.getMessage());
throw error;
}
String taskId=response.path("taskId").asText();
if(!taskId.matches("[a-fA-F0-9]{32}")){
journal.uncertain(key,"受理响应缺少有效taskId");throw new ScannerException("acceptance_uncertain","设备可能已受理,缺少任务编号,禁止重发",502);
}
// If persistence fails, INTENT remains locked: never send this POST again.
journal.accepted(key,taskId);return accepted(journal.get(key));
} finally {commandLock.unlock();}
}
public JsonNode executeAndWait(ScannerOperation op,ObjectNode body,String key,String owner,long timeoutMs) {
long deadline=deadline(timeoutMs);
ObjectNode accepted;
while(true){
try {accepted=submit(op,body,key,owner,null,deadline);break;}
catch(ScannerException error){if(!Set.of("command_busy","device_busy").contains(error.scannerCode))throw error;sleep(deadline);}
}
return waitCommandUntil(accepted.path("commandKey").asText(),deadline);
}
public JsonNode waitCommand(String key,long timeoutMs) {
return waitCommandUntil(key,deadline(timeoutMs));
}
private JsonNode waitCommandUntil(String key,long deadline) {
while(true){
requestBudget(deadline);
ScannerCommandJournal.Entry entry=journal.get(key(key));
if(entry==null)throw new ScannerException("command_not_found","本地命令记录不存在",404);
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;}
entry=journal.get(key);
if(entry.state().equals("SUCCEEDED"))return result(entry);
if(entry.state().equals("FAILED"))throw taskFailure(entry);
sleep(deadline);
}
}
public JsonNode waitRemoteTask(String id,long timeoutMs) {
long deadline=deadline(timeoutMs);
while(true){JsonNode task;
try {task=query(ScannerOperation.TASK,id,deadline);}catch(ScannerException error){if(!transientQuery(error))throw error;sleep(deadline);continue;}
if(!id.equals(task.path("taskId").asText()))throw new ScannerException("task_mismatch","任务响应编号不匹配",409);
String state=task.path("state").asText();
if(state.equals("succeeded"))return task;
if(state.equals("failed"))throw failure(task);
if(!Set.of("queued","running").contains(state))throw new ScannerException("invalid_task_state","设备任务状态无效",502);
sleep(deadline);
}
}
private void refresh(ScannerCommandJournal.Entry entry) {
refresh(entry,0);
}
private void refresh(ScannerCommandJournal.Entry entry,long deadline) {
if(!entry.state().equals("ACCEPTED"))return;
if(!entry.endpoint().equals(client.endpointKey()))throw new ScannerException("endpoint_changed","扫描服务地址已变更,禁止向新服务核对旧命令",409);
JsonNode task;
try{task=query(ScannerOperation.TASK,entry.taskId(),deadline);}
catch(ScannerException error){if(error.remoteStatus==404){journal.uncertain(entry.key(),"原任务已失效,设备服务可能已重启");throw new ScannerException("task_lost","原任务已失效,禁止自动重新提交",409);}throw error;}
if(!entry.taskId().equals(task.path("taskId").asText())){
journal.uncertain(entry.key(),"任务响应编号不匹配");throw new ScannerException("task_mismatch","任务响应编号不匹配,禁止重发",409);
}
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(!Set.of("queued","running").contains(state))throw new ScannerException("invalid_task_state","设备任务状态无效",502);
}
private long deadline(long timeoutMs) {
if(timeoutMs<=0)throw new ScannerException("invalid_timeout","等待超时必须大于0毫秒",400);
return System.nanoTime()+Math.min(TimeUnit.MILLISECONDS.toNanos(timeoutMs),Long.MAX_VALUE/2);
}
private long requestBudget(long deadline) {
if(deadline==0)return Math.max(1,settings.getRequestTimeoutMs());
long remaining=deadline-System.nanoTime();
if(remaining<=0)throw waitTimeout();
return Math.max(1,Math.min(settings.getRequestTimeoutMs(),TimeUnit.NANOSECONDS.toMillis(remaining)));
}
private JsonNode query(ScannerOperation operation,String id,long deadline) {
try {
JsonNode response=client.json(operation,id,null,requestBudget(deadline));
requestBudget(deadline); // A late response cannot turn an expired operation into success.
return response;
} catch(ScannerException error) {
if(deadline!=0&&deadline-System.nanoTime()<=0)throw waitTimeout();
throw error;
}
}
private void lock(long deadline) {
try {
if(deadline==0)commandLock.lockInterruptibly();
else if(!commandLock.tryLock(Math.max(0,deadline-System.nanoTime()),TimeUnit.NANOSECONDS))throw waitTimeout();
} catch(InterruptedException error) {
Thread.currentThread().interrupt();throw new ScannerException("interrupted","等待被中断;不会撤销设备动作",504);
}
}
private ScannerException waitTimeout(){return new ScannerException("task_wait_timeout","等待超时;已受理任务仍可能执行,可按原命令记录继续查询",504);}
private JsonNode result(ScannerCommandJournal.Entry entry) {
try{return ScannerRequestValidator.JSON.readTree(entry.result());}catch(Exception e){throw new ScannerException("journal_invalid","命令结果记录无效,禁止重复执行",500);}
}
private ScannerException taskFailure(ScannerCommandJournal.Entry entry){return entry.result()==null?new ScannerException("task_failed",Objects.toString(entry.error(),"设备任务失败"),502):failure(result(entry));}
private boolean transientQuery(ScannerException error){return Set.of(429,503,504).contains(error.remoteStatus)&&!error.scannerCode.equals("interrupted");}
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);}}
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

@ -0,0 +1,27 @@
package com.cmvr.scanner;
import com.cmvr.edge.client.service.RobotStopExtension;
import com.cmvr.resource.mapper.ResourceDeviceMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class ScannerStopExtension implements RobotStopExtension {
private final ScannerProperties settings;
private final ScannerService scanner;
private final ScannerHttpClient client;
private final ScannerCommandJournal journal;
private final ResourceDeviceMapper devices;
@Override public boolean handles(String robotId){return robotId!=null&&!robotId.isBlank()&&robotId.equals(settings.getRobotId());}
@Override public boolean stop(String robotId){
var active=journal.active(client.endpointKey());
if(active!=null)scanner.waitCommand(active.key(),settings.getOperationTimeoutMs());
var status=scanner.get(ScannerOperation.STATUS,null);
if(status.path("restartRequired").asBoolean()||status.path("stateUncertain").asBoolean()||status.path("busy").asBoolean())throw new ScannerException("stop_unconfirmed","设备状态尚未确认,保留资源占用",409);
if(status.path("scanning").asBoolean())scanner.executeAndWait(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),java.util.UUID.randomUUID().toString(),"stop:"+robotId,settings.getOperationTimeoutMs());
status=scanner.get(ScannerOperation.STATUS,null);
if(!status.has("scanning")||status.path("scanning").asBoolean()||status.path("busy").asBoolean()||status.path("stateUncertain").asBoolean())throw new ScannerException("stop_unconfirmed","尚未确认采集停止,保留资源占用",409);
return devices.selectByRobotId(robotId,null,false).stream().filter(d->"1".equals(d.getEnabled())).allMatch(d->Integer.valueOf(14).equals(d.getDeviceKind()));
}
}

View File

@ -0,0 +1,20 @@
package com.cmvr.scanner;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/** Only MJPEG subscriptions outlive MVC's ordinary asynchronous response deadline. */
@Configuration
public class ScannerStreamingConfiguration implements WebMvcConfigurer {
@Override public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AsyncHandlerInterceptor() {
@Override public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (request.isAsyncStarted()) request.getAsyncContext().setTimeout(0);
}
}).addPathPatterns("/admin-api/cmvr/scanner/preview/stream");
}
}

View File

@ -0,0 +1,54 @@
package com.cmvr.scanner;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.runtime.message.*;
import com.cmvr.test.flow.runtime.operator.edge.WorkcellDeviceAdapter;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class ScannerWorkflowAdapter implements WorkcellDeviceAdapter {
private final ScannerService service;
private final ScannerProperties settings;
private final ScannerAccessService access;
private final ScannerMonitoringService monitoring;
@Override public boolean supports(ActionEnum action){return action!=null&&ScannerOperation.forAction(action.getAction())!=null;}
@Override public void validateConfiguration(String robotId,String deviceId) {
if(!settings.configured())throw new ScannerException("not_configured","扫描服务地址、端口和密钥待配置",503);
if(!java.util.Objects.equals(robotId,settings.getRobotId())||!java.util.Objects.equals(deviceId,settings.getDeviceId()))
throw new ScannerException("device_not_bound","所选设备与扫描服务配置的永久身份不匹配",409);
}
@Override public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) {
JSONObject input=message.getInputParams();ScannerOperation op=ScannerOperation.forAction(message.getAction().getAction());
validateConfiguration(message.getRobotId(),input.getString("deviceId"));
long timeout=input.getLongValue("timeoutMs");
com.fasterxml.jackson.databind.JsonNode result;
if(op==ScannerOperation.TASK){result=service.waitRemoteTask(input.getString("taskId"),timeout);}
else if(!op.control()){result=service.get(op,null);}
else {
String commandKey=input.getString("commandKey");
if(message.getInstId()!=null&&!message.getInstId().isBlank()){
commandKey=ScannerService.hash(JSONObject.toJSONString(java.util.Arrays.asList(message.getInstId(),message.getItemId(),message.getItemOrder(),message.getItemOccurrence(),message.getNodeId(),message.getIterations(),message.getSubFlowExecutionId())));
}
// requestJson stays text until the backend, preserving 64-bit IDs and integer literals.
String body=input.getString("requestJson");
if(body==null){if(input.containsKey("planCode")||input.containsKey("jobId")||input.containsKey("format"))throw new ScannerException("legacy_node_parameters","旧扫描节点参数与真实协议不一致,请重新配置组件",400);body="{}";}
if(message.getInstId()==null || message.getInstId().isBlank()) {
var submitted=access.submit(op,body,commandKey);
result=service.waitCommand(submitted.path("commandKey").asText(),timeout);
}else result=service.executeAndWait(op,ScannerRequestValidator.parse(body),commandKey,"workflow:"+message.getInstId(),timeout);
}
JSONObject output=JSONObject.parseObject(result.toString());
output.put("responseJson",result.toString());
if(op.control()&&message.getInstId()!=null&&!message.getInstId().isBlank()) {
String key=ScannerService.hash(JSONObject.toJSONString(java.util.Arrays.asList(message.getInstId(),message.getItemId(),message.getItemOrder(),message.getItemOccurrence(),message.getNodeId(),message.getIterations(),message.getSubFlowExecutionId())));
try {
var context=monitoring.capture(op,key,message.getInstId(),message.getRobotId(),input.getString("deviceId"));
if(context!=null)output.put("scannerContext",JSONObject.parseObject(context.toString()));
}catch(ScannerException error){output.put("scannerPreviewMessage",error.getMessage());}
}
return TaskNodeExecuteResult.success(output);
}
}

View File

@ -41,6 +41,48 @@ public enum ActionEnum {
// 设备行为
DEVICE_EXECUTE_JSON_COMMAND("EDGE", "DEVICE_EXECUTE_JSON_COMMAND", "执行设备通用指令"),
SCANNER_INITIALIZE("EDGE", "SCANNER_INITIALIZE", "连接扫描仪"),
SCANNER_CREATE_PROJECT("EDGE", "SCANNER_CREATE_PROJECT", "创建扫描工程"),
SCANNER_DISCONNECT("EDGE", "SCANNER_DISCONNECT", "断开扫描会话"),
SCANNER_RECONNECT("EDGE", "SCANNER_RECONNECT", "重新连接扫描仪"),
SCANNER_PREVIEW_START("EDGE", "SCANNER_PREVIEW_START", "开启扫描预览"),
SCANNER_PREVIEW_STOP("EDGE", "SCANNER_PREVIEW_STOP", "关闭扫描预览"),
SCANNER_START("EDGE", "SCANNER_START", "开始或继续采集"),
SCANNER_STOP("EDGE", "SCANNER_STOP", "暂停采集"),
SCANNER_PARAMETERS("EDGE", "SCANNER_PARAMETERS", "配置扫描参数"),
SCANNER_MESH("EDGE", "SCANNER_MESH", "生成网格预览"),
SCANNER_MESH_CONFIRM("EDGE", "SCANNER_MESH_CONFIRM", "确认扫描网格"),
SCANNER_MESH_UNDO("EDGE", "SCANNER_MESH_UNDO", "撤销扫描网格"),
SCANNER_ALIGN("EDGE", "SCANNER_ALIGN", "扫描工程拼接"),
SCANNER_EDIT("EDGE", "SCANNER_EDIT", "删除扫描点或标志点"),
SCANNER_CLIP_PLANE("EDGE", "SCANNER_CLIP_PLANE", "平面裁剪"),
SCANNER_EXPORT("EDGE", "SCANNER_EXPORT", "导出扫描成果"),
SCANNER_SNAPSHOT("EDGE", "SCANNER_SNAPSHOT", "保存原始场景快照"),
SCANNER_SCENE("EDGE", "SCANNER_SCENE", "读取扫描场景摘要"),
SCANNER_CALIBRATION_ENTER("EDGE", "SCANNER_CALIBRATION_ENTER", "进入扫描标定"),
SCANNER_CALIBRATION_MODE("EDGE", "SCANNER_CALIBRATION_MODE", "设置标定模式"),
SCANNER_CALIBRATION_START("EDGE", "SCANNER_CALIBRATION_START", "开始扫描标定"),
SCANNER_CALIBRATION_TRAK("EDGE", "SCANNER_CALIBRATION_TRAK", "设置跟踪仪标定类型"),
SCANNER_CALIBRATION_SYSTEM("EDGE", "SCANNER_CALIBRATION_SYSTEM", "开始系统标定"),
SCANNER_CALIBRATION_FREE("EDGE", "SCANNER_CALIBRATION_FREE", "设置自由标定"),
SCANNER_CALIBRATION_CAPTURE("EDGE", "SCANNER_CALIBRATION_CAPTURE", "采集标定姿态"),
SCANNER_CALIBRATION_COMPUTE("EDGE", "SCANNER_CALIBRATION_COMPUTE", "计算自由标定结果"),
SCANNER_CALIBRATION_ADVANCED("EDGE", "SCANNER_CALIBRATION_ADVANCED", "设置精细标定"),
SCANNER_CALIBRATION_APPLY_LAST("EDGE", "SCANNER_CALIBRATION_APPLY_LAST", "应用上次标定结果"),
SCANNER_METADATA("EDGE", "SCANNER_METADATA", "读取扫描服务信息"),
SCANNER_HEALTH("EDGE", "SCANNER_HEALTH", "检查扫描服务"),
SCANNER_STATUS("EDGE", "SCANNER_STATUS", "读取扫描仪状态"),
SCANNER_CAPABILITIES("EDGE", "SCANNER_CAPABILITIES", "读取扫描能力"),
SCANNER_METRICS("EDGE", "SCANNER_METRICS", "读取预览指标"),
SCANNER_WAIT("EDGE", "SCANNER_WAIT", "等待扫描设备任务"),
MOTOR_ENABLE("EDGE", "MOTOR_ENABLE", "电机使能"),
MOTOR_DISABLE("EDGE", "MOTOR_DISABLE", "电机去使能"),
MOTOR_HOME("EDGE", "MOTOR_HOME", "电机回零"),
MOTOR_MOVE("EDGE", "MOTOR_MOVE", "电机定位"),
MOTOR_WAIT("EDGE", "MOTOR_WAIT", "等待电机到位"),
MOTOR_STOP("EDGE", "MOTOR_STOP", "停止电机"),
MOTOR_STATUS("EDGE", "MOTOR_STATUS", "读取电机状态"),
// ---------------相机---------------
CAMERA_START("EDGE", "CAMERA_START", "启动相机"),
CAMERA_STOP("EDGE", "CAMERA_STOP", "停止相机"),

View File

@ -41,7 +41,7 @@ public class FlowParamDef {
/**
* type=input 时填写的静态值
*/
private String input;
private Object input;
/**
* type=quote 时填写的引用路径

View File

@ -64,6 +64,9 @@ public class FlowControlService {
@Resource
private AsyncMediaAnalysisCoordinator asyncMediaAnalysisCoordinator;
@org.springframework.beans.factory.annotation.Autowired(required = false)
private List<FlowDeviceLifecycleExtension> deviceLifecycle = List.of();
/**
* 终止流程
*/
@ -85,6 +88,7 @@ public class FlowControlService {
taskThreadRegistry.interruptAll(instId);
// 终止必须等设备和后端媒体会话完成清理后再返回,防止立即重跑命中旧录音/录像状态。
stopAllRobots(ctx);
deviceLifecycle.forEach(extension -> extension.afterStop(instId));
taskInstHolder.unRegister(instId);
// 被中断的节点 状态修改成 PAUSED
for (TaskNodeExecuteContext pendingNode : taskThreadRegistry.getPendingNodes(instId)) {
@ -183,6 +187,11 @@ public class FlowControlService {
ctx.updateTimestamp();
List<TaskNodeExecuteContext> interruptedNodes = taskThreadRegistry.getPendingNodes(instId);
taskThreadRegistry.interruptAll(instId);
// Capture continuous acquisition before StopAll pauses it. Failure must not skip StopAll.
for (FlowDeviceLifecycleExtension extension : deviceLifecycle) {
try { extension.beforePause(instId, robotIds(ctx)); }
catch (RuntimeException error) { log.warn("保存设备暂停状态失败,恢复将要求人工处理: instId={}, error={}", instId, error.getMessage()); }
}
// StopAll 是阻塞式调用。只有设备侧停止完成,暂停接口才返回,避免恢复请求和旧动作并发。
boolean robotsStopped = stopAllRobotsAndWait(ctx);
boolean nodesFinished = waitForInterruptedNodes(instId, interruptedNodes);
@ -220,6 +229,8 @@ public class FlowControlService {
}
}
// Re-establish continuous device acquisition before replaying any interrupted node.
for (FlowDeviceLifecycleExtension extension : deviceLifecycle) extension.beforeResume(instId, robotIds(ctx));
List<TaskNodeExecuteContext> suspendedNodes = taskThreadRegistry.getPendingNodes(instId);
if (asyncMediaAnalysisCoordinator != null) {
suspendedNodes.stream()
@ -341,6 +352,11 @@ public class FlowControlService {
});
}
private List<String> robotIds(TaskContext context) {
return context.getRobotIds() == null || context.getRobotIds().isEmpty()
? Collections.singletonList(context.getRobotId()) : context.getRobotIds();
}
private boolean stopAllRobotsAndWait(TaskContext context) {
List<String> robotIds = context.getRobotIds() == null || context.getRobotIds().isEmpty()
? Collections.singletonList(context.getRobotId())

View File

@ -0,0 +1,11 @@
package com.cmvr.test.flow.control;
import java.util.List;
/** Device state that must survive interruption and replay of workflow nodes. */
public interface FlowDeviceLifecycleExtension {
void beforePause(String instId, List<String> robotIds);
void beforeResume(String instId, List<String> robotIds);
default void beforeComplete(String instId, List<String> robotIds) {}
default void afterStop(String instId) {}
}

View File

@ -27,6 +27,9 @@ public class FlowEndNodeHandler implements FlowNodeTypeHandler {
@Resource(name = "threadPoolTaskExecutor")
private final ThreadPoolTaskExecutor executor;
@org.springframework.beans.factory.annotation.Autowired(required = false)
private java.util.List<com.cmvr.test.flow.control.FlowDeviceLifecycleExtension> deviceLifecycle = java.util.List.of();
@Override
public TaskNodeExecuteResult handle(TaskNodeExecuteMessage message) {
String instId = message.getInstId();
@ -44,6 +47,11 @@ public class FlowEndNodeHandler implements FlowNodeTypeHandler {
if (context == null) {
return null;
}
if (!message.isNestedFlow() && message.getPendingItemCount() == 0) {
var robots = context.getRobotIds() == null || context.getRobotIds().isEmpty()
? java.util.Collections.singletonList(context.getRobotId()) : context.getRobotIds();
deviceLifecycle.forEach(extension -> extension.beforeComplete(instId, robots));
}
RunModeEnum runMode = context.getRunMode();
// if (runMode.equals(RunModeEnum.NORMAL) || runMode.equals(RunModeEnum.TRIAL)) {
// // 仅语音交互和触控交互进行评估

View File

@ -5,6 +5,9 @@ import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.runtime.operator.edge.WorkcellNodeContract;
import com.cmvr.test.flow.runtime.operator.edge.WorkcellDeviceAdapter;
import com.cmvr.test.model.vo.ResourceRuntimeAssignmentVO;
import com.cmvr.test.model.vo.RobotRuntimeMemberVO;
import lombok.RequiredArgsConstructor;
@ -23,6 +26,8 @@ import java.util.Set;
public class FlowRuntimeDefinitionValidator {
private final ObjectProvider<RobotDeviceAssignmentValidator> deviceValidatorProvider;
@org.springframework.beans.factory.annotation.Autowired
private List<WorkcellDeviceAdapter> workcellAdapters = List.of();
public void validate(String flowData, List<ResourceRuntimeAssignmentVO> assignments) {
JSONObject flow = JSON.parseObject(flowData);
@ -30,6 +35,16 @@ public class FlowRuntimeDefinitionValidator {
if (nodes == null) {
throw new GlobalException("流程节点数据不能为空");
}
for (int i = 0; i < nodes.size(); i++) {
JSONObject p = nodes.getJSONObject(i).getJSONObject("properties");
if (p == null) continue;
ActionEnum action = ActionEnum.fromAction(p.getString("action"));
if (!WorkcellNodeContract.supports(action)) continue;
try { WorkcellNodeContract.validateLiterals(action, p.getJSONArray("nodeParams")); }
catch (RuntimeException error) {
throw new GlobalException("节点[" + p.getString("name") + "]参数错误:" + error.getMessage());
}
}
JSONObject startProperties = null;
for (int i = 0; i < nodes.size(); i++) {
JSONObject node = nodes.getJSONObject(i);
@ -124,6 +139,23 @@ public class FlowRuntimeDefinitionValidator {
if (StrUtil.isNotBlank(deviceSlotKey) && !slotKeys.contains(deviceSlotKey)) {
throw new GlobalException("节点[" + properties.getString("name") + "]引用了不存在的设备用途");
}
ActionEnum action = ActionEnum.fromAction(properties.getString("action"));
if (WorkcellNodeContract.supports(action)) {
if (StrUtil.isBlank(deviceSlotKey)) throw new GlobalException("扫描仪或电机节点必须选择设备用途");
JSONObject role = roles.stream().map(JSONObject.class::cast)
.filter(item -> roleKey.equals(item.getString("roleKey"))).findFirst().orElseThrow();
JSONObject slot = role.getJSONArray("deviceSlots").stream().map(JSONObject.class::cast)
.filter(item -> deviceSlotKey.equals(item.getString("slotKey"))).findFirst().orElseThrow();
if (!Integer.valueOf(WorkcellNodeContract.deviceKind(action)).equals(slot.getInteger("deviceKind"))) {
throw new GlobalException("扫描仪或电机节点的设备用途类型不匹配");
}
RobotRuntimeMemberVO member = firstMember(assignmentByRole.get(roleKey));
if (member != null && StrUtil.isNotBlank(member.getRobotId())) {
List<WorkcellDeviceAdapter> drivers = workcellAdapters.stream().filter(a -> a.supports(action)).toList();
if (drivers.size() != 1) throw new GlobalException("节点[" + properties.getString("name") + "]缺少唯一设备驱动");
drivers.get(0).validateConfiguration(member.getRobotId(),member.getDevices().get(deviceSlotKey));
}
}
// 兼容Schema V2早期的deviceBindings结构。
JSONArray bindings = target.getJSONArray("deviceBindings");
if (bindings != null) {

View File

@ -0,0 +1,44 @@
package com.cmvr.test.flow.runtime.operator.edge;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.runtime.engine.RobotDeviceAssignmentValidator;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class EdgeWorkcellOperateService implements EdgeOperateService {
private final RobotDeviceAssignmentValidator deviceValidator;
private final List<WorkcellDeviceAdapter> adapters;
@Override public boolean supports(ActionEnum action) { return WorkcellNodeContract.supports(action); }
@Override public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) {
ActionEnum action = message.getAction();
JSONObject input = message.getInputParams() == null ? new JSONObject() : message.getInputParams();
WorkcellNodeContract.validate(action, input);
String robot = message.getRobotId();
if (robot == null || robot.isBlank()) robot = input.getString("robotId");
String device = input.getString("deviceId");
if (robot == null || robot.isBlank() || device == null || device.isBlank()) {
throw new GlobalException("扫描仪或电机节点必须绑定 robotId 和 deviceId");
}
deviceValidator.validate(robot, device, WorkcellNodeContract.deviceKind(action));
List<WorkcellDeviceAdapter> matches = adapters.stream().filter(adapter -> adapter.supports(action)).toList();
if (matches.isEmpty()) {
throw new GlobalException((WorkcellNodeContract.deviceKind(action) == 14 ? "扫描仪" : "电机")
+ "驱动尚未接入,无法执行「" + action.getDescription() + "」");
}
if (matches.size() != 1) throw new GlobalException("设备动作存在多个驱动,请明确设备路由");
message.setRobotId(robot);
TaskNodeExecuteResult result = matches.get(0).execute(message);
if (result == null || result.isDeferred()) throw new GlobalException("设备驱动未返回已确认的执行结果");
return result;
}
}

View File

@ -0,0 +1,20 @@
package com.cmvr.test.flow.runtime.operator.edge;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
/** Vendor drivers implement this contract. No application mock driver is installed. */
public interface WorkcellDeviceAdapter {
boolean supports(ActionEnum action);
/** Read-only configuration check before a workflow acquires resources. */
default void validateConfiguration(String robotId, String deviceId) { }
/**
* Honor timeoutMs and interruption. WAIT/STOP must confirm physical completion;
* START returns the accepted jobId, EXPORT returns completed file metadata.
* Re-dispatch after pause must not repeat a non-idempotent physical operation.
*/
TaskNodeExecuteResult execute(TaskNodeExecuteMessage message);
}

View File

@ -0,0 +1,114 @@
package com.cmvr.test.flow.runtime.operator.edge;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.scanner.ScannerOperation;
import com.cmvr.scanner.ScannerRequestValidator;
import java.util.EnumSet;
import java.util.Set;
/** Platform contracts only; kind 14 must be mapped by the scanner's discovery adapter. */
public final class WorkcellNodeContract {
private static final Set<ActionEnum> MOTOR = EnumSet.of(ActionEnum.MOTOR_ENABLE,
ActionEnum.MOTOR_DISABLE, ActionEnum.MOTOR_HOME, ActionEnum.MOTOR_MOVE,
ActionEnum.MOTOR_WAIT, ActionEnum.MOTOR_STOP, ActionEnum.MOTOR_STATUS);
private WorkcellNodeContract() {}
public static boolean supports(ActionEnum action) {
return action != null && (ScannerOperation.forAction(action.getAction()) != null || MOTOR.contains(action));
}
public static int deviceKind(ActionEnum action) {
if (!supports(action)) throw new GlobalException("不是扫描仪或电机节点");
return ScannerOperation.forAction(action.getAction()) != null ? 14 : 10;
}
public static void validate(ActionEnum action, JSONObject input) {
if (!supports(action)) throw new GlobalException("不是扫描仪或电机节点");
double timeout = number(input, "timeoutMs");
if (timeout < 1 || timeout > 3600000 || timeout != Math.rint(timeout)) {
throw new GlobalException("timeoutMs 必须是 1 至 3600000 的整数毫秒");
}
ScannerOperation scanner = ScannerOperation.forAction(action.getAction());
if (scanner != null) {
if (scanner == ScannerOperation.TASK) scanner.route(required(input, "taskId"));
else if (scanner.control()) {
if (input.containsKey("planCode") || input.containsKey("jobId") || input.containsKey("format")) {
throw new GlobalException("旧扫描组件参数与真实接口不一致,请重新配置节点");
}
ScannerRequestValidator.validate(scanner, ScannerRequestValidator.parse(input.getString("requestJson") == null ? "{}" : input.getString("requestJson")));
}
return;
}
switch (action) {
case MOTOR_MOVE, MOTOR_WAIT -> {
number(input, "targetPosition");
if (!Set.of("DEGREE", "MILLIMETER", "PULSE").contains(required(input, "unit"))) {
throw new GlobalException("电机位置单位无效");
}
if (action == ActionEnum.MOTOR_MOVE) {
if (number(input, "velocity") <= 0 || number(input, "acceleration") <= 0) {
throw new GlobalException("电机速度和加速度必须大于零");
}
} else if (number(input, "tolerance") < 0) {
throw new GlobalException("电机到位容差不能为负数");
}
}
default -> { }
}
}
/** Validate static values before dispatch; output references remain runtime checked. */
public static void validateLiterals(ActionEnum action, JSONArray params) {
JSONObject literals = new JSONObject();
Set<String> dynamic = new java.util.HashSet<>();
Set<String> names = new java.util.HashSet<>();
if (params != null) for (int i = 0; i < params.size(); i++) {
JSONObject param = params.getJSONObject(i);
String name = param.getString("name");
if (name == null || !names.add(name)) throw new GlobalException("设备节点参数名称为空或重复");
if ("input".equals(param.getString("type"))) literals.put(name, param.get("input"));
else if ("quote".equals(param.getString("type"))) {
JSONArray path = param.getJSONArray("quote");
if (path == null || path.size() < 3 || path.stream().anyMatch(v -> !(v instanceof String s) || s.isBlank())
|| !Set.of("input", "output").contains(param.getString("quoteType"))) {
throw new GlobalException(name + " 的参数引用不完整");
}
dynamic.add(name);
} else throw new GlobalException(name + " 的参数来源无效");
}
if (!dynamic.contains("timeoutMs")) {
double timeout = number(literals, "timeoutMs");
if (timeout < 1 || timeout > 3600000 || timeout != Math.rint(timeout))
throw new GlobalException("timeoutMs 必须是 1 至 3600000 的整数毫秒");
}
ScannerOperation scanner = ScannerOperation.forAction(action.getAction());
if (scanner != null) {
if (names.stream().anyMatch(Set.of("planCode", "jobId", "format")::contains))
throw new GlobalException("旧扫描组件参数与真实接口不一致,请重新配置节点");
if (scanner == ScannerOperation.TASK && !dynamic.contains("taskId")) scanner.route(required(literals, "taskId"));
if (scanner.control() && !dynamic.contains("requestJson")) {
ScannerRequestValidator.validate(scanner, ScannerRequestValidator.parse(
literals.getString("requestJson") == null ? "{}" : literals.getString("requestJson")));
}
} else if (dynamic.isEmpty()) validate(action, literals);
}
private static String required(JSONObject input, String key) {
Object value = input.get(key);
if (!(value instanceof String text) || text.isBlank()) throw new GlobalException(key + " 不能为空");
return text.trim();
}
private static double number(JSONObject input, String key) {
Object value = input.get(key);
if (!(value instanceof Number number) || !Double.isFinite(number.doubleValue())) {
throw new GlobalException(key + " 必须是有效数值");
}
return number.doubleValue();
}
}

View File

@ -28,5 +28,6 @@ public interface ITeTaskInstService extends IService<TeTaskInst> {
public boolean updateStatus(String instId, TaskStatusEnum taskStatusEnum);
List<TeNodeInst> detail(String instId);
List<TeNodeInst> detail(String instId, Long afterId);
}

View File

@ -68,8 +68,14 @@ public class TeTaskInstServiceImpl extends ServiceImpl<TeTaskInstMapper, TeTaskI
@Override
public List<TeNodeInst> detail(String instId) {
return detail(instId, null);
}
@Override
public List<TeNodeInst> detail(String instId, Long afterId) {
LambdaQueryWrapper<TeNodeInst> wrapper = Wrappers.lambdaQuery(TeNodeInst.class);
wrapper.eq(TeNodeInst::getInstId, instId)
.ge(afterId != null, TeNodeInst::getId, afterId)
.orderByAsc(TeNodeInst::getId);
return teNodeInstService.list(wrapper);
}

View File

@ -7,11 +7,17 @@ import org.springframework.core.annotation.Order;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
/** Maintains the original business error envelope in the compatibility namespace. */
@Order(-10)
@RestControllerAdvice(basePackages = "com.cmvr.web.controller")
public class CmvrExceptionAdvice {
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public AjaxResult parameterType(MethodArgumentTypeMismatchException exception) {
return AjaxResult.error(400, "请求参数类型错误:" + exception.getName());
}
@ExceptionHandler({GlobalException.class, ServiceException.class, IllegalArgumentException.class})
public AjaxResult business(RuntimeException exception) {
return AjaxResult.error(exception.getMessage());
@ -20,6 +26,6 @@ public class CmvrExceptionAdvice {
@ExceptionHandler(MethodArgumentNotValidException.class)
public AjaxResult validation(MethodArgumentNotValidException exception) {
var error = exception.getBindingResult().getFieldError();
return AjaxResult.error(error == null ? "请求参数校验失败" : error.getDefaultMessage());
return AjaxResult.error(400, error == null ? "请求参数校验失败" : error.getDefaultMessage());
}
}

View File

@ -0,0 +1,299 @@
package com.cmvr.web.controller.scanner;
import com.cmvr.common.core.controller.BaseController;
import com.cmvr.common.core.domain.AjaxResult;
import com.cmvr.scanner.*;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.springframework.http.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import java.util.*;
/** Explicit supplier routes. Generated by scripts/generate_scanner_routes.py. */
@Api(tags = "扫描仪接口")
@RestController
@RequestMapping("/admin-api/cmvr/scanner")
@PreAuthorize("@ss.hasPermission('lab:resource:query')")
@RequiredArgsConstructor
public class ScannerController extends BaseController {
private final ScannerService scanner;
private final ScannerAccessService access;
@GetMapping("/configuration")
public AjaxResult getConfiguration() { return success(scanner.configuration()); }
@GetMapping("/commands/{commandKey}")
public AjaxResult getCommand(@PathVariable String commandKey) { return success(scanner.command(commandKey)); }
@PostMapping("/validate")
public AjaxResult validateParameters(@RequestBody String source) {
var input = ScannerRequestValidator.parse(source);
ScannerOperation operation;
try { operation = ScannerOperation.valueOf(input.path("operation").asText()); }
catch (IllegalArgumentException error) { throw new ScannerException("invalid_operation", "扫描操作不存在", 400); }
if (input.has("requestJson") && !input.get("requestJson").isTextual())
throw new ScannerException("invalid_request", "requestJson必须是JSON对象的字符串", 400);
ScannerRequestValidator.validate(operation, ScannerRequestValidator.parse(input.path("requestJson").asText("{}")));
return success(true);
}
@ApiOperation("连接扫描仪")
@PostMapping("/device/connect")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postConnect(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.CONNECT, body, commandKey));
}
@ApiOperation("创建扫描工程")
@PostMapping("/projects")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postCreateProject(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.CREATE_PROJECT, body, commandKey));
}
@ApiOperation("断开扫描会话")
@PostMapping("/device/disconnect")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postDisconnect(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.DISCONNECT, body, commandKey));
}
@ApiOperation("重新连接扫描仪")
@PostMapping("/device/reconnect")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postReconnect(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.RECONNECT, body, commandKey));
}
@ApiOperation("开启扫描预览")
@PostMapping("/preview/start")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postPreviewStart(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.PREVIEW_START, body, commandKey));
}
@ApiOperation("关闭扫描预览")
@PostMapping("/preview/stop")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postPreviewStop(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.PREVIEW_STOP, body, commandKey));
}
@ApiOperation("开始或继续采集")
@PostMapping("/scan/start")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postScanStart(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.SCAN_START, body, commandKey));
}
@ApiOperation("暂停采集")
@PostMapping("/scan/stop")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postScanStop(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.SCAN_STOP, body, commandKey));
}
@ApiOperation("扫描预览图像")
@GetMapping("/preview/image")
public ResponseEntity<StreamingResponseBody> getPreviewImage() { return binary(ScannerOperation.PREVIEW_IMAGE, null); }
@ApiOperation("扫描实时预览")
@GetMapping("/preview/stream")
public ResponseEntity<StreamingResponseBody> getPreviewStream() { return binary(ScannerOperation.PREVIEW_STREAM, null); }
@ApiOperation("配置扫描参数")
@PostMapping("/parameters")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postParameters(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.PARAMETERS, body, commandKey));
}
@ApiOperation("生成网格预览")
@PostMapping("/mesh")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postMesh(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.MESH, body, commandKey));
}
@ApiOperation("确认扫描网格")
@PostMapping("/mesh/confirm")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postMeshConfirm(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.MESH_CONFIRM, body, commandKey));
}
@ApiOperation("撤销扫描网格")
@PostMapping("/mesh/undo")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postMeshUndo(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.MESH_UNDO, body, commandKey));
}
@ApiOperation("扫描工程拼接")
@PostMapping("/align")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postAlign(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.ALIGN, body, commandKey));
}
@ApiOperation("删除扫描点或标志点")
@PostMapping("/edit")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postEdit(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.EDIT, body, commandKey));
}
@ApiOperation("平面裁剪")
@PostMapping("/clip-plane")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postClipPlane(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.CLIP_PLANE, body, commandKey));
}
@ApiOperation("导出扫描成果")
@PostMapping("/exports")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postExport(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.EXPORT, body, commandKey));
}
@ApiOperation("保存原始场景快照")
@PostMapping("/data/snapshots")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postSnapshot(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.SNAPSHOT, body, commandKey));
}
@ApiOperation("读取扫描场景摘要")
@GetMapping("/data/scene")
public AjaxResult getScene() { return success(scanner.get(ScannerOperation.SCENE, null)); }
@ApiOperation("下载扫描成果文件")
@GetMapping("/files/{fileId}")
public ResponseEntity<StreamingResponseBody> getFile(@PathVariable String fileId) { return binary(ScannerOperation.FILE, fileId); }
@ApiOperation("进入扫描标定")
@PostMapping("/calibration/enter")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postCalibrationEnter(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.CALIBRATION_ENTER, body, commandKey));
}
@ApiOperation("设置标定模式")
@PostMapping("/calibration/setMode")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postCalibrationMode(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.CALIBRATION_MODE, body, commandKey));
}
@ApiOperation("开始扫描标定")
@PostMapping("/calibration/start")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postCalibrationStart(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.CALIBRATION_START, body, commandKey));
}
@ApiOperation("设置跟踪仪标定类型")
@PostMapping("/calibration/setTrakType")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postCalibrationTrak(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.CALIBRATION_TRAK, body, commandKey));
}
@ApiOperation("开始系统标定")
@PostMapping("/calibration/startSystem")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postCalibrationSystem(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.CALIBRATION_SYSTEM, body, commandKey));
}
@ApiOperation("设置自由标定")
@PostMapping("/calibration/setFree")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postCalibrationFree(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.CALIBRATION_FREE, body, commandKey));
}
@ApiOperation("采集标定姿态")
@PostMapping("/calibration/capturePose")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postCalibrationCapture(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.CALIBRATION_CAPTURE, body, commandKey));
}
@ApiOperation("计算自由标定结果")
@PostMapping("/calibration/compute")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postCalibrationCompute(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.CALIBRATION_COMPUTE, body, commandKey));
}
@ApiOperation("设置精细标定")
@PostMapping("/calibration/setAdvanced")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postCalibrationAdvanced(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.CALIBRATION_ADVANCED, body, commandKey));
}
@ApiOperation("应用上次标定结果")
@PostMapping("/calibration/applyLast")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public AjaxResult postCalibrationApplyLast(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {
return success(access.submit(ScannerOperation.CALIBRATION_APPLY_LAST, body, commandKey));
}
@ApiOperation("读取扫描服务信息")
@GetMapping("/metadata")
public AjaxResult getMetadata() { return success(scanner.get(ScannerOperation.METADATA, null)); }
@ApiOperation("检查扫描服务")
@GetMapping("/health")
public AjaxResult getHealth() { return success(scanner.get(ScannerOperation.HEALTH, null)); }
@ApiOperation("读取扫描仪状态")
@GetMapping("/status")
public AjaxResult getStatus() { return success(scanner.get(ScannerOperation.STATUS, null)); }
@ApiOperation("读取扫描能力")
@GetMapping("/capabilities")
public AjaxResult getCapabilities() { return success(scanner.get(ScannerOperation.CAPABILITIES, null)); }
@ApiOperation("读取预览指标")
@GetMapping("/preview/metrics")
public AjaxResult getMetrics() { return success(scanner.get(ScannerOperation.METRICS, null)); }
@ApiOperation("等待扫描设备任务")
@GetMapping("/tasks/{taskId}")
public AjaxResult getTask(@PathVariable String taskId) { return success(scanner.get(ScannerOperation.TASK, taskId)); }
private ResponseEntity<StreamingResponseBody> binary(ScannerOperation operation, String id) {
var source = scanner.binary(operation, id);
HttpHeaders headers = new HttpHeaders();
headers.setCacheControl("no-store");
source.headers().forEach((key, values) -> {
if (key.equalsIgnoreCase("content-type") || key.equalsIgnoreCase("content-length")
|| key.equalsIgnoreCase("content-disposition") || key.toLowerCase(Locale.ROOT).startsWith("x-frame-")) {
if (!values.isEmpty()) headers.put(key, values);
}
});
return ResponseEntity.ok().headers(headers).body(output -> {
try (source) {
byte[] buffer = new byte[16384];
int count;
while ((count = source.stream().read(buffer)) != -1) {
output.write(buffer, 0, count);
if (operation == ScannerOperation.PREVIEW_STREAM) output.flush();
}
}
});
}
@ExceptionHandler(ScannerException.class)
public AjaxResult scannerError(ScannerException error) {
AjaxResult result = AjaxResult.error(error.remoteStatus, error.getMessage());
result.put("scannerCode", error.scannerCode);
return result;
}
}

View File

@ -41,9 +41,10 @@ public class TeTaskInstController extends BaseController {
@ApiOperation("查询节点执行日志")
@GetMapping("/log/detail")
public TableDataInfo detail(@RequestParam String instId) {
public TableDataInfo detail(@RequestParam String instId, @RequestParam(required = false) Long afterId) {
if (afterId != null && afterId < 0) throw cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.invalidParamException("日志游标不能为负数");
startPage();
List<TeNodeInst> list = teTaskInstService.detail(instId);
List<TeNodeInst> list = teTaskInstService.detail(instId, afterId);
return getDataTable(list);
}

View File

@ -0,0 +1,46 @@
package com.cmvr.scanner;
import com.cmvr.test.flow.runtime.engine.FlowTaskRuntimeService;
import com.cmvr.test.service.ITeTaskInstService;
import com.cmvr.web.advice.CmvrExceptionAdvice;
import com.cmvr.web.controller.scanner.ScannerController;
import com.cmvr.web.controller.test.TeTaskInstController;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/** Exercise Spring argument binding/error envelopes, not just Java method calls. */
public class ScannerHttpBoundaryTest {
@Test public void nonnumericAndOverflowingCursorsAreClientErrorsBeforeTheServiceRuns() throws Exception {
var instances=mock(ITeTaskInstService.class);
var mvc=MockMvcBuilders.standaloneSetup(new TeTaskInstController(instances,mock(FlowTaskRuntimeService.class)))
.setControllerAdvice(new CmvrExceptionAdvice()).build();
for(String cursor:new String[]{"abc","9223372036854775808","1.5"}) {
mvc.perform(get("/admin-api/cmvr/test/inst/log/detail").param("instId","missing").param("afterId",cursor))
.andExpect(status().isOk()).andExpect(jsonPath("$.code").value(400));
}
verifyNoInteractions(instances);
}
@Test public void explicitNullObjectArrayNumberAndBooleanCannotBecomeAnEmptyRequest() throws Exception {
var mvc=MockMvcBuilders.standaloneSetup(new ScannerController(null,null)).build();
for(String value:new String[]{"null","{}","[]","1","true"}) {
mvc.perform(post("/admin-api/cmvr/scanner/validate").contentType(MediaType.APPLICATION_JSON)
.content("{\"operation\":\"CONNECT\",\"requestJson\":"+value+"}"))
.andExpect(status().isOk()).andExpect(jsonPath("$.code").value(400))
.andExpect(jsonPath("$.scannerCode").value("invalid_request"));
}
}
@Test public void omittedParameterBodyStillDefaultsToTheDocumentedEmptyObject() throws Exception {
var mvc=MockMvcBuilders.standaloneSetup(new ScannerController(null,null)).build();
for(String source:new String[]{"{\"operation\":\"CONNECT\"}","{\"operation\":\"CONNECT\",\"requestJson\":\"{}\"}"})
mvc.perform(post("/admin-api/cmvr/scanner/validate").contentType(MediaType.APPLICATION_JSON).content(source))
.andExpect(status().isOk()).andExpect(jsonPath("$.code").value(200))
.andExpect(jsonPath("$.data").value(true));
}
}

View File

@ -0,0 +1,289 @@
package com.cmvr.scanner;
import com.fasterxml.jackson.databind.JsonNode;
import com.sun.net.httpserver.HttpServer;
import org.junit.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.atomic.*;
import static org.junit.Assert.*;
public class ScannerIntegrationTest {
private HttpServer server;
private ScannerProperties config;
private ScannerHttpClient client;
private ScannerCommandJournal journal;
private ScannerService service;
private final AtomicInteger submissions=new AtomicInteger();
private final AtomicBoolean malformedAcceptance=new AtomicBoolean();
private final AtomicBoolean failedTask=new AtomicBoolean();
private final AtomicBoolean runningTask=new AtomicBoolean();
private final AtomicBoolean scanning=new AtomicBoolean();
private final AtomicBoolean taskLost=new AtomicBoolean();
private final AtomicBoolean wrongTask=new AtomicBoolean();
private final AtomicInteger transientQueries=new AtomicInteger();
private final AtomicInteger taskDelayMs=new AtomicInteger();
private final AtomicInteger statusDelayMs=new AtomicInteger();
private final AtomicInteger postDelayMs=new AtomicInteger();
private final java.util.concurrent.CountDownLatch statusEntered=new java.util.concurrent.CountDownLatch(1);
private final AtomicReference<String> session=new AtomicReference<>("S1");
private final List<String> seen=new ArrayList<>();
private final String taskId="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
@Before public void setup() throws Exception {
server=HttpServer.create(new InetSocketAddress("127.0.0.1",0),0);
server.createContext("/",exchange->{
synchronized(seen){seen.add(exchange.getRequestMethod()+" "+exchange.getRequestURI());}
assertNull(exchange.getRequestURI().getQuery());
if(!exchange.getRequestURI().getPath().equals("/"))assertEquals("test-key",exchange.getRequestHeaders().getFirst("X-Api-Key"));
byte[] response;int code=200;
if(exchange.getRequestMethod().equals("POST")){
assertTrue(exchange.getRequestHeaders().getFirst("Content-Type").startsWith("application/json"));
assertTrue(ScannerRequestValidator.JSON.readTree(exchange.getRequestBody()).isObject());submissions.incrementAndGet();code=202;
delay(postDelayMs.get());
if(exchange.getRequestURI().getPath().equals("/api/v1/scan/start"))scanning.set(true);
if(exchange.getRequestURI().getPath().equals("/api/v1/scan/stop"))scanning.set(false);
response=(malformedAcceptance.get()?"{}":"{\"taskId\":\""+taskId+"\",\"statusUrl\":\"/api/v1/tasks/"+taskId+"\"}").getBytes(StandardCharsets.UTF_8);
}else if(exchange.getRequestURI().getPath().startsWith("/api/v1/tasks/")){
delay(taskDelayMs.get());
if(taskLost.get())code=404;else if(transientQueries.getAndUpdate(n->Math.max(0,n-1))>0)code=503;
response=("{\"taskId\":\""+(wrongTask.get()?"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb":taskId)+"\",\"state\":\""+(runningTask.get()?"running":failedTask.get()?"failed":"succeeded")+"\",\"result\":{\"projectId\":\"P1\"},\"error\":{\"code\":\"sdk_failed\",\"message\":\"device fault\"}}").getBytes(StandardCharsets.UTF_8);
}else if(exchange.getRequestURI().getPath().contains("/files/")||exchange.getRequestURI().getPath().equals("/api/v1/preview/image")||exchange.getRequestURI().getPath().equals("/api/v1/preview/stream")){
response=new byte[]{1,2,3,4};exchange.getResponseHeaders().set("Content-Type","application/octet-stream");exchange.getResponseHeaders().set("X-Frame-Sequence","7");
}else {statusEntered.countDown();delay(statusDelayMs.get());response=("{\"busy\":false,\"scanning\":"+scanning.get()+",\"sessionId\":\""+session.get()+"\",\"projectId\":\"P1\",\"stateUncertain\":false,\"restartRequired\":false}").getBytes(StandardCharsets.UTF_8);}
exchange.sendResponseHeaders(code,response.length);try(var out=exchange.getResponseBody()){out.write(response);}
});
server.start();
config=new ScannerProperties();config.setHost("127.0.0.1");config.setPort(server.getAddress().getPort());config.setApiKey("test-key");config.setPollIntervalMs(10);
client=new ScannerHttpClient(config);
JdbcTemplate jdbc=new JdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";DB_CLOSE_DELAY=-1;MODE=MySQL","sa",""));
jdbc.execute("CREATE TABLE lab_scanner_command(command_key VARCHAR(64) PRIMARY KEY,active_endpoint VARCHAR(64) UNIQUE,endpoint_key VARCHAR(64),operation VARCHAR(64),request_hash VARCHAR(64),state VARCHAR(16),remote_task_id VARCHAR(32),request_json CLOB,result_json CLOB,error_message CLOB,owner_ref VARCHAR(255),created_at TIMESTAMP,updated_at TIMESTAMP,context_json CLOB)");
journal=new ScannerCommandJournal(jdbc);service=new ScannerService(config,client,journal);
}
@After public void close(){if(server!=null)server.stop(0);}
private static void delay(int milliseconds) {try{Thread.sleep(milliseconds);}catch(InterruptedException error){Thread.currentThread().interrupt();}}
@Test public void remoteWaitRejectsAnotherTasksSuccessfulResponse() {
wrongTask.set(true);
assertEquals("task_mismatch",assertThrows(ScannerException.class,()->service.waitRemoteTask(taskId,3000)).scannerCode);
assertEquals(0,submissions.get());
}
@Test public void slowRemoteSuccessCannotOutliveTheOperationDeadline() {
service.get(ScannerOperation.STATUS,null); // Warm up HTTP/JIT outside the measured deadline.
taskDelayMs.set(700);
long start=System.nanoTime();
assertEquals("task_wait_timeout",assertThrows(ScannerException.class,()->service.waitRemoteTask(taskId,100)).scannerCode);
assertTrue("Operation deadline must bound the HTTP query",java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-start)<550);
}
@Test public void slowJournalQueryTimesOutWithoutFinishingOrResendingTheCommand() {
service.submit(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"slow-journal-query","test");
taskDelayMs.set(700);
assertEquals("task_wait_timeout",assertThrows(ScannerException.class,()->service.waitCommand("slow-journal-query",100)).scannerCode);
assertEquals("ACCEPTED",journal.get("slow-journal-query").state());
taskDelayMs.set(0);
assertEquals("succeeded",service.waitCommand("slow-journal-query",3000).path("state").asText());
assertEquals(1,submissions.get());
}
@Test public void expiredPreflightCannotSendAControlPost() {
service.get(ScannerOperation.STATUS,null);
statusDelayMs.set(700);
assertEquals("task_wait_timeout",assertThrows(ScannerException.class,()->service.executeAndWait(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"expired-preflight","test",100)).scannerCode);
assertEquals(0,submissions.get());assertNull(journal.get("expired-preflight"));
}
@Test public void nonpositiveOperationBudgetsFailBeforeAnyNetworkOrJournalMutation() {
for(long timeout:new long[]{0,-1}) {
assertEquals("invalid_timeout",assertThrows(ScannerException.class,()->service.waitRemoteTask(taskId,timeout)).scannerCode);
assertEquals("invalid_timeout",assertThrows(ScannerException.class,()->service.waitCommand("invalid-timeout-1",timeout)).scannerCode);
assertEquals("invalid_timeout",assertThrows(ScannerException.class,()->service.executeAndWait(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"invalid-timeout-1","test",timeout)).scannerCode);
}
assertEquals(0,seen.size());assertNull(journal.get("invalid-timeout-1"));
}
@Test public void operationBudgetAlsoBoundsWaitingForTheControlLock() throws Exception {
statusDelayMs.set(700);
var executor=java.util.concurrent.Executors.newSingleThreadExecutor();
try {
var first=executor.submit(()->service.submit(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"lock-first-command","test"));
assertTrue(statusEntered.await(3,java.util.concurrent.TimeUnit.SECONDS));
long start=System.nanoTime();
assertEquals("task_wait_timeout",assertThrows(ScannerException.class,()->service.executeAndWait(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"lock-expired-command","test",100)).scannerCode);
assertTrue(java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-start)<550);
assertNull(journal.get("lock-expired-command"));
assertEquals("ACCEPTED",first.get(3,java.util.concurrent.TimeUnit.SECONDS).path("state").asText());
assertEquals(1,submissions.get());
} finally {executor.shutdownNow();}
}
@Test public void expiredAcceptanceRemainsUnknownAndCannotBeAutomaticallyReplayed() {
service.get(ScannerOperation.STATUS,null);postDelayMs.set(700);
assertEquals("transport_uncertain",assertThrows(ScannerException.class,()->service.executeAndWait(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"slow-acceptance-key","test",150)).scannerCode);
assertEquals("UNKNOWN",journal.get("slow-acceptance-key").state());
assertEquals("command_uncertain",assertThrows(ScannerException.class,()->service.submit(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"slow-acceptance-key","test")).scannerCode);
assertEquals("command_uncertain",assertThrows(ScannerException.class,()->service.submit(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"slow-acceptance-other","test")).scannerCode);
assertEquals(1,submissions.get());
}
@Test public void concurrentIdempotentSubmissionsSendExactlyOnePost() throws Exception {
var executor=java.util.concurrent.Executors.newFixedThreadPool(8);
try {
var start=new java.util.concurrent.CountDownLatch(1);
var futures=new ArrayList<java.util.concurrent.Future<String>>();
for(int i=0;i<8;i++)futures.add(executor.submit(()->{start.await();return service.submit(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"concurrent-one-key","test").path("taskId").asText();}));
start.countDown();
for(var future:futures)assertEquals(taskId,future.get(3,java.util.concurrent.TimeUnit.SECONDS));
assertEquals(1,submissions.get());assertEquals("ACCEPTED",journal.get("concurrent-one-key").state());
} finally {executor.shutdownNow();}
}
@Test public void deadlineExpiringWhilePersistingIntentNeverReachesTheDevice() {
service.get(ScannerOperation.STATUS,null);
var slowJournal=org.mockito.Mockito.spy(journal);
org.mockito.Mockito.doAnswer(invocation->{invocation.callRealMethod();delay(300);return null;}).when(slowJournal).intent(
org.mockito.ArgumentMatchers.anyString(),org.mockito.ArgumentMatchers.anyString(),org.mockito.ArgumentMatchers.any(),
org.mockito.ArgumentMatchers.anyString(),org.mockito.ArgumentMatchers.anyString(),org.mockito.ArgumentMatchers.anyString());
var slowService=new ScannerService(config,client,slowJournal);
assertEquals("task_wait_timeout",assertThrows(ScannerException.class,()->slowService.executeAndWait(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"slow-intent-key-1","test",150)).scannerCode);
assertEquals(0,submissions.get());assertEquals("FAILED",journal.get("slow-intent-key-1").state());
assertNull(journal.active(client.endpointKey()));
}
@Test public void stalledBinaryBodyCannotKeepAViewerThreadWaitingIndefinitely() throws Exception {
client.json(ScannerOperation.STATUS,null,null,3000);
server.createContext("/api/v1/files/"+taskId,exchange->{
exchange.sendResponseHeaders(200,4);exchange.getResponseBody().flush();
try{Thread.sleep(1300);exchange.getResponseBody().write(new byte[]{1,2,3,4});}
catch(InterruptedException e){Thread.currentThread().interrupt();}catch(java.io.IOException ignored){}
finally{exchange.close();}
});
config.setRequestTimeoutMs(200);
long start=System.nanoTime();
try(var binary=client.binary(ScannerOperation.FILE,taskId)){
assertThrows(java.io.IOException.class,()->binary.stream().readAllBytes());
}
assertTrue("Stalled body must be aborted before it arrives",java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-start)<1000);
}
@Test public void all37SupplierRoutesUseTheirExactMethodPathAndHeader() throws Exception {
assertEquals(37,ScannerOperation.values().length);
for(var op:ScannerOperation.values()) {
String id=op==ScannerOperation.TASK||op==ScannerOperation.FILE?taskId:null;
if(op.binary())try(var result=client.binary(op,id)){assertArrayEquals(new byte[]{1,2,3,4},result.stream().readAllBytes());}
else client.json(op,id,op.control()?"{}":null,3000);
assertTrue(seen.contains(op.method+" "+op.route(id)));
}
assertEquals(27,submissions.get());
}
@Test public void acceptedTaskIsPolledAndReplayAfterServiceRecreationDoesNotResubmit(){
var body=ScannerRequestValidator.parse("{\"mode\":\"trak\"}");
var first=service.executeAndWait(ScannerOperation.CREATE_PROJECT,body,"command-0001","test",3000);
service=new ScannerService(config,client,journal);
var second=service.executeAndWait(ScannerOperation.CREATE_PROJECT,body,"command-0001","test",3000);
assertEquals("succeeded",first.path("state").asText());assertEquals(first,second);assertEquals(1,submissions.get());
}
@Test public void uncertainAcceptanceBlocksSameAndDifferentCommandKeys(){
malformedAcceptance.set(true);
assertThrows(ScannerException.class,()->service.submit(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"command-0002","test"));
assertEquals("UNKNOWN",journal.get("command-0002").state());
assertThrows(ScannerException.class,()->service.submit(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"command-0002","test"));
assertThrows(ScannerException.class,()->service.submit(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"command-0003","test"));
assertEquals(1,submissions.get());
}
@Test public void taskFailureIsNotHttpSuccessAndDoesNotBecomeSuccessOnReplay(){
failedTask.set(true);
ScannerException error=assertThrows(ScannerException.class,()->service.executeAndWait(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"command-0004","test",3000));
assertEquals("sdk_failed",error.scannerCode);assertEquals("FAILED",journal.get("command-0004").state());
assertThrows(ScannerException.class,()->service.executeAndWait(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"command-0004","test",3000));assertEquals(1,submissions.get());
}
@Test public void timeoutKeepsAcceptedTaskAndCanContinuePollingWithoutNewPost(){
runningTask.set(true);
service.submit(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"command-0005","test");
assertThrows(ScannerException.class,()->service.waitCommand("command-0005",10));
assertEquals("ACCEPTED",journal.get("command-0005").state());runningTask.set(false);
assertEquals("succeeded",service.waitCommand("command-0005",3000).path("state").asText());assertEquals(1,submissions.get());
}
@Test public void validatesStrictIntegersFieldsAndLosslessPointIds(){
assertThrows(ScannerException.class,()->ScannerRequestValidator.validate(ScannerOperation.CONNECT,ScannerRequestValidator.parse("{\"deviceType\":3.0}")));
assertThrows(ScannerException.class,()->ScannerRequestValidator.validate(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{\"planCode\":\"P1\"}")));
assertThrows(ScannerException.class,()->ScannerRequestValidator.validate(ScannerOperation.EXPORT,ScannerRequestValidator.parse("{\"formats\":[]}")));
assertThrows(ScannerException.class,()->ScannerRequestValidator.validate(ScannerOperation.CLIP_PLANE,ScannerRequestValidator.parse("{\"center\":[0,0,0],\"normal\":[0,0,0],\"confirm\":true,\"deleteBelowPoints\":true}")));
var data=ScannerRequestValidator.parse("{\"projectUuid\":\"p\",\"cloudUuid\":\"c\",\"pointIds\":[9007199254740993],\"confirm\":true}");
ScannerRequestValidator.validate(ScannerOperation.EDIT,data);assertTrue(data.toString().contains("9007199254740993"));
}
@Test public void noAddressOrKeyDoesNotPretendToBeOnline(){
var pending=new ScannerProperties();var offline=new ScannerService(pending,new ScannerHttpClient(pending),journal);
assertFalse(offline.configuration().path("configured").asBoolean());
assertEquals("not_configured",assertThrows(ScannerException.class,()->offline.get(ScannerOperation.STATUS,null)).scannerCode);
}
@Test public void lostOrMismatchedRemoteTaskLocksJournalAndPreventsReplay(){
service.submit(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"lost-task-0001","test");taskLost.set(true);
assertEquals("task_lost",assertThrows(ScannerException.class,()->service.waitCommand("lost-task-0001",3000)).scannerCode);
assertEquals("UNKNOWN",journal.get("lost-task-0001").state());
taskLost.set(false);
assertThrows(ScannerException.class,()->service.submit(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"lost-task-0002","test"));
assertEquals(1,submissions.get());
}
@Test public void queryCanRetryWithoutRetryingTheControlPost(){
transientQueries.set(2);
assertEquals("succeeded",service.executeAndWait(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"retry-query-0001","test",3000).path("state").asText());
assertEquals(1,submissions.get());
service.submit(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"retry-query-0002","test");wrongTask.set(true);
assertEquals("task_mismatch",assertThrows(ScannerException.class,()->service.waitCommand("retry-query-0002",3000)).scannerCode);
assertEquals("UNKNOWN",journal.get("retry-query-0002").state());
}
@Test public void pauseResumesContinuousAcquisitionInSameSessionOnly(){
config.setRobotId("station-1");scanning.set(true);
var lifecycle=new ScannerPauseExtension(config,service,client,journal);
lifecycle.beforePause("inst-1",List.of("station-1"));scanning.set(false);
lifecycle.beforeResume("inst-1",List.of("station-1"));
assertTrue(scanning.get());assertEquals(1,submissions.get());
lifecycle.beforeResume("inst-1",List.of("station-1"));assertEquals(1,submissions.get());
lifecycle.beforePause("inst-1",List.of("station-1"));scanning.set(false);session.set("S2");
assertEquals("session_changed",assertThrows(ScannerException.class,()->lifecycle.beforeResume("inst-1",List.of("station-1"))).scannerCode);
assertEquals(1,submissions.get());
lifecycle.afterStop("inst-1");assertThrows(ScannerException.class,()->lifecycle.beforeResume("inst-1",List.of("station-1")));
}
@Test public void pendingConfigurationAndArbitraryIdsNeverReachTransport(){
assertThrows(ScannerException.class,()->service.binary(ScannerOperation.FILE,"../etc/passwd"));
assertThrows(ScannerException.class,()->service.get(ScannerOperation.TASK,"http://another-host"));
assertEquals(0,seen.size());
}
@Test public void successfulWorkflowStopsAcquisitionBeforeItCanReleaseItsResources(){
config.setRobotId("station-1");scanning.set(true);
var device=new com.cmvr.resource.domain.ResourceDevice();device.setEnabled("1");device.setDeviceKind(14);
var devices=(com.cmvr.resource.mapper.ResourceDeviceMapper)java.lang.reflect.Proxy.newProxyInstance(getClass().getClassLoader(),new Class<?>[]{com.cmvr.resource.mapper.ResourceDeviceMapper.class},(proxy,method,args)->List.of(device));
var stop=new ScannerStopExtension(config,service,client,journal,devices);
var lifecycle=new ScannerCompletionExtension(stop,new ScannerPauseExtension(config,service,client,journal));
lifecycle.beforeComplete("inst-complete",List.of("station-1"));
assertFalse(scanning.get());assertEquals(1,submissions.get());
lifecycle.beforeComplete("inst-complete",List.of("station-1"));assertEquals(1,submissions.get());
scanning.set(true);failedTask.set(true);
assertThrows(ScannerException.class,()->lifecycle.beforeComplete("inst-failed-stop",List.of("station-1")));
}
@Test public void controllerCoversEverySupplierRouteWithoutAnArbitraryProxy() {
var methods=com.cmvr.web.controller.scanner.ScannerController.class.getDeclaredMethods();
for(var op:ScannerOperation.values()) {
String path=op.path.equals("/")?"/metadata":op.path.substring("/api/v1".length());
boolean found=false;
for(var method:methods){
var post=method.getAnnotation(org.springframework.web.bind.annotation.PostMapping.class);
var get=method.getAnnotation(org.springframework.web.bind.annotation.GetMapping.class);
if(op.control()&&post!=null&&Arrays.asList(post.value()).contains(path)){
assertTrue(method.getAnnotation(org.springframework.security.access.prepost.PreAuthorize.class).value().contains("lab:execution:dispatch"));found=true;
}
if(!op.control()&&get!=null&&Arrays.asList(get.value()).contains(path))found=true;
}
assertTrue(op.name()+" is not exposed",found);
}
assertFalse(service.configuration().has("apiKey"));
}
@Test public void workflowWaitsForAcceptedSnapshotSlotInsteadOfFailingOrResending() throws Exception {
runningTask.set(true);service.submit(ScannerOperation.SNAPSHOT,ScannerRequestValidator.parse("{}"),"snapshot-slot-0001","test");
Thread completion=new Thread(()->{try{Thread.sleep(60);}catch(InterruptedException error){Thread.currentThread().interrupt();}runningTask.set(false);});completion.start();
var result=service.executeAndWait(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"start-after-slot-0001","test",3000);
completion.join();assertEquals("succeeded",result.path("state").asText());assertEquals(2,submissions.get());
}
@Test public void snapshotMustStillMatchTheExpectedProjectInsideTheControlSlot() {
assertEquals("project_changed",assertThrows(ScannerException.class,()->service.submitBound(ScannerOperation.SNAPSHOT,ScannerRequestValidator.parse("{}"),"wrong-project-snapshot","workflow:inst",ScannerRequestValidator.parse("{\"sessionId\":\"S1\",\"projectId\":\"OTHER\"}"))).scannerCode);
assertEquals(0,submissions.get());assertNull(journal.get("wrong-project-snapshot"));
}
}

View File

@ -0,0 +1,80 @@
package com.cmvr.scanner;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.io.ByteArrayInputStream;
import java.util.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class ScannerMonitoringTest {
private final ScannerService scanner=mock(ScannerService.class);
private ScannerProperties settings;
private ScannerHttpClient client;
private ScannerCommandJournal journal;
private ScannerMonitoringService monitoring;
private JdbcTemplate jdbc;
private final String key="monitor-project-0001";
private JsonNode status(String session,String project){return ScannerRequestValidator.parse("{\"sessionId\":\""+session+"\",\"projectId\":\""+project+"\",\"projectReady\":true,\"previewEnabled\":true}");}
@Before public void setup() {
settings=new ScannerProperties();settings.setHost("localhost");settings.setPort(18888);settings.setApiKey("test-key");settings.setRobotId("station");settings.setDeviceId("scanner");
client=new ScannerHttpClient(settings);
jdbc=new JdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DB_CLOSE_DELAY=-1","sa",""));
jdbc.execute("CREATE TABLE lab_scanner_command(command_key VARCHAR(64) PRIMARY KEY,active_endpoint VARCHAR(64) UNIQUE,endpoint_key VARCHAR(64),operation VARCHAR(64),request_hash VARCHAR(64),state VARCHAR(16),remote_task_id VARCHAR(32),request_json CLOB,result_json CLOB,error_message CLOB,owner_ref VARCHAR(255),created_at TIMESTAMP,updated_at TIMESTAMP,context_json CLOB)");
journal=new ScannerCommandJournal(jdbc);monitoring=new ScannerMonitoringService(scanner,settings,client,journal);
journal.intent(key,client.endpointKey(),ScannerOperation.CREATE_PROJECT,"hash","{}","workflow:inst-1");
journal.accepted(key,"a".repeat(32));journal.finish(key,true,ScannerRequestValidator.parse("{\"result\":{\"projectId\":\"P1\"}}"),null);
when(scanner.get(ScannerOperation.STATUS,null)).thenReturn(status("S1","P1"));
when(scanner.get(ScannerOperation.METRICS,null)).thenReturn(ScannerRequestValidator.parse("{\"latestSequence\":10}"));
}
private JsonNode capture(){return monitoring.capture(ScannerOperation.CREATE_PROJECT,key,"inst-1","station","scanner");}
private void frame(long sequence){when(scanner.binary(ScannerOperation.PREVIEW_IMAGE,null)).thenReturn(new ScannerHttpClient.Binary(new ByteArrayInputStream(new byte[]{(byte)255,(byte)216,(byte)255,(byte)217}),Map.of("content-type",List.of("image/jpeg"),"x-frame-sequence",List.of(String.valueOf(sequence)))));}
@Test public void capturesDurableSessionProjectAndDoesNotRebindCachedCommand() {
JsonNode original=capture();assertEquals("P1",original.path("projectId").asText());
monitoring=new ScannerMonitoringService(scanner,settings,client,new ScannerCommandJournal(jdbc));
when(scanner.get(ScannerOperation.STATUS,null)).thenReturn(status("S2","P2"));
assertEquals(original,capture());assertEquals(original,monitoring.binding("inst-1"));assertNull(monitoring.binding("inst-other"));
assertEquals("project_changed",assertThrows(ScannerException.class,()->monitoring.status(original)).scannerCode);
}
@Test public void rejectsProjectMismatchBeforeBindingAndOldFramesAfterBinding() {
when(scanner.get(ScannerOperation.STATUS,null)).thenReturn(status("S1","P2"));
assertThrows(ScannerException.class,this::capture);assertNull(journal.context(key));
when(scanner.get(ScannerOperation.STATUS,null)).thenReturn(status("S1","P1"));var bound=capture();frame(10);
assertEquals("frame_pending",assertThrows(ScannerException.class,()->monitoring.image(bound)).scannerCode);
frame(11);assertEquals(4,monitoring.image(bound).bytes().length);
}
@Test public void refusesFrameIfProjectOrEndpointChangesDuringRead() {
var bound=capture();frame(11);
when(scanner.get(ScannerOperation.STATUS,null)).thenReturn(status("S1","P1"),status("S1","P2"));
assertEquals("project_changed",assertThrows(ScannerException.class,()->monitoring.image(bound)).scannerCode);
settings.setPort(18889);assertEquals("device_changed",assertThrows(ScannerException.class,()->monitoring.status(bound)).scannerCode);
}
@Test public void previewFailureDoesNotSubmitAnyControlCommand() {
var bound=capture();
when(scanner.binary(ScannerOperation.PREVIEW_IMAGE,null)).thenThrow(new ScannerException("frame_stale","过期",503));
assertThrows(ScannerException.class,()->monitoring.image(bound));
verify(scanner,never()).submit(any(),any(),anyString(),anyString());
}
@Test public void snapshotAndItsFilesBelongToOneExecutionOnly() {
capture();
when(scanner.submitBound(eq(ScannerOperation.SNAPSHOT),any(),anyString(),eq("workflow:inst-1"),any())).thenAnswer(invocation->{
String snapshotKey=invocation.getArgument(2);
journal.intent(snapshotKey,client.endpointKey(),ScannerOperation.SNAPSHOT,"snapshot-hash","{}","workflow:inst-1");journal.accepted(snapshotKey,"b".repeat(32));
return ScannerRequestValidator.parse("{\"commandKey\":\""+snapshotKey+"\",\"state\":\"ACCEPTED\"}");
});
var accepted=monitoring.snapshot("inst-1","requested-snapshot-key");String snapshotKey=accepted.path("commandKey").asText();
assertNotNull(journal.context(snapshotKey));assertTrue(journal.ownedBy(snapshotKey,"inst-1"));
assertThrows(ScannerException.class,()->monitoring.snapshotCommand("inst-other",snapshotKey));
String fileId="c".repeat(32);
journal.finish(snapshotKey,true,ScannerRequestValidator.parse("{\"result\":{\"files\":[{\"fileId\":\""+fileId+"\",\"name\":\"points.ply\",\"bytes\":100}]}}"),null);
assertEquals(1,monitoring.assets("inst-1").size());assertTrue(monitoring.assets("inst-other").isEmpty());
assertThrows(ScannerException.class,()->monitoring.asset("inst-other",fileId));
when(scanner.binary(ScannerOperation.FILE,fileId)).thenReturn(new ScannerHttpClient.Binary(new ByteArrayInputStream(new byte[100]),Map.of()));
assertNotNull(monitoring.asset("inst-1",fileId));
settings.setPort(18889);assertEquals("endpoint_changed",assertThrows(ScannerException.class,()->monitoring.asset("inst-1",fileId)).scannerCode);
}
}

View File

@ -21,8 +21,9 @@ import static org.junit.Assert.assertTrue;
public class FlowEndNodeHandlerTest {
@Test
public void waitsForAsyncAnalysisOnlyAtLastItem() {
public void waitsForAsyncAnalysisOnlyAtLastItem() throws Exception {
AtomicInteger awaitAllCalls = new AtomicInteger();
AtomicInteger deviceCompletionCalls = new AtomicInteger();
AsyncMediaAnalysisCoordinator coordinator = new AsyncMediaAnalysisCoordinator(null, null, null, null) {
@Override
public TaskNodeExecuteResult awaitAll(String instId) {
@ -47,19 +48,28 @@ public class FlowEndNodeHandlerTest {
executor.initialize();
try {
FlowEndNodeHandler handler = new FlowEndNodeHandler(holder, null, coordinator, executor);
var extensions = FlowEndNodeHandler.class.getDeclaredField("deviceLifecycle");extensions.setAccessible(true);
extensions.set(handler,List.of(new com.cmvr.test.flow.control.FlowDeviceLifecycleExtension(){
public void beforePause(String id,List<String> robots){}
public void beforeResume(String id,List<String> robots){}
public void beforeComplete(String id,List<String> robots){deviceCompletionCalls.incrementAndGet();}
}));
TaskNodeExecuteMessage earlierItem = message(1);
assertTrue(handler.handle(earlierItem).isSuccess());
assertEquals(0, awaitAllCalls.get());
assertEquals(0, deviceCompletionCalls.get());
TaskNodeExecuteMessage nestedFlowEnd = message(0);
nestedFlowEnd.setNestedFlow(true);
assertTrue(handler.handle(nestedFlowEnd).isSuccess());
assertEquals(0, awaitAllCalls.get());
assertEquals(0, deviceCompletionCalls.get());
TaskNodeExecuteMessage lastItem = message(0);
assertTrue(handler.handle(lastItem).isSuccess());
assertEquals(1, awaitAllCalls.get());
assertEquals(1, deviceCompletionCalls.get());
} finally {
executor.shutdown();
}

View File

@ -0,0 +1,162 @@
package com.cmvr.test.flow.runtime.operator.edge;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.runtime.engine.RobotDeviceAssignmentValidator;
import com.cmvr.test.flow.runtime.engine.FlowRuntimeDefinitionValidator;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.*;
public class EdgeWorkcellOperateServiceTest {
private final RobotDeviceAssignmentValidator validDevice = (robot, device, kind) -> {};
@Test public void workflowParsingPreservesNumericAndBooleanLiterals() {
var graph = com.cmvr.test.flow.builder.FlowModelBuilder.buildExecutableGraph("""
{"nodes":[{"id":"start","type":"start","properties":{"action":"START"}},
{"id":"scan","type":"serviceNode","properties":{"action":"SCANNER_START","nodeParams":[
{"name":"timeoutMs","type":"input","input":120000},
{"name":"enabled","type":"input","input":false},
{"name":"requestJson","type":"input","input":"{}"}]}}],"edges":[]}
""");
var params = graph.getNode("scan").getNodeParams();
assertTrue(params.get(0).getInput() instanceof Number);
assertEquals(Boolean.FALSE, params.get(1).getInput());
WorkcellNodeContract.validate(ActionEnum.SCANNER_START, new JSONObject()
.fluentPut("timeoutMs",params.get(0).getInput()).fluentPut("requestJson",params.get(2).getInput()));
}
@Test public void preflightRejectsMissingTimeoutAndInvalidBodiesButDefersCompleteQuotes() {
var validator = new FlowRuntimeDefinitionValidator(new DefaultListableBeanFactory()
.getBeanProvider(RobotDeviceAssignmentValidator.class));
var graph = JSONObject.parseObject("""
{"nodes":[{"type":"serviceNode","properties":{"name":"采集","action":"SCANNER_START","nodeParams":[]}}]}
""");
assertTrue(assertThrows(GlobalException.class,()->validator.validate(graph.toJSONString(),List.of()))
.getMessage().contains("timeoutMs"));
var params=graph.getJSONArray("nodes").getJSONObject(0).getJSONObject("properties").getJSONArray("nodeParams");
params.add(JSONObject.parseObject("{\"name\":\"timeoutMs\",\"type\":\"input\",\"input\":120000}"));
params.add(JSONObject.parseObject("{\"name\":\"requestJson\",\"type\":\"input\",\"input\":\"{bad}\"}"));
assertThrows(GlobalException.class,()->validator.validate(graph.toJSONString(),List.of()));
params.getJSONObject(1).put("type","quote");
assertThrows(GlobalException.class,()->validator.validate(graph.toJSONString(),List.of()));
params.getJSONObject(1).put("quoteType","output");
params.getJSONObject(1).put("quote",List.of("code","output","requestJson"));
validator.validate(graph.toJSONString(),List.of());
}
@Test public void scannerConfigurationAndIdentityAreCheckedWithoutSendingCommands() {
var settings=new com.cmvr.scanner.ScannerProperties();
var adapter=new com.cmvr.scanner.ScannerWorkflowAdapter(null,settings,null,null);
assertEquals("not_configured",assertThrows(com.cmvr.scanner.ScannerException.class,
()->adapter.validateConfiguration("station","scanner")).scannerCode);
settings.setHost("127.0.0.1");settings.setPort(18888);settings.setApiKey("fixture");
settings.setRobotId("station");settings.setDeviceId("scanner");
assertEquals("device_not_bound",assertThrows(com.cmvr.scanner.ScannerException.class,
()->adapter.validateConfiguration("station","other")).scannerCode);
adapter.validateConfiguration("station","scanner");
}
@Test public void missingScannerDriverCannotSucceed() {
EdgeWorkcellOperateService service = new EdgeWorkcellOperateService(validDevice, List.of());
GlobalException error = assertThrows(GlobalException.class,
() -> service.execute(message(ActionEnum.SCANNER_START).withInput("requestJson", "{}")));
assertTrue(error.getMessage().contains("扫描仪驱动尚未接入"));
}
@Test public void missingMotorDriverCannotSucceed() {
EdgeWorkcellOperateService service = new EdgeWorkcellOperateService(validDevice, List.of());
assertTrue(assertThrows(GlobalException.class, () -> service.execute(message(ActionEnum.MOTOR_HOME)))
.getMessage().contains("电机驱动尚未接入"));
}
@Test public void routesResolvedJobAndValidatesScannerIdentity() {
AtomicInteger kind = new AtomicInteger();
WorkcellDeviceAdapter driver = adapter(ActionEnum.SCANNER_WAIT, TaskNodeExecuteResult.success(
new JSONObject().fluentPut("taskId", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").fluentPut("state", "succeeded")));
EdgeWorkcellOperateService service = new EdgeWorkcellOperateService((robot, device, expected) -> {
assertEquals("station-1", robot); assertEquals("device-1", device); kind.set(expected);
}, List.of(driver));
TaskNodeExecuteResult result = service.execute(message(ActionEnum.SCANNER_WAIT).withInput("taskId", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
assertTrue(result.isSuccess()); assertEquals(14, kind.get());
assertEquals("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", result.getOutputParams().getString("taskId"));
}
@Test public void invalidMovementNeverReachesDriver() {
AtomicInteger calls = new AtomicInteger();
WorkcellDeviceAdapter driver = new WorkcellDeviceAdapter() {
public boolean supports(ActionEnum action) { return true; }
public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) { calls.incrementAndGet(); return TaskNodeExecuteResult.success(); }
};
EdgeWorkcellOperateService service = new EdgeWorkcellOperateService(validDevice, List.of(driver));
var move = message(ActionEnum.MOTOR_MOVE).withInput("targetPosition", -45.25).withInput("unit", "DEGREE")
.withInput("velocity", 0).withInput("acceleration", 1);
assertThrows(GlobalException.class, () -> service.execute(move));
move.getInputParams().put("velocity", 1);
assertTrue(service.execute(move).isSuccess()); assertEquals(1, calls.get());
}
@Test public void rejectsInvalidResolvedValues() {
assertThrows(GlobalException.class, () -> WorkcellNodeContract.validate(ActionEnum.MOTOR_STATUS,
new JSONObject().fluentPut("timeoutMs", 1.5)));
assertThrows(GlobalException.class, () -> WorkcellNodeContract.validate(ActionEnum.SCANNER_EXPORT,
new JSONObject().fluentPut("timeoutMs", 60000).fluentPut("jobId", "J").fluentPut("format", "")));
assertThrows(GlobalException.class, () -> WorkcellNodeContract.validate(ActionEnum.MOTOR_WAIT,
new JSONObject().fluentPut("timeoutMs", 60000).fluentPut("targetPosition", 0)
.fluentPut("unit", "DEGREE").fluentPut("tolerance", -1)));
}
@Test public void rejectsAmbiguousDriversAndUnconfirmedResults() {
var driver = adapter(ActionEnum.MOTOR_STOP, TaskNodeExecuteResult.success());
assertThrows(GlobalException.class, () -> new EdgeWorkcellOperateService(validDevice, List.of(driver, driver))
.execute(message(ActionEnum.MOTOR_STOP)));
var deferred = adapter(ActionEnum.MOTOR_STOP, TaskNodeExecuteResult.deferred(new JSONObject()));
assertThrows(GlobalException.class, () -> new EdgeWorkcellOperateService(validDevice, List.of(deferred))
.execute(message(ActionEnum.MOTOR_STOP)));
}
@Test public void runtimeDefinitionRejectsWrongDeviceSlotBeforeDispatch() {
var validator = new FlowRuntimeDefinitionValidator(new DefaultListableBeanFactory()
.getBeanProvider(RobotDeviceAssignmentValidator.class));
JSONObject graph = JSONObject.parseObject("""
{"nodes":[
{"type":"start","properties":{"resourceRoles":[{
"roleKey":"station","displayName":"工位","required":false,
"deviceSlots":[{"slotKey":"scanner","deviceKind":14}]
}]}},
{"type":"serviceNode","properties":{"name":"扫描","nodeType":"EDGE",
"nodeParams":[{"name":"timeoutMs","type":"input","input":60000}],
"action":"SCANNER_STATUS","executionTarget":{"roleKey":"station","deviceSlotKey":"scanner"}}}
]}
""");
validator.validate(graph.toJSONString(), List.of());
graph.getJSONArray("nodes").getJSONObject(0).getJSONObject("properties")
.getJSONArray("resourceRoles").getJSONObject(0).getJSONArray("deviceSlots")
.getJSONObject(0).put("deviceKind", 10);
assertThrows(GlobalException.class, () -> validator.validate(graph.toJSONString(), List.of()));
}
private WorkcellDeviceAdapter adapter(ActionEnum expected, TaskNodeExecuteResult result) {
return new WorkcellDeviceAdapter() {
public boolean supports(ActionEnum action) { return action == expected; }
public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) { return result; }
};
}
private Message message(ActionEnum action) {
Message result = new Message(); result.setAction(action); result.setRobotId("station-1");
result.setInputParams(new JSONObject().fluentPut("deviceId", "device-1").fluentPut("timeoutMs", 60000));
return result;
}
private static class Message extends TaskNodeExecuteMessage {
Message withInput(String key, Object value) { getInputParams().put(key, value); return this; }
}
}

View File

@ -0,0 +1,54 @@
package cn.iocoder.yudao.module.lab.controller.admin.cmvr;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.lab.service.execution.LabScannerViewService;
import com.cmvr.scanner.ScannerException;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.http.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.Locale;
import java.util.List;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
@RestController
@RequestMapping("/lab/execution/scanner-view")
@PreAuthorize("@ss.hasPermission('lab:execution:query')")
@RequiredArgsConstructor
public class LabScannerViewController {
private final LabScannerViewService views;
@GetMapping
public CommonResult<JsonNode> view(@RequestParam Long executionId) {return CommonResult.success(views.view(executionId));}
@PostMapping("/snapshot")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public CommonResult<JsonNode> snapshot(@RequestParam Long executionId,@RequestHeader("X-Scanner-Command-Key") String key){return CommonResult.success(views.snapshot(executionId,key));}
@GetMapping("/snapshot-command")
public CommonResult<?> snapshotCommand(@RequestParam Long executionId,@RequestParam String commandKey){return CommonResult.success(views.snapshotCommand(executionId,commandKey));}
@GetMapping("/assets")
public CommonResult<List<JsonNode>> assets(@RequestParam Long executionId){return CommonResult.success(views.assets(executionId));}
@GetMapping("/asset/{fileId}")
public ResponseEntity<StreamingResponseBody> asset(@RequestParam Long executionId,@PathVariable String fileId){
var source=views.asset(executionId,fileId);
return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).cacheControl(CacheControl.noStore()).body(output->{
try(source){byte[] buffer=new byte[16384];long total=0;int count;
while((count=source.stream().read(buffer))!=-1){total+=count;if(total>100L*1024*1024)throw new java.io.IOException("Model exceeds online viewing size limit");output.write(buffer,0,count);}
}
});
}
@GetMapping("/image")
public ResponseEntity<byte[]> image(@RequestParam Long executionId) {
var frame=views.image(executionId);
HttpHeaders headers=new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);headers.setCacheControl("no-store");
frame.headers().forEach((name,values)->{if(name.toLowerCase(Locale.ROOT).startsWith("x-frame-")&&!values.isEmpty())headers.put(name,values);});
return ResponseEntity.ok().headers(headers).body(frame.bytes());
}
@ExceptionHandler(ScannerException.class)
public CommonResult<?> scannerError(ScannerException error){return CommonResult.error(error.remoteStatus,error.getMessage());}
}

View File

@ -102,6 +102,7 @@ public class LabLaboratoryController {
}
private void fill(LabLaboratoryRespVO vo) {
if (vo == null) return;
vo.setOccupancy("-");
if (vo.getOwnerId() == null) {
return;

View File

@ -3,6 +3,9 @@ package cn.iocoder.yudao.module.lab.controller.admin.master.vo.attachment;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.Size;
import lombok.Data;
@Schema(description = "管理后台 - 主数据附件保存 Request VO")
@ -10,12 +13,17 @@ import lombok.Data;
public class LabMasterAttachmentSaveReqVO {
@NotBlank
@Pattern(regexp = "SAMPLE|DEVICE|FIXTURE|METHOD|MATERIAL|LAB")
private String bizType;
@NotNull
@Positive
private Long bizId;
@NotBlank
@Size(max = 255)
private String fileName;
@NotBlank
@Size(max = 512)
private String fileUrl;
@Pattern(regexp = "IMAGE|DRAWING|MODEL|MANUAL|OTHER")
private String fileType;
}

View File

@ -79,7 +79,13 @@ public class LabResultController {
@PreAuthorize("@ss.hasPermission('lab:result:query')")
public CommonResult<List<Map<String, Object>>> compare(@RequestParam("taskId") Long taskId,
@RequestParam("batchIds") String batchIds) {
List<Long> ids = Arrays.stream(batchIds.split(",")).filter(s -> !s.isBlank()).map(Long::valueOf).toList();
List<Long> ids;
try {
ids = Arrays.stream(batchIds.split(",",-1)).map(String::trim).map(Long::valueOf).toList();
if(ids.isEmpty() || ids.size()>4 || ids.stream().anyMatch(id->id<=0)) throw new IllegalArgumentException();
} catch (IllegalArgumentException error) {
throw cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.invalidParamException("请选择1至4个有效的结果批次编号");
}
return success(resultService.compare(taskId, ids));
}
}

View File

@ -11,6 +11,9 @@ import java.util.List;
@Mapper
public interface LabReportMapper extends BaseMapperX<LabReportDO> {
@org.apache.ibatis.annotations.Select("SELECT * FROM lab_report WHERE id=#{id} AND deleted=0 FOR UPDATE")
LabReportDO selectByIdForUpdate(@org.apache.ibatis.annotations.Param("id") Long id);
default PageResult<LabReportDO> selectPage(LabReportPageReqVO reqVO) {
return selectPage(reqVO, new LambdaQueryWrapperX<LabReportDO>()
.eqIfPresent(LabReportDO::getTaskId, reqVO.getTaskId())

View File

@ -4,8 +4,11 @@ import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import java.util.List;
import java.util.Map;
import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
@ -16,6 +19,28 @@ public class LabTaskSeqRedisDAO {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private JdbcTemplate jdbcTemplate;
// Redis may be cleared or moved to a different logical database. Keep all
// persisted numbers, including deleted records, below the next allocation.
private static final Map<String,String> NUMBER_COLUMNS = Map.ofEntries(
Map.entry("T","lab_test_task.task_no"),Map.entry("IB","lab_task_import_batch.batch_no"),
Map.entry("ST","lab_sample_transfer.transfer_no"),Map.entry("DR","lab_device_reservation.reservation_no"),
Map.entry("LR","lab_lab_reservation.reservation_no"),Map.entry("MI","lab_material_issue.issue_no"),
Map.entry("EX","lab_execution.execution_no"),Map.entry("AF","lab_artifact_file.artifact_no"),
Map.entry("MB","lab_measurement_batch.batch_no"),Map.entry("RP","lab_report.report_no"),
Map.entry("OR","lab_original_record.record_no"),Map.entry("PK","lab_export_package.package_no"),
Map.entry("EE","lab_execution_exception.exception_no"),Map.entry("IR","lab_integration_log.request_no"),
Map.entry("IF","lab_integration_failure.failure_no"),Map.entry("CMD","lab_execution_command.command_no"));
private static final DefaultRedisScript<Long> NEXT = new DefaultRedisScript<>("""
local current = tonumber(redis.call('GET', KEYS[1]) or '0')
local floor = tonumber(ARGV[1])
if current < floor then redis.call('SET', KEYS[1], floor) end
local next = redis.call('INCR', KEYS[1])
if redis.call('TTL', KEYS[1]) < 0 then redis.call('EXPIRE', KEYS[1], 172800) end
return next
""",Long.class);
public String nextBatchNo() {
return nextNo("IB");
@ -79,11 +104,17 @@ public class LabTaskSeqRedisDAO {
public String nextNo(String prefix) {
String date = LocalDate.now().format(DAY);
String key = "lab:task:seq:" + TenantContextHolder.getRequiredTenantId() + ":" + prefix + ":" + date;
Long seq = stringRedisTemplate.opsForValue().increment(key);
if (seq != null && seq == 1L) {
stringRedisTemplate.expire(key, Duration.ofDays(2));
}
return prefix + "-" + date + "-" + String.format("%04d", seq == null ? 1 : seq);
Long tenant = TenantContextHolder.getRequiredTenantId();
String identity = NUMBER_COLUMNS.get(prefix);
if (identity == null) throw new IllegalArgumentException("未知业务编号类型:" + prefix);
String[] parts = identity.split("\\.");
String stem = prefix + "-" + date + "-";
// Table and column names come only from the fixed map above.
Long floor = jdbcTemplate.queryForObject("SELECT COALESCE(MAX(CAST(SUBSTRING(`"+parts[1]+"`, ?) AS UNSIGNED)),0) FROM `"+parts[0]+"` WHERE tenant_id=? AND `"+parts[1]+"` LIKE ?",
Long.class,stem.length()+1,tenant,stem+"%");
String key = "lab:task:seq:" + tenant + ":" + prefix + ":" + date;
Long seq = stringRedisTemplate.execute(NEXT,List.of(key),String.valueOf(floor == null ? 0 : floor));
if (seq == null) throw new IllegalStateException("业务编号生成失败,请稍后重试");
return stem + String.format("%04d",seq);
}
}

View File

@ -331,8 +331,14 @@ public class LabArtifactServiceImpl implements LabArtifactService {
throw exception(FILE_PATH_INVALID);
}
String nasRoot = bizProperties.getArtifact().getNasRoot();
if (StrUtil.isNotBlank(path) && StrUtil.isNotBlank(nasRoot) && !path.startsWith(nasRoot)) {
throw exception(FILE_PATH_INVALID);
if (StrUtil.isNotBlank(path) && StrUtil.isNotBlank(nasRoot)) {
try {
java.nio.file.Path root = java.nio.file.Path.of(nasRoot).toAbsolutePath().normalize();
java.nio.file.Path file = java.nio.file.Path.of(path).toAbsolutePath().normalize();
if (!file.startsWith(root)) throw exception(FILE_PATH_INVALID);
} catch (java.nio.file.InvalidPathException error) {
throw exception(FILE_PATH_INVALID);
}
}
}

View File

@ -133,8 +133,11 @@ public class LabDocumentServiceImpl implements LabDocumentService {
@Override
@Transactional(rollbackFor = Exception.class)
public void updateDraft(Long id, String contentHtml, String title) {
LabReportDO report = validateReport(id);
if ("PUBLISHED".equals(report.getStatus()) && report.getFormalVersionId() != null) {
LabReportDO report = lockReport(id);
List<LabReportVersionDO> versions = versionMapper.selectListByReportId(id);
LabReportVersionDO existingDraft = versions.stream().filter(item -> "DRAFT".equals(item.getStatus()))
.max(java.util.Comparator.comparing(LabReportVersionDO::getVersionNo)).orElse(null);
if ("PUBLISHED".equals(report.getStatus()) && report.getFormalVersionId() != null && existingDraft == null) {
Integer next = versionMapper.selectMaxVersion(id) + 1;
LabReportVersionDO formal = versionMapper.selectById(report.getFormalVersionId());
LabReportVersionDO draft = LabReportVersionDO.builder()
@ -154,9 +157,7 @@ public class LabDocumentServiceImpl implements LabDocumentService {
if ("VOID".equals(report.getStatus())) {
throw exception(REPORT_ALREADY_PUBLISHED);
}
List<LabReportVersionDO> versions = versionMapper.selectListByReportId(id);
LabReportVersionDO draft = versions.stream().filter(item -> "DRAFT".equals(item.getStatus())).findFirst()
.orElse(versions.isEmpty() ? null : versions.get(0));
LabReportVersionDO draft = existingDraft;
if (draft == null) {
throw exception(REPORT_NOT_EXISTS);
}
@ -171,7 +172,8 @@ public class LabDocumentServiceImpl implements LabDocumentService {
@Override
@Transactional(rollbackFor = Exception.class)
public void publish(Long id) {
LabReportDO report = validateReport(id);
LabReportDO report = lockReport(id);
if ("VOID".equals(report.getStatus())) throw cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.invalidParamException("已作废报告不能发布");
if (!resultService.hasConfirmedClosed(report.getTaskId())) {
throw exception(REPORT_RESULT_NOT_CONFIRMED);
}
@ -184,7 +186,8 @@ public class LabDocumentServiceImpl implements LabDocumentService {
throw exception(REPORT_FILE_INVALID);
}
List<LabReportVersionDO> versions = versionMapper.selectListByReportId(id);
LabReportVersionDO draft = versions.stream().filter(item -> "DRAFT".equals(item.getStatus())).findFirst()
LabReportVersionDO draft = versions.stream().filter(item -> "DRAFT".equals(item.getStatus()))
.max(java.util.Comparator.comparing(LabReportVersionDO::getVersionNo))
.orElseThrow(() -> exception(REPORT_NOT_EXISTS));
if (report.getFormalVersionId() != null) {
LabReportVersionDO old = versionMapper.selectById(report.getFormalVersionId());
@ -209,7 +212,7 @@ public class LabDocumentServiceImpl implements LabDocumentService {
if (StrUtil.isBlank(reason)) {
throw exception(REPORT_VOID_REASON_REQUIRED);
}
LabReportDO report = validateReport(id);
LabReportDO report = lockReport(id);
report.setStatus("VOID");
report.setVoidReason(reason);
reportMapper.updateById(report);
@ -330,6 +333,12 @@ public class LabDocumentServiceImpl implements LabDocumentService {
return report;
}
private LabReportDO lockReport(Long id) {
LabReportDO report = reportMapper.selectByIdForUpdate(id);
if (report == null) throw exception(REPORT_NOT_EXISTS);
return report;
}
private Map<String, Object> buildSummary(LabTestTaskDO task) {
Map<String, Object> summary = new HashMap<>();
summary.put("taskNo", task.getTaskNo());

View File

@ -0,0 +1,91 @@
package cn.iocoder.yudao.module.lab.service.execution;
import cn.iocoder.yudao.module.lab.dal.dataobject.execution.LabCmvrExecutionDO;
import cn.iocoder.yudao.module.lab.dal.dataobject.execution.LabExecutionDO;
import cn.iocoder.yudao.module.lab.dal.mysql.execution.LabExecutionMapper;
import com.cmvr.scanner.*;
import com.cmvr.test.flow.context.TaskInstHolder;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
/** Resolves the business execution server-side; historical executions never show the live device. */
@Service
@RequiredArgsConstructor
public class LabScannerViewService {
private final LabExecutionMapper executions;
private final CmvrExecutionBridge bridge;
private final TaskInstHolder runtime;
private final ScannerProperties settings;
private final ScannerMonitoringService monitoring;
public ObjectNode view(Long executionId) {
LabExecutionDO execution=required(executionId);
ObjectNode result=ScannerRequestValidator.JSON.createObjectNode();
result.put("executionId",String.valueOf(execution.getId()));result.put("executionNo",execution.getExecutionNo());
result.put("taskId",String.valueOf(execution.getTaskId()));result.put("executionStatus",execution.getStatus());
if(execution.getSampleUnitId()!=null)result.put("sampleUnitId",String.valueOf(execution.getSampleUnitId()));
result.put("available",false);
try {
if(!active(execution))return unavailable(result,"history","本次执行已结束,实时画面不作为历史扫描结果展示");
if(!settings.configured())return unavailable(result,"not_configured","扫描服务待配置,接入设备后将在这里显示实时画面");
var link=requiredRuntime(executionId);
JsonNode context=monitoring.binding(link.getCmvrInstId());
JsonNode status=monitoring.status(context);
result.put("available",true);result.put("state","ready");result.put("message","");
result.put("robotId",context.path("robotId").asText());result.put("deviceId",context.path("deviceId").asText());
result.put("sessionId",context.path("sessionId").asText());result.put("projectId",context.path("projectId").asText());
result.put("scanning",status.path("scanning").asBoolean());result.put("previewEnabled",status.path("previewEnabled").asBoolean());
result.put("meshState",status.path("meshState").asText());
return result;
}catch(ScannerException error){return unavailable(result,error.scannerCode,error.getMessage());}
}
public ScannerMonitoringService.Frame image(Long executionId) {
var link=requiredRuntime(executionId);
JsonNode context=monitoring.binding(link.getCmvrInstId());
ScannerMonitoringService.Frame frame=monitoring.image(context);
var current=requiredRuntime(executionId);
JsonNode latest=monitoring.binding(current.getCmvrInstId());
if(!current.getCmvrInstId().equals(link.getCmvrInstId())||latest==null||!latest.path("commandKey").equals(context.path("commandKey")))throw new ScannerException("execution_changed","本次执行的扫描工程已更新,重新获取画面",409);
return frame;
}
public ObjectNode snapshot(Long id,String key) {
var link=requiredRuntime(id);
return monitoring.snapshot(link.getCmvrInstId(),key);
}
public ScannerCommandJournal.Entry snapshotCommand(Long id,String key) {
required(id);var link=bridge.get(id);
if(link==null||link.getCmvrInstId()==null)throw new ScannerException("runtime_pending","没有本次执行的工作流记录",404);
return monitoring.snapshotCommand(link.getCmvrInstId(),key);
}
public List<JsonNode> assets(Long id) {
required(id);var link=bridge.get(id);
if(link==null||link.getCmvrInstId()==null)return List.of();
return monitoring.assets(link.getCmvrInstId()).stream().map(file->{var value=(ObjectNode)file.deepCopy();value.remove("binding");return (JsonNode)value;}).toList();
}
public ScannerHttpClient.Binary asset(Long id,String fileId) {
required(id);var link=bridge.get(id);
if(link==null||link.getCmvrInstId()==null)throw new ScannerException("file_not_owned","没有本次执行的扫描文件",404);
return monitoring.asset(link.getCmvrInstId(),fileId);
}
private LabExecutionDO required(Long id) {
CmvrMethodBindingService.requirePrimaryTenant();
LabExecutionDO execution=executions.selectById(id);
if(execution==null)throw new ScannerException("execution_not_found","执行记录不存在",404);
return execution;
}
private LabCmvrExecutionDO requiredRuntime(Long id) {
if(!active(required(id)))throw new ScannerException("execution_finished","本次执行已结束,停止读取实时画面",409);
LabCmvrExecutionDO link=bridge.get(id);
if(link==null||link.getCmvrInstId()==null)throw new ScannerException("runtime_pending","等待本次执行的工作流启动",409);
var context=runtime.getContext(link.getCmvrInstId());
if(context==null||context.isStopped()||(context.getStatus()!=com.cmvr.test.enums.TaskStatusEnum.RUNNING&&context.getStatus()!=com.cmvr.test.enums.TaskStatusEnum.PAUSED))throw new ScannerException("runtime_inactive","本次工作流未在运行,不展示当前设备画面",409);
List<String> robots=context.getRobotIds()==null||context.getRobotIds().isEmpty()?java.util.Collections.singletonList(context.getRobotId()):context.getRobotIds();
if(settings.getRobotId().isBlank()||!robots.contains(settings.getRobotId()))throw new ScannerException("device_not_assigned","本次执行未分配已配置的扫描设备",409);
return link;
}
private boolean active(LabExecutionDO execution){return "RUNNING".equals(execution.getStatus())||"PAUSED".equals(execution.getStatus());}
private ObjectNode unavailable(ObjectNode result,String state,String message){result.put("state",state);result.put("message",message);return result;}
}

View File

@ -4,6 +4,8 @@ import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.lab.controller.admin.master.vo.attachment.LabMasterAttachmentSaveReqVO;
import cn.iocoder.yudao.module.lab.dal.dataobject.master.LabMasterAttachmentDO;
import cn.iocoder.yudao.module.lab.dal.mysql.master.LabMasterAttachmentMapper;
import cn.iocoder.yudao.module.lab.dal.mysql.master.*;
import cn.iocoder.yudao.framework.security.core.service.SecurityFrameworkService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
@ -12,6 +14,8 @@ import java.util.List;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.lab.enums.ErrorCodeConstants.ATTACHMENT_NOT_EXISTS;
import static cn.iocoder.yudao.module.lab.enums.ErrorCodeConstants.MASTER_NOT_EXISTS;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.invalidParamException;
@Service
@Validated
@ -19,9 +23,19 @@ public class LabMasterAttachmentServiceImpl implements LabMasterAttachmentServic
@Resource
private LabMasterAttachmentMapper attachmentMapper;
@Resource private LabSampleMapper samples;
@Resource private LabDeviceMapper devices;
@Resource private LabFixtureMapper fixtures;
@Resource private LabTestMethodRefMapper methods;
@Resource private LabMaterialMapper materials;
@Resource private LabLaboratoryMapper laboratories;
@Resource private SecurityFrameworkService security;
@Override
public Long createAttachment(LabMasterAttachmentSaveReqVO reqVO) {
authorize(reqVO.getBizType(), true);
requireMaster(reqVO.getBizType(),reqVO.getBizId());
validateUrl(reqVO.getFileUrl());
LabMasterAttachmentDO attachment = BeanUtils.toBean(reqVO, LabMasterAttachmentDO.class);
attachmentMapper.insert(attachment);
return attachment.getId();
@ -29,14 +43,48 @@ public class LabMasterAttachmentServiceImpl implements LabMasterAttachmentServic
@Override
public void deleteAttachment(Long id) {
if (attachmentMapper.selectById(id) == null) {
LabMasterAttachmentDO row = attachmentMapper.selectById(id);
if (row == null) {
throw exception(ATTACHMENT_NOT_EXISTS);
}
authorize(row.getBizType(), true);
attachmentMapper.deleteById(id);
}
@Override
public List<LabMasterAttachmentDO> getAttachmentList(String bizType, Long bizId) {
authorize(bizType, false);
requireMaster(bizType,bizId);
return attachmentMapper.selectListByBiz(bizType, bizId);
}
private void authorize(String type,boolean write) {
if (type == null || !java.util.Set.of("SAMPLE","DEVICE","FIXTURE","METHOD","MATERIAL","LAB").contains(type))
throw invalidParamException("附件业务类型无效");
String action = write ? ("METHOD".equals(type) ? "mapping" : "update") : "query";
if (!security.hasPermission("lab:"+type.toLowerCase(java.util.Locale.ROOT)+":"+action))
throw new org.springframework.security.access.AccessDeniedException("没有该类主数据的附件操作权限");
}
private void requireMaster(String type,Long id) {
if (id == null || id <= 0) throw invalidParamException("附件所属主数据编号无效");
Object row = switch(type) {
case "SAMPLE" -> samples.selectById(id);
case "DEVICE" -> devices.selectById(id);
case "FIXTURE" -> fixtures.selectById(id);
case "METHOD" -> methods.selectById(id);
case "MATERIAL" -> materials.selectById(id);
case "LAB" -> laboratories.selectById(id);
default -> null;
};
if (row == null) throw exception(MASTER_NOT_EXISTS);
}
private void validateUrl(String value) {
try {
java.net.URI uri = java.net.URI.create(value);
boolean relative = uri.getScheme()==null && value.startsWith("/") && !value.startsWith("//");
boolean remote = java.util.Set.of("http","https").contains(java.util.Objects.toString(uri.getScheme(),""))
&& uri.getHost()!=null && uri.getUserInfo()==null;
if (!relative && !remote) throw new IllegalArgumentException();
} catch (RuntimeException error) { throw invalidParamException("附件地址必须是有效的HTTP下载地址或站内路径"); }
}
}

View File

@ -107,6 +107,8 @@ public class ScanResourceService extends ResourceOccupationStore {
}
}
public void guardReservationMutation(String type,Long resourceId) {
if(resourceId==null||resourceId<=0)throw invalidParamException("请提供有效的资源编号");
if(!Set.of("DEVICE","LAB").contains(Objects.toString(type,"")))throw invalidParamException("资源类型无效");
primary();String table="DEVICE".equals(type)?"lab_device":"lab_laboratory";rows("SELECT id FROM "+table+" WHERE id=? AND tenant_id=1 AND deleted=0 FOR UPDATE",resourceId);
if(!rows("SELECT id FROM lab_resource_occupation WHERE resource_type=? AND resource_id=? AND tenant_id=1 AND deleted=0 FOR UPDATE",type,resourceId.toString()).isEmpty())throw invalidParamException("资源仍由执行占用,请从任务工作台结束,或确认原生流程/人工操作停止后释放");
if("LAB".equals(type)&&!rows("SELECT o.id FROM lab_resource_occupation o JOIN lab_device d ON o.resource_type='DEVICE' AND o.resource_id=CAST(d.id AS CHAR) WHERE d.laboratory_id=? AND o.tenant_id=1 AND o.deleted=0 AND d.deleted=0",resourceId).isEmpty())throw invalidParamException("该实验室仍有设备执行占用,暂不能更改场地配置");

View File

@ -0,0 +1,65 @@
package cn.iocoder.yudao.module.lab.service.execution;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.lab.dal.dataobject.execution.*;
import cn.iocoder.yudao.module.lab.dal.mysql.execution.LabExecutionMapper;
import com.cmvr.scanner.*;
import com.cmvr.test.enums.TaskStatusEnum;
import com.cmvr.test.flow.context.*;
import org.junit.jupiter.api.*;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class LabScannerViewServiceTest {
private final LabExecutionMapper executions=mock(LabExecutionMapper.class);
private final CmvrExecutionBridge bridge=mock(CmvrExecutionBridge.class);
private final TaskInstHolder runtime=mock(TaskInstHolder.class);
private final ScannerMonitoringService monitoring=mock(ScannerMonitoringService.class);
private final ScannerProperties settings=new ScannerProperties();
private final LabScannerViewService views=new LabScannerViewService(executions,bridge,runtime,settings,monitoring);
private LabExecutionDO execution;
@BeforeEach void setup(){
TenantContextHolder.setTenantId(1L);
settings.setHost("localhost");settings.setPort(18888);settings.setApiKey("test-key");settings.setRobotId("station");settings.setDeviceId("scanner");
execution=LabExecutionDO.builder().id(1L).taskId(2L).sampleUnitId(3L).executionNo("E1").status("RUNNING").build();
when(executions.selectById(1L)).thenReturn(execution);
var link=new LabCmvrExecutionDO();link.setExecutionId(1L);link.setCmvrInstId("inst-1");when(bridge.get(1L)).thenReturn(link);
var context=new TaskContext();context.setRobotIds(List.of("station"));context.setStatus(TaskStatusEnum.RUNNING);when(runtime.getContext("inst-1")).thenReturn(context);
var binding=ScannerRequestValidator.parse("{\"commandKey\":\"original\",\"projectId\":\"P1\",\"sessionId\":\"S1\",\"robotId\":\"station\",\"deviceId\":\"scanner\"}");
when(monitoring.binding("inst-1")).thenReturn(binding);
when(monitoring.status(binding)).thenReturn(ScannerRequestValidator.parse("{\"scanning\":true,\"previewEnabled\":true}"));
when(monitoring.image(binding)).thenReturn(new ScannerMonitoringService.Frame(new byte[]{1},Map.of()));
}
@AfterEach void cleanup(){TenantContextHolder.clear();}
@Test void associatesTaskUnitExecutionAndScannerProject(){
var view=views.view(1L);assertTrue(view.path("available").asBoolean());
assertEquals("2",view.path("taskId").asText());assertEquals("3",view.path("sampleUnitId").asText());assertEquals("P1",view.path("projectId").asText());
assertArrayEquals(new byte[]{1},views.image(1L).bytes());
}
@Test void historicalExecutionNeverReadsTheCurrentDevice(){
execution.setStatus("SUCCEEDED");assertFalse(views.view(1L).path("available").asBoolean());
assertThrows(ScannerException.class,()->views.image(1L));verifyNoInteractions(monitoring);
}
@Test void blocksWrongTenantInactiveRuntimeAndWrongWorkstation(){
TenantContextHolder.setTenantId(2L);assertThrows(RuntimeException.class,()->views.view(1L));
TenantContextHolder.setTenantId(1L);when(runtime.getContext("inst-1")).thenReturn(null);
assertEquals("runtime_inactive",views.view(1L).path("state").asText());
var context=new TaskContext();context.setStatus(TaskStatusEnum.RUNNING);context.setRobotIds(List.of("other"));when(runtime.getContext("inst-1")).thenReturn(context);
assertEquals("device_not_assigned",views.view(1L).path("state").asText());verifyNoInteractions(monitoring);
}
@Test void dropsFrameWhenExecutionCompletesOrProjectBindingChangesDuringRead(){
var done=LabExecutionDO.builder().id(1L).taskId(2L).status("SUCCEEDED").build();
when(executions.selectById(1L)).thenReturn(execution,done);
assertThrows(ScannerException.class,()->views.image(1L));
when(executions.selectById(1L)).thenReturn(execution);
var first=monitoring.binding("inst-1");var next=first.deepCopy();((com.fasterxml.jackson.databind.node.ObjectNode)next).put("commandKey","next-project");
when(monitoring.binding("inst-1")).thenReturn(first,next);
assertEquals("execution_changed",assertThrows(ScannerException.class,()->views.image(1L)).scannerCode);
}
@Test void emptyConfigurationShowsPendingWithoutContactingHardware(){
settings.setHost("");assertEquals("not_configured",views.view(1L).path("state").asText());verifyNoInteractions(monitoring);
}
}

View File

@ -0,0 +1,24 @@
package cn.iocoder.yudao.module.lab.service.scanonly;
import cn.iocoder.yudao.module.lab.framework.config.LabBizProperties;
import cn.iocoder.yudao.module.lab.service.data.LabArtifactServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.*;
class ArtifactPathTest {
@Test void acceptsNormalizedPlatformPathsAndRejectsSiblingPrefixes() {
var service=new LabArtifactServiceImpl();
var properties=new LabBizProperties();
Path root=Path.of("target","artifacts").toAbsolutePath();
properties.getArtifact().setNasRoot(root.toString());
ReflectionTestUtils.setField(service,"bizProperties",properties);
assertDoesNotThrow(()->ReflectionTestUtils.invokeMethod(service,"validatePath",
root.resolve("1/scan-output.json").toString().replace('\\','/'),"scan-output.json"));
assertThrows(RuntimeException.class,()->ReflectionTestUtils.invokeMethod(service,"validatePath",
root+"-other/scan-output.json","scan-output.json"));
assertThrows(RuntimeException.class,()->ReflectionTestUtils.invokeMethod(service,"validatePath",
root+"/../scan-output.json","scan-output.json"));
}
}

View File

@ -0,0 +1,47 @@
package cn.iocoder.yudao.module.lab.service.scanonly;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.lab.dal.redis.LabTaskSeqRedisDAO;
import org.junit.jupiter.api.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class BusinessNumberTest {
private final JdbcTemplate jdbc=mock(JdbcTemplate.class);
private final StringRedisTemplate redis=mock(StringRedisTemplate.class);
private final LabTaskSeqRedisDAO numbers=new LabTaskSeqRedisDAO();
@BeforeEach void setup(){
TenantContextHolder.setTenantId(7L);
ReflectionTestUtils.setField(numbers,"jdbcTemplate",jdbc);
ReflectionTestUtils.setField(numbers,"stringRedisTemplate",redis);
}
@AfterEach void cleanup(){TenantContextHolder.clear();}
@Test void recoversAbovePersistedNumbersInTheCurrentTenantAfterRedisReset(){
when(jdbc.queryForObject(anyString(),eq(Long.class),any(Object[].class))).thenAnswer(inv->{
assertTrue(inv.getArgument(0,String.class).contains("`lab_test_task`"));
assertFalse(inv.getArgument(0,String.class).contains("deleted=0"));
assertEquals(Long.valueOf(7),inv.getArgument(3,Long.class));
return 40L;
});
when(redis.execute(any(RedisScript.class),anyList(),any(Object[].class))).thenAnswer(inv->{
assertEquals("40",inv.getArgument(2));
assertTrue(inv.getArgument(1,java.util.List.class).get(0).toString().contains(":7:T:"));
return 41L;
});
assertTrue(numbers.nextTaskNo().endsWith("-0041"));
}
@Test void missingRedisResultCannotSilentlyReuseNumberOne(){
when(jdbc.queryForObject(anyString(),eq(Long.class),any(Object[].class))).thenReturn(2L);
assertThrows(IllegalStateException.class,()->numbers.nextExecutionNo());
}
@Test void rejectsUnregisteredNumberPrefixesBeforeDatabaseAccess(){
assertThrows(IllegalArgumentException.class,()->numbers.nextNo("UNTRUSTED"));
verifyNoInteractions(jdbc,redis);
}
}

View File

@ -0,0 +1,77 @@
package cn.iocoder.yudao.module.lab.service.scanonly;
import cn.iocoder.yudao.module.lab.controller.admin.master.LabLaboratoryController;
import cn.iocoder.yudao.module.lab.controller.admin.master.vo.attachment.LabMasterAttachmentSaveReqVO;
import cn.iocoder.yudao.module.lab.dal.dataobject.master.*;
import cn.iocoder.yudao.module.lab.dal.mysql.master.*;
import cn.iocoder.yudao.module.lab.service.master.*;
import cn.iocoder.yudao.framework.security.core.service.SecurityFrameworkService;
import org.junit.jupiter.api.*;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class MasterBoundaryTest {
private final LabMasterAttachmentMapper attachments=mock(LabMasterAttachmentMapper.class);
private final LabSampleMapper samples=mock(LabSampleMapper.class);
private final SecurityFrameworkService security=mock(SecurityFrameworkService.class);
private final LabMasterAttachmentServiceImpl service=new LabMasterAttachmentServiceImpl();
@BeforeEach void setup(){
ReflectionTestUtils.setField(service,"attachmentMapper",attachments);
ReflectionTestUtils.setField(service,"samples",samples);
ReflectionTestUtils.setField(service,"security",security);
}
@Test void missingLaboratoryDoesNotThrowNullPointerException(){
var controller=new LabLaboratoryController();
ReflectionTestUtils.setField(controller,"laboratoryService",mock(LabLaboratoryService.class));
assertNull(controller.get(999L).getData());
}
@Test void resourceMutationMissingIdIsAValidationFailure(){
var service=new ScanResourceService();
for(Long id:new Long[]{null,0L,-1L})
assertThrows(cn.iocoder.yudao.framework.common.exception.ServiceException.class,()->service.guardReservationMutation("LAB",id));
}
@Test void malformedComparisonIdsDoNotReachResultQueries(){
var controller=new cn.iocoder.yudao.module.lab.controller.admin.result.LabResultController();
var results=mock(cn.iocoder.yudao.module.lab.service.result.LabResultService.class);
ReflectionTestUtils.setField(controller,"resultService",results);
for(String ids:new String[]{"bad","1,","1,,2","9223372036854775808","0","1,2,3,4,5"})
assertThrows(cn.iocoder.yudao.framework.common.exception.ServiceException.class,()->controller.compare(1L,ids),ids);
verifyNoInteractions(results);
controller.compare(1L,"1, 2");
verify(results).compare(1L,java.util.List.of(1L,2L));
}
@Test void deniedPermissionPreventsAttachmentWritesAndReads(){
assertThrows(AccessDeniedException.class,()->service.createAttachment(request("https://example.test/file")));
assertThrows(AccessDeniedException.class,()->service.getAttachmentList("SAMPLE",1L));
verifyNoInteractions(samples,attachments);
}
@Test void deletionChecksStoredBusinessTypeBeforeDeleting(){
var row=new LabMasterAttachmentDO();row.setBizType("SAMPLE");row.setBizId(1L);
when(attachments.selectById(2L)).thenReturn(row);
assertThrows(AccessDeniedException.class,()->service.deleteAttachment(2L));
verify(attachments,never()).deleteById(anyLong());
}
@Test void missingParentAndUnsupportedBusinessTypeCannotCreateOrphans(){
when(security.hasPermission("lab:sample:update")).thenReturn(true);
assertThrows(RuntimeException.class,()->service.createAttachment(request("https://example.test/file")));
var request=request("https://example.test/file");request.setBizType("UNSUPPORTED");
assertThrows(RuntimeException.class,()->service.createAttachment(request));
verifyNoInteractions(attachments);
}
@Test void rejectsExecutableAndAmbiguousUrlsButAcceptsWebDownloads(){
when(security.hasPermission("lab:sample:update")).thenReturn(true);
when(samples.selectById(1L)).thenReturn(new LabSampleDO());
for(String url:new String[]{"javascript:alert(1)","data:text/html,bad","file:///tmp/file","//example.test/file","https://user:password@example.test/file"})
assertThrows(RuntimeException.class,()->service.createAttachment(request(url)),url);
verifyNoInteractions(attachments);
service.createAttachment(request("https://example.test/file.txt"));
service.createAttachment(request("/admin-api/infra/file/1/get/file.txt"));
verify(attachments,times(2)).insert(any(LabMasterAttachmentDO.class));
}
private LabMasterAttachmentSaveReqVO request(String url){
var request=new LabMasterAttachmentSaveReqVO();request.setBizType("SAMPLE");request.setBizId(1L);
request.setFileName("fixture.txt");request.setFileUrl(url);request.setFileType("OTHER");return request;
}
}

View File

@ -0,0 +1,46 @@
package cn.iocoder.yudao.module.lab.service.scanonly;
import cn.iocoder.yudao.module.lab.service.document.LabDocumentServiceImpl;
import cn.iocoder.yudao.module.lab.dal.mysql.document.*;
import cn.iocoder.yudao.module.lab.dal.dataobject.document.*;
import org.junit.jupiter.api.*;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.List;
class ReportRevisionTest {
private final LabReportMapper reports=mock(LabReportMapper.class);
private final LabReportVersionMapper versions=mock(LabReportVersionMapper.class);
private final LabDocumentServiceImpl service=new LabDocumentServiceImpl();
private final LabReportDO report=LabReportDO.builder().id(1L).status("PUBLISHED").formalVersionId(11L).build();
@BeforeEach void setup(){
ReflectionTestUtils.setField(service,"reportMapper",reports);
ReflectionTestUtils.setField(service,"versionMapper",versions);
when(reports.selectByIdForUpdate(1L)).thenReturn(report);
}
@Test void repeatedSavesUpdateOneDraftAndLeaveFormalContentUntouched(){
var formal=LabReportVersionDO.builder().id(11L).versionNo(1).status("PUBLISHED").contentHtml("formal").build();
var draft=LabReportVersionDO.builder().id(12L).versionNo(2).status("DRAFT").build();
when(versions.selectListByReportId(1L)).thenReturn(List.of(draft,formal));
service.updateDraft(1L,"first","title");service.updateDraft(1L,"second","title");
verify(versions,never()).insert(any(LabReportVersionDO.class));
verify(versions,times(2)).updateById(draft);
assertEquals("second",draft.getContentHtml());assertEquals("formal",formal.getContentHtml());
verify(reports,times(2)).selectByIdForUpdate(1L);
}
@Test void firstRevisionCreatesExactlyOneDraftAfterLockingReport(){
when(versions.selectListByReportId(1L)).thenReturn(List.of());
when(versions.selectMaxVersion(1L)).thenReturn(1);
when(versions.selectById(11L)).thenReturn(LabReportVersionDO.builder().contentHtml("formal").build());
service.updateDraft(1L,null,"title");
var captor=org.mockito.ArgumentCaptor.forClass(LabReportVersionDO.class);
verify(versions).insert(captor.capture());
assertEquals(2,captor.getValue().getVersionNo());assertEquals("formal",captor.getValue().getContentHtml());
}
@Test void voidReportCannotBePublishedAgain(){
report.setStatus("VOID");
assertThrows(cn.iocoder.yudao.framework.common.exception.ServiceException.class,()->service.publish(1L));
verifyNoInteractions(versions);
}
}

View File

@ -1,3 +1,16 @@
cmvr:
scanner:
# 待现场确认。端口为空时不连接设备;18888/18890不能混用。
host: ${AM_FREESCAN_SCANNER_HOST:}
port: ${AM_FREESCAN_SCANNER_PORT:}
api-key: ${AM_FREESCAN_SCANNER_API_KEY:}
robot-id: ${AM_FREESCAN_SCANNER_ROBOT_ID:}
device-id: ${AM_FREESCAN_SCANNER_DEVICE_ID:}
connect-timeout-ms: 5000
request-timeout-ms: 15000
operation-timeout-ms: 120000
poll-interval-ms: 500
spring:
application:
name: am-freescan

View File

@ -29,7 +29,7 @@ export const getReportPage = (params: any) => request.get({ url: '/lab/document/
export const getReport = (id: number | string) => request.get({ url: '/lab/document/report/get', params: { id } })
export const createReport = (data: any) => request.post({ url: '/lab/document/report/create', data })
export const updateReport = (id: number | string, title: string, contentHtml: string) =>
request.post({ url: '/lab/document/report/update', params: { id, title }, data: contentHtml })
request.post({ url: '/lab/document/report/update', params: { id, title }, data: contentHtml, headersType: 'text/plain; charset=UTF-8' })
export const publishReport = (id: number | string) => request.post({ url: '/lab/document/report/publish', params: { id } })
export const voidReport = (id: number | string, reason: string) =>
request.post({ url: '/lab/document/report/void', params: { id, reason } })

View File

@ -171,11 +171,11 @@ export const addAttachment = (data: {
}) => request.post({ url: base + '/attachment', data })
export const deleteAttachment = (taskId: Id, id: Id) =>
request.delete({ url: base + '/attachment', params: { taskId, id } })
export const getCmvrBinding = (executionId: Id) =>
export const getCmvrBinding = (executionId: Id, signal?: AbortSignal) =>
request.get<{
cmvrTaskId: string
cmvrInstId: string
versionNo: number
flowData: string
testCaseId: string
}>({ url: '/lab/execution/cmvr-binding', params: { executionId } })
}>({ url: '/lab/execution/cmvr-binding', params: { executionId }, signal })

View File

@ -0,0 +1,63 @@
import request from '@/config/axios'
import { getAccessToken, getTenantId, getVisitTenantId } from '@/utils/auth'
import { readScannerBinary } from '@/views/lab/scan-task/scannerBinary.mjs'
export interface ScannerExecutionView {
executionId: string
executionNo?: string
taskId?: string
sampleUnitId?: string
executionStatus?: string
available: boolean
state: string
message?: string
robotId?: string
deviceId?: string
sessionId?: string
projectId?: string
scanning?: boolean
previewEnabled?: boolean
meshState?: string
}
const path = '/lab/execution/scanner-view'
export const getScannerExecutionView = (executionId: string | number, signal?: AbortSignal) =>
request.get<ScannerExecutionView>({ url: path, params: { executionId }, signal })
export interface ScannerAsset { fileId: string; name: string; bytes?: number; projectId?: string; capturedAt?: number; commandKey?: string }
export interface ScannerSnapshotCommand { commandKey?: string; key?: string; state: string; taskId?: string; error?: string; result?: string }
export const getScannerAssets = (executionId: string | number, signal?: AbortSignal) =>
request.get<ScannerAsset[]>({ url: path + '/assets', params: { executionId }, signal })
export const createScannerSnapshot = (executionId: string | number, commandKey: string, signal?: AbortSignal) =>
request.post<ScannerSnapshotCommand>({ url: path + '/snapshot', params: { executionId }, data: {}, headers: { 'X-Scanner-Command-Key': commandKey }, signal })
export const getScannerSnapshotCommand = (executionId: string | number, commandKey: string, signal?: AbortSignal) =>
request.get<ScannerSnapshotCommand>({ url: path + '/snapshot-command', params: { executionId, commandKey }, signal })
function scannerHeaders() {
const headers: Record<string, string> = { Authorization: `Bearer ${getAccessToken()}`, 'tenant-id': String(getTenantId() || 1) }
const visit = getVisitTenantId()
if (visit) headers['visit-tenant-id'] = String(visit)
return headers
}
export async function getScannerAsset(executionId: string | number, fileId: string, signal: AbortSignal) {
const response = await fetch(`${import.meta.env.VITE_BASE_URL}/admin-api${path}/asset/${encodeURIComponent(fileId)}?executionId=${encodeURIComponent(executionId)}`, { headers: scannerHeaders(), signal })
if (!response.ok || response.headers.get('content-type')?.includes('application/json')) {
const error = await response.json().catch(() => ({}))
throw new Error(error.msg || '三维文件不可用;扫描服务重启后原下载编号可能失效')
}
return readScannerBinary(response)
}
export async function getScannerExecutionImage(executionId: string | number, signal: AbortSignal) {
const headers: Record<string, string> = {
Authorization: `Bearer ${getAccessToken()}`,
'tenant-id': String(getTenantId() || 1)
}
const visit = getVisitTenantId()
if (visit) headers['visit-tenant-id'] = String(visit)
const response = await fetch(`${import.meta.env.VITE_BASE_URL}/admin-api${path}/image?executionId=${encodeURIComponent(executionId)}`, { headers, signal, cache: 'no-store' })
if (!response.ok || !response.headers.get('content-type')?.startsWith('image/jpeg')) {
const error = await response.json().catch(() => ({}))
throw new Error(error.msg || '扫描画面暂不可用,正在重新核对状态')
}
return response.blob()
}

View File

@ -2,7 +2,10 @@
* 平台设备类型枚举,供流程资源匹配、机器人设备筛选和界面展示共同使用。
* Object.freeze 防止运行期间被改写,数值与后端 deviceKind 协议保持一致。
*/
import { WORKCELL_ACTION_KINDS, WORKCELL_DEVICE_KIND } from '../../common/utils/scanMotorNodes.mjs'
export const DEVICE_KIND = Object.freeze({
...WORKCELL_DEVICE_KIND,
AGV: 1,
ARM: 2,
BIO_HEAD: 4,
@ -17,6 +20,7 @@ export const DEVICE_KIND = Object.freeze({
* 作用范围为所有根据 action 判断执行设备的流程模块;未列出的动作视为没有固定设备类型。
*/
export const DEVICE_KIND_BY_ACTION = Object.freeze({
...WORKCELL_ACTION_KINDS,
AGV_MOVE_TO_POINT: DEVICE_KIND.AGV,
AGV_MOVE_TO_STATION: DEVICE_KIND.AGV,
ARM_MOVE_TO_POINT: DEVICE_KIND.ARM,

View File

@ -49,6 +49,7 @@ export function flowAction(data) {
return request({
url: '/flow/action',
method: 'post',
timeout: String(data.action || '').startsWith('SCANNER_') ? Math.min(3600000, Number(data.payload?.timeoutMs) || 120000) + 10000 : 60000,
data: data
})
}

View File

@ -0,0 +1,38 @@
import request, { cmvrApiBase } from '@/cmvr/request'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { SCANNER_OPERATIONS } from '../../utils/scannerOperations.mjs'
const base = '/scanner'
const operation = (key) => {
const value = SCANNER_OPERATIONS.find((item) => item.key === key)
if (!value) throw new Error('扫描操作不存在')
return value
}
export const getScannerConfiguration = () => request.get(base + '/configuration')
export const validateScannerRequest = (key, requestJson) => request.post(base + '/validate', { operation: key, requestJson })
export const getScannerCommand = (key) => request.get(base + '/commands/' + encodeURIComponent(key))
export function queryScanner(key, id) {
const op = operation(key)
if (op.method !== 'GET') throw new Error('此操作不是查询接口')
const path = op.path.replace('{taskId}', encodeURIComponent(id || ''))
return request.get(base + path)
}
export function submitScanner(key, requestJson, commandKey) {
const op = operation(key)
if (op.method !== 'POST') throw new Error('此操作不是控制接口')
return request.post(base + op.path, requestJson, {
headers: { 'Content-Type': 'application/json', 'X-Scanner-Command-Key': commandKey },
})
}
export async function scannerBinary(key, id, signal) {
const op = operation(key)
if (!['FILE', 'PREVIEW_IMAGE', 'PREVIEW_STREAM'].includes(key)) throw new Error('此操作不返回文件或图像')
const response = await fetch(cmvrApiBase + base + op.path.replace('{fileId}', encodeURIComponent(id || '')), {
headers: { Authorization: `Bearer ${getAccessToken()}`, 'tenant-id': String(getTenantId() || 1) }, signal,
})
if (!response.ok || response.headers.get('content-type')?.includes('application/json')) {
const error = await response.json().catch(() => ({}))
throw new Error(error.msg || error.error?.message || `扫描服务返回 ${response.status}`)
}
return response
}

View File

@ -61,11 +61,12 @@ export function rerunInst(id) {
}
// 查询任务实例日志
export function getInst(query) {
export function getInst(query, signal) {
return request({
url: '/test/inst/log/detail',
method: 'get',
params: query
params: query,
signal
})
}

View File

@ -1,4 +1,5 @@
import { getDeviceKindForAction } from '@/cmvr/common/utils/robotDevice'
import { getDeviceKindForAction } from './robotDevice.js'
import { validateWorkcellLiterals } from './scanMotorNodes.mjs'
export const FLOW_SCHEMA_VERSION = 2
export const DEFAULT_ROLE_KEY = 'default_executor'
@ -25,8 +26,10 @@ const DEVICE_KIND_META = Object.freeze({
4: { key: 'bio_head', name: '仿生头' },
5: { key: 'camera', name: '摄像头' },
9: { key: 'microphone', name: '麦克风' },
10: { key: 'motor', name: '电机' },
12: { key: 'robot', name: '机器人本体' },
13: { key: 'speaker', name: '扬声器' },
14: { key: 'scanner', name: '扫描仪' },
})
const clone = (value) => JSON.parse(JSON.stringify(value ?? null))
@ -330,6 +333,9 @@ export const validateFlowResources = (sourceGraph) => {
})
graph.nodes.filter(isRobotNode).forEach((node) => {
validateWorkcellLiterals(node.properties?.action, node.properties?.nodeParams).forEach((message) => {
errors.push({ nodeId: node.id, message })
})
const target = node.properties?.executionTarget
const role = roles.find((item) => item.roleKey === target?.roleKey)
if (!role) {
@ -339,6 +345,12 @@ export const validateFlowResources = (sourceGraph) => {
if (target.deviceSlotKey && !(role.deviceSlots || []).some((slot) => slot.slotKey === target.deviceSlotKey)) {
errors.push({ nodeId: node.id, message: `${node.properties?.name || node.id}引用的设备用途不存在` })
}
const expectedKind = getDeviceKindForAction(node.properties?.action)
const selectedSlot = role.deviceSlots?.find((slot) => slot.slotKey === target.deviceSlotKey)
if (expectedKind != null && selectedSlot?.deviceKind != null
&& Number(selectedSlot.deviceKind) !== Number(expectedKind)) {
errors.push({ nodeId: node.id, message: `${node.properties?.name || node.id}的设备用途类型不匹配` })
}
;(target.deviceBindings || []).forEach((binding) => {
if (!binding?.parameterName || !binding?.slotKey) {
errors.push({ nodeId: node.id, message: `${node.properties?.name || node.id}存在未配置的设备绑定` })

View File

@ -2,7 +2,10 @@
* 平台设备类型枚举,供流程资源匹配、机器人设备筛选和界面展示共同使用。
* Object.freeze 防止运行期间被改写,数值与后端 deviceKind 协议保持一致。
*/
import { WORKCELL_ACTION_KINDS, WORKCELL_DEVICE_KIND } from './scanMotorNodes.mjs'
export const DEVICE_KIND = Object.freeze({
...WORKCELL_DEVICE_KIND,
AGV: 1,
ARM: 2,
BIO_HEAD: 4,
@ -17,6 +20,7 @@ export const DEVICE_KIND = Object.freeze({
* 作用范围为所有根据 action 判断执行设备的流程模块;未列出的动作视为没有固定设备类型。
*/
export const DEVICE_KIND_BY_ACTION = Object.freeze({
...WORKCELL_ACTION_KINDS,
AGV_MOVE_TO_POINT: DEVICE_KIND.AGV,
AGV_MOVE_TO_STATION: DEVICE_KIND.AGV,
ARM_MOVE_TO_POINT: DEVICE_KIND.ARM,

View File

@ -0,0 +1,119 @@
// Platform workflow kinds. Scanner 14 is a platform extension, not a vendor SDK enum.
import { SCANNER_OPERATIONS, getScannerOperation } from './scannerOperations.mjs'
export const WORKCELL_DEVICE_KIND = Object.freeze({ MOTOR: 10, SCANNER: 14 })
const field = (name, label, input, options = {}) => ({
name, label, type: 'input', input, required: true, disabled: true, ...options,
})
const timeout = () => field('timeoutMs', '超时(毫秒)', 60000, {
componentType: 'number', min: 1, max: 3600000, step: 1,
})
const unit = () => field('unit', '位置单位', 'DEGREE', {
componentType: 'select', selectOptions: [
{ value: 'DEGREE', label: '度' },
{ value: 'MILLIMETER', label: '毫米' },
{ value: 'PULSE', label: '脉冲' },
],
})
const number = (name, label, input, min = 0) => field(name, label, input, {
componentType: 'number', min, step: 0.01, precision: 4,
})
const output = (name, type, desc) => ({ name, type, desc, disabled: true, children: [] })
const position = () => number('targetPosition', '目标位置', 0, -1e9)
const queryOutputs = {
METADATA: [['service', 'string'], ['apiVersion', 'string'], ['routes', 'array<string>']],
HEALTH: [['running', 'boolean'], ['service', 'string'], ['utc', 'string']],
STATUS: [['state', 'string'], ['sessionId', 'string'], ['projectId', 'string'], ['scanning', 'boolean'], ['busy', 'boolean'], ['meshState', 'string'], ['projectReady', 'boolean'], ['deviceOnline', 'boolean'], ['stateUncertain', 'boolean'], ['restartRequired', 'boolean']],
CAPABILITIES: [['exportFormats', 'array<string>'], ['controls', 'object'], ['features', 'object'], ['calibration', 'object'], ['rawDataAvailable', 'boolean']],
SCENE: [['available', 'boolean'], ['projectUuid', 'string'], ['cloudUuid', 'string'], ['pointIdsAvailable', 'boolean'], ['pointCount', 'number'], ['markerCount', 'number']],
METRICS: [['latestSequence', 'number'], ['averageEncodedFps', 'number'], ['frameAgeMs', 'number'], ['encoderRunning', 'boolean']],
}
function scannerOutputs(op) {
const fields = op.method === 'POST' || op.key === 'TASK'
? [output('taskId', 'string', '设备命令编号'), output('state', 'string', '设备任务状态'),
{ ...output('result', 'object', '设备操作结果'), children: [output('projectId', 'string', '工程目录编号'), output('files', 'array<object>', '可下载成果文件')] }]
: (queryOutputs[op.key] || []).map(([name, type]) => output(name, type, '设备接口原始字段'))
return [...fields, output('responseJson', 'string', '完整响应 JSON 文本,保留64位整数')]
}
const specs = [
['MOTOR_ENABLE', '电机使能', '开启电机使能', []],
['MOTOR_DISABLE', '电机去使能', '关闭电机使能', []],
['MOTOR_HOME', '电机回零', '按设备配置执行回零并等待完成', []],
['MOTOR_MOVE', '电机定位', '按指定单位运动到绝对位置', [
position(), unit(), number('velocity', '速度(位置单位/秒)', 1, 0.0001),
number('acceleration', '加速度(位置单位/秒²)', 1, 0.0001),
]],
['MOTOR_WAIT', '等待电机到位', '确认电机已停止且在目标位置容差内', [position(), unit(), number('tolerance', '允许位置误差', 0.1)]],
['MOTOR_STOP', '停止电机', '请求停止并等待设备确认', []],
['MOTOR_STATUS', '读取电机状态', '读取实际位置、运动状态和故障', []],
]
export const WORKCELL_ACTION_KINDS = Object.freeze(Object.fromEntries([...specs, ...SCANNER_OPERATIONS.filter((op) => op.action).map((op) => [op.action])].map(([action]) => [
action, action.startsWith('SCANNER_') ? WORKCELL_DEVICE_KIND.SCANNER : WORKCELL_DEVICE_KIND.MOTOR,
])))
export const isWorkcellAction = (action) => Object.hasOwn(WORKCELL_ACTION_KINDS, action || '')
export function createWorkcellNodeGroups(icons = {}) {
const scannerGroup = {
collapseTitle: '扫描仪',
nodeList: SCANNER_OPERATIONS.filter((op) => op.action).map((op) => ({
icon: icons.SCANNER, name: op.title, type: 'serviceNode', nodeType: 'EDGE', action: op.action,
scannerOperation: op.key,
desc: op.method === 'POST' ? '提交设备操作并等待任务结果' : op.key === 'TASK' ? '等待设备命令终态,不代表整件扫描完成' : '读取扫描服务数据',
nodeParams: [
...(op.method === 'POST' ? [field('requestJson', '扫描操作参数', JSON.stringify(op.defaultBody, null, 2))] : []),
...(op.key === 'TASK' ? [field('taskId', '设备任务编号', '')] : []),
{ ...timeout(), input: 120000 },
],
outputType: 'json',
outputParams: scannerOutputs(op),
})),
}
return [scannerGroup, ...['MOTOR'].map((family) => ({
collapseTitle: '电机',
nodeList: specs.filter(([action]) => action.startsWith(`${family}_`)).map(([action, name, desc, params]) => ({
icon: icons[family], name, desc, action, type: 'serviceNode', nodeType: 'EDGE',
nodeParams: structuredClone([...params, timeout()]), outputType: 'json',
outputParams: [output('position', 'number', '实际位置'), output('unit', 'string', '位置单位'),
output('state', 'string', '电机状态')],
})),
}))]
}
// Only literal values can be checked before execution. Quoted values are checked after resolution.
export function validateWorkcellLiterals(action, params = []) {
if (!isWorkcellAction(action)) return []
const errors = []
const scanner = getScannerOperation(action)
if (!params.some(param => param.name === 'timeoutMs')) errors.push('缺少超时(毫秒)参数,请重新配置节点')
if (scanner?.key === 'TASK' && !params.some(param => param.name === 'taskId')) errors.push('缺少设备任务编号')
if (scanner && params.some((param) => ['planCode', 'jobId', 'format'].includes(param.name))) errors.push('旧扫描节点参数与真实接口不一致,请重新配置')
for (const param of params) {
if (param.type !== 'input') continue
const label = param.label || param.name
const value = param.input
if (param.required && (value == null || String(value).trim() === '')) {
errors.push(`${label}不能为空`)
continue
}
if (param.componentType === 'number' && value != null) {
if (typeof value !== 'number' || !Number.isFinite(value)
|| (param.min != null && value < param.min) || (param.max != null && value > param.max)
|| (param.name === 'timeoutMs' && !Number.isInteger(value))) errors.push(`${label}超出有效范围`)
}
if (param.componentType === 'select' && !param.selectOptions?.some((item) => item.value === value)) {
errors.push(`${label}无效`)
}
if (scanner && param.name === 'requestJson') {
try {
const body = JSON.parse(value)
if (!body || typeof body !== 'object' || Array.isArray(body)) errors.push('扫描参数必须为JSON对象')
} catch { errors.push('扫描参数JSON格式无效') }
}
if (scanner?.key === 'TASK' && param.name === 'taskId' && value && !/^[a-fA-F0-9]{32}$/.test(value)) errors.push('设备任务编号必须为32位十六进制字符')
}
return errors
}

View File

@ -0,0 +1,99 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { createWorkcellNodeGroups, validateWorkcellLiterals } from './scanMotorNodes.mjs'
import { getDeviceKindForAction } from './robotDevice.js'
import { normalizeFlowResourceSchema, validateFlowResources, pruneUnusedNodeResources } from './flowResources.js'
import { SCANNER_OPERATIONS } from './scannerOperations.mjs'
const node = (action, id = action) => ({
id, type: 'serviceNode', properties: structuredClone(
createWorkcellNodeGroups().flatMap((group) => group.nodeList).find((item) => item.action === action),
),
})
const set = (item, name, value) => { item.properties.nodeParams.find((param) => param.name === name).input = value }
const graph = (...nodes) => ({ nodes: [
{ id: 'start', type: 'start', properties: { action: 'START', nodeType: 'NONE' } }, ...nodes,
], edges: [] })
test('扫描与运动流程保存后保留设备角色、作业引用和负数位置', () => {
const scan = node('SCANNER_START', 'scan')
const wait = node('SCANNER_WAIT', 'wait')
Object.assign(wait.properties.nodeParams.find((param) => param.name === 'taskId'), {
type: 'quote', quoteType: 'output', quote: ['scan', 'OUTPUT', 'taskId'],
})
const move = node('MOTOR_MOVE', 'move')
set(move, 'targetPosition', -45.25)
const saved = JSON.parse(JSON.stringify(normalizeFlowResourceSchema(graph(scan, wait, move))))
assert.deepEqual(validateFlowResources(saved).errors, [])
const roles = saved.nodes[0].properties.resourceRoles
assert.deepEqual(roles[0].deviceSlots.map((slot) => slot.deviceKind).sort(), [10, 14])
assert.deepEqual(saved.nodes[2].properties.nodeParams[0].quote, ['scan', 'OUTPUT', 'taskId'])
assert.equal(saved.nodes[3].properties.nodeParams[0].input, -45.25)
assert.equal(pruneUnusedNodeResources(saved).removedSlots, 0)
})
test('修改已保存流程的设备用途不能把扫描动作绑定到电机', () => {
const saved = normalizeFlowResourceSchema(graph(node('SCANNER_STATUS'), node('MOTOR_STATUS')))
saved.nodes[1].properties.executionTarget.deviceSlotKey = saved.nodes[2].properties.executionTarget.deviceSlotKey
assert.match(validateFlowResources(saved).errors.map((item) => item.message).join(','), /类型不匹配/)
})
test('扫描作业编号允许引用,但不允许空的字面量', () => {
const wait = node('SCANNER_WAIT')
assert.match(validateWorkcellLiterals('SCANNER_WAIT', wait.properties.nodeParams).join(','), /任务编号/)
Object.assign(wait.properties.nodeParams[0], { type: 'quote', quote: ['scan', 'OUTPUT', 'taskId'] })
assert.deepEqual(validateWorkcellLiterals('SCANNER_WAIT', wait.properties.nodeParams), [])
})
test('超时必须为整数,电机允许负位置但不允许零速度或负容差', () => {
const move = node('MOTOR_MOVE')
set(move, 'targetPosition', -1)
set(move, 'velocity', 0)
set(move, 'timeoutMs', 1.5)
assert.equal(validateWorkcellLiterals('MOTOR_MOVE', move.properties.nodeParams).length, 2)
const wait = node('MOTOR_WAIT')
set(wait, 'tolerance', -0.1)
assert.match(validateWorkcellLiterals('MOTOR_WAIT', wait.properties.nodeParams).join(','), /误差/)
})
test('各动作正确筛选设备,拖入多个节点时参数互不污染', () => {
const first = createWorkcellNodeGroups()
first[0].nodeList[1].nodeParams[0].input = 'CHANGED'
assert.equal(createWorkcellNodeGroups()[0].nodeList[1].nodeParams[0].input, '{\n "mode": "trak"\n}')
for (const group of createWorkcellNodeGroups()) for (const item of group.nodeList) {
assert.equal(getDeviceKindForAction(item.action), group.collapseTitle === '扫描仪' ? 14 : 10)
}
assert.equal(getDeviceKindForAction('DEVICE_EXECUTE_JSON_COMMAND'), 2)
})
test('37个接口映射34个工作流动作,预览和下载由面板调用', () => {
assert.equal(SCANNER_OPERATIONS.length, 37)
assert.equal(SCANNER_OPERATIONS.filter(op => op.method === 'POST').length, 27)
const nodes = createWorkcellNodeGroups()[0].nodeList
assert.equal(nodes.length, 34)
assert.equal(new Set(nodes.map(node => node.action)).size, 34)
assert.deepEqual(SCANNER_OPERATIONS.filter(op => !op.action).map(op => op.key), ['PREVIEW_IMAGE', 'PREVIEW_STREAM', 'FILE'])
const start = nodes.find(node => node.action === 'SCANNER_START')
assert.equal(start.nodeParams.find(param => param.name === 'requestJson').input, '{}')
assert.equal(start.outputParams[0].name, 'taskId')
})
test('JSON和任务编号校验,保留64位整数文本,拒绝旧协议字段', () => {
const edit = node('SCANNER_EDIT')
const body = '{"projectUuid":"p","pointIds":[9007199254740993],"confirm":true}'
set(edit, 'requestJson', body)
assert.deepEqual(validateWorkcellLiterals('SCANNER_EDIT', edit.properties.nodeParams), [])
assert.equal(JSON.parse(JSON.stringify(edit)).properties.nodeParams[0].input, body)
set(edit, 'requestJson', '[]')
assert.match(validateWorkcellLiterals('SCANNER_EDIT', edit.properties.nodeParams).join(','), /JSON对象/)
const wait = node('SCANNER_WAIT')
set(wait, 'taskId', 'NOT-A-TASK')
assert.match(validateWorkcellLiterals('SCANNER_WAIT', wait.properties.nodeParams).join(','), /32位/)
assert.match(validateWorkcellLiterals('SCANNER_START', [{ name: 'planCode', type: 'input', input: 'old' }]).join(','), /旧扫描/)
})
test('导入或编辑后缺少超时、设备任务编号时阻止执行', () => {
assert.match(validateWorkcellLiterals('SCANNER_START', []).join(','), /缺少超时/)
const wait = node('SCANNER_WAIT')
assert.match(validateWorkcellLiterals('SCANNER_WAIT', wait.properties.nodeParams.filter(p => p.name !== 'taskId')).join(','), /缺少设备任务编号/)
})

View File

@ -0,0 +1,34 @@
// Parse Content-Length framed JPEG parts after fetch has decoded HTTP chunking.
export async function consumeScannerMjpeg(stream, onFrame, signal) {
const reader = stream.getReader()
const header = new Uint8Array(16 * 1024)
let headerLength = 0, frame, received = 0
const decoder = new TextDecoder()
const abort = () => { void reader.cancel().catch(() => {}) }
signal?.addEventListener('abort', abort, { once: true })
try {
while (!signal?.aborted) {
const { done, value } = await reader.read()
if (done || signal?.aborted) break
let offset = 0
while (offset < value.length && !signal?.aborted) {
if (!frame) {
if (headerLength === header.length) throw new Error('预览帧头超过大小限制')
header[headerLength++] = value[offset++]
if (headerLength < 4 || header[headerLength-4] !== 13 || header[headerLength-3] !== 10 || header[headerLength-2] !== 13 || header[headerLength-1] !== 10) continue
const match = /Content-Length:\s*(\d+)/i.exec(decoder.decode(header.subarray(0, headerLength-4)))
if (!match) throw new Error('预览帧缺少长度信息')
const length = Number(match[1])
if (!Number.isSafeInteger(length) || length < 1 || length > 20 * 1024 * 1024) throw new Error('预览帧长度无效')
// Allocate once per frame, not once per HTTP chunk. This keeps a
// fragmented multi-megabyte JPEG linear in size instead of quadratic.
frame = new Uint8Array(length); received = 0; headerLength = 0
}
const count = Math.min(frame.length-received, value.length-offset)
frame.set(value.subarray(offset,offset+count),received); received += count; offset += count
if (received === frame.length) { await onFrame(frame); frame = undefined; received = 0 }
}
}
if (frame && !signal?.aborted) throw new Error('预览帧数据不完整')
} finally { signal?.removeEventListener('abort',abort); await reader.cancel().catch(() => {}); reader.releaseLock() }
}

View File

@ -0,0 +1,51 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { consumeScannerMjpeg } from './scannerMjpeg.mjs'
const bytes = text => new TextEncoder().encode(text)
const streamOf = chunks => new ReadableStream({ start(controller) { chunks.forEach(chunk => controller.enqueue(chunk)); controller.close() } })
const part = value => bytes(`--scanframe\r\nContent-Type: image/jpeg\r\nContent-Length: ${value.length}\r\n\r\n${value}\r\n`)
test('MJPEG帧可跨任意网络分块,单块可包含多帧', async () => {
const joined = new Uint8Array([...part('JPEG1'), ...part('JPEG2'), ...bytes('--scanframe--\r\n')])
for (const chunks of [[joined], Array.from(joined, byte => new Uint8Array([byte]))]) {
const frames = []
await consumeScannerMjpeg(streamOf(chunks), frame => frames.push(new TextDecoder().decode(frame)))
assert.deepEqual(frames, ['JPEG1', 'JPEG2'])
}
})
test('JPEG内部包含换行及边界字节仍按Content-Length读取', async () => {
const content = 'a\r\n--scanframe\r\n\r\nb'
const frames = []
await consumeScannerMjpeg(streamOf([part(content)]), frame => frames.push(new TextDecoder().decode(frame)))
assert.deepEqual(frames, [content])
})
test('拒绝缺失或超大的帧长度,并在关闭时取消读取', async () => {
await assert.rejects(consumeScannerMjpeg(streamOf([bytes('--scanframe\r\nContent-Type: image/jpeg\r\n\r\nx')]), () => {}), /缺少长度/)
await assert.rejects(consumeScannerMjpeg(streamOf([bytes('--scanframe\r\nContent-Length: 999999999\r\n\r\nx')]), () => {}), /长度无效/)
const abort = new AbortController(); abort.abort()
let cancelled = false
await consumeScannerMjpeg(new ReadableStream({ cancel() { cancelled = true } }), () => {}, abort.signal)
assert.equal(cancelled, true)
})
test('大帧跨大量网络块仍保留完整字节,多帧合并网络块不会串帧', async () => {
const data = new Uint8Array(2*1024*1024).fill(123)
const header = new TextEncoder().encode(`--frame\r\nContent-Length: ${data.length}\r\n\r\n`)
const bytes = new Uint8Array(header.length+data.length); bytes.set(header); bytes.set(data,header.length)
let offset=0,frames=[]
await consumeScannerMjpeg(new ReadableStream({pull(c){if(offset>=bytes.length){c.close();return}c.enqueue(bytes.subarray(offset,offset+2048));offset+=2048}}),frame=>frames.push(frame))
assert.equal(frames.length,1);assert.deepEqual(frames[0],data)
const combined = new Uint8Array(bytes.length*2);combined.set(bytes);combined.set(bytes,bytes.length);frames=[]
await consumeScannerMjpeg(new ReadableStream({start(c){c.enqueue(combined);c.close()}}),frame=>frames.push(frame))
assert.equal(frames.length,2);assert.deepEqual(frames[1],data)
})
test('预览中断立即取消挂起的网络读取,拒绝超长帧头和截断的正文', async () => {
const controller=new AbortController();let cancelled=false
const pending=consumeScannerMjpeg(new ReadableStream({cancel(){cancelled=true}}),()=>assert.fail('不能收到迟到帧'),controller.signal)
controller.abort();await pending;assert.equal(cancelled,true)
await assert.rejects(consumeScannerMjpeg(new ReadableStream({start(c){c.enqueue(new Uint8Array(17000));c.close()}}),()=>{}),/帧头/)
const truncated=new TextEncoder().encode('--frame\r\nContent-Length: 100\r\n\r\nshort')
await assert.rejects(consumeScannerMjpeg(new ReadableStream({start(c){c.enqueue(truncated);c.close()}}),()=>{}),/不完整/)
})

View File

@ -0,0 +1,753 @@
// Generated from ScannerOperation.java by scripts/generate_scanner_frontend.py.
export const SCANNER_OPERATIONS = [
{
"key": "CONNECT",
"method": "POST",
"path": "/device/connect",
"title": "连接扫描仪",
"action": "SCANNER_INITIALIZE",
"defaultBody": {
"deviceType": 3
},
"fields": [
{
"key": "deviceType",
"label": "设备类型",
"type": "number",
"options": [
{
"value": 3,
"label": "单套 Trak Nova / Trak"
},
{
"value": 4,
"label": "多套设备"
}
],
"optional": false,
"nullable": false
}
],
"advanced": false
},
{
"key": "CREATE_PROJECT",
"method": "POST",
"path": "/projects",
"title": "创建扫描工程",
"action": "SCANNER_CREATE_PROJECT",
"defaultBody": {
"mode": "trak"
},
"fields": [
{
"key": "mode",
"label": "工程或标定模式",
"type": "text",
"options": [
{
"value": "trak",
"label": "trak"
},
{
"value": "laser",
"label": "laser"
}
],
"optional": false,
"nullable": false
},
{
"key": "name",
"label": "工程或导出名称",
"type": "text",
"options": null,
"optional": true,
"nullable": false
}
],
"advanced": false
},
{
"key": "DISCONNECT",
"method": "POST",
"path": "/device/disconnect",
"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": "舍弃尚未导出的内存工程",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
},
{
"key": "expectedProjectId",
"label": "已核对的工程目录编号",
"type": "text",
"options": null,
"optional": false,
"nullable": true
},
{
"key": "expectedSessionId",
"label": "已核对的设备会话编号",
"type": "text",
"options": null,
"optional": false,
"nullable": true
}
],
"advanced": false
},
{
"key": "RECONNECT",
"method": "POST",
"path": "/device/reconnect",
"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": "舍弃尚未导出的内存工程",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
},
{
"key": "expectedProjectId",
"label": "已核对的工程目录编号",
"type": "text",
"options": null,
"optional": false,
"nullable": true
},
{
"key": "expectedSessionId",
"label": "已核对的设备会话编号",
"type": "text",
"options": null,
"optional": false,
"nullable": true
},
{
"key": "deviceType",
"label": "设备类型",
"type": "number",
"options": [
{
"value": 3,
"label": "单套 Trak Nova / Trak"
},
{
"value": 4,
"label": "多套设备"
}
],
"optional": false,
"nullable": false
}
],
"advanced": false
},
{
"key": "PREVIEW_START",
"method": "POST",
"path": "/preview/start",
"title": "开启扫描预览",
"action": "SCANNER_PREVIEW_START",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "PREVIEW_STOP",
"method": "POST",
"path": "/preview/stop",
"title": "关闭扫描预览",
"action": "SCANNER_PREVIEW_STOP",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "SCAN_START",
"method": "POST",
"path": "/scan/start",
"title": "开始或继续采集",
"action": "SCANNER_START",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "SCAN_STOP",
"method": "POST",
"path": "/scan/stop",
"title": "暂停采集",
"action": "SCANNER_STOP",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "PREVIEW_IMAGE",
"method": "GET",
"path": "/preview/image",
"title": "扫描预览图像",
"action": "",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "PREVIEW_STREAM",
"method": "GET",
"path": "/preview/stream",
"title": "扫描实时预览",
"action": "",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "PARAMETERS",
"method": "POST",
"path": "/parameters",
"title": "配置扫描参数",
"action": "SCANNER_PARAMETERS",
"defaultBody": {
"pointDistance": 0.2,
"brightness": 8
},
"fields": [],
"advanced": true
},
{
"key": "MESH",
"method": "POST",
"path": "/mesh",
"title": "生成网格预览",
"action": "SCANNER_MESH",
"defaultBody": {},
"fields": [],
"advanced": true
},
{
"key": "MESH_CONFIRM",
"method": "POST",
"path": "/mesh/confirm",
"title": "确认扫描网格",
"action": "SCANNER_MESH_CONFIRM",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "MESH_UNDO",
"method": "POST",
"path": "/mesh/undo",
"title": "撤销扫描网格",
"action": "SCANNER_MESH_UNDO",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "ALIGN",
"method": "POST",
"path": "/align",
"title": "扫描工程拼接",
"action": "SCANNER_ALIGN",
"defaultBody": {
"action": "enter"
},
"fields": [],
"advanced": true
},
{
"key": "EDIT",
"method": "POST",
"path": "/edit",
"title": "删除扫描点或标志点",
"action": "SCANNER_EDIT",
"defaultBody": {
"projectUuid": "",
"markerIds": [],
"confirm": false
},
"fields": [],
"advanced": true
},
{
"key": "CLIP_PLANE",
"method": "POST",
"path": "/clip-plane",
"title": "平面裁剪",
"action": "SCANNER_CLIP_PLANE",
"defaultBody": {
"center": [
0,
0,
0
],
"normal": [
0,
0,
1
],
"deleteBelowPoints": false,
"deleteBelowMarkers": false,
"confirm": false
},
"fields": [],
"advanced": true
},
{
"key": "EXPORT",
"method": "POST",
"path": "/exports",
"title": "导出扫描成果",
"action": "SCANNER_EXPORT",
"defaultBody": {
"formats": [
"STL"
]
},
"fields": [
{
"key": "formats",
"label": "导出格式",
"type": "array",
"options": null,
"optional": false,
"nullable": false
},
{
"key": "name",
"label": "工程或导出名称",
"type": "text",
"options": null,
"optional": true,
"nullable": false
}
],
"advanced": false
},
{
"key": "SNAPSHOT",
"method": "POST",
"path": "/data/snapshots",
"title": "保存原始场景快照",
"action": "SCANNER_SNAPSHOT",
"defaultBody": {
"maxPoints": 100000,
"include": [
"points",
"markers",
"meshes"
]
},
"fields": [],
"advanced": true
},
{
"key": "SCENE",
"method": "GET",
"path": "/data/scene",
"title": "读取扫描场景摘要",
"action": "SCANNER_SCENE",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "FILE",
"method": "GET",
"path": "/files/{fileId}",
"title": "下载扫描成果文件",
"action": "",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "CALIBRATION_ENTER",
"method": "POST",
"path": "/calibration/enter",
"title": "进入扫描标定",
"action": "SCANNER_CALIBRATION_ENTER",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "CALIBRATION_MODE",
"method": "POST",
"path": "/calibration/setMode",
"title": "设置标定模式",
"action": "SCANNER_CALIBRATION_MODE",
"defaultBody": {
"mode": 0
},
"fields": [
{
"key": "mode",
"label": "工程或标定模式",
"type": "number",
"options": [
{
"value": 0,
"label": "0"
},
{
"value": 1,
"label": "1"
},
{
"value": 2,
"label": "2"
},
{
"value": 3,
"label": "3"
}
],
"optional": false,
"nullable": false
}
],
"advanced": false
},
{
"key": "CALIBRATION_START",
"method": "POST",
"path": "/calibration/start",
"title": "开始扫描标定",
"action": "SCANNER_CALIBRATION_START",
"defaultBody": {
"confirm": false
},
"fields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"advanced": false
},
{
"key": "CALIBRATION_TRAK",
"method": "POST",
"path": "/calibration/setTrakType",
"title": "设置跟踪仪标定类型",
"action": "SCANNER_CALIBRATION_TRAK",
"defaultBody": {
"trakType": 1,
"confirm": false
},
"fields": [
{
"key": "trakType",
"label": "跟踪仪标定类型",
"type": "number",
"options": [
{
"value": 0,
"label": "快速"
},
{
"value": 1,
"label": "标准"
},
{
"value": 2,
"label": "精细"
},
{
"value": 3,
"label": "UE Nova蓝光"
}
],
"optional": false,
"nullable": false
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"advanced": false
},
{
"key": "CALIBRATION_SYSTEM",
"method": "POST",
"path": "/calibration/startSystem",
"title": "开始系统标定",
"action": "SCANNER_CALIBRATION_SYSTEM",
"defaultBody": {
"confirm": false
},
"fields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"advanced": false
},
{
"key": "CALIBRATION_FREE",
"method": "POST",
"path": "/calibration/setFree",
"title": "设置自由标定",
"action": "SCANNER_CALIBRATION_FREE",
"defaultBody": {
"enabled": true,
"confirm": false
},
"fields": [
{
"key": "enabled",
"label": "启用",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"advanced": false
},
{
"key": "CALIBRATION_CAPTURE",
"method": "POST",
"path": "/calibration/capturePose",
"title": "采集标定姿态",
"action": "SCANNER_CALIBRATION_CAPTURE",
"defaultBody": {
"confirm": false
},
"fields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"advanced": false
},
{
"key": "CALIBRATION_COMPUTE",
"method": "POST",
"path": "/calibration/compute",
"title": "计算自由标定结果",
"action": "SCANNER_CALIBRATION_COMPUTE",
"defaultBody": {
"confirm": false
},
"fields": [
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"advanced": false
},
{
"key": "CALIBRATION_ADVANCED",
"method": "POST",
"path": "/calibration/setAdvanced",
"title": "设置精细标定",
"action": "SCANNER_CALIBRATION_ADVANCED",
"defaultBody": {
"enabled": true,
"confirm": false
},
"fields": [
{
"key": "enabled",
"label": "启用",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"advanced": false
},
{
"key": "CALIBRATION_APPLY_LAST",
"method": "POST",
"path": "/calibration/applyLast",
"title": "应用上次标定结果",
"action": "SCANNER_CALIBRATION_APPLY_LAST",
"defaultBody": {
"mode": 0,
"confirm": false
},
"fields": [
{
"key": "mode",
"label": "工程或标定模式",
"type": "number",
"options": [
{
"value": 0,
"label": "0"
},
{
"value": 1,
"label": "1"
},
{
"value": 2,
"label": "2"
},
{
"value": 3,
"label": "3"
}
],
"optional": false,
"nullable": false
},
{
"key": "confirm",
"label": "已核对本次操作的目标和影响",
"type": "boolean",
"options": null,
"optional": false,
"nullable": false
}
],
"advanced": false
},
{
"key": "METADATA",
"method": "GET",
"path": "/metadata",
"title": "读取扫描服务信息",
"action": "SCANNER_METADATA",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "HEALTH",
"method": "GET",
"path": "/health",
"title": "检查扫描服务",
"action": "SCANNER_HEALTH",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "STATUS",
"method": "GET",
"path": "/status",
"title": "读取扫描仪状态",
"action": "SCANNER_STATUS",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "CAPABILITIES",
"method": "GET",
"path": "/capabilities",
"title": "读取扫描能力",
"action": "SCANNER_CAPABILITIES",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "METRICS",
"method": "GET",
"path": "/preview/metrics",
"title": "读取预览指标",
"action": "SCANNER_METRICS",
"defaultBody": {},
"fields": [],
"advanced": false
},
{
"key": "TASK",
"method": "GET",
"path": "/tasks/{taskId}",
"title": "等待扫描设备任务",
"action": "SCANNER_WAIT",
"defaultBody": {},
"fields": [],
"advanced": false
}
]
export const getScannerOperation = (action) => SCANNER_OPERATIONS.find((item) => item.action === action)

View File

@ -21,6 +21,7 @@
v-bind="componentExtraProps"
@save-success="handleSaveSuccess"
@save-error="handleSaveError"
@cancel="emits('close')"
@extract-step="handleExtractStep"
/>
</el-drawer>
@ -46,6 +47,7 @@ const EndParams = defineAsyncComponent(() => import('./params/EndParams.vue'))
const SubFlowParams = defineAsyncComponent(() => import('./params/SubFlowParams.vue'))
const ChatParams = defineAsyncComponent(() => import('./params/ChatParams.vue'))
const VisionLocateParams = defineAsyncComponent(() => import('./params/VisionLocateParams.vue'))
const ScannerParams = defineAsyncComponent(() => import('./params/ScannerParams.vue'))
const props = defineProps({
drawer: Boolean,
@ -66,6 +68,7 @@ const drawerSize = computed(() => (
// 根据节点类型决定渲染哪个子组件
const currentComponent = computed(() => {
const type = props.data?.type
if (String(props.data?.properties?.action || '').startsWith('SCANNER_')) return ScannerParams
if (type === 'start') return StartParams
if (type === 'end') return EndParams
if (type === 'subFlow') return SubFlowParams

View File

@ -25,7 +25,7 @@
label-width="auto">
<div v-for="(property, index) in formData.nodeParams" :key="index">
<el-row>
<el-form-item :label="index === 0 ? '参数名' : ''" :prop="`nodeParams.${index}.name`"
<el-form-item :label="property.label || (index === 0 ? '参数名' : '')" :prop="`nodeParams.${index}.name`"
:rules="[{ required: true, message: '请输入参数名', trigger: 'blur' }]">
<el-input :disabled="property?.disabled || false" class="param-name"
v-model="property.name" placeholder="请输入" clearable />
@ -40,7 +40,7 @@
:prop="`nodeParams.${index}.input`">
<el-input-number class="param-value" v-if="property.componentType === 'number'"
v-model="property.input" :min="property.min ?? 0" :max="property.max || Infinity"
:controls="property?.controls || true" :step-strictly="true" :step="property.step || 1" placeholder="请输入" clearable />
:controls="property?.controls || true" :step-strictly="!isWorkcellAction(props.data.properties.action)" :step="property.step || 1" :precision="property.precision" placeholder="请输入" clearable />
<el-select v-model="property.input" class="param-value"
v-else-if="property.componentType === 'select'">
<el-option v-for="item in property.selectOptions" :key="item.value"
@ -130,6 +130,7 @@ import { getRobotList, getRobotDevicesByRobotId } from '@/cmvr/common/api/resour
import { ElMessage } from 'element-plus'
import { getDeviceKindForAction, toDeviceOptions } from '@/cmvr/common/utils/robotDevice'
import { actionRequiresDevice } from '@/cmvr/common/utils/flowResources'
import { isWorkcellAction, validateWorkcellLiterals } from '@/cmvr/common/utils/scanMotorNodes.mjs'
const props = defineProps({
data: Object
@ -226,6 +227,11 @@ watch(
const validateAndSave = async () => {
let inputValid = true
let outputValid = true
const deviceErrors = validateWorkcellLiterals(props.data.properties.action, formData.nodeParams)
if (deviceErrors.length) {
inputValid = false
ElMessage.warning(deviceErrors[0])
}
if (dynamicFormRef.value) {
await dynamicFormRef.value.validate((valid) => { if (!valid) inputValid = false })
}
@ -309,6 +315,9 @@ const loadRobotDevices = async (robotId) => {
* @param {*} property 参数属性
*/
const testRule = (property) => {
if (isWorkcellAction(props.data.properties.action)) {
return [{ required: property.required ?? true, message: `请填写${property.label || property.name}`, trigger: 'change' }]
}
if (property?.name === 'stationId' && props.data.properties.action === 'AGV_MOVE_TO_STATION') {
return [
{ required: true, message: '请从站点列表中选择站点', trigger: 'change' },

View File

@ -0,0 +1,165 @@
<template>
<RobotExecutionTarget :data="data" v-model="target" />
<div class="scanner-status">
<el-tag :type="configuration.configured ? 'success' : 'info'">{{ configuration.configured ? '扫描服务已配置' : '扫描服务待配置' }}</el-tag>
<el-button link type="primary" :disabled="!configuration.configured" @click="readStatus">读取状态</el-button>
<el-button link type="primary" :disabled="!configuration.configured" @click="previewOpen = true">查看预览</el-button>
</div>
<el-alert v-if="legacy" title="旧节点参数需要按设备实际接口重新确认,保存后更新。" type="warning" :closable="false" />
<el-collapse v-model="sections">
<el-collapse-item name="input" title="输入参数">
<el-form label-position="top">
<template v-if="operation?.method === 'POST'">
<el-form-item label="参数来源">
<el-select v-model="request.type" @change="changeSource">
<el-option label="填写参数" value="input" />
<el-option label="引用上游参数" value="quote" />
</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 }"
@visible-change="refreshQuoteOptions" @change="value => cascaderChange(value, request)" />
</el-form-item>
<template v-else>
<el-form-item v-for="field in visibleFields" :key="field.key" :label="field.label">
<el-select v-if="field.options" v-model="form[field.key]" @change="syncBody">
<el-option v-for="item in field.options" :key="item.value" :label="item.label" :value="item.value" />
</el-select>
<el-checkbox v-else-if="field.type === 'boolean'" v-model="form[field.key]" @change="syncBody">{{ field.label }}</el-checkbox>
<el-select v-else-if="field.type === 'array'" v-model="form[field.key]" multiple allow-create filterable default-first-option @change="syncBody">
<el-option v-for="format in exportFormats" :key="format" :label="format" :value="format" />
</el-select>
<el-input-number v-else-if="field.type === 'number'" v-model="form[field.key]" :precision="0" @change="syncBody" />
<el-input v-else v-model="form[field.key]" :placeholder="field.optional ? '可留空,由设备服务分配' : field.nullable ? '填写已核对的编号,无会话时可留空' : '请输入'" @input="syncBody" />
</el-form-item>
<el-form-item v-if="operation?.advanced || rawMode" label="操作参数 JSON">
<el-input v-model="request.input" type="textarea" :autosize="{ minRows: 9, maxRows: 22 }" spellcheck="false" />
<div class="field-note">保留原始整数,勿将点编号替换为 PLY 行号。参数由后端统一校验。</div>
</el-form-item>
<div v-if="operation?.method === 'POST' && !visibleFields.length && !operation.advanced" class="field-note">此操作无需参数,发送空对象。</div>
<el-button v-if="!operation?.advanced && operation?.fields.length" link type="primary" @click="toggleRaw">{{ rawMode ? '返回表单' : '编辑参数 JSON' }}</el-button>
</template>
</template>
<el-form-item v-if="operation?.key === 'TASK'" label="设备任务编号" required>
<el-select v-model="task.type" @change="() => handleTypeChange(task)"><el-option label="输入" value="input" /><el-option label="引用" value="quote" /></el-select>
<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>
<div class="field-note">{{ operation?.key === 'SCAN_START' ? '本节点等待启动命令完成,随后设备持续采集;结束采集需要“暂停采集”节点。' : '控制操作会等待设备任务终态;等待超时不会撤销已受理的设备动作。' }}</div>
</el-collapse-item>
<el-collapse-item name="output" title="输出参数">
<el-table :data="outputs" size="small"><el-table-column prop="name" label="变量" /><el-table-column prop="type" label="类型" /><el-table-column prop="desc" label="说明" /></el-table>
</el-collapse-item>
<el-collapse-item name="diagnostics" title="设备状态与任务">
<el-form label-position="top"><el-form-item label="设备任务编号"><el-input v-model="inspectTask" placeholder="输入任务编号后查询" /></el-form-item></el-form>
<el-button :disabled="!configuration.configured || !inspectTask" :loading="querying" @click="readTask">查询任务</el-button>
<JsonViewer v-if="diagnostics" :value="diagnostics" copyable boxed theme="light" />
<el-button v-for="file in diagnostics?.result?.files || []" :key="file.fileId" link type="primary" @click="download(file)">{{ file.name }}</el-button>
</el-collapse-item>
</el-collapse>
<div class="scanner-actions"><el-button @click="emit('cancel')">取消编辑</el-button><el-button type="primary" @click="validateAndSave">完成配置</el-button></div>
<ScannerPreview v-if="previewOpen" v-model="previewOpen" />
</template>
<script setup>
import { computed, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'
import RobotExecutionTarget from './RobotExecutionTarget.vue'
import ScannerPreview from './ScannerPreview.vue'
import { useQuote } from './useQuote.js'
import { getScannerOperation } from '@/cmvr/common/utils/scannerOperations.mjs'
import { createWorkcellNodeGroups, validateWorkcellLiterals } from '@/cmvr/common/utils/scanMotorNodes.mjs'
import { getScannerConfiguration, queryScanner, validateScannerRequest, scannerBinary } from '@/cmvr/common/api/scanner'
const props = defineProps({ data: { type: Object, required: true } })
const clone = value => JSON.parse(JSON.stringify(value))
const emit = defineEmits(['save-success', 'save-error', 'cancel'])
const operation = computed(() => getScannerOperation(props.data.properties?.action))
const target = ref({})
const request = reactive({ name: 'requestJson', type: 'input', input: '{}', required: true, disabled: true })
const task = reactive({ name: 'taskId', type: 'input', input: '', required: true, disabled: true })
const timeout = reactive({ name: 'timeoutMs', type: 'input', input: 120000, required: true, disabled: true, componentType: 'number', min: 1, max: 3600000 })
const form = reactive({})
const configuration = ref({ configured: false })
const sections = ref(['input', 'output'])
const rawMode = ref(false)
const legacy = ref(false)
const previewOpen = ref(false)
const exportFormats = ref([])
const diagnostics = ref()
const inspectTask = ref('')
const querying = ref(false)
const { quoteOptions, handleTypeChange, cascaderChange, refreshQuoteOptions } = useQuote(props.data.id)
const outputs = computed(() => createWorkcellNodeGroups()[0].nodeList.find(node => node.action === props.data.properties.action)?.outputParams || [])
const visibleFields = computed(() => rawMode.value ? [] : operation.value?.fields || [])
function syncBody() {
if (request.type !== 'input' || rawMode.value || operation.value?.advanced) return
const body = {}
for (const field of operation.value?.fields || []) {
const value = form[field.key]
if (field.optional && (value === '' || value == null)) continue
body[field.key] = field.nullable && value === '' ? null : value
}
request.input = JSON.stringify(body, null, 2)
}
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 编辑并核对参数')
for (const field of operation.value.fields) form[field.key] = value[field.key] ?? (field.type === 'boolean' ? false : field.type === 'array' ? [] : '')
}
function toggleRaw() {
if (rawMode.value) { try { loadForm() } catch (error) { ElMessage.warning(error.message); return } }
else syncBody()
rawMode.value = !rawMode.value
}
function changeSource() {
handleTypeChange(request)
if (request.type === 'input') { request.input = JSON.stringify(operation.value.defaultBody, null, 2); loadForm() }
}
watch(() => [props.data.id, props.data.properties?.action], async () => {
const parameters = props.data.properties?.nodeParams || []
target.value = clone(props.data.properties?.executionTarget || {})
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') || {}))
legacy.value = parameters.some(p => ['planCode', 'jobId', 'format'].includes(p.name))
rawMode.value = false
try { loadForm() } catch { rawMode.value = true }
try { configuration.value = (await getScannerConfiguration()).data || { configured: false } } catch { configuration.value = { configured: false } }
if (configuration.value.configured) { try { exportFormats.value = (await queryScanner('CAPABILITIES')).data?.exportFormats || [] } catch { exportFormats.value = [] } }
}, { immediate: true })
async function readStatus() { try { diagnostics.value = (await queryScanner('STATUS')).data; sections.value = [...new Set([...sections.value, 'diagnostics'])] } catch {} }
async function readTask() { querying.value = true; try { diagnostics.value = (await queryScanner('TASK', inspectTask.value)).data } finally { querying.value = false } }
async function download(file) { try { const response = await scannerBinary('FILE', file.fileId); saveAs(await response.blob(), file.name) } catch (error) { ElMessage.error(error.message) } }
async function validateAndSave() {
syncBody()
const params = [
...(operation.value.method === 'POST' ? [clone(request)] : []),
...(operation.value.key === 'TASK' ? [clone(task)] : []),
clone(timeout),
]
try {
if (!target.value.roleKey || !target.value.deviceSlotKey) throw new Error('请选择执行角色和扫描仪设备用途')
const errors = validateWorkcellLiterals(props.data.properties.action, params)
if (errors.length) throw new Error(errors[0])
if (request.type === 'quote' && operation.value.method === 'POST' && !request.quote?.length) throw new Error('请选择要引用的操作参数')
if (operation.value.key === 'TASK' && task.type === 'quote' && !task.quote?.length) throw new Error('请选择要引用的设备任务编号')
if (operation.value.method === 'POST' && request.type === 'input') await validateScannerRequest(operation.value.key, request.input)
window.lf.setProperties(props.data.id, { ...props.data.properties, scannerOperation: operation.value.key, nodeParams: params, executionTarget: clone(target.value), outputParams: clone(outputs.value) })
emit('save-success')
} catch (error) { ElMessage.warning(error.message || '请检查扫描参数') }
}
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; }
.el-select, .el-cascader, .el-input-number { width: 100%; }
:deep(textarea) { font-family: Consolas, monospace; }
</style>

View File

@ -0,0 +1,35 @@
<template>
<el-dialog :model-value="modelValue" title="扫描预览" width="min(960px, 94vw)" append-to-body @close="close">
<div class="preview-toolbar"><el-radio-group v-model="mode" @change="start"><el-radio-button value="PREVIEW_IMAGE">最新图像</el-radio-button><el-radio-button value="PREVIEW_STREAM">实时预览</el-radio-button></el-radio-group><el-button :loading="loading" @click="start">刷新</el-button></div>
<el-alert v-if="error" :title="error" type="warning" :closable="false" />
<img v-if="url" :src="url" class="scanner-image" alt="扫描仪三维渲染预览" />
<el-empty v-else-if="!loading" description="暂无新鲜预览帧,请先开启扫描预览" />
</el-dialog>
</template>
<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue'
import { scannerBinary } from '@/cmvr/common/api/scanner'
import { consumeScannerMjpeg } from '@/cmvr/common/utils/scannerMjpeg.mjs'
defineProps({ modelValue: Boolean })
const emit = defineEmits(['update:modelValue'])
const mode = ref('PREVIEW_IMAGE'), url = ref(''), error = ref(''), loading = ref(false)
let controller
let generation = 0
function frame(bytes) { if (url.value) URL.revokeObjectURL(url.value); url.value = URL.createObjectURL(new Blob([bytes], { type: 'image/jpeg' })) }
async function start() {
controller?.abort(); controller = new AbortController(); const current = ++generation; error.value = ''; loading.value = true
try {
const response = await scannerBinary(mode.value, undefined, controller.signal)
if (mode.value === 'PREVIEW_IMAGE') { const blob = await response.blob(); if (current === generation) frame(await blob.arrayBuffer()) }
else await consumeScannerMjpeg(response.body, bytes => { if (current === generation) { frame(bytes); loading.value = false } }, controller.signal)
} catch (failure) { if (failure.name !== 'AbortError' && current === generation) error.value = failure.message }
finally { if (current === generation) loading.value = false }
}
function close() { generation++; controller?.abort(); emit('update:modelValue', false) }
onMounted(start)
onBeforeUnmount(() => { generation++; controller?.abort(); if (url.value) URL.revokeObjectURL(url.value) })
</script>
<style scoped>
.preview-toolbar { display: flex; gap: 12px; margin-bottom: 16px; }
.scanner-image { display: block; width: 100%; max-height: 65vh; object-fit: contain; background: #f5f7fa; }
</style>

View File

@ -76,6 +76,8 @@ const props = defineProps({ data: Object })
const emit = defineEmits(['save-success', 'save-error'])
const deviceKinds = [
{ label: '扫描仪', value: 14 },
{ label: '电机', value: 10 },
{ label: '移动底盘', value: 1 },
{ label: '机械臂', value: 2 },
{ label: '仿生头', value: 4 },

View File

@ -16,6 +16,9 @@ import audioSvg from './icon/audio.svg'
import touchSvg from './icon/touch.svg'
import expressionSvg from './icon/expression.svg'
import { DEFAULT_CHAT_SYSTEM_PROMPT } from './chatPrompt.js'
import scannerSvg from './icon/scanner.svg'
import motorSvg from './icon/motor.svg'
import { createWorkcellNodeGroups } from '../../utils/scanMotorNodes.mjs'
const pointOutputChildren = () => [
{ name: 'x', type: 'number', desc: 'X坐标' },
@ -120,6 +123,7 @@ const corpus_type = () => {
}
export const collapseList = [
...createWorkcellNodeGroups({ SCANNER: scannerSvg, MOTOR: motorSvg }),
{
collapseTitle: "相机",
nodeList: [

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" fill="none" stroke="#1677ff" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><rect x="8" y="13" width="27" height="24" rx="5"/><path d="M35 21h8v8h-8M13 37v5h17v-5M14 8h14M15 20v10M22 20v10M29 20v10"/></svg>

After

Width:  |  Height:  |  Size: 284 B

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" fill="none" stroke="#1677ff" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M8 18h32v20H8zM14 18V9h20v9M15 29h18M12 43h24"/><path d="m18 24 6 9 6-9" stroke="#36a3ff"/></svg>

After

Width:  |  Height:  |  Size: 260 B

View File

@ -2293,11 +2293,13 @@ const execute = async () => {
rememberSingleNodeRobot();
singleNodeExecuting.value = true;
try {
const payload = nodeAction.value === 'IMAGE_ANALYZE'
? buildImageAnalysisSingleNodePayload(formData.nodeParams)
: buildSingleNodePayload(formData.nodeParams);
if (String(nodeAction.value).startsWith('SCANNER_')) payload.commandKey = crypto.randomUUID();
const res = await flowAction({
action: nodeAction.value,
payload: nodeAction.value === 'IMAGE_ANALYZE'
? buildImageAnalysisSingleNodePayload(formData.nodeParams)
: buildSingleNodePayload(formData.nodeParams),
payload,
});
if (res.code === 200) {
ElMessage.success("执行成功");

View File

@ -77,6 +77,7 @@ const loading = ref(false), robotLoading = ref(false), saving = ref(false), rows
const query = reactive({ pageNum: 1, pageSize: 20, robotId: '', deviceRole: '', onlineOnly: false })
const active = reactive({})
kindNames[14] = '扫描仪'
const kindName = value => kindNames[value] || `未知(${value ?? '-'})`
const robotOptionLabel = robot => robot.robotName
? `${robot.robotName}(${robot.robotId})`

View File

@ -298,6 +298,7 @@ async function syncRuntimeState(row) {
function robotTypeLabel(value) { return robot_type.value?.find(item => String(item.value) === String(value))?.label || value || '-' }
const kindNames = { 1: 'AGV', 2: '机械臂', 3: '电池', 4: '仿生头', 5: '摄像头', 6: 'CAN总线', 7: '灵巧手', 8: '夹爪', 9: '麦克风', 10: '电机', 11: '电机系统', 12: '机器人', 13: '扬声器' }
const stateNames = { 1: '停用', 2: '初始化', 3: '已注册', 4: '就绪', 5: '运行中', 6: '已停止', 7: '错误' }
kindNames[14] = '扫描仪'
function deviceKindLabel(value) { return kindNames[value] || `未知(${value ?? '-'})` }
function managerStateLabel(value) { return stateNames[value] || '-' }
function healthLabel(row) { if (row.hasError === '1') return '故障'; return ({ 1: '健康', 2: '降级', 3: '故障' })[row.healthStatus] || '未知' }

View File

@ -1,4 +1,5 @@
import axios from 'axios'
import { rejectRequestFailure } from '@/config/axios/requestFailure.mjs'
import { ElLoading, ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'
import { getAccessToken, getTenantId, getVisitTenantId } from '@/utils/auth'
@ -24,10 +25,9 @@ request.interceptors.response.use((response) => {
return Promise.reject(error)
}
return result
}, (error) => {
}, (error) => rejectRequestFailure(error, (error) => {
ElMessage.error(error.response?.data?.msg || error.message || 'CMVR 服务连接失败')
return Promise.reject(error)
})
}))
export async function download(url: string, params: Record<string, any>, filename: string, config = {}) {
const loading = ElLoading.service({ text: '正在下载数据,请稍候' })
try {

View File

@ -0,0 +1,8 @@
import axios from 'axios'
// Navigation and polling deliberately abort obsolete requests. Keep rejection
// semantics for the caller, while reserving notifications for real failures.
export function rejectRequestFailure(error, notify) {
if (!axios.isCancel(error) && error?.name !== 'AbortError') notify(error)
return Promise.reject(error)
}

View File

@ -0,0 +1,34 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import axios from 'axios'
import { rejectRequestFailure } from './requestFailure.mjs'
test('页面切换中止实际Axios请求:调用方仍收到取消,界面不弹错误', async () => {
const messages = []
const api = axios.create({adapter: config => new Promise((resolve, reject) => {
config.signal.addEventListener('abort', () => reject(new axios.CanceledError('canceled')), {once:true})
})})
api.interceptors.response.use(undefined, error => rejectRequestFailure(error, value => messages.push(value)))
const controller = new AbortController()
const pending = api.get('/obsolete-execution', {signal:controller.signal})
controller.abort()
await assert.rejects(pending, error => axios.isCancel(error))
assert.deepEqual(messages, [])
})
test('真实网络失败和超时各提示一次,不能因取消优化而被吞掉', async () => {
const messages = []
for (const code of ['ERR_NETWORK', 'ECONNABORTED']) {
const failure = new axios.AxiosError('real failure', code)
await assert.rejects(rejectRequestFailure(failure, error => messages.push(error)), error => error === failure)
}
assert.deepEqual(messages.map(error => error.code), ['ERR_NETWORK', 'ECONNABORTED'])
})
test('原生AbortError与已取消Axios请求保持安静且保留原始异常', async () => {
const messages = []
for (const failure of [new DOMException('aborted', 'AbortError'), new axios.CanceledError()]) {
await assert.rejects(rejectRequestFailure(failure, error => messages.push(error)), error => error === failure)
}
assert.equal(messages.length, 0)
})

View File

@ -1,4 +1,5 @@
import axios, { AxiosError, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { rejectRequestFailure } from './requestFailure.mjs'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import qs from 'qs'
@ -101,11 +102,10 @@ service.interceptors.request.use(
}
return config
},
(error: AxiosError) => {
(error: AxiosError) => rejectRequestFailure(error, (error: AxiosError) => {
// Do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
})
)
// response 拦截器

View File

@ -287,7 +287,7 @@ export default {
usage: 'Utilization',
idle: 'Idle',
inUse: 'In use',
shortcutNewTask: 'New task',
shortcutNewTask: 'Task pool',
shortcutImport: 'Import',
shortcutReceive: 'Receive sample',
shortcutMethod: 'Detection items',

View File

@ -289,7 +289,7 @@ export default {
usage: '使用率',
idle: '空闲',
inUse: '使用中',
shortcutNewTask: '新建任务',
shortcutNewTask: '任务池',
shortcutImport: '导入任务',
shortcutReceive: '样品接收',
shortcutMethod: '检测项配置',

View File

@ -3,7 +3,8 @@
<el-page-header @back="push({ name: 'LabReport' })" :content="detail.reportNo || '报告详情'" />
<div class="mt-12px flex flex-wrap gap-8px">
<dict-tag :type="DICT_TYPE.LAB_REPORT_STATUS" :value="detail.status" />
<el-button v-if="detail.status === 'DRAFT'" v-hasPermi="['lab:document:update']" @click="save">保存草稿</el-button>
<el-button v-if="detail.status === 'DRAFT' || (detail.status === 'PUBLISHED' && hasDraft)" v-hasPermi="['lab:document:update']" @click="save">保存草稿</el-button>
<el-button v-if="detail.status === 'PUBLISHED' && !hasDraft" v-hasPermi="['lab:document:update']" @click="createRevision">新建修订</el-button>
<el-button v-if="detail.status !== 'VOID'" type="primary" v-hasPermi="['lab:document:publish']" @click="publish">
{{ detail.status === 'PUBLISHED' ? '发布新版本' : '发布正式版' }}
</el-button>
@ -21,8 +22,8 @@
<el-descriptions-item label="外部报告号">{{ detail.externalReportNo || '-' }}</el-descriptions-item>
</el-descriptions>
<el-form label-width="90px">
<el-form-item label="标题"><el-input v-model="detail.title" :disabled="detail.status === 'PUBLISHED' && !hasDraft" /></el-form-item>
<el-form-item label="正文"><el-input v-model="contentHtml" type="textarea" :rows="12" :disabled="detail.status === 'PUBLISHED' && !hasDraft" /></el-form-item>
<el-form-item label="标题"><el-input v-model="detail.title" :disabled="detail.status === 'VOID' || (detail.status === 'PUBLISHED' && !hasDraft)" /></el-form-item>
<el-form-item label="正文"><el-input v-model="contentHtml" type="textarea" :rows="12" :disabled="detail.status === 'VOID' || (detail.status === 'PUBLISHED' && !hasDraft)" /></el-form-item>
</el-form>
<div class="mt-16px font-bold">历史版本</div>
<el-table :data="detail.versions || []">
@ -56,6 +57,11 @@ const save = async () => {
message.success('已保存')
await load()
}
const createRevision = async () => {
await DocumentApi.updateReport(detail.value.id!, detail.value.title, contentHtml.value)
message.success('已创建修订草稿')
await load()
}
const publish = async () => {
await DocumentApi.publishReport(detail.value.id!)
message.success('已发布')

View File

@ -39,6 +39,7 @@
/>
</ContentWrap>
<ContentWrap><el-collapse><el-collapse-item title="本次运行参数快照" name="runParams"><pre class="text-12px overflow-auto">{{ JSON.stringify(detail.runParams || {}, null, 2) }}</pre></el-collapse-item></el-collapse></ContentWrap>
<ContentWrap v-if="isScanAttempt && detail.id"><ScannerExecutionViews :execution-id="detail.id" :execution-no="detail.executionNo" :status="detail.status" /></ContentWrap>
<ContentWrap v-if="isLocalDetection"><div class="font-bold mb-12px">检测流程运行日志</div><RunResult :run="detectionRun || undefined" empty-text="发布执行后在这里查看真实节点状态与日志" /></ContentWrap>
<ContentWrap v-loading="loading">
<el-row :gutter="16">
@ -138,6 +139,7 @@ import * as DataApi from '@/api/lab/data'
import * as DetectionApi from '@/api/lab/detection-item'
import RunResult from '@/views/lab/detection-item/components/RunResult.vue'
import { downloadArtifactFile } from '@/utils/labArtifactDownload'
import ScannerExecutionViews from '@/views/lab/scan-task/ScannerExecutionViews.vue'
defineOptions({ name: 'LabExecutionWorkbench' })
const route = useRoute()

View File

@ -45,9 +45,9 @@
</ContentWrap>
<ContentWrap>
<el-table v-loading="loading" :data="list">
<el-table-column label="样品编号" prop="sampleCode" min-width="120" />
<el-table-column label="样品名称" prop="sampleName" min-width="140" />
<el-table-column label="零件号" prop="partNo" min-width="110" />
<el-table-column label="样品编号" prop="sampleCode" min-width="160" show-overflow-tooltip />
<el-table-column label="样品名称" prop="sampleName" min-width="140" show-overflow-tooltip />
<el-table-column label="零件号" prop="partNo" min-width="160" show-overflow-tooltip />
<el-table-column label="类型" align="center" prop="sampleType" width="90">
<template #default="scope">
<dict-tag :type="DICT_TYPE.LAB_SAMPLE_TYPE" :value="scope.row.sampleType" />

View File

@ -36,6 +36,8 @@
:title="execution.failureReason"
/>
<el-alert v-if="error" class="mb-12px" type="warning" :closable="false" :title="error" />
<ScannerExecutionViews v-if="execution?.id" :key="String(execution.id)" :execution-id="execution.id"
:execution-no="execution.executionNo" :status="execution.status" :active="active" />
<h3 class="log-heading">执行日志</h3>
<NativeTaskLog
v-if="execution?.id"
@ -55,8 +57,10 @@ import * as ScanApi from '@/api/lab/scan-task'
import type { LabExecutionVO } from '@/api/lab/execution'
import { getInst } from '@/cmvr/common/api/test/log'
import NativeTaskLog from '@/cmvr/aima/views/intelligenceTest/runningTask/task-log.vue'
import ScannerExecutionViews from './ScannerExecutionViews.vue'
import { executionIdentity, executionProgress, readableLogs } from './executionPresentation.mjs'
import { statusLabel } from './scanForm.mjs'
import { scannerLogCursor, mergeScannerLogs } from './scannerLogs.mjs'
const props = withDefaults(
defineProps<{
@ -111,15 +115,20 @@ const currentNode = computed(() => {
})
let generation = 0
let pending: { id: string; token: number } | undefined
let controller: AbortController | undefined
let suspended = false
async function load(force = false) {
const id = props.execution?.id
if (!id || (!force && pending?.id === String(id))) return
const token = ++generation
controller?.abort()
controller = new AbortController()
const signal = controller.signal
pending = { id: String(id), token }
loading.value = true
error.value = ''
try {
const result = await ScanApi.getCmvrBinding(id)
const result = (!force && binding.value?.cmvrInstId) ? binding.value : await ScanApi.getCmvrBinding(id, signal)
if (token !== generation) return
binding.value = result
if (!result?.cmvrInstId) {
@ -127,18 +136,19 @@ async function load(force = false) {
return
}
const found: any[] = []
const afterId = force ? undefined : scannerLogCursor(nativeLogs.value)
let pageNum = 1
while (true) {
const response: any = await getInst({ instId: result.cmvrInstId, pageNum, pageSize: 100 })
const response: any = await getInst({ instId: result.cmvrInstId, afterId, pageNum, pageSize: 100 }, signal)
if (token !== generation) return
const rows = response.rows || []
found.push(...rows)
if (!rows.length || found.length >= (response.total ?? found.length)) break
pageNum++
}
nativeLogs.value = found
nativeLogs.value = force ? found : mergeScannerLogs(nativeLogs.value, found)
} catch (failure: any) {
if (token === generation) error.value = failure.message || '日志加载失败,请刷新重试。'
if (token === generation && !signal.aborted) error.value = failure.message || '日志加载失败,请刷新重试。'
} finally {
if (token === generation) loading.value = false
if (pending?.token === token) pending = undefined
@ -163,26 +173,31 @@ watch(
nativeLogs.value = []
loading.value = false
error.value = ''
if (props.active) load(true)
if (props.active && !suspended) load(true)
},
{ immediate: true }
)
watch(
() => [props.active, props.execution?.status],
[() => props.active, () => props.execution?.status],
() => {
if (props.active) load(true)
if (props.active && !suspended) load(true)
else { generation++; controller?.abort(); pending = undefined; loading.value = false }
}
)
const timer = setInterval(() => {
if (
props.active &&
!suspended &&
!document.hidden &&
['RUNNING', 'QUEUED', 'PREPARING', 'PAUSED'].includes(props.execution?.status || '')
)
load()
}, 2000)
onActivated(() => { suspended = false; if (props.active) load(true) })
onDeactivated(() => { suspended = true; generation++; controller?.abort(); pending = undefined; loading.value = false })
onBeforeUnmount(() => {
generation++
controller?.abort()
clearInterval(timer)
})
</script>

View File

@ -0,0 +1,16 @@
<template>
<el-tabs v-model="tab" class="scanner-execution-views">
<el-tab-pane label="实时扫描画面" name="live">
<ScannerLiveView :execution-id="executionId" :execution-no="executionNo" :status="status" :active="active && tab === 'live'" />
</el-tab-pane>
<el-tab-pane label="三维点云 / 网格" name="model" lazy>
<ScannerModelPanel :execution-id="executionId" :status="status" :active="active && tab === 'model'" />
</el-tab-pane>
</el-tabs>
</template>
<script setup lang="ts">
import ScannerLiveView from './ScannerLiveView.vue'
const ScannerModelPanel = defineAsyncComponent(() => import('./ScannerModelPanel.vue'))
withDefaults(defineProps<{ executionId: string | number; executionNo?: string; status?: string; active?: boolean }>(), { active: true })
const tab = ref('live')
</script>

View File

@ -0,0 +1,133 @@
<template>
<section class="scanner-live-view" aria-label="本次执行实时扫描画面">
<div class="view-heading">
<div><h3>实时扫描画面</h3><span class="view-hint">{{ view.executionNo || executionNo || '本次执行' }} · 画面跟随扫描软件当前视角</span></div>
<div class="view-controls">
<el-tag :type="view.executionStatus === 'PAUSED' && view.scanning ? 'warning' : view.available && !error ? 'success' : 'info'">{{ caption }}</el-tag>
<el-switch v-model="watching" active-text="实时查看" :disabled="!live" />
<el-button :disabled="!imageUrl" @click="expanded = true">放大查看</el-button>
</div>
</div>
<div v-if="view.projectId" class="view-identity">
<span>扫描工程 <code>{{ view.projectId }}</code></span>
<span>工位 <code>{{ view.robotId }}</code> / 设备 <code>{{ view.deviceId }}</code></span>
<span v-if="receivedAt">画面更新 {{ receivedAt }}</span>
</div>
<div class="view-canvas" v-loading="loading">
<img v-if="imageUrl" :src="imageUrl" decoding="async" alt="本次样件扫描过程中绘制的三维画面" />
<el-empty v-else :description="error || caption" :image-size="80" />
</div>
<el-dialog v-model="expanded" title="本次执行扫描画面" width="min(1200px, 94vw)" append-to-body>
<img v-if="imageUrl" :src="imageUrl" decoding="async" class="expanded-image" alt="本次执行扫描画面" />
<el-empty v-else :description="error || caption" />
</el-dialog>
</section>
</template>
<script setup lang="ts">
import { getScannerExecutionImage, getScannerExecutionView, type ScannerExecutionView } from '@/api/lab/scan-task/scannerView'
import { acceptsScannerFrame, isLiveScannerExecution, scannerViewCaption } from './scannerView.mjs'
const props = withDefaults(defineProps<{
executionId?: string | number
executionNo?: string
status?: string
active?: boolean
}>(), { active: true })
const view = ref<Partial<ScannerExecutionView>>({})
const watching = ref(true)
const imageUrl = ref('')
const receivedAt = ref('')
const error = ref('')
const loading = ref(false)
const expanded = ref(false)
const live = computed(() => isLiveScannerExecution(props.status))
const caption = computed(() => scannerViewCaption(view.value, props.active, watching.value))
let generation = 0
let controller: AbortController | undefined
let timer: ReturnType<typeof setTimeout> | undefined
let nextMetadata = 0
let suspended = false
function clearImage() {
if (imageUrl.value) URL.revokeObjectURL(imageUrl.value)
imageUrl.value = ''
receivedAt.value = ''
}
function current() { return { generation, executionId: props.executionId, active: props.active && !document.hidden && !suspended, watching: watching.value, status: props.status } }
async function tick(token: number, signal: AbortSignal) {
const id = props.executionId
if (id == null || token !== generation || !props.active || document.hidden || suspended) return
let delay = 800
try {
if (Date.now() >= nextMetadata) {
const result = await getScannerExecutionView(id, signal)
if (token !== generation) return
view.value = result
error.value = ''
nextMetadata = Date.now() + 3000
}
if (!live.value || !watching.value || !view.value.available || !view.value.previewEnabled) {
clearImage()
delay = 3000
return
}
const blob = await getScannerExecutionImage(id, signal)
if (!acceptsScannerFrame({ generation: token, executionId: id }, current())) return
const url = URL.createObjectURL(blob)
clearImage()
imageUrl.value = url
receivedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
error.value = ''
} catch (failure: any) {
if (token !== generation || signal.aborted) return
clearImage()
error.value = failure.message || '扫描画面暂不可用'
nextMetadata = 0
delay = 3000
} finally {
if (token === generation) {
loading.value = false
if (!signal.aborted && !suspended && props.active && !document.hidden && live.value && watching.value) timer = setTimeout(() => tick(token, signal), delay)
}
}
}
function restart(reset = false) {
generation++
controller?.abort()
clearTimeout(timer)
clearImage()
error.value = ''
expanded.value = false
if (reset) view.value = {}
nextMetadata = 0
loading.value = props.executionId != null && props.active && !document.hidden && !suspended
controller = new AbortController()
void tick(generation, controller.signal)
}
watch(() => [props.executionId, props.status, props.active, watching.value], () => restart(true), { immediate: true })
const onVisibility = () => restart()
onMounted(() => document.addEventListener('visibilitychange', onVisibility))
onActivated(() => { suspended = false; restart() })
onDeactivated(() => { suspended = true; restart() })
onBeforeUnmount(() => {
generation++
controller?.abort()
clearTimeout(timer)
clearImage()
document.removeEventListener('visibilitychange', onVisibility)
})
</script>
<style scoped>
.scanner-live-view { margin: 20px 0; padding: 16px; border: 1px solid var(--el-border-color-light); border-radius: 6px; }
.view-heading, .view-controls, .view-identity { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; }
.view-heading { justify-content: space-between; margin-bottom: 12px; }
h3 { margin: 0 0 6px; font-size: 16px; }
.view-hint, .view-identity { font-size: 13px; color: var(--el-text-color-secondary); }
.view-identity { margin-bottom: 12px; overflow-wrap: anywhere; }
.view-canvas { display: flex; justify-content: center; align-items: center; min-height: 300px; background: var(--el-fill-color-lighter); border-radius: 4px; }
.view-canvas img { display: block; width: 100%; max-height: 560px; object-fit: contain; }
.expanded-image { display: block; width: 100%; max-height: 78vh; object-fit: contain; }
@media (max-width: 768px) { .scanner-live-view { padding: 12px; } .view-canvas { min-height: 220px; } }
</style>

View File

@ -0,0 +1,148 @@
<template>
<section class="scanner-model-panel" aria-label="本次执行三维数据">
<div class="model-heading">
<div><h3>三维点云与网格</h3><span class="model-hint">按本次执行的快照、导出文件查看,可旋转、缩放和平移</span></div>
<div class="model-actions">
<el-button @click="refresh" :disabled="!active" :loading="loading">刷新文件</el-button>
<el-button v-if="live" type="primary" v-hasPermi="['lab:execution:dispatch']" :disabled="!view.available" :loading="snapshotBusy" @click="updateSnapshot">{{ snapshotKey ? '查询快照状态' : '更新三维数据' }}</el-button>
</div>
</div>
<el-alert v-if="snapshotMessage" :title="snapshotMessage" type="info" :closable="false" class="mb-12px" />
<el-alert v-if="error" :title="error" type="warning" :closable="false" class="mb-12px" />
<div v-if="models.length" class="file-controls">
<el-select v-model="selectedId" class="file-select" @change="followLatest = false"><el-option v-for="file in models" :key="file.fileId" :value="file.fileId" :label="file.name" /></el-select>
<el-checkbox v-model="followLatest" @change="chooseFile">跟随最新数据</el-checkbox>
<el-button link type="primary" :loading="downloading" @click="download">下载当前文件</el-button>
</div>
<template v-if="selected">
<div class="model-hint file-info">{{ selected.name }} · 工程 {{ selected.projectId || '-' }} <template v-if="selected.capturedAt"> · {{ new Date(selected.capturedAt).toLocaleString('zh-CN', { hour12: false }) }}</template></div>
<ScannerModelViewer v-if="active" :key="selected.fileId" :execution-id="executionId" :asset="selected" />
</template>
<el-empty v-else :description="!view.available && live ? view.message || '等待扫描工程就绪' : '暂无三维数据。可更新快照,或由流程中的快照、导出步骤生成文件。'" :image-size="80" />
<p class="model-hint">过程快照最多取10万点,文件可能包含采样数据;完整扫描成果按流程导出。设备忙时请等待当前步骤完成后再更新。</p>
</section>
</template>
<script setup lang="ts">
import { saveAs } from 'file-saver'
import { createScannerSnapshot, getScannerAssets, getScannerAsset, getScannerExecutionView, getScannerSnapshotCommand, type ScannerAsset, type ScannerSnapshotCommand, type ScannerExecutionView } from '@/api/lab/scan-task/scannerView'
import { isLiveScannerExecution } from './scannerView.mjs'
import { modelFormat } from './scannerModel.mjs'
const ScannerModelViewer = defineAsyncComponent(() => import('./ScannerModelViewer.vue'))
const props = withDefaults(defineProps<{ executionId: string | number; status?: string; active?: boolean }>(), { active: true })
const view = ref<Partial<ScannerExecutionView>>({})
const files = ref<ScannerAsset[]>([])
const models = computed(() => files.value.filter(file => !!modelFormat(file.name)))
const selectedId = ref('')
const selected = computed(() => models.value.find(file => file.fileId === selectedId.value))
const live = computed(() => isLiveScannerExecution(props.status))
const followLatest = ref(true)
const loading = ref(false), downloading = ref(false), snapshotBusy = ref(false)
const error = ref(''), snapshotMessage = ref(''), snapshotKey = ref('')
let requestedKey = ''
let generation = 0
let controller: AbortController | undefined
let timer: ReturnType<typeof setTimeout> | undefined
let pending: Promise<void> | undefined
let suspended = false
function chooseFile() {
if (!models.value.length) { selectedId.value = ''; return }
if (!followLatest.value && selected.value) return
const newest = models.value[0].capturedAt
const latest = models.value.filter(file => file.capturedAt === newest)
selectedId.value = (latest.find(file => /points/i.test(file.name)) || latest[0]).fileId
}
function applyCommand(command: ScannerSnapshotCommand) {
const state = command.state
if (state === 'SUCCEEDED') {
snapshotBusy.value = false; snapshotKey.value = ''; requestedKey = ''; snapshotMessage.value = '三维数据已生成,可旋转查看本次执行文件'; error.value = ''
followLatest.value = true
} else if (state === 'FAILED') {
snapshotBusy.value = false; snapshotKey.value = ''; requestedKey = ''; snapshotMessage.value = ''
error.value = command.error || '设备生成三维快照失败,请核对设备返回信息'
} else if (['INTENT', 'UNKNOWN'].includes(state)) {
snapshotBusy.value = false; snapshotMessage.value = '上次快照结果尚未确认,请核对设备和命令状态后处理,不能重复下发'
} else { snapshotBusy.value = true; snapshotMessage.value = '设备正在生成三维快照,完成后自动加载;扫描按原流程继续' }
}
async function refreshNow() {
const token = generation, id = props.executionId, signal = controller?.signal
if (!props.active || document.hidden || suspended || !signal || signal.aborted) return
try {
const [state, assets] = await Promise.all([getScannerExecutionView(id, signal), getScannerAssets(id, signal)])
if (token !== generation) return
view.value = state; files.value = assets || []; error.value = ''; chooseFile()
if (snapshotKey.value) {
const command = await getScannerSnapshotCommand(id, snapshotKey.value, signal)
if (token !== generation) return
const finished = command.state === 'SUCCEEDED'
applyCommand(command)
if (finished) { const assets = await getScannerAssets(id, signal); if (token === generation) { files.value = assets; chooseFile() } }
}
} catch (failure: any) { if (token === generation && !signal.aborted) error.value = failure.message || '三维数据加载失败' }
finally { if (token === generation) loading.value = false }
}
function refresh() {
if (pending) return pending
const request = refreshNow().finally(() => { if (pending === request) pending = undefined })
pending = request
return pending
}
async function updateSnapshot() {
if (snapshotKey.value) { loading.value = true; await refresh(); return }
const token = generation
requestedKey ||= crypto.randomUUID()
snapshotBusy.value = true; error.value = ''
try {
const command = await createScannerSnapshot(props.executionId, requestedKey, controller?.signal)
if (token !== generation) return
snapshotKey.value = command.commandKey || command.key || ''
applyCommand(command)
await refresh()
} catch (failure: any) {
if (token === generation && !controller?.signal.aborted) { error.value = failure.message || '快照请求失败,重试将复用原命令标识'; snapshotBusy.value = false }
}
}
async function download() {
if (!selected.value || !controller) return
const token = generation, signal = controller.signal, executionId = props.executionId
const file = selected.value
downloading.value = true
try {
const bytes = await getScannerAsset(executionId, file.fileId, signal)
if (token === generation && !signal.aborted) saveAs(new Blob([bytes]), file.name)
}
catch (failure: any) { if (token === generation && !signal.aborted) error.value = failure.message || '文件下载失败' }
finally { if (token === generation) downloading.value = false }
}
function schedule(token: number) {
timer = setTimeout(async () => {
await refresh()
if (token === generation && !suspended && props.active && !document.hidden && (live.value || snapshotBusy.value)) schedule(token)
}, snapshotBusy.value ? 1000 : 4000)
}
function restart(reset: boolean) {
generation++; controller?.abort(); clearTimeout(timer); pending = undefined
controller = new AbortController(); loading.value = props.active && !document.hidden && !suspended; downloading.value = false
if (reset) { files.value = []; selectedId.value = ''; view.value = {}; error.value = ''; snapshotKey.value = ''; requestedKey = ''; snapshotBusy.value = false; snapshotMessage.value = '' }
if (props.active && !document.hidden && !suspended) { const token = generation; void refresh().finally(() => { if (token === generation && (live.value || snapshotBusy.value)) schedule(token) }) }
}
watch(() => props.executionId, () => restart(true), { immediate: true })
watch(() => [props.active, props.status], () => restart(false))
const visibility = () => restart(false)
onMounted(() => document.addEventListener('visibilitychange', visibility))
onActivated(() => { suspended = false; restart(false) })
onDeactivated(() => { suspended = true; restart(false) })
onBeforeUnmount(() => { generation++; controller?.abort(); clearTimeout(timer); document.removeEventListener('visibilitychange', visibility) })
</script>
<style scoped>
.scanner-model-panel { margin: 20px 0; padding: 16px; border: 1px solid var(--el-border-color-light); border-radius: 6px; }
.model-heading, .model-actions, .file-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; }
.model-heading { justify-content: space-between; margin-bottom: 16px; }
h3 { margin: 0 0 6px; font-size: 16px; }
.model-hint { color: var(--el-text-color-secondary); font-size: 13px; line-height: 1.6; }
.file-select { width: min(420px, 100%); }
.file-info { margin: 12px 0; overflow-wrap: anywhere; }
</style>

View File

@ -0,0 +1,111 @@
<template>
<div class="model-viewer" :data-model-parse-ms="parseMs" :data-model-render-count="renderCount" :data-model-hydrate-ms="hydrateMs">
<div class="model-toolbar">
<el-button size="small" @click="fit">复位视角</el-button>
<el-checkbox v-model="axesVisible" @change="updateAxes">坐标轴</el-checkbox>
<template v-if="info.points"><span>点大小</span><el-slider v-model="pointSize" :min="1" :max="6" :step="0.5" class="point-slider" @input="updatePointSize" /></template>
<span class="model-hint">拖动旋转 · 滚轮缩放 · 右键平移</span>
</div>
<div ref="container" class="model-canvas" v-loading="loading"><el-empty v-if="error" :description="error" /></div>
<div class="model-hint" v-if="info.vertices">{{ info.points ? `点数 ${info.points.toLocaleString()}` : `顶点 ${info.vertices.toLocaleString()} · 三角面 ${info.triangles.toLocaleString()}` }} · 按文件原始坐标显示</div>
<div class="model-hint" v-if="info.points > info.displayedPoints">当前预览 {{ info.displayedPoints.toLocaleString() }} 点,完整数据保留在原始文件中,可下载查看。</div>
</div>
</template>
<script setup>
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import { getScannerAsset } from '@/api/lab/scan-task/scannerView'
import { disposeScannerModel } from './scannerModel.mjs'
import { hydrateScannerModel } from './scannerModelTransfer.mjs'
import { parseScannerModelAsync } from './scannerModelWorker.mjs'
import { createScannerRenderer } from './scannerRender.mjs'
const props = defineProps({ executionId: { type: [String, Number], required: true }, asset: { type: Object, required: true } })
const container = ref()
const loading = ref(false), error = ref(''), axesVisible = ref(false), pointSize = ref(2)
const info = ref({ vertices: 0, points: 0, displayedPoints: 0, triangles: 0 })
const parseMs = ref(0), hydrateMs = ref(0), renderCount = ref(0)
let renderer, scene, camera, controls, model, axes, resizeObserver, intersectionObserver, controller, frames
let intersecting = true, suspended = false
let generation = 0
function updateAxes() { if (axes) axes.visible = axesVisible.value; frames?.invalidate() }
function updatePointSize() { model?.object.traverse(item => { if (item.isPoints) item.material.size = pointSize.value }); frames?.invalidate() }
function visibility() { frames?.setVisible(intersecting && !document.hidden && !suspended) }
function fit() {
if (!model || !camera) return
const center = model.bounds.getCenter(new THREE.Vector3())
const size = Math.max(model.bounds.getSize(new THREE.Vector3()).length(), 0.001)
const distance = size / (2 * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2))) * 1.35 / Math.min(1, camera.aspect)
camera.position.copy(center).add(new THREE.Vector3(distance * 0.6, distance * 0.45, distance))
camera.near = Math.max(size / 10000, 0.000001); camera.far = Math.max(size * 100, distance * 10)
camera.updateProjectionMatrix(); controls.target.copy(center); controls.update()
if (axes) { axes.position.copy(center); axes.scale.setScalar(size * 0.2) }
frames?.invalidate()
}
async function load() {
const token = ++generation
controller?.abort(); controller = new AbortController()
loading.value = true; error.value = ''
if (model) { scene?.remove(model.object); disposeScannerModel(model.object); model = undefined }
info.value = { vertices: 0, points: 0, displayedPoints: 0, triangles: 0 }
try {
if (!renderer || !scene || !controls) throw new Error('当前浏览器无法启用三维显示,请检查浏览器图形支持')
const bytes = await getScannerAsset(props.executionId, props.asset.fileId, controller.signal)
if (token !== generation) return
const data = await parseScannerModelAsync(bytes, props.asset.name, controller.signal)
if (token !== generation) return
const started = performance.now()
model = hydrateScannerModel(data)
hydrateMs.value = performance.now() - started; parseMs.value = data.parseMs
scene.add(model.object); info.value = { vertices: model.vertices, points: model.points, displayedPoints: model.displayedPoints, triangles: model.triangles }; updatePointSize(); fit()
} catch (failure) { if (token === generation && failure.name !== 'AbortError') error.value = failure.message || '三维文件加载失败' }
finally { if (token === generation) loading.value = false }
}
onMounted(() => {
try {
renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2))
scene = new THREE.Scene(); scene.background = new THREE.Color(0xf5f7fa)
camera = new THREE.PerspectiveCamera(45, 1, 0.01, 10000)
controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true
frames = createScannerRenderer(() => { controls.update(); renderer.render(scene, camera); renderCount.value++ })
controls.addEventListener('change', frames.invalidate)
scene.add(new THREE.HemisphereLight(0xffffff, 0x667788, 2.5))
const light = new THREE.DirectionalLight(0xffffff, 2); light.position.set(1, 2, 3); scene.add(light)
axes = new THREE.AxesHelper(1); axes.visible = axesVisible.value; scene.add(axes)
container.value.appendChild(renderer.domElement)
resizeObserver = new ResizeObserver(() => {
const width = container.value.clientWidth, height = container.value.clientHeight
if (!width || !height) return
renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); frames.invalidate()
})
resizeObserver.observe(container.value)
intersectionObserver = new IntersectionObserver(entries => { intersecting = entries[0].isIntersecting; visibility() })
intersectionObserver.observe(container.value)
document.addEventListener('visibilitychange', visibility)
visibility()
} catch { error.value = '当前浏览器无法启用三维显示,请检查浏览器图形支持' }
load()
})
watch([() => props.executionId, () => props.asset.fileId], () => { if (container.value) load() })
onActivated(() => { suspended = false; visibility(); if (!model && !loading.value && container.value) load() })
onDeactivated(() => { suspended = true; generation++; controller?.abort(); loading.value = false; visibility() })
onBeforeUnmount(() => {
generation++; controller?.abort(); resizeObserver?.disconnect(); intersectionObserver?.disconnect()
document.removeEventListener('visibilitychange', visibility)
frames?.dispose(); controls?.dispose()
disposeScannerModel(model?.object); axes?.geometry.dispose(); axes?.material.dispose()
renderer?.dispose(); renderer?.domElement.remove()
})
</script>
<style scoped>
.model-toolbar { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; margin-bottom: 12px; }
.model-canvas { height: 440px; position: relative; overflow: hidden; border-radius: 4px; background: #f5f7fa; }
.model-canvas :deep(canvas) { display: block; }
.model-canvas :deep(.el-empty) { position: absolute; inset: 0; z-index: 1; background: #f5f7fa; }
.model-hint { color: var(--el-text-color-secondary); font-size: 13px; margin-top: 8px; }
.point-slider { width: 110px; }
@media (max-width: 768px) { .model-canvas { height: 320px; } }
</style>

View File

@ -843,11 +843,12 @@ const refresh = async (replaceForm = false) => {
const result = await ScanApi.getDetail(taskId.value)
if (generation !== pageGeneration) return
const previousRevision = detail.value?.config.revision
const previousStartedAt = detail.value?.config.startedAt
detail.value = result
if (
replaceForm ||
(!dirty.value && previousRevision !== result.config.revision) ||
result.config.startedAt
(result.config.startedAt && previousStartedAt !== result.config.startedAt)
) {
const config = result.config
Object.assign(form, {
@ -1226,6 +1227,7 @@ const openLogs = (execution: Partial<LabExecutionVO>) => {
logVisible.value = true
}
let timer: ReturnType<typeof setInterval> | undefined
let pollingSuspended = false
const initialize = async () => {
logVisible.value = false
logSelection.value = undefined
@ -1262,11 +1264,13 @@ const initialize = async () => {
onMounted(() => {
initialize().catch(() => {})
timer = setInterval(() => {
if (!document.hidden && !busy.value) {
if (!pollingSuspended && !document.hidden && !busy.value && !terminal.value) {
refresh().catch(() => {})
}
}, 3000)
})
onActivated(() => { pollingSuspended = false })
onDeactivated(() => { pollingSuspended = true })
watch(() => route.params.id, initialize)
onBeforeRouteLeave(async () => {
if (dirty.value && !locked.value) {

View File

@ -0,0 +1,24 @@
export const MAX_SCANNER_MODEL_BYTES = 100 * 1024 * 1024
export async function readScannerBinary(response, maximum = MAX_SCANNER_MODEL_BYTES) {
const error = () => new Error('文件超过在线查看限制,请使用原始成果下载')
if (Number(response.headers.get('content-length')) > maximum) {
await response.body?.cancel(); throw error()
}
if (!response.body) return new ArrayBuffer(0)
const reader = response.body.getReader(), chunks = []
let size = 0
try {
while (true) {
const { value, done } = await reader.read()
if (done) break
size += value.byteLength
if (size > maximum) { await reader.cancel(); throw error() }
chunks.push(value)
}
const bytes = new Uint8Array(size)
let offset = 0
for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength }
return bytes.buffer
} finally { reader.releaseLock() }
}

View File

@ -0,0 +1,19 @@
const terminal = new Set(['SUCCESS','SUCCEEDED','COMPLETED','SKIPPED','FAILED','ERROR','STOPPED','CANCELLED','0','2','4'])
const valid = row => /^\d+$/.test(String(row?.id ?? ''))
const compare = (a, b) => BigInt(a.id) < BigInt(b.id) ? -1 : BigInt(a.id) > BigInt(b.id) ? 1 : 0
// Include the oldest unfinished row so a RUNNING -> SUCCESS update cannot be lost.
export function scannerLogCursor(rows = []) {
const sorted = rows.filter(valid).sort(compare)
const pending = sorted.find(row => !terminal.has(String(row.status).toUpperCase()))
return pending?.id ?? sorted.at(-1)?.id
}
export function mergeScannerLogs(previous = [], incoming = []) {
const byId = new Map(previous.filter(valid).map(row => [String(row.id), row]))
let changed = false
for (const row of incoming.filter(valid)) {
const old = byId.get(String(row.id))
if (!old || JSON.stringify(old) !== JSON.stringify(row)) { byId.set(String(row.id), row); changed = true }
}
return changed ? [...byId.values()].sort(compare) : previous
}

View File

@ -0,0 +1,23 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { scannerLogCursor, mergeScannerLogs } from './scannerLogs.mjs'
test('增量游标覆盖最早未完成节点,不能丢失运行中节点转成功的日志', () => {
const rows = [{id:'1',status:'SUCCESS'},{id:'2',status:'RUNNING'},{id:'3',status:'SUCCESS'}]
assert.equal(scannerLogCursor(rows),'2')
const updated = mergeScannerLogs(rows,[{id:'2',status:'SUCCESS',paramsOut:'{"ok":true}'},{id:'3',status:'SUCCESS'},{id:'4',status:'RUNNING'}])
assert.equal(updated.length,4); assert.equal(updated[1].status,'SUCCESS'); assert.equal(scannerLogCursor(updated),'4')
assert.equal(updated[0],rows[0], '已完成历史日志应保留')
})
test('同一页重复返回不复制日志或触发整个日志区域重新计算', () => {
const rows = [{id:'5',status:'SUCCESS',message:'done'}]
assert.equal(mergeScannerLogs(rows,[{...rows[0]}]),rows)
assert.equal(scannerLogCursor(rows),'5'); assert.equal(scannerLogCursor([]),undefined)
})
test('暂停与未知状态继续追踪,64位日志编号不经过浮点转换', () => {
const rows = [{id:'9007199254740993',status:'SUCCESS'},{id:'9007199254740992',status:'PAUSED'}]
assert.equal(scannerLogCursor(rows),'9007199254740992')
const merged = mergeScannerLogs(rows,[{id:'9007199254740994',status:'RUNNING'}])
assert.deepEqual(merged.map(row=>row.id),['9007199254740992','9007199254740993','9007199254740994'])
assert.equal(scannerLogCursor([{id:'1',status:'UNRECOGNIZED'},{id:'2',status:'SUCCESS'}]),'1')
})

View File

@ -0,0 +1,64 @@
import * as THREE from 'three'
import { PLYLoader } from 'three/examples/jsm/loaders/PLYLoader.js'
import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js'
export const modelFormat = name => /\.(ply|stl|obj)$/i.exec(name || '')?.[1]?.toLowerCase() || ''
export function disposeScannerModel(root) {
root?.traverse(item => {
item.geometry?.dispose()
const materials = Array.isArray(item.material) ? item.material : [item.material]
materials.forEach(material => material?.dispose())
})
}
export function parseScannerModel(buffer, name) {
const format = modelFormat(name)
const group = new THREE.Group()
try {
if (format === 'obj') group.add(new OBJLoader().parse(new TextDecoder().decode(buffer)))
else if (format === 'ply' || format === 'stl') {
const geometry = format === 'ply' ? new PLYLoader().parse(buffer) : new STLLoader().parse(buffer)
const header = format === 'ply' ? new TextDecoder().decode(new Uint8Array(buffer, 0, Math.min(buffer.byteLength, 65536))).split('end_header')[0] : ''
const mesh = format === 'stl' || Number(/element\s+face\s+(\d+)/i.exec(header)?.[1] || 0) > 0
if (mesh) {
if (format === 'ply') {
const faces = Number(/element\s+face\s+(\d+)/i.exec(header)?.[1] || 0)
// PLYLoader expands indices only for per-face UVs/colors.
const faceProperties = /element\s+face\s+\d+([^]*?)(?:\nelement\s|$)/i.exec(header)?.[1] || ''
const expanded = /property\s+list\s+\w+\s+\w+\s+texcoord\b|property\s+\w+\s+red\b/i.test(faceProperties)
const indices = geometry.index ? geometry.index.count : expanded ? geometry.getAttribute('position').count : 0
if (indices < faces * 3) { geometry.dispose(); throw new Error('三维文件三角面数据不完整') }
}
group.add(new THREE.Mesh(geometry, new THREE.MeshStandardMaterial({ color: geometry.hasAttribute('color') ? 0xffffff : 0xa6c5dc, vertexColors: geometry.hasAttribute('color'), side: THREE.DoubleSide, roughness: 0.8 })))
} else group.add(new THREE.Points(geometry, new THREE.PointsMaterial({ color: geometry.hasAttribute('color') ? 0xffffff : 0x3d8bbd, vertexColors: geometry.hasAttribute('color'), size: 2, sizeAttenuation: false })))
} else throw new Error('在线查看支持 PLY 点云/网格、STL 和 OBJ 文件')
let vertices = 0, triangles = 0, points = 0
group.traverse(item => {
const position = item.geometry?.getAttribute('position')
if (!position) return
for (const [name, attribute] of Object.entries(item.geometry.attributes)) {
if (attribute.count !== position.count) throw new Error('三维文件属性数量不完整')
for (let i = 0; i < attribute.array.length; i++) {
if (!Number.isFinite(attribute.array[i])) throw new Error(name === 'position' ? '三维文件包含无效坐标' : '三维文件包含无效属性')
}
}
if (item.isMesh) {
const index = item.geometry.index
const count = index ? index.count : position.count
if (!count || count % 3 !== 0) throw new Error('三维文件三角面数据不完整')
if (index) for (let i = 0; i < index.count; i++) {
const vertex = index.getX(i)
if (!Number.isInteger(vertex) || vertex < 0 || vertex >= position.count) throw new Error('三维文件包含无效顶点索引')
}
if (!item.geometry.hasAttribute('normal')) item.geometry.computeVertexNormals()
}
vertices += position.count
if (item.isPoints) points += position.count
if (item.isMesh) triangles += (item.geometry.index ? item.geometry.index.count : position.count) / 3
})
if (!vertices) throw new Error('设备返回的文件中没有可显示的三维数据')
const bounds = new THREE.Box3().setFromObject(group)
if (bounds.isEmpty() || !Number.isFinite(bounds.getSize(new THREE.Vector3()).length())) throw new Error('三维数据范围无效')
return { object: group, bounds, vertices, triangles: Math.floor(triangles), points }
} catch (error) { disposeScannerModel(group); throw error }
}

View File

@ -0,0 +1,68 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { parseScannerModel, disposeScannerModel, modelFormat } from './scannerModel.mjs'
const buffer = text => new TextEncoder().encode(text).buffer
const header = (count, extra = '') => `ply\nformat ascii 1.0\nelement vertex ${count}\nproperty float x\nproperty float y\nproperty float z\n${extra}end_header\n`
test('解析带颜色的点云,保留真实坐标范围和颜色', () => {
const model = parseScannerModel(buffer(header(2, 'property uchar red\nproperty uchar green\nproperty uchar blue\n') + '1 2 3 255 0 0\n4 5 6 0 255 0\n'), 'points.PLY')
assert.equal(model.points, 2); assert.equal(model.triangles, 0)
assert.deepEqual(model.bounds.min.toArray(), [1, 2, 3]); assert.deepEqual(model.bounds.max.toArray(), [4, 5, 6])
assert.equal(model.object.children[0].geometry.getAttribute('color').count, 2)
let disposed = 0
model.object.children[0].geometry.addEventListener('dispose', () => disposed++)
disposeScannerModel(model.object); assert.equal(disposed, 1)
})
test('解析二进制小端PLY点云', () => {
const prefix = new TextEncoder().encode('ply\nformat binary_little_endian 1.0\nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nend_header\n')
const bytes = new Uint8Array(prefix.length + 12); bytes.set(prefix)
const view = new DataView(bytes.buffer)
;[1, -2, 3].forEach((value, index) => view.setFloat32(prefix.length + index * 4, value, true))
const model = parseScannerModel(bytes.buffer, 'cloud.ply')
assert.equal(model.points, 1); assert.deepEqual(model.bounds.min.toArray(), [1, -2, 3]); disposeScannerModel(model.object)
})
test('区分PLY网格和点云,并解析STL及OBJ三角面', () => {
const ply = header(3, 'element face 1\nproperty list uchar int vertex_indices\n') + '0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n'
const stl = 'solid s\nfacet normal 0 0 1\nouter loop\nvertex 0 0 0\nvertex 1 0 0\nvertex 0 1 0\nendloop\nendfacet\nendsolid s'
const obj = 'mtllib ignored-external.mtl\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n'
for (const [name, data] of [['mesh.ply', ply], ['mesh.stl', stl], ['mesh.obj', obj]]) {
const model = parseScannerModel(buffer(data), name)
assert.equal(model.triangles, 1); assert.equal(model.points, 0); assert.equal(model.vertices, 3); disposeScannerModel(model.object)
}
})
test('拒绝空数据、无效坐标和未经支持的格式', () => {
assert.throws(() => parseScannerModel(buffer(header(0)), 'empty.ply'), /没有可显示/)
assert.throws(() => parseScannerModel(buffer(header(1) + 'NaN 2 3\n'), 'invalid.ply'), /无效坐标/)
assert.throws(() => parseScannerModel(buffer('data'), 'part.stp'), /支持 PLY/)
assert.equal(modelFormat('manifest.json'), '')
})
test('拒绝引用不存在顶点的PLY三角面,避免发送无效索引到GPU', () => {
const prefix = header(3, 'element face 1\nproperty list uchar int vertex_indices\n') + '0 0 0\n1 0 0\n0 1 0\n'
for (const face of ['3 0 1 99\n', '3 0 1 -1\n']) {
assert.throws(() => parseScannerModel(buffer(prefix + face), 'broken.ply'), /索引|无效/)
}
})
test('声明了面的PLY不能以缺失三角面冒充可用网格', () => {
const source = header(3, 'element face 1\nproperty list uchar int vertex_indices\n') + '0 0 0\n1 0 0\n0 1 0\n'
assert.throws(() => parseScannerModel(buffer(source), 'truncated.ply'), /三角面|不完整|无效/)
})
test('拒绝非有限法向量和颜色,避免模型显示黑屏或渲染异常', () => {
const normal = header(1, 'property float nx\nproperty float ny\nproperty float nz\n') + '1 2 3 NaN 0 1\n'
const color = header(1, 'property float red\nproperty float green\nproperty float blue\n') + '1 2 3 NaN 0 1\n'
assert.throws(() => parseScannerModel(buffer(normal), 'normal.ply'), /无效/)
assert.throws(() => parseScannerModel(buffer(color), 'color.ply'), /无效/)
})
test('正常四边形和逐面颜色PLY仍能展开为可用三角面', () => {
const quad = header(4, 'element face 1\nproperty list uchar int vertex_indices\n') + '0 0 0\n1 0 0\n1 1 0\n0 1 0\n4 0 1 2 3\n'
const colored = header(3, 'element face 1\nproperty list uchar int vertex_indices\nproperty uchar red\nproperty uchar green\nproperty uchar blue\n') + '0 0 0\n1 0 0\n0 1 0\n3 0 1 2 255 0 0\n'
for (const [source, triangles] of [[quad, 2], [colored, 1]]) {
const model = parseScannerModel(buffer(source), 'valid.ply')
assert.equal(model.triangles, triangles)
disposeScannerModel(model.object)
}
})

View File

@ -0,0 +1,10 @@
import { prepareScannerModel } from './scannerModelTransfer.mjs'
self.onmessage = ({ data: { buffer, name } }) => {
try {
const started = performance.now()
const result = prepareScannerModel(buffer, name)
result.data.parseMs = performance.now() - started
self.postMessage({ data: result.data }, result.transfer)
} catch (error) { self.postMessage({ error: error.message || '三维文件解析失败' }) }
}

Some files were not shown because too many files have changed in this diff Show More