feat(scanner): show native calibration window and SDK progress

Use the existing successful calibration-enter workflow to display the same SDK manufacturer's window and actual callback progress in the task UI. Bind metadata, JPEG and MJPEG to the execution, SDK session, calibration ID and trusted process/window identity; closing the monitor only stops viewing.

Include source-only FreeScanCpp integration, WGC capture lifecycle fixes and immediate ENTER acknowledgement cache synchronization. Preserve original scanner project guards, regression sources and third-party licensing; exclude private runtime configuration and generated artifacts.

Validated platform Java compilation/regressions, frontend type checks and standalone build, native compilation/offline and HTTP regressions, immediate calibration identity checks and ten synthetic window close/reopen cycles. Production installation/restart and real scanner calibration remain pending.
This commit is contained in:
Codex 2026-11-21 19:52:07 +08:00
parent 6874fabeb6
commit a16f16e19a
61 changed files with 38567 additions and 103 deletions

5
.gitignore vendored
View File

@ -16,3 +16,8 @@
**/__pycache__/ **/__pycache__/
am-backend/script/ am-backend/script/
am-backend/sql/AM.sql am-backend/sql/AM.sql
integrations/freescan-service/build/
integrations/freescan-service/bin/
integrations/freescan-service/tests/bin/
integrations/freescan-service/**/api-settings.json
integrations/freescan-service/**/settings.xml

View File

@ -1,5 +1,7 @@
# AM FreeScan 开发约定 # AM FreeScan 开发约定
- 2026-11-21 用户要求平台显示厂家 FreeScan Trak 的实际标定页面(前视图、俯视图、操作提示)及 SDK 回调真实进度,明确须先 Sn3DEnterCalibrationPage。已授权将扫描仪服务纯源码副本纳入 integrations/freescan-service,原安装保持不动;通过同一 SDK 服务显示并采集受信厂家窗口,独立 calibration/view 接口与 calibrationId 关联。普通 preview/start 要求扫描工程并拒绝标定,不可再自动插入该步骤。本轮已完成代码、编译、离线和合成窗口验证。2026-11-21 用户另行明确要求核对当日修改并上传最新代码,授权提交并推送现有 main;不包含安装、重启服务或实际标定,正式生效和厂家真机画面验收仍需用户当次指示。
- 2026-11-21 同站点导航修复补充:边端按新鲜地图/目标几何、双来源当前站点和连续停稳确认已在目标站点时,同步请求可直接成功,不要求生成新控制器任务。平台仅对显式同步请求且业务结果头完整success=true的完成确认结束当前节点,禁止再用控制器旧全局None/Failed/Canceled否定本次成功;异步与旧未确认实现继续原轮询,缺失/失败业务回执和通信异常不算成功。边端定位有效性沿用既有driver的confidence>0契约并校验有限/<=1,不再另造0.95门槛,未知loc_state仅诊断不猜枚举;不以closest_target或历史任务单独证明到位。 - 2026-11-21 同站点导航修复补充:边端按新鲜地图/目标几何、双来源当前站点和连续停稳确认已在目标站点时,同步请求可直接成功,不要求生成新控制器任务。平台仅对显式同步请求且业务结果头完整success=true的完成确认结束当前节点,禁止再用控制器旧全局None/Failed/Canceled否定本次成功;异步与旧未确认实现继续原轮询,缺失/失败业务回执和通信异常不算成功。边端定位有效性沿用既有driver的confidence>0契约并校验有限/<=1,不再另造0.95门槛,未知loc_state仅诊断不猜枚举;不以closest_target或历史任务单独证明到位。
- 2026-11-21 用户要求坐标系使用只保存名称、按名称调用。GET/APPLY、工作流目标位姿和命名MoveL/MoveJPose、动作队列使用节点忽略历史固定版本;新保存剔除对应版本字段,不改写数据库中的冻结版本及历史执行。UPDATE/DELETE仍保留记录版本并发保护。内部必须继续核对同名最新记录已完整实际应用、实际TCP和运动期间记录身份,不能为按名字调用取消这些检查、自动应用或重发运动。用户本轮明确授权全部平台代码完成验证后提交并推送现有main;不据此重启正式服务或部署边端。 - 2026-11-21 用户要求坐标系使用只保存名称、按名称调用。GET/APPLY、工作流目标位姿和命名MoveL/MoveJPose、动作队列使用节点忽略历史固定版本;新保存剔除对应版本字段,不改写数据库中的冻结版本及历史执行。UPDATE/DELETE仍保留记录版本并发保护。内部必须继续核对同名最新记录已完整实际应用、实际TCP和运动期间记录身份,不能为按名字调用取消这些检查、自动应用或重发运动。用户本轮明确授权全部平台代码完成验证后提交并推送现有main;不据此重启正式服务或部署边端。

View File

@ -30,6 +30,27 @@ public class ScannerCommandJournal {
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) 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); .stream().map(this::parseContext).max(Comparator.comparingLong(node->node.path("capturedAt").asLong())).orElse(null);
} }
/** Calibration owns a session without opening a scanning project. Recovery retires that binding. */
public JsonNode calibrationContext(String instId) {
return jdbc.queryForList("SELECT context_json FROM lab_scanner_command WHERE owner_ref=? AND operation='CALIBRATION_ENTER' AND state='SUCCEEDED' AND context_json IS NOT NULL",String.class,"workflow:"+instId)
.stream().map(this::parseContext).filter(node->!node.path("retired").asBoolean())
.max(Comparator.comparingLong(node->node.path("capturedAt").asLong())).orElse(null);
}
public void retireCalibrationContext(String instId) {
var records=jdbc.query("SELECT command_key,context_json FROM lab_scanner_command WHERE owner_ref=? AND operation='CALIBRATION_ENTER' AND state='SUCCEEDED' AND context_json IS NOT NULL",(row,n)->Map.of("key",row.getString(1),"context",row.getString(2)),"workflow:"+instId);
for(var record:records) {
String original=record.get("context");
var context=(com.fasterxml.jackson.databind.node.ObjectNode)parseContext(original);
if(context.path("retired").asBoolean())continue;
context.put("retired",true);
jdbc.update("UPDATE lab_scanner_command SET context_json=? WHERE command_key=? AND owner_ref=? AND context_json=?",context.toString(),record.get("key"),"workflow:"+instId,original);
}
}
/** Compare the complete original context so retirement or a newer preview cannot be overwritten. */
public boolean refreshCalibrationContext(String instId,JsonNode original,JsonNode updated) {
return jdbc.update("UPDATE lab_scanner_command SET context_json=? WHERE command_key=? AND owner_ref=? AND operation='CALIBRATION_ENTER' AND state='SUCCEEDED' AND context_json=?",
updated.toString(),original.path("commandKey").asText(),"workflow:"+instId,original.toString())==1;
}
public void bindContext(String key,String instId,JsonNode context) { 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); 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);
} }

View File

@ -20,6 +20,12 @@ public class ScannerMonitoringService {
return capture(operation,commandKey,instId,robot,device,0,0); return capture(operation,commandKey,instId,robot,device,0,0);
} }
public JsonNode capture(ScannerOperation operation,String commandKey,String instId,String robot,String device,int itemOrder,int itemOccurrence) { public JsonNode capture(ScannerOperation operation,String commandKey,String instId,String robot,String device,int itemOrder,int itemOccurrence) {
if(EnumSet.of(ScannerOperation.CALIBRATION_RECOVER,ScannerOperation.CONNECT,ScannerOperation.DISCONNECT,ScannerOperation.RECONNECT,ScannerOperation.CREATE_PROJECT).contains(operation)) {
var completed=journal.get(commandKey);
if(completed!=null&&"SUCCEEDED".equals(completed.state())&&journal.ownedBy(commandKey,instId))journal.retireCalibrationContext(instId);
}
if(operation==ScannerOperation.CALIBRATION_ENTER)
return captureCalibration(commandKey,instId,robot,device,itemOrder,itemOccurrence);
if(operation!=ScannerOperation.CREATE_PROJECT && operation!=ScannerOperation.SCAN_START) { if(operation!=ScannerOperation.CREATE_PROJECT && operation!=ScannerOperation.SCAN_START) {
JsonNode context=journal.latestContext(instId); JsonNode context=journal.latestContext(instId);
if(context!=null&&(operation==ScannerOperation.SNAPSHOT||operation==ScannerOperation.EXPORT)) { if(context!=null&&(operation==ScannerOperation.SNAPSHOT||operation==ScannerOperation.EXPORT)) {
@ -51,6 +57,107 @@ public class ScannerMonitoringService {
return journal.context(commandKey); return journal.context(commandKey);
} }
public JsonNode binding(String instId){return journal.latestContext(instId);} public JsonNode binding(String instId){return journal.latestContext(instId);}
public JsonNode calibrationBinding(String instId){return journal.calibrationContext(instId);}
private JsonNode captureCalibration(String key,String instId,String robot,String device,int order,int occurrence) {
JsonNode existing=journal.context(key);if(existing!=null)return existing;
var command=journal.get(key);
if(command==null||!"CALIBRATION_ENTER".equals(command.operation())||!"SUCCEEDED".equals(command.state())||!journal.ownedBy(key,instId))return null;
if(!client.endpointKey().equals(command.endpoint())||!Objects.equals(robot,settings.getRobotId())||!Objects.equals(device,settings.getDeviceId()))
throw new ScannerException("device_changed","标定命令的扫描设备身份已变化",409);
// Dedicated endpoint reads the supervisor's cached calibration callbacks/window,
// never the scanner SDK status or the 3D preview/project state.
JsonNode view=scanner.get(ScannerOperation.CALIBRATION_VIEW,null);requireCalibrationSession(view);
ObjectNode context=ScannerRequestValidator.JSON.createObjectNode();
context.put("kind","calibration").put("instId",instId).put("robotId",robot).put("deviceId",device);
context.put("itemOrder",order).put("itemOccurrence",occurrence).put("endpoint",client.endpointKey());
context.put("sessionId",view.path("sessionId").asText()).put("calibrationId",view.path("calibrationId").asText()).put("projectId","").put("commandKey",key);
context.put("baselineSequence",calibrationSequence(view)).put("capturedAt",System.currentTimeMillis());
journal.bindContext(key,instId,context);
return journal.context(key);
}
private long calibrationSequence(JsonNode view) {
JsonNode sequence=view.path("frameSequence");
if(!sequence.isIntegralNumber()||!sequence.canConvertToLong()||sequence.asLong()<0)
throw new ScannerException("frame_sequence_unavailable","厂商标定画面缺少有效帧编号",503);
return sequence.asLong();
}
public JsonNode calibrationStatus(JsonNode binding) {
if(binding==null||binding.path("retired").asBoolean()||!"calibration".equals(binding.path("kind").asText()))
throw new ScannerException("calibration_not_bound","等待本次执行成功进入标定流程并关联设备会话",409);
requireBinding(binding);
JsonNode view=scanner.get(ScannerOperation.CALIBRATION_VIEW,null);requireCalibrationSession(view);
if(!binding.path("sessionId").asText().equals(view.path("sessionId").asText())
||!binding.path("calibrationId").asText().equals(view.path("calibrationId").asText()))
throw new ScannerException("session_changed","扫描会话已切换,停止本次标定画面",409);
return view;
}
public JsonNode calibrationSourceBinding(JsonNode binding) {
JsonNode view=calibrationStatus(binding);requireCalibrationSource(view);
ObjectNode source=binding.deepCopy();source.set("frameSource",view.path("frameSource").deepCopy());
return source;
}
public ScannerPreviewStream calibrationStream(JsonNode binding) {
JsonNode view=calibrationStatus(binding);requireCalibrationSource(view);
if(!view.path("frameSource").equals(binding.path("frameSource")))
throw new ScannerException("calibration_source_changed","厂商标定窗口身份已变化,请重新核对画面",409);
var source=scanner.binary(ScannerOperation.CALIBRATION_STREAM,null);
try{return new ScannerPreviewStream(source);}
catch(RuntimeException invalid){try{source.close();}catch(IOException ignored){}throw invalid;}
}
public long calibrationFrameSequence(JsonNode binding,Frame frame) {
requireBinding(binding);
if(binding.path("retired").asBoolean())throw new ScannerException("calibration_not_bound","本次标定会话已结束",409);
JsonNode source=binding.path("frameSource");
if(!"sdk_calibration_window".equals(header(frame.headers(),"x-frame-source"))
||!binding.path("sessionId").asText().equals(header(frame.headers(),"x-frame-session-id"))
||!binding.path("calibrationId").asText().equals(header(frame.headers(),"x-frame-calibration-id"))
||!source.path("pid").asText().equals(header(frame.headers(),"x-frame-source-pid"))
||!source.path("startedAt").asText().equals(header(frame.headers(),"x-frame-source-started-at"))
||!source.path("windowHandle").asText().equals(header(frame.headers(),"x-frame-window-handle")))
throw new ScannerException("calibration_source_changed","画面不属于本次厂商标定窗口,已停止展示",409);
long sequence=streamSequence(binding,frame);
if(sequence<0)throw new ScannerException("invalid_frame","厂商标定画面帧编号无效",502);
return sequence;
}
public Frame calibrationImage(JsonNode binding) {
JsonNode source=calibrationSourceBinding(binding);
try(var binary=scanner.binary(ScannerOperation.CALIBRATION_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);
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||(bytes[bytes.length-2]&255)!=255||(bytes[bytes.length-1]&255)!=217)
throw new ScannerException("invalid_frame","厂商标定画面内容无效",502);
Frame frame=new Frame(bytes,binary.headers());
if(calibrationFrameSequence(source,frame)<=binding.path("baselineSequence").asLong())
throw new ScannerException("frame_pending","等待本次标定的新画面",503);
JsonNode current=calibrationStatus(binding);requireCalibrationSource(current);
if(!current.path("frameSource").equals(source.path("frameSource")))
throw new ScannerException("calibration_source_changed","厂商标定窗口身份已变化,已停止展示",409);
return frame;
}catch(IOException error){throw new ScannerException("frame_unavailable","厂商标定画面读取失败,请稍后重试",503);}
}
private void requireCalibrationSession(JsonNode view) {
if(!"sdk_calibration_window".equals(view.path("source").asText()))
throw new ScannerException("calibration_source_unavailable","当前扫描服务尚未提供真实厂商标定画面",503);
if(!view.path("sessionId").isTextual()||view.path("sessionId").asText().isBlank())
throw new ScannerException("session_not_ready","标定设备会话尚未就绪",409);
if(!view.path("calibrationId").isTextual()||view.path("calibrationId").asText().isBlank()||view.path("calibrationId").asText().length()>128)
throw new ScannerException("calibration_not_bound","厂商标定会话缺少本次标定编号",409);
if(!view.path("calibrationActive").isBoolean()||!view.path("calibrationActive").asBoolean())
throw new ScannerException("calibration_inactive","当前标定会话已结束或尚未进入,厂商画面已停止",409);
calibrationSequence(view);
}
public void requireCalibrationSource(JsonNode view) {
JsonNode source=view.path("frameSource");
if(!view.path("available").isBoolean()||!view.path("available").asBoolean()
||!source.path("pid").isIntegralNumber()||source.path("pid").asLong()<=0
||!source.path("startedAt").isTextual()||!source.path("startedAt").asText().matches("[0-9]{1,20}")
||!source.path("path").isTextual()||source.path("path").asText().isBlank()
||!source.path("windowHandle").isTextual()||source.path("windowHandle").asText().isBlank())
throw new ScannerException("calibration_view_unavailable","真实厂商标定窗口暂不可用,请查看标定画面状态提示",503);
}
public ObjectNode snapshot(String instId,String requestedKey) { public ObjectNode snapshot(String instId,String requestedKey) {
String key=ScannerService.hash("view-snapshot:"+instId+":"+ScannerService.key(requestedKey)); String key=ScannerService.hash("view-snapshot:"+instId+":"+ScannerService.key(requestedKey));

View File

@ -29,6 +29,9 @@ public enum ScannerOperation {
SNAPSHOT("POST", "/api/v1/data/snapshots", "创建原始场景快照", "SCANNER_SNAPSHOT"), SNAPSHOT("POST", "/api/v1/data/snapshots", "创建原始场景快照", "SCANNER_SNAPSHOT"),
SCENE("GET", "/api/v1/data/scene", "读取最近场景摘要", "SCANNER_SCENE"), SCENE("GET", "/api/v1/data/scene", "读取最近场景摘要", "SCANNER_SCENE"),
FILE("GET", "/api/v1/files/{fileId}", "下载已登记导出或快照文件", null), FILE("GET", "/api/v1/files/{fileId}", "下载已登记导出或快照文件", null),
CALIBRATION_VIEW("GET", "/api/v1/calibration/view", "读取厂商标定画面状态", null),
CALIBRATION_IMAGE("GET", "/api/v1/calibration/view/image", "读取厂商标定指引JPEG", null),
CALIBRATION_STREAM("GET", "/api/v1/calibration/view/stream", "订阅厂商标定指引画面", null),
CALIBRATION_ENTER("POST", "/api/v1/calibration/enter", "进入标定流程", "SCANNER_CALIBRATION_ENTER"), CALIBRATION_ENTER("POST", "/api/v1/calibration/enter", "进入标定流程", "SCANNER_CALIBRATION_ENTER"),
CALIBRATION_MODE("POST", "/api/v1/calibration/setMode", "选择标定模式", "SCANNER_CALIBRATION_MODE"), CALIBRATION_MODE("POST", "/api/v1/calibration/setMode", "选择标定模式", "SCANNER_CALIBRATION_MODE"),
CALIBRATION_START("POST", "/api/v1/calibration/start", "开始当前标定", "SCANNER_CALIBRATION_START"), CALIBRATION_START("POST", "/api/v1/calibration/start", "开始当前标定", "SCANNER_CALIBRATION_START"),
@ -54,7 +57,7 @@ public enum ScannerOperation {
} }
public boolean upload() { return this==FRAMEWORK_UPLOAD; } public boolean upload() { return this==FRAMEWORK_UPLOAD; }
public boolean control() { return method.equals("POST")&&!upload(); } public boolean control() { return method.equals("POST")&&!upload(); }
public boolean binary() { return this==FILE || this==PREVIEW_IMAGE || this==PREVIEW_STREAM; } public boolean binary() { return this==FILE || this==PREVIEW_IMAGE || this==PREVIEW_STREAM || this==CALIBRATION_IMAGE || this==CALIBRATION_STREAM; }
public boolean usableWithoutDevice() {return !control()||this==CONNECT||this==DISCONNECT||this==RECONNECT||this==SCAN_STOP||this==CALIBRATION_RECOVER;} public boolean usableWithoutDevice() {return !control()||this==CONNECT||this==DISCONNECT||this==RECONNECT||this==SCAN_STOP||this==CALIBRATION_RECOVER;}
public static ScannerOperation forAction(String action) { public static ScannerOperation forAction(String action) {
return Arrays.stream(values()).filter(op -> op.action!=null && op.action.equals(action)).findFirst().orElse(null); return Arrays.stream(values()).filter(op -> op.action!=null && op.action.equals(action)).findFirst().orElse(null);

View File

@ -15,6 +15,6 @@ public class ScannerStreamingConfiguration implements WebMvcConfigurer {
@Override public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) { @Override public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (request.isAsyncStarted()) request.getAsyncContext().setTimeout(0); if (request.isAsyncStarted()) request.getAsyncContext().setTimeout(0);
} }
}).addPathPatterns("/admin-api/cmvr/scanner/preview/stream", "/admin-api/lab/execution/scanner-view/stream", "/admin-api/lab/master/fixture/framework/preview-stream"); }).addPathPatterns("/admin-api/cmvr/scanner/preview/stream", "/admin-api/lab/execution/scanner-view/stream", "/admin-api/lab/maintenance/scanner-view/stream", "/admin-api/lab/master/fixture/framework/preview-stream");
} }
} }

View File

@ -0,0 +1,43 @@
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.LabMaintenanceScannerViewService;
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 org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
@RestController @RequiredArgsConstructor
@RequestMapping("/lab/maintenance/scanner-view")
@PreAuthorize("@ss.hasPermission('lab:execution:dispatch') or @cmvrSs.hasPermi('test:config:execute') or @cmvrSs.hasPermi('test:inst:list')")
public class LabMaintenanceScannerViewController {
private final LabMaintenanceScannerViewService views;
@GetMapping public CommonResult<JsonNode> view(@RequestParam String instId){return CommonResult.success(views.view(instId));}
@GetMapping("/execution") public CommonResult<JsonNode> execution(@RequestParam String instId){return CommonResult.success(views.execution(instId));}
@GetMapping("/image") public ResponseEntity<byte[]> image(@RequestParam String instId) {
var frame=views.image(instId);
return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).cacheControl(CacheControl.noStore()).body(frame.bytes());
}
@GetMapping("/stream") public ResponseEntity<StreamingResponseBody> stream(@RequestParam String instId) {
views.check(instId);
Long tenant=cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.getRequiredTenantId();
return ResponseEntity.ok().contentType(MediaType.parseMediaType("multipart/x-mixed-replace; boundary=scanframe"))
.cacheControl(CacheControl.noStore()).header("X-Accel-Buffering","no").body(output->{
Long previous=cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.getTenantId();
boolean ignored=cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.isIgnore();
try {
cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.setTenantId(tenant);
cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.setIgnore(false);
views.stream(instId,output);
}catch(ScannerException ended){/* Recheck metadata before reconnecting this calibration session. */}
finally {
cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.setTenantId(previous);
cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.setIgnore(ignored);
}
});
}
@ExceptionHandler(ScannerException.class) public CommonResult<?> scannerError(ScannerException error){return CommonResult.error(error.remoteStatus,error.getMessage());}
}

View File

@ -0,0 +1,149 @@
package cn.iocoder.yudao.module.lab.service.execution;
import com.cmvr.scanner.*;
import com.cmvr.test.enums.TaskStatusEnum;
import com.cmvr.test.flow.context.TaskContext;
import com.cmvr.test.flow.context.TaskInstHolder;
import com.cmvr.test.flow.runtime.engine.RobotDeviceAssignmentValidator;
import com.cmvr.test.model.domain.TeTaskInst;
import com.cmvr.test.service.ITeTaskInstService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;
/** Read-only calibration monitoring bound to the frozen trial, assigned scanner and current occupation. */
@Service @RequiredArgsConstructor
public class LabMaintenanceScannerViewService {
private static final Semaphore SLOTS=new Semaphore(2);
private static final ScheduledExecutorService GUARDS=Executors.newScheduledThreadPool(2,r->{Thread t=new Thread(r,"calibration-preview-guard");t.setDaemon(true);return t;});
private final ITeTaskInstService instances;
private final TaskInstHolder runtime;
private final RobotDeviceAssignmentValidator devices;
private final ScannerProperties settings;
private final ScannerMonitoringService monitoring;
private record Frozen(TeTaskInst instance,JsonNode request,JsonNode flow) {}
private Frozen required(String id) {
CmvrMethodBindingService.requirePrimaryTenant();
if(id==null||!id.matches("[a-fA-F0-9]{32}"))throw new ScannerException("instance_not_found","标定执行实例不存在",404);
var instance=instances.getById(id);
if(instance==null||!"TRIAL".equals(instance.getRunMode()))throw new ScannerException("instance_not_found","标定快捷执行实例不存在",404);
try {
var request=ScannerRequestValidator.JSON.readTree(instance.getConfig());
var flow=ScannerRequestValidator.JSON.readTree(request.path("flowData").asText());
boolean calibration=false;
for(var node:flow.path("nodes"))if(node.path("properties").path("action").asText().startsWith("SCANNER_CALIBRATION_"))calibration=true;
if(!calibration)throw new ScannerException("not_calibration","本次执行不是扫描仪标定流程",409);
return new Frozen(instance,request,flow);
}catch(ScannerException known){throw known;}
catch(Exception invalid){throw new ScannerException("snapshot_invalid","本次标定执行的冻结流程不可用",409);}
}
public ObjectNode execution(String id) {
var frozen=required(id);var instance=frozen.instance();
var result=ScannerRequestValidator.JSON.createObjectNode().put("instId",id).put("status",instance.getStatus())
.put("flowData",frozen.request().path("flowData").asText()).put("itemId",frozen.request().path("itemId").asText());
if(instance.getCreateTime()==null)result.putNull("createTime");else result.put("createTime",instance.getCreateTime().getTime());
if(instance.getUpdateTime()==null)result.putNull("updateTime");else result.put("updateTime",instance.getUpdateTime().getTime());
return result;
}
private Frozen active(String id) {
var frozen=required(id);var instance=frozen.instance();var context=runtime.getContext(id);
if(!("1".equals(instance.getStatus())||"3".equals(instance.getStatus()))||context==null||context.isStopped()
||context.getStatus()!=TaskStatusEnum.RUNNING&&context.getStatus()!=TaskStatusEnum.PAUSED)
throw new ScannerException("execution_finished","本次标定执行已结束,实时画面已停止",409);
if(!settings.configured())throw new ScannerException("not_configured","扫描服务待配置,标定画面暂不可用",503);
if(settings.getRobotId().isBlank()||settings.getDeviceId().isBlank()||!runtime.ownsRobot(id,settings.getRobotId()))
throw new ScannerException("occupation_changed","本次标定未持有当前扫描设备的执行占用",409);
if(!scannerAssigned(frozen,context))throw new ScannerException("device_not_assigned","本次标定的冻结流程与实际分配未绑定当前扫描设备",409);
try{devices.validateAssignment(settings.getRobotId(),settings.getDeviceId(),14);}
catch(RuntimeException changed){throw new ScannerException("device_not_assigned","本次标定的扫描设备登记或启用状态已变化",409);}
return frozen;
}
private boolean scannerAssigned(Frozen frozen,TaskContext context) {
for(var node:frozen.flow().path("nodes")) {
var properties=node.path("properties");
if(!properties.path("action").asText().startsWith("SCANNER_CALIBRATION_"))continue;
var target=properties.path("executionTarget");String role=target.path("roleKey").asText();String slot=target.path("deviceSlotKey").asText();
if(!role.isBlank()&&!slot.isBlank()) {
boolean frozenAssigned=false;
for(var assignment:frozen.request().path("runtimeAssignments"))if(role.equals(assignment.path("roleKey").asText())) {
var member=assignment.path("members").path(0);
frozenAssigned|=settings.getRobotId().equals(member.path("robotId").asText())&&settings.getDeviceId().equals(member.path("devices").path(slot).asText());
}
if(!frozenAssigned||context.getRuntimeAssignments()==null)continue;
for(var assignment:context.getRuntimeAssignments())if(role.equals(assignment.getRoleKey())&&assignment.getMembers()!=null&&!assignment.getMembers().isEmpty()) {
var member=assignment.getMembers().get(0);
if(settings.getRobotId().equals(member.getRobotId())&&member.getDevices()!=null&&settings.getDeviceId().equals(member.getDevices().get(slot)))return true;
}
} else if(settings.getRobotId().equals(frozen.instance().getRobotId())&&settings.getRobotId().equals(context.getRobotId())) {
for(var param:properties.path("nodeParams"))if("deviceId".equals(param.path("name").asText())&&"input".equals(param.path("type").asText())&&settings.getDeviceId().equals(param.path("input").asText()))return true;
}
}
return false;
}
private JsonNode binding(String id) {
var binding=monitoring.calibrationBinding(id);
if(binding==null||!id.equals(binding.path("instId").asText()))throw new ScannerException("calibration_not_bound","等待本次执行成功进入标定流程并关联设备会话",409);
return binding;
}
public ObjectNode view(String id) {
var frozen=required(id);
var result=ScannerRequestValidator.JSON.createObjectNode().put("instId",id).put("executionId",id).put("executionNo","扫描仪标定")
.put("executionStatus",switch(Objects.toString(frozen.instance().getStatus(),"")){case "1"->"RUNNING";case "3"->"PAUSED";case "0"->"SUCCESS";case "2"->"FAILED";default->"STOPPED";})
.put("source","sdk_calibration_window").put("available",false).put("calibrationActive",false);
result.putNull("progress");result.putNull("temperatures");
try {
active(id);var binding=binding(id);var status=monitoring.calibrationStatus(binding);
if(status.path("available").asBoolean())monitoring.requireCalibrationSource(status);
result.put("available",status.path("available").asBoolean()).put("calibrationActive",true);
result.put("state",status.path("state").asText("unavailable")).put("message",status.path("message").asText(""));
for(String key:List.of("robotId","deviceId","sessionId","calibrationId"))result.put(key,binding.path(key).asText());
result.set("frameSequence",status.path("frameSequence"));
// Host filesystem paths/window handles stay inside the server's source proof.
for(String key:List.of("progress","temperatures"))if(!status.path(key).isMissingNode())result.set(key,status.path(key));
}catch(ScannerException unavailable){result.put("state",unavailable.scannerCode).put("message",unavailable.getMessage());}
return result;
}
public void check(String id) {
active(id);monitoring.calibrationSourceBinding(binding(id));
}
public ScannerMonitoringService.Frame image(String id) {
active(id);JsonNode original=binding(id);
var frame=monitoring.calibrationImage(original);unchanged(id,original);return frame;
}
private void unchanged(String id,JsonNode original) {
active(id);var latest=binding(id);
if(!original.path("commandKey").equals(latest.path("commandKey"))||!original.path("sessionId").equals(latest.path("sessionId"))
||!original.path("calibrationId").equals(latest.path("calibrationId"))
||!original.path("endpoint").equals(latest.path("endpoint"))||latest.path("retired").asBoolean())
throw new ScannerException("session_changed","本次标定会话关联已变化,实时画面已停止",409);
}
public void stream(String id,OutputStream output)throws IOException {
if(!SLOTS.tryAcquire())throw new ScannerException("stream_busy","标定实时预览连接已满,请关闭其他预览窗口",429);
try {
active(id);JsonNode binding=monitoring.calibrationSourceBinding(binding(id));long sequence=binding.path("baselineSequence").asLong();
try(var source=monitoring.calibrationStream(binding)) {
Long tenant=cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.getRequiredTenantId();
var ended=new java.util.concurrent.atomic.AtomicReference<RuntimeException>();
var guard=GUARDS.scheduleWithFixedDelay(()->cn.iocoder.yudao.framework.tenant.core.util.TenantUtils.execute(tenant,()->{
try{unchanged(id,binding);}catch(RuntimeException stop){ended.compareAndSet(null,stop);try{source.close();}catch(IOException ignored){}}
}),500,500,TimeUnit.MILLISECONDS);
try {
ScannerMonitoringService.Frame frame;
while((frame=source.next())!=null) {
unchanged(id,binding);
long next=monitoring.calibrationFrameSequence(binding,frame);if(next<=sequence)continue;sequence=next;
String header="--scanframe\r\nContent-Type: image/jpeg\r\nContent-Length: "+frame.bytes().length+"\r\nX-Frame-Sequence: "+sequence+"\r\n\r\n";
output.write(header.getBytes(StandardCharsets.US_ASCII));output.write(frame.bytes());output.write(new byte[]{13,10});output.flush();
}
}catch(IOException closed){if(ended.get()!=null)throw ended.get();throw closed;}
finally{guard.cancel(false);}
}
}finally{SLOTS.release();}
}
}

View File

@ -1,4 +1,5 @@
import request from '@/cmvr/request' import request from '@/cmvr/request'
import platformRequest from '@/config/axios'
import { loadMaintenanceDefinition } from '@/views/lab/dimension/maintenance.mjs' import { loadMaintenanceDefinition } from '@/views/lab/dimension/maintenance.mjs'
interface NativeResult<T> { interface NativeResult<T> {
@ -54,3 +55,42 @@ export async function getMaintenanceStatus(instId: string, signal: AbortSignal)
if (data?.instId !== instId) throw new Error('执行状态暂未同步') if (data?.instId !== instId) throw new Error('执行状态暂未同步')
return data return data
} }
export async function getMaintenanceExecution(instId: string, signal?: AbortSignal) {
const data = await platformRequest.get<any>({
url: '/lab/maintenance/scanner-view/execution',
params: { instId },
signal,
timeout: 15000,
silentError: true
})
if (data?.instId !== instId) throw new Error('标定执行记录暂未同步')
return data
}
export async function getMaintenanceLogs(
instId: string,
afterId: string | undefined,
pageNum: number,
signal: AbortSignal
) {
return request.get<never, { rows?: any[]; total?: number }>('/test/inst/log/detail', {
params: { instId, afterId, pageNum, pageSize: 100 },
signal,
timeout: 15000,
silentError: true
} as any)
}
/** Cached supplier callbacks, not workflow progress or a live SDK status poll. */
export interface CalibrationTelemetry {
source?: 'sdk_calibration_window'
calibrationId?: string
calibrationActive?: boolean
frameSequence?: number
progress?: Record<string, any> | null
temperatures?: {
scanner?: { value: number; receivedAt?: string } | null
tracker?: { value: number; receivedAt?: string } | null
} | null
}

View File

@ -1,10 +1,11 @@
import type { CalibrationTelemetry } from '@/api/lab/maintenance'
import request from '@/config/axios' import request from '@/config/axios'
import { authenticatedFetch } from '@/config/axios/authenticatedFetch' import { authenticatedFetch } from '@/config/axios/authenticatedFetch'
import { readScannerBinary } from '@/views/lab/scan-task/scannerBinary.mjs' import { readScannerBinary } from '@/views/lab/scan-task/scannerBinary.mjs'
import { consumeScannerMjpeg } from '@/cmvr/common/utils/scannerMjpeg.mjs' import { consumeScannerMjpeg } from '@/cmvr/common/utils/scannerMjpeg.mjs'
import { scannerPreviewTarget } from '@/views/lab/scan-task/scannerPreviewTarget.mjs' import { scannerPreviewTarget } from '@/views/lab/scan-task/scannerPreviewTarget.mjs'
export interface ScannerExecutionView { export interface ScannerExecutionView extends CalibrationTelemetry {
executionId: string executionId: string
executionNo?: string executionNo?: string
taskId?: string taskId?: string
@ -22,22 +23,72 @@ export interface ScannerExecutionView {
meshState?: string meshState?: string
} }
const path = '/lab/execution/scanner-view' const path = '/lab/execution/scanner-view'
export const getScannerExecutionView = (executionId: string | number, signal?: AbortSignal, scope: 'execution' | 'fixture' = 'execution') => { export const getScannerExecutionView = (
executionId: string | number,
signal?: AbortSignal,
scope: 'execution' | 'fixture' | 'maintenance' = 'execution'
) => {
const target = scannerPreviewTarget(scope, executionId) const target = scannerPreviewTarget(scope, executionId)
return request.get<ScannerExecutionView>({ url: target.path + target.view, params: target.params, signal }) return request.get<ScannerExecutionView>({
url: target.path + target.view,
params: target.params,
signal,
silentError: scope === 'maintenance'
})
} }
export interface ScannerAsset { fileId: string; name: string; bytes?: number; projectId?: string; capturedAt?: number; commandKey?: string; itemOrder?: number; itemOccurrence?: number } export interface ScannerAsset {
export interface ScannerSnapshotCommand { commandKey?: string; key?: string; state: string; taskId?: string; error?: string; result?: string } fileId: string
name: string
bytes?: number
projectId?: string
capturedAt?: number
commandKey?: string
itemOrder?: number
itemOccurrence?: number
}
export interface ScannerSnapshotCommand {
commandKey?: string
key?: string
state: string
taskId?: string
error?: string
result?: string
}
export const getScannerAssets = (executionId: string | number, signal?: AbortSignal) => export const getScannerAssets = (executionId: string | number, signal?: AbortSignal) =>
request.get<ScannerAsset[]>({ url: path + '/assets', params: { executionId }, signal }) request.get<ScannerAsset[]>({ url: path + '/assets', params: { executionId }, signal })
export const createScannerSnapshot = (executionId: string | number, commandKey: string, signal?: AbortSignal) => export const createScannerSnapshot = (
request.post<ScannerSnapshotCommand>({ url: path + '/snapshot', params: { executionId }, data: {}, headers: { 'X-Scanner-Command-Key': commandKey }, signal }) executionId: string | number,
export const getScannerSnapshotCommand = (executionId: string | number, commandKey: string, signal?: AbortSignal) => commandKey: string,
request.get<ScannerSnapshotCommand>({ url: path + '/snapshot-command', params: { executionId, commandKey }, signal }) 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
})
export async function getScannerAsset(executionId: string | number, fileId: string, signal: AbortSignal) { export async function getScannerAsset(
const response = await authenticatedFetch(`${import.meta.env.VITE_BASE_URL}/admin-api${path}/asset/${encodeURIComponent(fileId)}?executionId=${encodeURIComponent(executionId)}`, { signal }) executionId: string | number,
fileId: string,
signal: AbortSignal
) {
const response = await authenticatedFetch(
`${import.meta.env.VITE_BASE_URL}/admin-api${path}/asset/${encodeURIComponent(fileId)}?executionId=${encodeURIComponent(executionId)}`,
{ signal }
)
if (!response.ok || response.headers.get('content-type')?.includes('application/json')) { if (!response.ok || response.headers.get('content-type')?.includes('application/json')) {
const error = await response.json().catch(() => ({})) const error = await response.json().catch(() => ({}))
throw new Error(error.msg || '三维文件不可用;扫描服务重启后原下载编号可能失效') throw new Error(error.msg || '三维文件不可用;扫描服务重启后原下载编号可能失效')
@ -46,7 +97,10 @@ export async function getScannerAsset(executionId: string | number, fileId: stri
} }
export async function getScannerExecutionImage(executionId: string | number, signal: AbortSignal) { export async function getScannerExecutionImage(executionId: string | number, signal: AbortSignal) {
const response = await authenticatedFetch(`${import.meta.env.VITE_BASE_URL}/admin-api${path}/image?executionId=${encodeURIComponent(executionId)}`, { signal, cache: 'no-store' }) const response = await authenticatedFetch(
`${import.meta.env.VITE_BASE_URL}/admin-api${path}/image?executionId=${encodeURIComponent(executionId)}`,
{ signal, cache: 'no-store' }
)
if (!response.ok || !response.headers.get('content-type')?.startsWith('image/jpeg')) { if (!response.ok || !response.headers.get('content-type')?.startsWith('image/jpeg')) {
const error = await response.json().catch(() => ({})) const error = await response.json().catch(() => ({}))
throw new Error(error.msg || '扫描画面暂不可用,正在重新核对状态') throw new Error(error.msg || '扫描画面暂不可用,正在重新核对状态')
@ -54,13 +108,28 @@ export async function getScannerExecutionImage(executionId: string | number, sig
return response.blob() return response.blob()
} }
export async function streamScannerExecution(executionId: string | number, onFrame: (bytes: Uint8Array) => void, signal: AbortSignal, scope: 'execution' | 'fixture' = 'execution') { export async function streamScannerExecution(
executionId: string | number,
onFrame: (bytes: Uint8Array) => void,
signal: AbortSignal,
scope: 'execution' | 'fixture' | 'maintenance' = 'execution'
) {
const target = scannerPreviewTarget(scope, executionId) const target = scannerPreviewTarget(scope, executionId)
const query = new URLSearchParams(Object.entries(target.params).map(([key,value]) => [key,String(value)])) const query = new URLSearchParams(
const response = await authenticatedFetch(`${import.meta.env.VITE_BASE_URL}/admin-api${target.path}/${target.stream}?${query}`, { Object.entries(target.params).map(([key, value]) => [key, String(value)])
signal, cache: 'no-store' )
}) const response = await authenticatedFetch(
if (!response.ok || !response.headers.get('content-type')?.startsWith('multipart/x-mixed-replace') || !response.body) { `${import.meta.env.VITE_BASE_URL}/admin-api${target.path}/${target.stream}?${query}`,
{
signal,
cache: 'no-store'
}
)
if (
!response.ok ||
!response.headers.get('content-type')?.startsWith('multipart/x-mixed-replace') ||
!response.body
) {
const error = await response.json().catch(() => ({})) const error = await response.json().catch(() => ({}))
throw new Error(error.msg || '扫描流暂不可用,正在重新核对状态') throw new Error(error.msg || '扫描流暂不可用,正在重新核对状态')
} }

View File

@ -0,0 +1,288 @@
<template>
<section class="calibration-monitor" aria-label="扫描仪标定过程" :aria-busy="loading">
<header class="calibration-overview">
<div
><strong>{{ statusLabel }}</strong
><span class="elapsed">耗时 {{ plan.duration }}</span></div
>
<el-button text :loading="loading" @click="refresh">刷新记录</el-button>
</header>
<p class="calibration-reference"
>本次标定编号:<code>{{ instId }}</code></p
>
<el-alert
v-if="phase === 'recovering'"
:title="message || '执行状态同步暂不可用,正在重新连接'"
type="warning"
:closable="false"
show-icon
/>
<el-alert v-if="error" :title="error" type="warning" :closable="false" show-icon />
<el-alert v-if="failure" :title="failure" type="error" :closable="false" show-icon />
<div class="calibration-layout">
<ScannerLiveView
:key="instId"
:execution-id="instId"
execution-no="扫描仪标定"
:status="status"
:active="active && !!snapshot"
scope="maintenance"
/>
<div class="calibration-progress" role="status">
<strong>平台流程记录 · {{ plan.heading }}</strong>
<span>{{
plan.hasPlan
? `已完成 ${plan.completed} / ${plan.total} 个流程步骤`
: `已收到 ${plan.total} 步记录`
}}</span>
<p>以下为平台流程节点记录;厂商实际标定阶段、温度和指引见上方真实窗口。</p>
</div>
<ScanExecutionLog
:key="instId"
:logs="logs"
:status="status"
:loading="loading"
:active="active"
:steps="plan.steps"
:focus-id="plan.focusId"
:has-plan="plan.hasPlan"
:height="520"
/>
</div>
<p class="calibration-note">关闭窗口后标定按流程继续执行,可通过“查看标定过程”再次打开。</p>
</section>
</template>
<script setup lang="ts">
import {
computed,
ref,
shallowRef,
watch,
onMounted,
onActivated,
onDeactivated,
onBeforeUnmount
} from 'vue'
import { getMaintenanceExecution, getMaintenanceLogs } from '@/api/lab/maintenance'
import ScannerLiveView from '@/views/lab/scan-task/ScannerLiveView.vue'
import ScanExecutionLog from '@/views/lab/scan-task/ScanExecutionLog.vue'
import { executionStepPlan } from '@/views/lab/scan-task/executionSteps.mjs'
import { readableLogs } from '@/views/lab/scan-task/executionPresentation.mjs'
import { scannerLogCursor, mergeScannerLogs } from '@/views/lab/scan-task/scannerLogs.mjs'
import { maintenanceExecutionStatus } from './maintenance.mjs'
const props = withDefaults(
defineProps<{
instId: string
status?: string
phase?: string
message?: string
active?: boolean
}>(),
{ active: true }
)
const snapshot = shallowRef<any>()
const nativeLogs = shallowRef<any[]>([])
const loading = ref(false),
error = ref(''),
now = ref(Date.now())
const terminalStates = new Set(['SUCCEEDED', 'FAILED', 'CANCELLED'])
const snapshotStatus = computed(() => maintenanceExecutionStatus(snapshot.value?.status))
const status = computed(() =>
terminalStates.has(snapshotStatus.value)
? snapshotStatus.value
: props.status || snapshotStatus.value || 'RUNNING'
)
const terminal = computed(() => terminalStates.has(status.value))
const statusLabel = computed(
() =>
({
SUCCEEDED: '标定执行已完成',
FAILED: '标定执行失败',
CANCELLED: '标定执行已终止',
PAUSED: '标定已暂停',
RUNNING: '标定流程执行中'
})[status.value] || '等待标定状态'
)
const logs = computed(() => readableLogs(nativeLogs.value, snapshot.value?.flowData))
const plan = computed(() =>
executionStepPlan(
{
id: props.instId,
status: status.value,
startedAt: snapshot.value?.createTime,
finishedAt: terminal.value ? snapshot.value?.updateTime : undefined
},
logs.value,
snapshot.value?.flowData,
now.value
)
)
const failure = computed(() =>
['FAILED', 'CANCELLED'].includes(status.value)
? props.message ||
plan.value.steps.find((step: any) => step.state === 'failed')?.summary ||
(status.value === 'CANCELLED' ? '本次标定执行已终止' : '标定执行失败,请查看步骤日志')
: ''
)
let generation = 0,
suspended = false
let controller: AbortController | undefined
let timer: ReturnType<typeof setTimeout> | undefined
let clock: ReturnType<typeof setInterval> | undefined
const visible = () => props.active && !document.hidden && !suspended
async function load(token: number, signal: AbortSignal, force = false) {
const id = props.instId
if (!visible() || token !== generation || signal.aborted) return
loading.value = true
error.value = ''
now.value = Date.now()
try {
if (!snapshot.value || force || terminal.value) {
const found = await getMaintenanceExecution(id, signal)
if (token !== generation || signal.aborted) return
if (found.instId !== id || !maintenanceExecutionStatus(found.status))
throw new Error('标定执行记录暂未同步')
snapshot.value = found
}
const incoming: any[] = []
const afterId = force || terminal.value ? undefined : scannerLogCursor(nativeLogs.value)
let pageNum = 1
while (true) {
const response = await getMaintenanceLogs(id, afterId, pageNum, signal)
if (token !== generation || signal.aborted) return
const rows = response.rows || []
if (!Array.isArray(rows) || rows.some((row: any) => String(row.instId) !== id))
throw new Error('执行日志与本次标定不一致,已停止显示该批记录')
incoming.push(...rows)
if (!rows.length || incoming.length >= (response.total ?? incoming.length)) break
if (++pageNum > 100) throw new Error('标定日志较多,请刷新后继续查看')
}
nativeLogs.value = mergeScannerLogs(nativeLogs.value, incoming)
} catch (failure: any) {
if (token === generation && !signal.aborted)
error.value = failure.message || '标定记录加载失败,正在重试'
} finally {
if (token === generation && !signal.aborted) {
loading.value = false
if (terminal.value) {
clearInterval(clock)
clock = undefined
}
// These are platform execution logs, never repeated scanner SDK status calls.
if (visible() && (!terminal.value || error.value))
timer = setTimeout(() => void load(token, signal), 2000)
}
}
}
function restart(reset = false, force = false) {
generation++
controller?.abort()
clearTimeout(timer)
clearInterval(clock)
loading.value = false
if (reset) {
snapshot.value = undefined
nativeLogs.value = []
error.value = ''
}
if (!visible()) return
if (!terminal.value)
clock = setInterval(() => {
if (visible() && !terminal.value) now.value = Date.now()
}, 1000)
controller = new AbortController()
void load(generation, controller.signal, force)
}
function refresh() {
restart(false, true)
}
watch(
() => props.instId,
() => restart(true),
{ immediate: true }
)
watch(
() => [props.active, props.status],
() => restart()
)
const onVisibility = () => restart()
onMounted(() => document.addEventListener('visibilitychange', onVisibility))
onActivated(() => {
suspended = false
restart()
})
onDeactivated(() => {
suspended = true
restart()
})
onBeforeUnmount(() => {
suspended = true
restart()
document.removeEventListener('visibilitychange', onVisibility)
})
</script>
<style scoped>
.calibration-overview,
.calibration-overview > div,
.progress-line {
display: flex;
align-items: center;
gap: 16px;
}
.calibration-overview {
justify-content: space-between;
}
.calibration-overview strong {
font-size: 17px;
}
.calibration-reference,
.calibration-note,
.calibration-progress p,
.elapsed {
color: var(--el-text-color-secondary);
font-size: 13px;
}
.calibration-reference {
overflow-wrap: anywhere;
}
.calibration-progress {
padding: 16px;
margin-top: 16px;
border-radius: 6px;
background: var(--el-fill-color-light);
}
.progress-line {
margin-top: 12px;
}
.progress-line .el-progress {
flex: 1;
}
.progress-line > span {
white-space: nowrap;
font-size: 13px;
}
.calibration-progress p {
margin-bottom: 0;
}
.calibration-layout {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 20px;
margin-top: 12px;
}
.calibration-layout > * {
min-width: 0;
}
.el-alert + .el-alert {
margin-top: 8px;
}
@media (max-width: 900px) {
.calibration-layout {
grid-template-columns: minmax(0, 1fr);
}
}
</style>

View File

@ -8,6 +8,9 @@
@click="openAction(action)" @click="openAction(action)"
>{{ action.label }}{{ busy && state.actionKey === action.key ? '(正在执行)' : '' }}</el-button >{{ action.label }}{{ busy && state.actionKey === action.key ? '(正在执行)' : '' }}</el-button
> >
<el-button v-if="calibrationInstId" link type="primary" @click="monitorVisible = true"
>查看标定过程</el-button
>
<span class="calibration-time" role="status" aria-live="polite"> <span class="calibration-time" role="status" aria-live="polite">
扫描仪最后标定时间:{{ calibrationDate }} 扫描仪最后标定时间:{{ calibrationDate }}
</span> </span>
@ -75,6 +78,25 @@
> >
</template> </template>
</el-dialog> </el-dialog>
<el-dialog
v-model="monitorVisible"
title="扫描仪标定 · 厂商指引与平台执行记录"
width="min(1800px, 96vw)"
append-to-body
destroy-on-close
:close-on-click-modal="false"
>
<CalibrationMonitor
v-if="calibrationInstId"
:key="calibrationInstId"
:inst-id="calibrationInstId"
:status="calibrationStatus"
:phase="calibrationPhase"
:message="calibrationMessage"
:active="monitorVisible && pageActive"
/>
<template #footer><el-button @click="monitorVisible = false">关闭窗口</el-button></template>
</el-dialog>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@ -96,12 +118,14 @@ import {
import { useUserStore } from '@/store/modules/user' import { useUserStore } from '@/store/modules/user'
import RuntimeAssignmentsEditor from '@/cmvr/common/views/flow/components/RuntimeAssignmentsEditor.vue' import RuntimeAssignmentsEditor from '@/cmvr/common/views/flow/components/RuntimeAssignmentsEditor.vue'
import ParameterFields from '@/views/lab/scan-task/ParameterFields.vue' import ParameterFields from '@/views/lab/scan-task/ParameterFields.vue'
import CalibrationMonitor from './CalibrationMonitor.vue'
import { import {
createMaintenanceExecution, createMaintenanceExecution,
createMaintenanceForm, createMaintenanceForm,
prepareMaintenanceRequest, prepareMaintenanceRequest,
maintenanceActions, maintenanceActions,
formatScannerCalibrationDate formatScannerCalibrationDate,
maintenanceExecutionStatus
} from './maintenance.mjs' } from './maintenance.mjs'
const message = useMessage() const message = useMessage()
@ -110,6 +134,11 @@ const state = ref({ actionKey: '', phase: 'idle', instId: '', message: '' })
const busy = computed(() => state.value.phase !== 'idle') const busy = computed(() => state.value.phase !== 'idle')
const calibrationDate = ref('正在获取…') const calibrationDate = ref('正在获取…')
const dialogVisible = ref(false) const dialogVisible = ref(false)
const monitorVisible = ref(false),
calibrationInstId = ref(''),
calibrationStatus = ref('RUNNING')
const calibrationPhase = ref(''),
calibrationMessage = ref('')
const currentAction = shallowRef<any>() const currentAction = shallowRef<any>()
const definition = shallowRef<any>() const definition = shallowRef<any>()
const definitionLoading = ref(false) const definitionLoading = ref(false)
@ -120,7 +149,7 @@ const runParams = ref<Record<string, any>>({})
const assignmentsEditor = ref<InstanceType<typeof RuntimeAssignmentsEditor>>() const assignmentsEditor = ref<InstanceType<typeof RuntimeAssignmentsEditor>>()
const formCache = new Map<string, any>() const formCache = new Map<string, any>()
let definitionRequest: AbortController | undefined let definitionRequest: AbortController | undefined
let pageActive = false const pageActive = ref(false)
let statusRequest: AbortController | undefined let statusRequest: AbortController | undefined
const storageKey = `am-freescan:maintenance:${user.getUser.id}` const storageKey = `am-freescan:maintenance:${user.getUser.id}`
const execution = createMaintenanceExecution({ const execution = createMaintenanceExecution({
@ -129,11 +158,29 @@ const execution = createMaintenanceExecution({
onState: (value: typeof state.value) => { onState: (value: typeof state.value) => {
state.value = value state.value = value
if (value.instId) dialogVisible.value = false if (value.instId) dialogVisible.value = false
if (value.actionKey === 'scanner-calibration' && value.instId) {
if (calibrationInstId.value !== value.instId) {
calibrationInstId.value = value.instId
monitorVisible.value = pageActive.value
}
calibrationPhase.value = value.phase
calibrationMessage.value = value.message
if (value.phase === 'running') calibrationStatus.value = 'RUNNING'
else if (value.phase === 'paused') calibrationStatus.value = 'PAUSED'
}
}, },
onResult: ({ action, success, message: detail }: any) => { onResult: ({ action, success, message: detail, instId, status }: any) => {
if (success) message.success(`${action.label}执行成功`) if (success) message.success(`${action.label}执行成功`)
else message.error(`${action.label}执行失败${detail ? `:${detail}` : ''}`) else message.error(`${action.label}执行失败${detail ? `:${detail}` : ''}`)
if (action.key === 'scanner-calibration') void refreshCalibrationDate() if (action.key === 'scanner-calibration') {
if (instId && calibrationInstId.value === instId) {
calibrationStatus.value =
maintenanceExecutionStatus(status) || (success ? 'SUCCEEDED' : 'FAILED')
calibrationPhase.value = 'finished'
calibrationMessage.value = detail || ''
}
void refreshCalibrationDate()
}
}, },
readPending: () => { readPending: () => {
try { try {
@ -169,6 +216,7 @@ function applyDefinition(value: any, previous?: any) {
async function openAction(action: any) { async function openAction(action: any) {
if (busy.value || dialogVisible.value) return if (busy.value || dialogVisible.value) return
monitorVisible.value = false
currentAction.value = action currentAction.value = action
definition.value = undefined definition.value = undefined
definitionError.value = '' definitionError.value = ''
@ -246,7 +294,8 @@ async function confirmExecution() {
checkingVersion.value = false checkingVersion.value = false
await execution.run(currentAction.value, data) await execution.run(currentAction.value, data)
} catch (error) { } catch (error) {
if (!request.signal.aborted) message.error((error as Error).message || '读取扫描方案执行配置失败') if (!request.signal.aborted)
message.error((error as Error).message || '读取扫描方案执行配置失败')
} finally { } finally {
if (definitionRequest === request) { if (definitionRequest === request) {
definitionRequest = undefined definitionRequest = undefined
@ -256,7 +305,7 @@ async function confirmExecution() {
} }
async function refreshCalibrationDate() { async function refreshCalibrationDate() {
if (!pageActive) return if (!pageActive.value) return
statusRequest?.abort() statusRequest?.abort()
const request = new AbortController() const request = new AbortController()
statusRequest = request statusRequest = request
@ -272,13 +321,14 @@ async function refreshCalibrationDate() {
} }
function activate() { function activate() {
if (pageActive) return if (pageActive.value) return
pageActive = true pageActive.value = true
void execution.restore() void execution.restore()
void refreshCalibrationDate() void refreshCalibrationDate()
} }
function deactivate() { function deactivate() {
pageActive = false pageActive.value = false
monitorVisible.value = false
execution.dispose() execution.dispose()
closeDialog() closeDialog()
dialogVisible.value = false dialogVisible.value = false

View File

@ -207,12 +207,12 @@ export function createMaintenanceExecution({
let monitoringEnabled = true let monitoringEnabled = true
const emit = (action, phase, instId = '', message = '') => const emit = (action, phase, instId = '', message = '') =>
onState({ actionKey: action?.key || '', phase, instId, message }) onState({ actionKey: action?.key || '', phase, instId, message })
const finish = (action, token, success, message = '') => { const finish = (action, token, success, message = '', instId = '', status = '') => {
if (active !== token || token.signal.aborted) return if (active !== token || token.signal.aborted) return
active = null active = null
writePending(null) writePending(null)
emit(null, 'idle') emit(null, 'idle')
onResult({ action, success, message }) onResult({ action, success, message, instId, status })
} }
const monitor = async (action, instId, token) => { const monitor = async (action, instId, token) => {
while (active === token && !token.signal.aborted) { while (active === token && !token.signal.aborted) {
@ -221,7 +221,7 @@ export function createMaintenanceExecution({
if (active !== token || token.signal.aborted) return false if (active !== token || token.signal.aborted) return false
const status = String(result?.status) const status = String(result?.status)
if (status === '0') { if (status === '0') {
finish(action, token, true) finish(action, token, true, '', instId, status)
return true return true
} }
if (status === '2' || status === '4') { if (status === '2' || status === '4') {
@ -229,7 +229,9 @@ export function createMaintenanceExecution({
action, action,
token, token,
false, false,
result.message || (status === '4' ? '执行已终止' : '流程执行失败') result.message || (status === '4' ? '执行已终止' : '流程执行失败'),
instId,
status
) )
return false return false
} }
@ -293,3 +295,6 @@ export function createMaintenanceExecution({
} }
} }
} }
export const maintenanceExecutionStatus = (status) =>
({ 0: 'SUCCEEDED', 1: 'RUNNING', 2: 'FAILED', 3: 'PAUSED', 4: 'CANCELLED' })[String(status)]

View File

@ -1,26 +1,87 @@
<template> <template>
<section class="scanner-live-view" aria-label="本次执行实时扫描画面"> <section
class="scanner-live-view"
:aria-label="calibration ? 'FreeScan Trak 厂商标定指引' : '本次执行实时扫描画面'"
:class="{ 'calibration-view': calibration }"
>
<div class="view-heading"> <div class="view-heading">
<div><h3>实时扫描画面</h3><span class="view-hint">{{ view.executionNo || executionNo || '本次执行' }} · 画面跟随扫描软件当前视角</span></div> <div
><h3>{{ calibration ? 'FreeScan Trak 厂商标定指引' : '实时扫描画面' }}</h3
><span class="view-hint">{{
calibration
? '只读查看厂商真实标定窗口;请按设备或厂家软件提示完成标定操作'
: `${view.executionNo || executionNo || '本次执行'} · 画面跟随扫描软件当前视角`
}}</span></div
>
<div class="view-controls"> <div class="view-controls">
<el-tag :type="props.status === 'PAUSED' ? 'warning' : view.available && !error ? 'success' : 'info'">{{ caption }}</el-tag> <el-tag
:type="
props.status === 'PAUSED'
? 'warning'
: view.available && !error && (!calibration || !!imageUrl)
? 'success'
: 'info'
"
>{{ caption }}</el-tag
>
<el-switch v-model="watching" active-text="实时查看" :disabled="!live" /> <el-switch v-model="watching" active-text="实时查看" :disabled="!live" />
<el-button :disabled="!imageUrl" @click="expanded = true">放大查看</el-button> <el-button :disabled="!imageUrl" @click="expanded = true">放大查看</el-button>
</div> </div>
</div> </div>
<div v-if="view.projectId" class="view-identity"> <div v-if="view.projectId || view.deviceId || view.sessionId" class="view-identity">
<span>扫描工程 <code>{{ view.projectId }}</code></span> <span v-if="view.projectId"
<span>工位 <code>{{ view.robotId }}</code> / 设备 <code>{{ view.deviceId }}</code></span> >扫描工程 <code>{{ view.projectId }}</code></span
>
<span
>工位 <code>{{ view.robotId }}</code> / 设备 <code>{{ view.deviceId }}</code></span
>
<span v-if="receivedAt">画面更新 {{ receivedAt }}</span> <span v-if="receivedAt">画面更新 {{ receivedAt }}</span>
<span>MJPEG 流式预览<span v-if="streamFps"> · {{ streamFps }} 帧/秒</span></span> <span
>MJPEG 流式预览<span v-if="streamFps"> · {{ streamFps }} 帧/秒</span></span
>
</div>
<div v-if="calibration" class="supplier-telemetry" role="status" aria-live="polite">
<div
><strong>厂商标定阶段</strong>:{{ telemetry.title }}
<span v-for="detail in telemetry.details" :key="detail"> · {{ detail }}</span>
<small v-if="telemetry.receivedAt"
>(回传 {{ formatNullableDate(telemetry.receivedAt) }})</small
>
</div>
<div
>扫描仪温度(厂家原值):{{ telemetry.scanner ? `${telemetry.scanner.value}` : '—' }}
<small v-if="telemetry.scanner?.receivedAt"
>({{ formatNullableDate(telemetry.scanner.receivedAt) }})</small
>
<span>跟踪仪温度(厂家原值):{{ telemetry.tracker ? `${telemetry.tracker.value}` : '—' }}</span>
<small v-if="telemetry.tracker?.receivedAt"
>({{ formatNullableDate(telemetry.tracker.receivedAt) }})</small
>
</div>
</div> </div>
<el-alert v-if="error" :title="error" type="warning" :closable="false" class="mb-12px" /> <el-alert v-if="error" :title="error" type="warning" :closable="false" class="mb-12px" />
<div class="view-canvas" v-loading="loading"> <div class="view-canvas" v-loading="loading">
<img v-if="imageUrl" :src="imageUrl" decoding="async" alt="本次样件扫描过程中绘制的三维画面" /> <img
v-if="imageUrl"
:src="imageUrl"
decoding="async"
:alt="calibration ? 'FreeScan Trak 厂商实际标定窗口' : '本次样件扫描过程中绘制的三维画面'"
/>
<el-empty v-else :description="error || caption" :image-size="80" /> <el-empty v-else :description="error || caption" :image-size="80" />
</div> </div>
<el-dialog v-model="expanded" title="本次执行扫描画面" width="min(1200px, 94vw)" append-to-body> <el-dialog
<img v-if="imageUrl" :src="imageUrl" decoding="async" class="expanded-image" alt="本次执行扫描画面" /> v-model="expanded"
:title="calibration ? 'FreeScan Trak 厂商实际标定窗口' : '本次执行扫描画面'"
:width="calibration ? 'min(1800px, 96vw)' : 'min(1200px, 94vw)'"
append-to-body
>
<img
v-if="imageUrl"
:src="imageUrl"
decoding="async"
class="expanded-image"
:alt="calibration ? 'FreeScan Trak 厂商实际标定窗口' : '本次执行扫描画面'"
/>
<el-empty v-else :description="error || caption" /> <el-empty v-else :description="error || caption" />
</el-dialog> </el-dialog>
</section> </section>
@ -28,19 +89,29 @@
<script setup lang="ts"> <script setup lang="ts">
import { formatNullableDate } from '@/utils/formatTime' import { formatNullableDate } from '@/utils/formatTime'
import { streamScannerExecution, getScannerExecutionView, type ScannerExecutionView } from '@/api/lab/scan-task/scannerView' import {
streamScannerExecution,
getScannerExecutionView,
type ScannerExecutionView
} from '@/api/lab/scan-task/scannerView'
import { acceptsScannerFrame, isLiveScannerExecution, scannerViewCaption } from './scannerView.mjs' import { acceptsScannerFrame, isLiveScannerExecution, scannerViewCaption } from './scannerView.mjs'
import { createScannerFramePump } from './scannerFramePump.mjs' import { createScannerFramePump } from './scannerFramePump.mjs'
import { calibrationTelemetry } from './calibrationTelemetry.mjs'
const props = withDefaults(defineProps<{ const props = withDefaults(
executionId?: string | number defineProps<{
executionNo?: string executionId?: string | number
status?: string executionNo?: string
active?: boolean status?: string
scope?: 'execution' | 'fixture' active?: boolean
}>(), { active: true, scope: 'execution' }) scope?: 'execution' | 'fixture' | 'maintenance'
}>(),
{ active: true, scope: 'execution' }
)
const calibration = computed(() => props.scope === 'maintenance')
const emit = defineEmits<{ ended: [recordingId: string] }>() const emit = defineEmits<{ ended: [recordingId: string] }>()
const view = ref<Partial<ScannerExecutionView>>({}) const view = ref<Partial<ScannerExecutionView>>({})
const telemetry = computed(() => calibrationTelemetry(view.value.progress, view.value.temperatures))
const watching = ref(true) const watching = ref(true)
const imageUrl = ref('') const imageUrl = ref('')
const receivedAt = ref('') const receivedAt = ref('')
@ -48,10 +119,24 @@ const error = ref('')
const loading = ref(false) const loading = ref(false)
const expanded = ref(false) const expanded = ref(false)
const streamFps = ref(0) const streamFps = ref(0)
const live = computed(() => isLiveScannerExecution(props.status) && !(props.scope === 'fixture' && view.value.state === 'execution_finished')) const live = computed(
const caption = computed(() => imageUrl.value && !error.value && props.active && watching.value () =>
? props.status === 'PAUSED' ? '流程已暂停,画面已连接' : '实时画面已连接' isLiveScannerExecution(props.status) &&
: scannerViewCaption(view.value, props.active, watching.value)) !(props.scope === 'fixture' && view.value.state === 'execution_finished')
)
const caption = computed(() =>
imageUrl.value && !error.value && props.active && watching.value
? props.status === 'PAUSED'
? '流程已暂停,画面已连接'
: '实时画面已连接'
: calibration.value && !live.value
? '标定执行已结束,可查看步骤和结果'
: calibration.value && (!props.active || !watching.value)
? '已暂停查看画面,标定按流程继续执行'
: calibration.value
? view.value.message || '等待厂商标定窗口画面'
: scannerViewCaption(view.value, props.active, watching.value)
)
let generation = 0 let generation = 0
let controller: AbortController | undefined let controller: AbortController | undefined
let timer: ReturnType<typeof setTimeout> | undefined let timer: ReturnType<typeof setTimeout> | undefined
@ -59,45 +144,85 @@ let nextMetadata = 0
let suspended = false let suspended = false
let streamController: AbortController | undefined let streamController: AbortController | undefined
let framePump: ReturnType<typeof createScannerFramePump> | undefined let framePump: ReturnType<typeof createScannerFramePump> | undefined
let frames = 0, fpsStarted = 0 let frames = 0,
fpsStarted = 0
function stopStream() { function stopStream() {
streamController?.abort(); streamController = undefined streamController?.abort()
framePump?.stop(); framePump = undefined streamController = undefined
streamFps.value = 0; frames = 0; fpsStarted = 0 framePump?.stop()
framePump = undefined
streamFps.value = 0
frames = 0
fpsStarted = 0
} }
function startStream(id: string | number, token: number, signal: AbortSignal) { function startStream(id: string | number, token: number, signal: AbortSignal) {
if (streamController || signal.aborted) return if (streamController || signal.aborted) return
const source = new AbortController(); streamController = source const source = new AbortController()
streamController = source
const abort = () => source.abort() const abort = () => source.abort()
signal.addEventListener('abort', abort, { once: true }) signal.addEventListener('abort', abort, { once: true })
const pump = createScannerFramePump({ const pump = createScannerFramePump({
async decode(bytes: Uint8Array) { async decode(bytes: Uint8Array) {
const url = URL.createObjectURL(new Blob([new Uint8Array(bytes).buffer], { type: 'image/jpeg' })) const url = URL.createObjectURL(
try { const image = new Image(); image.src = url; await image.decode(); return url } new Blob([new Uint8Array(bytes).buffer], { type: 'image/jpeg' })
catch (failure) { URL.revokeObjectURL(url); throw failure } )
try {
const image = new Image()
image.src = url
await image.decode()
return url
} catch (failure) {
URL.revokeObjectURL(url)
throw failure
}
}, },
publish(url: string) { publish(url: string) {
if (!acceptsScannerFrame({ generation: token, executionId: id }, current()) || source.signal.aborted) { URL.revokeObjectURL(url); return } if (
const previous = imageUrl.value; imageUrl.value = url !acceptsScannerFrame({ generation: token, executionId: id }, current()) ||
source.signal.aborted
) {
URL.revokeObjectURL(url)
return
}
const previous = imageUrl.value
imageUrl.value = url
if (previous) URL.revokeObjectURL(previous) if (previous) URL.revokeObjectURL(previous)
receivedAt.value = formatNullableDate(new Date()) receivedAt.value = formatNullableDate(new Date())
loading.value = false; error.value = '' loading.value = false
const now = performance.now(); if (!fpsStarted) fpsStarted = now error.value = ''
const now = performance.now()
if (!fpsStarted) fpsStarted = now
frames++ frames++
if (now - fpsStarted >= 1000) { streamFps.value = Math.round(frames * 1000 / (now - fpsStarted)); fpsStarted = now; frames = 0 } if (now - fpsStarted >= 1000) {
streamFps.value = Math.round((frames * 1000) / (now - fpsStarted))
fpsStarted = now
frames = 0
}
}, },
dispose: (url: string) => URL.revokeObjectURL(url), dispose: (url: string) => URL.revokeObjectURL(url),
onError: () => { if (token === generation) error.value = '扫描帧解码失败,等待后续画面' } onError: () => {
if (token === generation) error.value = '扫描帧解码失败,等待后续画面'
}
}) })
framePump = pump framePump = pump
void streamScannerExecution(id, (bytes) => pump.push(bytes), source.signal, props.scope).catch((failure: any) => { void streamScannerExecution(id, (bytes) => pump.push(bytes), source.signal, props.scope)
if (token !== generation || signal.aborted || source.signal.aborted) return .catch((failure: any) => {
clearImage(); error.value = failure.message || '扫描流暂不可用'; nextMetadata = 0 if (token !== generation || signal.aborted || source.signal.aborted) return
}).finally(() => { clearImage()
signal.removeEventListener('abort', abort); pump.stop() error.value = failure.message || '扫描流暂不可用'
if (streamController === source) { streamController = undefined; framePump = undefined; streamFps.value = 0; loading.value = false } nextMetadata = 0
}) })
.finally(() => {
signal.removeEventListener('abort', abort)
pump.stop()
if (streamController === source) {
streamController = undefined
framePump = undefined
streamFps.value = 0
loading.value = false
}
})
} }
function clearImage() { function clearImage() {
@ -105,35 +230,78 @@ function clearImage() {
imageUrl.value = '' imageUrl.value = ''
receivedAt.value = '' receivedAt.value = ''
} }
function current() { return { generation, executionId: props.executionId, active: props.active && !document.hidden && !suspended, watching: watching.value, status: props.status } } 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) { async function tick(token: number, signal: AbortSignal) {
const id = props.executionId const id = props.executionId
if (id == null || token !== generation || !props.active || document.hidden || suspended) return if (id == null || token !== generation || !props.active || document.hidden || suspended) return
const delay = 1000 const delay = 1000
if (calibration.value && !live.value) {
loading.value = false
return
}
try { try {
// A healthy stream already supplies frames. Query status only before connecting // Ordinary scan preview checks status only on connection/recovery. Calibration
// or after a disconnect; do not poll the SDK while video is flowing. // metadata is the dedicated cached window/callback snapshot, never SDK status.
if (!streamController && Date.now() >= nextMetadata) { if ((!streamController || calibration.value) && Date.now() >= nextMetadata) {
const result = await getScannerExecutionView(id, signal, props.scope) const result = await getScannerExecutionView(id, signal, props.scope)
if (token !== generation) return if (token !== generation) return
if (
calibration.value &&
streamController &&
(result.source !== 'sdk_calibration_window' ||
result.sessionId !== view.value.sessionId ||
result.calibrationId !== view.value.calibrationId ||
!result.calibrationActive ||
!result.available)
) {
stopStream()
clearImage()
}
view.value = result view.value = result
if (props.scope === 'fixture' && result.state === 'execution_finished') emit('ended', String(id)) if (props.scope === 'fixture' && result.state === 'execution_finished')
emit('ended', String(id))
nextMetadata = Date.now() + 3000 nextMetadata = Date.now() + 3000
} }
if (!live.value || !watching.value || !view.value.available || !view.value.previewEnabled) { if (
stopStream(); clearImage(); error.value = '' !live.value ||
!watching.value ||
!view.value.available ||
(calibration.value
? view.value.source !== 'sdk_calibration_window' || !view.value.calibrationActive
: !view.value.previewEnabled)
) {
stopStream()
clearImage()
error.value = ''
return return
} }
startStream(id, token, signal) startStream(id, token, signal)
} catch (failure: any) { } catch (failure: any) {
if (token !== generation || signal.aborted) return if (token !== generation || signal.aborted) return
stopStream(); clearImage() stopStream()
clearImage()
error.value = failure.message || '扫描画面暂不可用' error.value = failure.message || '扫描画面暂不可用'
nextMetadata = 0 nextMetadata = 0
} finally { } finally {
if (token === generation) { if (token === generation) {
if (!streamController) loading.value = false if (!streamController) loading.value = false
if (!signal.aborted && !suspended && props.active && !document.hidden && live.value && watching.value) timer = setTimeout(() => tick(token, signal), delay) if (
!signal.aborted &&
!suspended &&
props.active &&
!document.hidden &&
live.value &&
watching.value
)
timer = setTimeout(() => tick(token, signal), delay)
} }
} }
} }
@ -151,11 +319,21 @@ function restart(reset = false) {
controller = new AbortController() controller = new AbortController()
void tick(generation, controller.signal) void tick(generation, controller.signal)
} }
watch(() => [props.executionId, props.status, props.active, props.scope, watching.value], () => restart(true), { immediate: true }) watch(
() => [props.executionId, props.status, props.active, props.scope, watching.value],
() => restart(true),
{ immediate: true }
)
const onVisibility = () => restart() const onVisibility = () => restart()
onMounted(() => document.addEventListener('visibilitychange', onVisibility)) onMounted(() => document.addEventListener('visibilitychange', onVisibility))
onActivated(() => { suspended = false; restart() }) onActivated(() => {
onDeactivated(() => { suspended = true; restart() }) suspended = false
restart()
})
onDeactivated(() => {
suspended = true
restart()
})
onBeforeUnmount(() => { onBeforeUnmount(() => {
generation++ generation++
controller?.abort() controller?.abort()
@ -167,14 +345,76 @@ onBeforeUnmount(() => {
</script> </script>
<style scoped> <style scoped>
.scanner-live-view { margin: 12px 0; } .scanner-live-view {
.view-heading, .view-controls, .view-identity { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; } margin: 12px 0;
.view-heading { justify-content: space-between; margin-bottom: 12px; } }
h3 { margin: 0 0 6px; font-size: 14px; } .view-heading,
.view-hint, .view-identity { font-size: 13px; color: var(--el-text-color-secondary); } .view-controls,
.view-identity { margin-bottom: 12px; overflow-wrap: anywhere; } .view-identity {
.view-canvas { display: flex; justify-content: center; align-items: center; min-height: 300px; background: var(--el-fill-color-lighter); border-radius: 4px; } display: flex;
.view-canvas img { display: block; width: 100%; max-height: 560px; object-fit: contain; } align-items: center;
.expanded-image { display: block; width: 100%; max-height: 78vh; object-fit: contain; } flex-wrap: wrap;
@media (max-width: 768px) { .scanner-live-view { padding: 12px; } .view-canvas { min-height: 220px; } } gap: 12px;
}
.view-heading {
justify-content: space-between;
margin-bottom: 12px;
}
h3 {
margin: 0 0 6px;
font-size: 14px;
}
.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;
}
.supplier-telemetry {
margin-bottom: 12px;
padding: 12px;
line-height: 1.8;
background: var(--el-fill-color-light);
border-radius: 4px;
}
.supplier-telemetry small {
color: var(--el-text-color-secondary);
}
.supplier-telemetry > div > span {
margin-left: 12px;
}
.calibration-view .view-canvas img {
max-height: 75vh;
}
@media (max-width: 768px) {
.scanner-live-view {
padding: 12px;
}
.view-canvas {
min-height: 220px;
}
}
</style> </style>

View File

@ -0,0 +1,50 @@
// Render only supplier callback values. Workflow node counts never become SDK progress.
export function calibrationTelemetry(progress, temperatures) {
const row = progress && typeof progress === 'object' && !Array.isArray(progress) ? progress : null
const data = row?.data && typeof row.data === 'object' ? row.data : row
const scalar = (value) =>
typeof value === 'string' ||
typeof value === 'boolean' ||
(typeof value === 'number' && Number.isFinite(value))
? String(value)
: ''
const labels = {
handeyeCalibStep: '厂商标定步骤',
calibCalculateResult: '厂商计算结果',
sdk_calibFinished: '厂商标定完成回调',
showProgress: '厂商进度提示',
hideProgress: '厂商已隐藏进度提示'
}
const title =
scalar(data?.title) || labels[row?.cmd] || (row ? '厂商标定消息' : '等待厂商标定阶段回传')
const fields = [
['currentStep', '当前步骤'],
['totalStep', '总步骤'],
['totalSteps', '总步骤'],
['totalStepIndex', '步骤索引'],
['value', '进度值'],
['calibResult', '厂商结果'],
['camErr', '相机误差'],
['calibTarget', '标定目标']
]
const details = fields
.map(([key, label]) => {
const value = scalar(data?.[key] ?? row?.[key])
return value ? `${label}:${value}` : ''
})
.filter(Boolean)
const temperature = (value) =>
value && typeof value.value === 'number' && Number.isFinite(value.value)
? {
value: value.value,
receivedAt: typeof value.receivedAt === 'string' ? value.receivedAt : ''
}
: null
return {
title,
details,
receivedAt: typeof row?.receivedAt === 'string' ? row.receivedAt : '',
scanner: temperature(temperatures?.scanner),
tracker: temperature(temperatures?.tracker)
}
}

View File

@ -1,8 +1,27 @@
export function scannerPreviewTarget(scope, id) { export function scannerPreviewTarget(scope, id) {
if (scope === 'fixture') return { path: '/lab/master/fixture/framework', params: { recordingId: id }, stream: 'preview-stream', view: '/view' } if (scope === 'fixture')
if (scope === 'execution') return { path: '/lab/execution/scanner-view', params: { executionId: id }, stream: 'stream', view: '' } return {
throw new Error('未知扫描预览来源') path: '/lab/master/fixture/framework',
params: { recordingId: id },
stream: 'preview-stream',
view: '/view'
}
if (scope === 'maintenance')
return {
path: '/lab/maintenance/scanner-view',
params: { instId: id },
stream: 'stream',
view: ''
}
if (scope === 'execution')
return {
path: '/lab/execution/scanner-view',
params: { executionId: id },
stream: 'stream',
view: ''
}
throw new Error('未知扫描预览来源')
} }
export function activeFixtureRecording(history = []) { export function activeFixtureRecording(history = []) {
return history.find(record => record.status === 'RUNNING' && record.id && record.instanceId) return history.find((record) => record.status === 'RUNNING' && record.id && record.instanceId)
} }

View File

@ -4,6 +4,7 @@ import { scannerPreviewTarget, activeFixtureRecording } from './scannerPreviewTa
test('夹具预览按录入记录绑定,普通执行的接口保持原样',()=>{ test('夹具预览按录入记录绑定,普通执行的接口保持原样',()=>{
assert.deepEqual(scannerPreviewTarget('fixture','record-A'),{path:'/lab/master/fixture/framework',params:{recordingId:'record-A'},stream:'preview-stream',view:'/view'}) assert.deepEqual(scannerPreviewTarget('fixture','record-A'),{path:'/lab/master/fixture/framework',params:{recordingId:'record-A'},stream:'preview-stream',view:'/view'})
assert.deepEqual(scannerPreviewTarget('execution','123'),{path:'/lab/execution/scanner-view',params:{executionId:'123'},stream:'stream',view:''}) assert.deepEqual(scannerPreviewTarget('execution','123'),{path:'/lab/execution/scanner-view',params:{executionId:'123'},stream:'stream',view:''})
assert.deepEqual(scannerPreviewTarget('maintenance','calibration-A'),{path:'/lab/maintenance/scanner-view',params:{instId:'calibration-A'},stream:'stream',view:''})
assert.throws(()=>scannerPreviewTarget('bad',1)) assert.throws(()=>scannerPreviewTarget('bad',1))
}) })
test('开始录入自动提供预览,完成、失败与终止均不再预览历史工程',()=>{ test('开始录入自动提供预览,完成、失败与终止均不再预览历史工程',()=>{

View File

@ -0,0 +1,9 @@
# 扫描仪标定页面与真实 SDK 进度
“我的任务”启动扫描仪标定后,平台自动显示本次执行的监视窗口。沿用现有 `POST /api/v1/calibration/enter`,等待成功回执后显示同一 SDK 的厂家标定窗口,前视图、俯视图和操作提示均来自实际窗口像素;真实 SDK 步骤、温度及计算结果按回调原值展示。平台流程节点记录保留供核对,窗口关闭/重开不重复下发标定或设备停止。
配套 FreeScanCpp 源码纳入 `integrations/freescan-service`,来源及第三方许可随源码保留;不包含厂家 SDK 二进制、私有配置或运行数据。新增独立的标定元数据/JPEG/MJPEG 接口,绑定设备会话、独立标定编号和可信厂家进程窗口。普通扫描预览的工程门禁保持。修复捕获线程跨会话生命周期及进入页回执后首次读取缓存的竞态,旧画面或身份变化时终止流,不自动重发控制命令。
平台按原 Windows 更新脚本构建;要启用实际画面,还需在用户当次同意且现场停止后,同步更新配套扫描仪服务。服务可用模块内 `build.ps1` 指定已安装的 MSVC/Windows SDK 和厂家 SDK 头文件构建,输出本模块 `build/bin`,不覆盖原安装;实际密钥及设备设置沿用现场配置。无需数据库结构变更,不导入全量数据。
平台 Java 编译、相关隔离回归、前端类型/组件检查与完整构建通过;配套服务完整原生编译、原离线/HTTP 回归、专用窗口接口和立即读取身份检查通过,单窗口真实像素采集已完成10轮合成GUI关闭/重开验证。新增临时测试源码、构建产物和验证材料均已清理,原回归保留。尚未安装发布,未连接 SDK 执行真实设备标定,厂家 OpenGL 窗口及现场弹窗布局仍需部署后验收。

View File

@ -84,7 +84,7 @@
窗口再次打开时复用当前页面中仍适用的上次选择,机器人及设备按实时资源列表重新匹配,失效或新增配置需要补选。弹窗期间若用例重新发布,开始前刷新配置并提示再次核对,不按旧版本静默启动。需要临时输入的业务参数应在开始节点声明,节点内部固定配置仍在用例页面维护。 窗口再次打开时复用当前页面中仍适用的上次选择,机器人及设备按实时资源列表重新匹配,失效或新增配置需要补选。弹窗期间若用例重新发布,开始前刷新配置并提示再次核对,不按旧版本静默启动。需要临时输入的业务参数应在开始节点声明,节点内部固定配置仍在用例页面维护。
沿用资源类型、身份、设备状态和占用校验;取得执行实例后关闭窗口,按钮保持 loading 并跟踪该实例的真实成功、失败或终止状态。扫描仪标定结束后重新获取最后标定时间。 沿用资源类型、身份、设备状态和占用校验;取得执行实例后关闭执行设置窗口,按钮保持 loading 并跟踪该实例的真实成功、失败或终止状态。扫描仪标定另自动打开画面与步骤监视窗口,结束后重新获取最后标定时间。
### 结束标定并恢复设备(2026-11-07) ### 结束标定并恢复设备(2026-11-07)
@ -274,3 +274,15 @@ STL 导出可能包含退化三角面的非有限法向量;在线查看从原
修正版 `T-20261023-0002` 的现场复测中,新建工程、开始采集均成功,采集期间快照仍返回同一错误。2026-10-23 13:50 对比原始 JPEG 与平台转发 JPEG,二者 SHA-256 完全一致,画面已包含扫描内容;预览指标约 19.6fps、无编码失败。与此同时场景摘要仍为 `no_scene_snapshot`。由此可确认预览图像传输正常,而原始 SDK 场景复制路径没有成功返回数据;提高 MJPEG 帧率不能解决该快照接口错误。可另行现场验证“停止→网格化→确认网格→导出PLY/STL”的真实文件路径,当前不能宣称网格化和导出已通过现场验收。 修正版 `T-20261023-0002` 的现场复测中,新建工程、开始采集均成功,采集期间快照仍返回同一错误。2026-10-23 13:50 对比原始 JPEG 与平台转发 JPEG,二者 SHA-256 完全一致,画面已包含扫描内容;预览指标约 19.6fps、无编码失败。与此同时场景摘要仍为 `no_scene_snapshot`。由此可确认预览图像传输正常,而原始 SDK 场景复制路径没有成功返回数据;提高 MJPEG 帧率不能解决该快照接口错误。可另行现场验证“停止→网格化→确认网格→导出PLY/STL”的真实文件路径,当前不能宣称网格化和导出已通过现场验收。
已运行任务保持冻结版本及失败日志。显式运行 `python scripts/prepare_real_scan_task.py --replace-failed` 可为已停止且全部单件失败的任务准备修正版;准备成功且确认设备空闲后,再取消旧任务并确认资源释放。替代任务重新要求操作人确认收样、装夹及开始动作。不得改写历史执行版本、静默重试采集,或跳过 SDK 快照失败。 已运行任务保持冻结版本及失败日志。显式运行 `python scripts/prepare_real_scan_task.py --replace-failed` 可为已停止且全部单件失败的任务准备修正版;准备成功且确认设备空闲后,再取消旧任务并确认资源释放。替代任务重新要求操作人确认收样、装夹及开始动作。不得改写历史执行版本、静默重试采集,或跳过 SDK 快照失败。
### 扫描仪标定画面与执行进度(2026-11-21)
“我的任务”启动扫描仪标定并取得执行实例后,自动打开监视窗口,展示本次冻结流程的步骤、当前节点、耗时和执行结果。进度按实际节点记录计算,只有实例成功终态才能完成;不是扫描仪姿态覆盖率或标定质量百分比。窗口可关闭并通过“查看标定过程”重开,关闭、切页或刷新不会向设备下发停止或重复标定。未结束实例从浏览器会话恢复后,按原实例重新读取冻结流程和日志。
标定监视只读接口为 `/lab/maintenance/scanner-view/execution?instId=...`、`/lab/maintenance/scanner-view?instId=...` 和 `/lab/maintenance/scanner-view/stream?instId=...`。按租户、执行权限、冻结/实际运行分配、设备登记和当前占用校验目标;仅本次成功进入标定后建立的设备会话可以供画面查看。标定会话与扫描工程绑定分别保存;结束恢复或会话变化后旧绑定停用,旧帧不回显。正常收帧期间不轮询 SDK 状态。
用户要求平台展示 FreeScan Trak 的真实标定指引画面(前视图、俯视图、现场提示与标定阶段)。配套扫描仪服务源码保存在 `integrations/freescan-service`,来源与指纹见该目录 `SOURCE-ORIGIN.json`;本机原安装及私有配置保持不变。标定流程先等待 `Sn3DEnterCalibrationPage` 的 `enterCalibrationPageFinish` 成功确认,随后通过同一 SDK 服务显示厂家主窗口,使用 Windows Graphics Capture 采集该受信窗口整幅像素,提供独立的 `/api/v1/calibration/view`、`/image`、`/stream` 只读输出。平台按本次设备会话和独立 `calibrationId` 代理此画面,并原样展示 SDK `currentStep`、`totalStep`、`calibCalculateResult` 等回调。关闭或重开平台监视窗口不重新进入标定、不停止设备;图中的“下一步”仍是厂家窗口内容,应按设备或厂家软件提示操作。
普通扫描 `/preview/start` 的工程门禁保持不变,标定不会自动插入该步骤。整窗采集只绑定 SDK 已核实的厂家进程创建时间、可执行路径和窗口句柄,拒绝其他程序、失效会话、空帧和过期帧;不采集整张桌面。窗口被最小化、隐藏、关闭、采集不受支持或首帧未到时显示明确状态,进度与温度缺失时不推算数据。进入新标定或结束恢复会停用旧画面来源,同一 SDK 会话再次进入标定也产生新的 `calibrationId`。
此功能需要同时更新平台和配套扫描仪服务。源代码编译与离线、合成窗口验证不等于已安装或完成厂家真机标定验收;正式替换及现场验证应在用户另行通知更新、设备停稳后进行。

View File

@ -0,0 +1,8 @@
BasedOnStyle: LLVM
IndentWidth: 4
ColumnLimit: 110
BreakBeforeBraces: Attach
AllowShortFunctionsOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
SortIncludes: Never

View File

@ -0,0 +1,70 @@
cmake_minimum_required(VERSION 3.16)
cmake_policy(SET CMP0091 NEW)
project(FreeScanCpp VERSION 1.3.0 LANGUAGES CXX)
if(NOT WIN32 OR NOT MSVC)
message(FATAL_ERROR "FreeScanCpp requires Windows x64 and an MSVC-compatible C++ compiler.")
endif()
if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8)
message(FATAL_ERROR "Configure an x64 build (for Visual Studio generators: -A x64).")
endif()
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
# The vendor SDK exchanges STL structures across the DLL boundary. All build
# configurations use the release DLL CRT and iterator ABI used by the SDK.
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreadedDLL")
include(CheckCXXSourceCompiles)
check_cxx_source_compiles("#if !defined(_M_X64)\n#error The vendor SDK requires x64.\n#endif\nint main() { return 0; }" FREESCAN_TARGET_X64)
if(NOT FREESCAN_TARGET_X64)
message(FATAL_ERROR "The official SDK requires x64; ARM64 and x86 targets are unsupported.")
endif()
set(SDK_INCLUDE_DIR "C:/Program Files/Shining3d/FreeTrak_TRAK/sdk/include"
CACHE PATH "Matching FreeScan Trak SDK include directory")
if(NOT EXISTS "${SDK_INCLUDE_DIR}/sn3dsdkcorepub.h" OR NOT EXISTS "${SDK_INCLUDE_DIR}/Sn3DSDKDataLibpub.h")
message(FATAL_ERROR "Set SDK_INCLUDE_DIR to the matching official FreeScan SDK headers.")
endif()
set(FREESCAN_SYSTEM_LIBRARIES httpapi advapi32 ole32 shell32 user32 gdiplus shlwapi crypt32 bcrypt ws2_32 version d3d11 dxgi windowsapp windowscodecs dwmapi)
function(freescan_target target)
target_compile_features(${target} PRIVATE cxx_std_17)
target_compile_definitions(${target} PRIVATE _ITERATOR_DEBUG_LEVEL=0 _WIN32_WINNT=0x0602 WIN32_LEAN_AND_MEAN NOMINMAX)
target_compile_options(${target} PRIVATE /EHsc /utf-8 /W4)
target_include_directories(${target} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src" "${SDK_INCLUDE_DIR}")
target_link_libraries(${target} PRIVATE ${FREESCAN_SYSTEM_LIBRARIES})
endfunction()
file(GLOB FREESCAN_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp")
add_executable(FreeScanCpp ${FREESCAN_SOURCES})
freescan_target(FreeScanCpp)
include(CTest)
if(BUILD_TESTING)
# Separate source lists deliberately omit main.cpp, HTTP and supervisor from
# offline tests. worker_test always constructs WorkerService(..., true).
add_executable(contracts_test src/contracts.cpp tests/contracts_test.cpp)
freescan_target(contracts_test)
add_test(NAME contracts_offline COMMAND contracts_test)
add_executable(worker_test src/common.cpp src/contracts.cpp src/sdk_worker.cpp src/calibration_window_capture.cpp tests/worker_test.cpp)
freescan_target(worker_test)
add_test(NAME worker_offline COMMAND worker_test)
add_executable(preview_capture_test src/common.cpp tests/preview_capture_test.cpp)
freescan_target(preview_capture_test)
add_test(NAME preview_capture_offline COMMAND preview_capture_test)
add_executable(battery_test src/common.cpp tests/battery_test.cpp)
freescan_target(battery_test)
add_test(NAME battery_offline COMMAND battery_test)
add_executable(calibration_files_test src/common.cpp tests/calibration_files_test.cpp)
freescan_target(calibration_files_test)
add_test(NAME calibration_files_offline COMMAND calibration_files_test)
add_executable(calibration_recovery_test src/common.cpp tests/calibration_recovery_test.cpp)
freescan_target(calibration_recovery_test)
add_test(NAME calibration_recovery_offline COMMAND calibration_recovery_test)
set_tests_properties(contracts_offline worker_offline preview_capture_offline battery_offline calibration_files_offline calibration_recovery_offline
PROPERTIES TIMEOUT 30)
endif()

View File

@ -0,0 +1,165 @@
## 平台配套标定窗口输出
此目录是经用户授权纳入平台项目的扫描仪服务源码副本,来源与原文件 SHA-256 见 `SOURCE-ORIGIN.json`;不包含实际密钥、运行配置、厂家 SDK 二进制或正式数据。修改及构建此目录不会替换原安装。
标定画面使用当前已确认 SDK 服务的真实厂家窗口。只有 `Sn3DEnterCalibrationPage` 完成确认后才显示同一服务主窗口并开始窗口采集;设置标定模式、读取画面或关闭平台弹窗均不会另行初始化 SDK。Windows Graphics Capture 仅针对本会话核实过的进程与单一窗口,默认保留完整构图,最大输出宽度 1920、约 5 帧/秒。未出帧、窗口最小化/隐藏/关闭、进程变化或过期时返回不可用;不回退整屏截取或三维场景假画面。
新增鉴权只读接口:
- `GET /api/v1/calibration/view`:缓存的会话、画面状态、真实 SDK 标定消息和温度。
- `GET /api/v1/calibration/view/image`:当前新鲜 JPEG,头部携带来源、SDK 会话、本次标定编号及进程/窗口身份证明。
- `GET /api/v1/calibration/view/stream`:相同身份固定的 MJPEG,身份变化或无新鲜帧时结束。
每次成功进入标定生成独立 `calibrationId`。回调中的 `currentStep`、`totalStep`、`calibResult`、`camErr` 和温度只保存实际值及收到时间;未上报值为未知,不设自定义质量阈值。普通 `/preview` 仍用于扫描工程离屏渲染,原工程与设备门禁不放宽。
构建使用 `build.ps1`,可显式提供 `-ToolchainRoot` 与 `-SdkInclude`;默认工具链仅从本机现有安装只读使用。输出位于本副本的 `bin`/`build`,不写入原运行目录。`run-tests.ps1` 默认仅离线模拟,`-IncludeHttp` 使用本机模拟服务。生成文件和临时验证材料不纳入源码。
安装新程序、重启扫描仪服务或实际进入标定仍需用户当次指示。现场验收应核对厂家窗口画面、双视图/提示、回调进度以及最小化/关闭时的状态;合成窗口验证不能替代厂家现场验收。
# FreeScan 原生 C++ 接口后端
这是现有 FreeScan HTTP API 的 C++17 实现。HTTP 监听、异步任务、SDK 工作进程管理、厂家 SDK 调用、JPEG 编码和下载登记均在原生 C++ 进程中完成,不启动 C# 程序,不加载 .NET CLR。
对外继续使用 `/api/v1/`;字段、异步任务、鉴权及功能顺序见 [完整 HTTP 接口文档](../FreeScanViewer/HTTP接口与部署说明.md)。网页控制台继续使用现有 HTML/CSS/JavaScript 和 Node.js 网页代理。
## API1.3 摄影测量与框架
2026-10-26 新增以下接口,已有接口路径保持兼容:
| 方法 / 路径 | 用途 | 返回方式 |
|---|---|---|
| POST `/api/v1/scan/type` | 选择摄影测量、表面或标志点采集类型,可明确切换SDK采集设备 | 202异步;等待SDK完成消息 |
| POST `/api/v1/framework/files` | 上传`.p3/.txt/.asc`原始框架文件,返回受控fileId | 201同步;不调用SDK |
| POST `/api/v1/framework/import` | 将已上传文件交给`Sn3DImportGlobalMarkers` | 202异步;需confirm:true |
| POST `/api/v1/framework/optimize` | 对已采集且暂停的摄影测量框架调用`Sn3DGlobalMarkerOptimize` | 202异步;请求{} |
现有 `/api/v1/exports` 增加摄影测量纯P3保存例外:当前为trak+photogrammetry+tracker,框架已开始采集且优化完成时,`{"name":"Frame001","formats":["P3"]}`无需表面网格。其他及混合格式请求仍需确认网格;仅在SDK生成实际可读文件后才成功,不伪造P3数据。
模式选择与采集类型分开;`mesh`采集类型不是后处理`/mesh`。`tracker`映射SDK UENOVA(0),`scanner`映射TENOVA(1)。摄影测量仅trak+tracker,标志点仅laser+scanner,导入仅trak+mesh+scanner。实际切换device要confirm:true,工程已经开始采集或导入框架时会拒绝切换,须先保留数据并新建工程。框架采集→暂停→优化→纯P3导出下载后,另建跟踪工程,上传导入并按现场流程开始表面扫描。
上传必须为application/octet-stream和URL编码的X-File-Name,非空且每文件≤16MiB,每次导入1至8个fileId;最多并行上传2路、父服务登记64个编号,FrameworkUploads磁盘历史文件总额≤256MiB。HTTP父进程重启后上传编号失效须重传;重启不会清空历史文件或重置磁盘配额。所有API均需原有鉴权;网页代理仍要求同源与CSRF令牌。
Apifox已有项目和新项目都使用[API1.3完整42项OpenAPI](../接口文档/FreeScan_HTTP_API_v1.3.openapi.json)。在原模块按方法+路径更新,资源清理选择“不删除”,保留环境及密钥。五项框架增量仅作定向补充,不能替代全量文件。详细字段和流程见[完整说明](../接口文档/FreeScan_HTTP_API_v1.3.详细说明.md)及[主文档第九节](../FreeScanViewer/HTTP接口与部署说明.md#framework-api)。v1.3 PDF/HTML/ZIP已更新,旧v1.2保留为历史交付。
上传201、异步202、接口代码测试通过都不表示真实摄影测量框架或转站流程已验收。框架导入完成不等于当前位置对齐、跟踪有效或连续转台运动补偿;未新增混合转站下一站命令、转台或AGV控制。
## 扫描仪与跟踪仪电量
2026-10-30 API1.3 增量新增同步 `GET /api/v1/device/battery`,原 `GET /api/v1/status` 新增同结构的 `battery` 对象。继续使用现有 Bearer / X-Api-Key 鉴权,无 Body、查询参数或 taskId;读取缓存不连接 SDK、不创建工程、不开始或暂停扫描。已有 SDK 会话收到 `sdkDeviceStatus` 后,分别保存 `scannerBattery` 与 `trakBattery`。
返回结构包含 `source:"sdkDeviceStatus"`、`freshnessLimitMs:30000`、`scanner` 和 `tracker.channels`。扫描仪与各跟踪仪频道分别提供 `percent`、`rawValue`、`available`、`fresh`、`updatedUtc`;跟踪仪另有原始数字索引字符串 `index`,消息不带索引时为 null,最多 16 个频道。索引的物理含义没有确认,不推断电池槽或计算平均电量。
仅当前 SDK 会话有效、消息距今不超过 30 秒且原始整数在 0–100 时,`percent` 才是可显示的百分比。`-1`、越界、格式无效、离线、故障、超时均使 `percent:null`、`available:false`,界面应显示未知,不能用 0% 代替。新收到的未知值可以 `fresh:true`,须同时检查 `available`。过期 `rawValue` 与 `updatedUtc` 仅供历史诊断;断开或重建会话会清空缓存。未收到跟踪仪消息时 `channels:[]`。不提供充电、续航或健康度推算。
Apifox统一导入[完整42项OpenAPI](../接口文档/FreeScan_HTTP_API_v1.3.openapi.json),选择原模块、按方法+路径更新并设为“不删除”其他资源,保留原环境与`bearerToken`;不要用两项电量增量替代全量接口。全量 v1.3 更新为 42 项操作,原框架增量仍为 5 项。详细结构、示例和导入步骤见[设备电量说明](../FreeScanViewer/HTTP接口与部署说明.md#device-battery)。静态文档示例不代表当前实机电量或厂家上报频率验收。
## 标定模式中文名称
2026-11-04 标定模式中文名称兼容更新:`calibration/setMode`、`calibration/applyLast` 原请求仍发送数字 `mode`;成功任务 `result` 保留原字段,追加 `mode` 和 `modeName`(0 跟踪仪标定、1 系统标定、2 探针标定、3 UE Nova 激光标定)。`capabilities.calibration` 同步增加 `modeName`,数字 `mode` 不变。接口路径、鉴权、202受理及任务轮询均不改变,旧接入方无需调整原调用。新增字段不代表标定质量合格;真实标定应遵循厂家流程。导入使用[完整 42 项接口 JSON](../接口文档/FreeScan_HTTP_API_v1.3.openapi.json)。
查询标定模式:GET `/api/v1/capabilities`,读取`calibration.mode`、`calibration.modeName`。SDK未就绪或需要重启时calibration可为null;初始mode=0且lastConfirmedAction=none只是缓存默认值。工程扫描模式另查`GET /api/v1/status`的scanMode。完整用途、参数和返回字典见[详细说明](../接口文档/FreeScan_HTTP_API_v1.3.详细说明.md)。
## 最后一次标定时间
2026-11-06:`GET /api/v1/status` 兼容新增 `lastCalibrationUtc`、`lastCalibrationSource` 和 `calibrationFileTimes`。按现有 SDK 定位规则,只读扫描其 `res/FreeScanTrak` 顶层已知命名的非空跟踪仪、扫描仪与手眼标定 `.bin` 文件;`lastCalibrationUtc` 取这些文件修改时间的最大值,各文件时间另列数组。来源固定为 `local_calibration_file_modified_time`。UTC 时间在北京时间显示时加 8 小时;文件不可读或目录未定位时返回 `null` 和空数组,模拟模式不读取真实安装目录。原接口、鉴权和请求不变,任务内嵌状态可不包含新增字段,读取请独立调用状态接口。
此时间按本项目约定表示本机标定文件的最后修改时间,不证明设备当前加载的参数、对应哪台已连接设备或标定质量合格;同类多份文件均保留。复制、恢复及其他写入也可能改变时间。查询不执行 SDK 标定命令,不调用 `applyLast`,不触发设备连接。
## 代码组成
2026-11-05 标定计算回调兼容修复:`/api/v1/calibration/compute` 等待期间,同时接受 SDK 正式 `freeCalibrationComputeFinish` 与 `calibCalculateResult` 的明确成功计算结果;后者要求 `calibResult` 为布尔 `true` 或字符串 `"true"`,且无失败标志、无十进制/十六进制非零错误码。只有 `result:success`、零错误码或缺少计算结论的模糊消息不作为该替代完成条件。明确失败仍及时结束任务为 `failed/sdk_error`,保留厂家目标及错误信息;其他待执行动作不受计算回调影响。
成功任务的 `result` 保留原 `action`、`calibrationActive`、`status:confirmed`,兼容新增 `sdkResult`,原样保存真正结束本次等待的 SDK 消息。例如 `sdkResult.cmd:calibCalculateResult`、`calibResult:"true"`、`calibTarget:"6"`、`camErr:"0.004910327805427969"`、`errorCode:"0x00000000"`;正式 ACK 路径保存实际 ACK,不伪造不存在的字段。不汇总全部目标,不推断参数已写回设备,也不自行解释厂家残差单位或合格阈值。旧版成功结果可没有 `sdkResult`。接口地址、请求参数、202 受理及 GET 任务查询方式均保持兼容,无新增接口;姿态数量、有效性与最终质量仍由厂家流程决定。
| 文件 | 负责内容 |
|---|---|
| `src/http_server.cpp` | Windows HTTP Server API、鉴权、请求限额、任务、JPEG/MJPEG 与下载 |
| `src/supervisor.cpp` | 稳定父进程、更换 SDK 工作进程、保留历史任务/下载及图像缓存 |
| `src/pipe_rpc.cpp` | 仅当前用户可访问的本地管道、长度前缀 JSON、有界 I/O 与回复消费确认 |
| `src/sdk_worker.cpp` | 厂家 SDK 生命周期、采集、参数、网格、导出、标定和原始场景桥接 |
| `src/contracts.cpp` | 全部已公开动作的静态参数与确认规则 |
| `src/main.cpp` | 启动、受控停止、父进程监视及测试模式 |
每个 SDK 工作进程最多尝试一次初始化。手动断开或重连时先暂停/释放设备,核验原厂家服务退出,再核验原工作进程退出;通过后才能启动下一工作进程。自动异常重启的空闲保护及退出后备机制见下文。原生库和回调所有者保留至进程退出,不通过卸载仍有回调的 DLL 重置 SDK。
## 运行部署
正式 EXE 输出到 `FreeScanViewer/FreeScanCpp.exe`,与原运行目录中的配置、原生桥接及配套 CRT 共处。数据目录继续使用 `FreeScanViewer`,保留 `api-settings.json`、`settings.xml`、`Scans`、`Exports` 和需要的日志;原 C# 源码及 EXE 留作历史回退,不参与新后端运行。
连接扫描仪的电脑需具备匹配的厂家完整软件、SDK、驱动、授权以及可用的显卡和已登录桌面。运行不要求安装 .NET、Visual Studio、Python 或构建工具链。配套 Microsoft CRT 和 `FreeScanNativeBridge.dll` 必须随运行文件保留。仅使用设备 API 时无需 Node.js;使用本项目网页时仍需现有 Node.js 环境。
日常双击启动推荐使用 `FreeScanViewer/启动C++后端.cmd`,或项目根目录的 `启动HTTP上位机.cmd` / `启动上位机.cmd`。这些入口先核验已有后端的 PID、路径、启动时间和 HTTP 健康,已运行时显示提示并复用;未运行时先启动接口服务,再按配置自动连接 SDK。窗口会保留启动结果,方便查看错误。直接重复双击 EXE 会因监听地址已被现有服务占用而退出。
直接运行 EXE 默认会尝试连接设备。先只开服务可运行:
```powershell
.\FreeScanCpp.exe --api-no-auto-connect
```
日常关闭使用:
```powershell
.\FreeScanCpp.exe --stop
```
停止命令核验记录的进程路径、PID 和启动时间,通过当前用户专用管道请求正常清理,并等待该父进程退出。当前有任务时会拒绝关闭;释放/退出未确认时会保留服务及诊断信息,不通过批量终止进程来表示成功。
API 监听地址和访问密钥由实际运行数据目录中的 `api-settings.json` 读取,不随本源码分发。部署时按目标机器网络配置监听地址、访问权限和防火墙;设备 API 始终保留鉴权,平台通过后端代理访问。网页服务的访问控制应由其部署配置明确设置,源码说明不携带某台现场机器的地址、账户或免登录配置。`--data-root` 可指定已有数据目录;`--worker` 是父进程内部参数,不手动启动。
## 登录后自动启动
在项目根目录右键 `启用接口自启.cmd`,选择“以管理员身份运行”。任务 `FreeScanCpp-API-Autostart` 在该账户登录 Windows 后延迟 30 秒隐藏启动 API。厂家 SDK 需要交互桌面;不在未登录的 Session 0 中运行,不配置自动登录。自启按 `api-settings.json` 的 `autoConnect` 配置自动恢复 SDK,不自动创建工程或扫描。
2026-11-04 SDK 自动重启:默认 `autoConnect:true`、`autoConnectRetrySeconds:15`(5–300秒)。SDK 初始化失败、异常或确认离线后,在无工程、未采集、非标定时先正常退出旧工作进程;若卡住,核验自有进程句柄、PID、启动时间、EXE路径和空闲状态后,可强制结束该 SDK 工作进程,确认退出才重建。HTTP 父进程、原任务和已登记下载保持运行。不会强杀另开的厂家软件;厂家进程仍占用时等待重试。有工程或标定会话时保留会话,不自动重启或继续扫描。身份、退出或状态无法核验时停止恢复并报告 blocked。手动断开/停止会暂停自动恢复,手动连接/重连可恢复。重试间隔从失败结束后计算,不含初始化和清理耗时。
通过 `GET /api/v1/status` 的 `autoConnection` 查询:`state` 为 recovering 时正在重启,`restartCount`、`lastRestartUtc`、`lastRestartForced` 分别表示自动后台更换次数、最近时间、是否采用强制退出后备方式;`lastError` 说明最近失败原因。更换成功不代表设备连接成功,应同时查看 `initialized` 和错误。显式 `--api-no-auto-connect` 或配置 `autoConnect:false` 可关闭。
`关闭接口自启.cmd` 只禁用下次登录自启,`检查接口自启.cmd` 查询任务状态。正常停止当前接口仍用 `停止HTTP上位机.cmd`。已有服务时启动器核验 PID、路径、启动时间及 HTTP 健康后仅跟踪现有服务,不重新连接或重启当前工程。运行结果及限制见[部署说明 3.2](../FreeScanViewer/HTTP接口与部署说明.md)。
## 本机开发构建
使用已经准备好的项目内 MSVC 14.44 / Windows SDK 工具链:
```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File .\FreeScanCpp\build.ps1
```
执行位置是项目根目录“扫描仪”。编译为 x64 C++17、动态 CRT `/MD`、`_ITERATOR_DEBUG_LEVEL=0`,与厂家 C++ 数据结构和原生桥接约定一致。自定义厂家头文件位置可传 `-SdkInclude`。构建前正常停止当前 C++ 后端,避免覆盖正在使用的 EXE。
另提供 `CMakeLists.txt`,供具备 CMake 与 MSVC 的开发机使用。本机未安装 CMake/Ninja,因此交付验证使用上述 PowerShell/MSVC 入口;不把未执行的 CMake 配置宣称为已通过。
## 原始场景快照
`POST /api/v1/data/snapshots` 新增可选布尔参数 `pauseAcquisition`,默认 `false`。需要暂停后场景时可提交:
```json
{"maxPoints":100000,"include":["points","markers","meshes"],"pauseAcquisition":true}
```
`true` 会先准备原始场景回调,再暂停正在进行的采集;`include` 包含 `meshes` 时必须收到 SDK 非空整场网格(`whole_mesh`),仅有点云、标志点或增量网格不能满足此次请求,不会自动降级。任务结束后保持暂停,不自动继续扫描。`false` 不主动暂停采集,沿用等待实际场景更新的行为。结果仍通过异步任务中的 `files` 清单下载。
整场来源仍受 `maxPoints` 输出上限约束,必须检查 manifest 的截断标志;SDK 没有提供的点云、标志点或网格类型不会被补造。工程已暂停、没有新通知时,反复 GET 场景或旧任务不会触发新的三维数据。首次处理此情况可保留当前工程,手动继续实际采集,等待开始任务成功,再带 `pauseAcquisition:true` 请求新快照;随后如需扫描须手动继续。
2026-10-23 14:37(北京时间)已在升级后的原生 C++ 后端完成一次真实 Trak 工程验收:采集中提交 `maxPoints:1000000, include:["meshes"], pauseAcquisition:true`,约 1.63 秒成功,得到 537908 个顶点、1004339 个三角面,`meshSource:whole`、`meshTruncated:false`;下载文件大小与 PLY 头、manifest 相符,工程保留且采集暂停。此结果仅证明该设备、模式和工程的本次流程,不能代替其他类型及模式验收。完整参数及限制见主接口文档。
## 离线验证
`tests/contracts_test.cpp` 检查参数和路由,`tests/worker_test.cpp` 使用显式模拟 SDK 测试动态状态及业务门禁,`tests/native-api.test.mjs` 对独立 C++ 父/工作进程执行真实 HTTP 测试。它们不代表硬件扫描结果。
在项目根目录执行 `powershell -NoProfile -ExecutionPolicy Bypass -File .\FreeScanCpp\run-tests.ps1`,会独立编译并运行契约、工作进程、电量三个离线C++测试;加 `-IncludeHttp` 可同时运行隔离的 HTTP 测试(需要现有 Node.js)。测试不会覆盖正式 EXE;升级正式后端须单独执行 `build.ps1`。
模拟服务必须同时显式指定 `--mock` 和隔离的数据目录,且配置地址只能是 `http://127.0.0.1:18889/`,不允许用于正式 18888 端口。模拟状态与返回值标注 `simulated:true`,日志及测试文件标注 `OFFLINE_TEST_FIXTURE`,不会把模拟几何或编号当作真实 SDK 数据。
## 依赖来源
Windows HTTP.sys、命名管道与 GDI+ 使用系统 API。JSON 使用项目内固定的 nlohmann/json 3.12.0 单头文件,官方发布 SHA-256 已核对,许可证与来源见 [third_party/README.md](third_party/README.md)。`tools` 内的固定版本源码格式化工具仅用于开发,不随运行包部署。
2026-11-04标定中文字段发布已通过契约339、工作进程304、电量355、HTTP14项隔离验证,不代表实机标定质量验收。
## 历史验收(2026-10-22,非当前运行状态)
2026-10-22 已完成原生 C++ 编译(`/W4` 零警告),接口契约 302 项、显式模拟工作进程 198 项及隔离 HTTP 测试 9 项通过。真实 FreeScan Trak Nova 的连接、创建工程、开始/暂停采集、预览关闭/开启、断开及重新连接均成功;正常停止命令也已验证。最终父进程与 SDK 工作进程均未加载 CLR。
最终保留的是测试工程,设备在线、未采集、预览开启。当前测试没有可用的真实场景快照,尚未验收新版后端的真实网格/导出、原始点云、标志点、拼接、编辑裁剪、标定及全部参数。详细记录见 [最终真机证据](verification/real-device-final.json)、[网页画面](verification/native-web-final.png) 和主接口文档的验收部分。
最终版本的只读 10 秒预览窗口收到 191 帧(19.10 FPS),输出 1280×615;19 次 JPEG 响应的帧年龄中位数 62 ms。测试时未采集,帧年龄不含硬件曝光,不保证复杂模型或长时间运行性能。完整采样及计算方式见 [预览测量](verification/real-preview-window.json)。

View File

@ -0,0 +1,70 @@
{
"source": "C:\\Users\\Administrator\\Desktop\\扫描仪\\FreeScanCpp",
"copiedAt": "2026-11-21",
"purpose": "User-authorized calibration window streaming; source only, no private configuration, SDK binaries or runtime data",
"sha256": {
".clang-format": "d875c8d06143d5e6866df7a8e6645f2bc3318cd6cabfa4bcdc5670a0f1a1db2a",
"build.ps1": "8a36b3f78d7e633ea821a064d8c0218c8f75b2c92e428f266833daf5b271f5bb",
"CMakeLists.txt": "1d924614cd508fdb7db9d7405904626e49a0f8e974996e1fc9d44a14afaa9bdf",
"README.md": "694113e0a7a4279ccf6371ecb928aa93a716c334797f30927c357a2771a388d4",
"run-tests.ps1": "8f65145f5087fa75db644889207c909f3059c410dfed09db1a1cd210bc5f53f5",
"src/auto_connection.hpp": "2ac6583a4d2cc9339ef1c7a5b3bdb8bf4295ee500b8d685dcc3f3865102f8ced",
"src/calibration_completion.hpp": "4e1e45d035100239ab2a9ff00d5c04a46eedbe5f282a7289ac7bf47d723f1678",
"src/calibration_files.hpp": "87c07544a3e123f5c9598dbec5846293afb4949f5506026d845a2805fd82e99c",
"src/calibration_recovery.hpp": "4f0540f464079f1f1a692229bbd8a41ad0685dc17e2b20051799f5eaf62698eb",
"src/common.cpp": "90eecadcb8947470aa1f4410793f893276338732597478a45f370c210e673710",
"src/common.hpp": "3d4c23194bf90e8c02cbf340bac37634d6c813f69c34f21af88ff7837fb83f42",
"src/contracts.cpp": "3899ed43b938df4e81d78bed8c0c6a786690e3bb3338382adab83afe886d5577",
"src/contracts.hpp": "b4a693bded1d360a1d5a4a1c8490160cef56fb8219bd0f04e5aac661a944a68c",
"src/device_battery.hpp": "1734de14014c076d323f9960c949a8c7d04e471e84186d68e4533baaeef459a5",
"src/http_server.cpp": "7cf19fa6cc7c67bd9ecec0e6e95f9c44e5e3ee2486c02719585fd79da1a5d1dd",
"src/http_server.hpp": "929c46403a8d14cdf3172d397b4bd1ecdbcd7f82b85b59d0178f11d3a8892124",
"src/main.cpp": "64cc21743f3d81cf65e1b05d8fbeb85807545523183a5ac7ad4990c9a76f099c",
"src/pipe_rpc.cpp": "ff2def3c862a076f6c85e47ad288d76dbb883faf4ef38fdeaaa0fc1fd1587ebf",
"src/pipe_rpc.hpp": "f040046e00b09e7086f57b1cd73ac238a5d9a09825904898aabe4697b904555f",
"src/preview_capture.hpp": "e32485527dd4994a842d21a7a0fa8656784fa59ea9aeee4ac66d91c446e0bc53",
"src/scene_snapshot_flow.hpp": "765026c23e5c0d45201935223f45cd9aea4597dd0388d852119d839124a0d5f5",
"src/sdk_location.hpp": "eef54bd0ac6784fadfdb9708237ded15dcd0f9cefee1f4e61c239043f77da0e2",
"src/sdk_worker.cpp": "f4fa83c0c91b94357f4ef86c29827f60d3976e012feadb916bfc56b1bf07b8d3",
"src/sdk_worker.hpp": "510a23ce4c7ac0fa96ec2bc5d86b04a51cd3cf7d067831949cd5cf778b6ff1bf",
"src/supervisor.cpp": "bf867b821cc0f9a1d947f4214ebabbd081138b65a0eac08d1118a880bc855888",
"src/supervisor.hpp": "e76c72fcf3c84578188d4f673c9d1d7f0b4bb240b2d47a42cc37b367d21e6107",
"tests/battery_test.cpp": "432b258070be3a5c93a4af306ff0f2c7dd5a237def67e0932331716e3ce58e32",
"tests/calibration_files_test.cpp": "6da870af82edf92f0a6cf654ed856d87b61cede0888b2880225c2900c8d43d64",
"tests/calibration_recovery_test.cpp": "91a254c4f77edc3e5582374f8fd1c3d19786bfcc0ec38d72bad0f1f725509ff8",
"tests/contracts_test.cpp": "3013dc8102721a7b70b262bfa8249ca3a1076bf34339aff1dda2fa06dd8af05f",
"tests/measure-preview.mjs": "19675281b717e8176359a95b5e040f13afbe622fbcd91d7918ad4bdb5c955844",
"tests/native-api.test.mjs": "1d1e9c2d3ddbfd19649379724adfce63e7c8f5ae420e2e362502a3637a2f6eda",
"tests/preview_capture_test.cpp": "90e102d4e121409c860e23ed3b263a7b13664a98db11a9e0efc916f9d6852814",
"tests/worker_test.cpp": "b43d7dc7805ff4560e19ef25b14110e849415a5a542ed9483ac08d768ad4c494",
"third_party/json.hpp": "aaf127c04cb31c406e5b04a63f1ae89369fccde6d8fa7cdda1ed4f32dfc5de63",
"third_party/LICENSE.nlohmann-json": "46a65cffd1ea955132d95a8dd921640714a8d6b537d2e4e482d31145ae95b603",
"third_party/README.md": "1ee0520efa54c3f157d7e3738325aea1bff453a2732000d342ae0b4b3c38a9f7"
},
"extraDependencies": [
{
"path": "tests/support/preview-pipeline.js",
"source": "C:\\Users\\Administrator\\Desktop\\扫描仪\\FreeScanWeb\\public\\preview-pipeline.js",
"sha256": "a857ae9aba6a07ef1089a3e82823d61a1513c5e28b6ba67055d000948125e2ae"
}
],
"excludedPrebuiltArtifacts": {
"reason": "Prebuilt regression outputs initially copied with tests were removed from this source-only module; original C: files were verified unchanged and retained. Regression source is preserved.",
"sourceSha256": {
"tests/bin/battery_test.exe": "cbc8b0b3e365535d2744e3ddfe7b5bab212bc958892a16e897aafc7b8dd2c672",
"tests/bin/calibration_files_test.exe": "8a30095b56adb8fda7d5a3a7809de1d573f5660592687a83585144f4a623e069",
"tests/bin/calibration_recovery_test.exe": "e30984380238cd0b3cc51cd0990c5c32d61484a341e0ca0fa35780be35e0937e",
"tests/bin/common.obj": "c0bbd89372e361747b2dc8807662d21b3daddf09892811c4a0b80f95ee593788",
"tests/bin/contracts-test.exe": "8492e558160f95b359f312d1964ec10427141f21fe4242deeba206eacae1fe3e",
"tests/bin/contracts.obj": "800a3ac0218d571e1678d2dd76e9299280769dd0935259e737c8ddb1aff3757a",
"tests/bin/contracts_test.exe": "065bfe803b77bd69b79de321e321f595075b8c5123a8b3cd289526444bbf3e0b",
"tests/bin/contracts_test.obj": "1f7066228c0177941c972fd213271d0bb2674718f09b73b807cfcbae265a97fa",
"tests/bin/preview_capture_test.exe": "ac5c84d04bbeecac4647245158fa2cb50e18683c4838e6a840605b5614558d21",
"tests/bin/sdk_worker.obj": "bd73e58da2e2efd7c0ad618b99eaff187021ef88407d5f836b10593dff455ace",
"tests/bin/snapshot_contracts_test.exe": "5856d430c2089ae3604f3f3244eb3a95ef8b7f2b5f6f8880f24cf038e469b93a",
"tests/bin/worker_preview_capture_audit.exe": "3a284a39c363b8e4cf12b03859a793d5c3e4dd52b1c8496ee14f48edac82d5c7",
"tests/bin/worker_test.exe": "0ee7d7f0019773d384ac63c92b059f3ca5bfe95d32ba3b482724f9a9676d5c86",
"tests/bin/worker_test.obj": "08d1842986ec56f8e191923331184cdea60e0ac6f451c582502801896dd20132"
}
}
}

View File

@ -0,0 +1,38 @@
param(
[string]$ToolchainRoot='C:\Users\Administrator\Desktop\扫描仪\FreeScanViewer\native\toolchain',
[string]$SdkInclude='C:\Program Files\Shining3d\FreeTrak_TRAK\sdk\include',
[string]$OutputName='FreeScanCpp.exe',
[switch]$CompileOnly,
[string[]]$SourceFiles,
[string]$OutputDirectory,
[string]$BuildDirectory
)
$ErrorActionPreference='Stop'
$taskProject=$PSScriptRoot
$taskWorkspace=Split-Path -Parent $taskProject
if([IO.Path]::GetFileName($OutputName) -ne $OutputName -or -not $OutputName.EndsWith('.exe')){throw 'OutputName must be an exe filename.'}
$taskToolchain=[IO.Path]::GetFullPath($ToolchainRoot)
$taskMsvc=Join-Path $taskToolchain 'msvc\VC\Tools\MSVC\14.44.35207'
$taskHeaders=Join-Path $taskToolchain 'winsdk\microsoft.windows.sdk.cpp\c\Include\10.0.26100.0'
$taskLibraries=Join-Path $taskToolchain 'winsdk\microsoft.windows.sdk.cpp.x64\c'
$taskCompiler=Join-Path $taskMsvc 'bin\Hostx64\x64\cl.exe'
if(-not(Test-Path -LiteralPath $taskCompiler)){throw 'The project-local verified MSVC toolchain is missing. See FreeScanViewer/native/README.md.'}
$taskSignature=Get-AuthenticodeSignature -LiteralPath $taskCompiler
if($taskSignature.Status-ne 'Valid' -or $taskSignature.SignerCertificate.Subject-notmatch 'Microsoft Corporation'){throw 'Microsoft compiler signature verification failed.'}
$taskBuild=if($BuildDirectory){[IO.Path]::GetFullPath($BuildDirectory)}else{Join-Path $taskProject 'build'}
$taskOutputDirectory=if($OutputDirectory){[IO.Path]::GetFullPath($OutputDirectory)}else{Join-Path $taskProject 'build\bin'}
New-Item -ItemType Directory -Path $taskBuild -Force|Out-Null
New-Item -ItemType Directory -Path $taskOutputDirectory -Force|Out-Null
$taskPreviousPath=$env:PATH;$taskPreviousInclude=$env:INCLUDE;$taskPreviousLib=$env:LIB
try{
$env:PATH=(Join-Path $taskMsvc 'bin\Hostx64\x64')+';'+$env:PATH
$env:INCLUDE=(Join-Path $taskMsvc 'include')+';'+(Join-Path $taskHeaders 'ucrt')+';'+(Join-Path $taskHeaders 'shared')+';'+(Join-Path $taskHeaders 'um')+';'+(Join-Path $taskHeaders 'cppwinrt')+';'+(Join-Path $taskHeaders 'winrt')+';'+$SdkInclude
$env:LIB=(Join-Path $taskMsvc 'lib\x64')+';'+(Join-Path $taskLibraries 'um\x64')+';'+(Join-Path $taskLibraries 'ucrt\x64')
[string[]]$taskSources=@(if($SourceFiles){$SourceFiles|ForEach-Object{if([IO.Path]::IsPathRooted($_)){$_}else{Join-Path $taskProject $_}}}else{Get-ChildItem (Join-Path $taskProject 'src') -Filter '*.cpp'|Select-Object -ExpandProperty FullName})
$taskOutput=Join-Path $taskOutputDirectory $OutputName
$taskArgs=@('/nologo','/MD','/O2','/EHsc','/std:c++17','/D_ITERATOR_DEBUG_LEVEL=0','/D_WIN32_WINNT=0x0602','/utf-8','/W4',('/Fo'+$taskBuild+'\'))
if($CompileOnly){$taskArgs+='/c'}else{$taskArgs+=('/Fe'+$taskOutput)}
& $taskCompiler @taskArgs @taskSources /link /INCREMENTAL:NO httpapi.lib advapi32.lib ole32.lib shell32.lib user32.lib gdiplus.lib shlwapi.lib crypt32.lib bcrypt.lib ws2_32.lib version.lib
if($LASTEXITCODE-ne 0){throw 'Native C++ build failed.'}
if(-not $CompileOnly){Write-Output ('Built native C++ executable: '+$taskOutput)}
}finally{$env:PATH=$taskPreviousPath;$env:INCLUDE=$taskPreviousInclude;$env:LIB=$taskPreviousLib}

View File

@ -0,0 +1,95 @@
param(
[string]$ToolchainRoot = 'C:\Users\Administrator\Desktop\扫描仪\FreeScanViewer\native\toolchain',
[string]$SdkInclude = 'C:\Program Files\Shining3d\FreeTrak_TRAK\sdk\include',
[switch]$IncludeHttp,
[string]$NodePath
)
# The default run is offline. worker_test explicitly selects simulation and
# asserts that neither SDKCWrapper.dll nor FreeScanNativeBridge.dll is loaded.
# -IncludeHttp also runs the isolated 127.0.0.1:18889 mock HTTP suite. It needs
# the already-built production executable but never starts the real SDK.
$ErrorActionPreference = 'Stop'
$taskProject = $PSScriptRoot
$taskWorkspace = Split-Path -Parent $taskProject
$taskTestBin = Join-Path $taskProject 'tests\bin'
$taskBuildScript = Join-Path $taskProject 'build.ps1'
$taskTests = @(
@{
Name = 'contracts_test'
Sources = @('src/contracts.cpp', 'tests/contracts_test.cpp')
},
@{
Name = 'worker_test'
Sources = @('src/common.cpp', 'src/contracts.cpp', 'src/sdk_worker.cpp', 'src/calibration_window_capture.cpp', 'tests/worker_test.cpp')
},
@{
Name = 'preview_capture_test'
Sources = @('src/common.cpp', 'tests/preview_capture_test.cpp')
},
@{
Name = 'battery_test'
Sources = @('src/common.cpp', 'tests/battery_test.cpp')
},
@{
Name = 'calibration_files_test'
Sources = @('src/common.cpp', 'tests/calibration_files_test.cpp')
},
@{
Name = 'calibration_recovery_test'
Sources = @('src/common.cpp', 'tests/calibration_recovery_test.cpp')
}
)
# Give each test its own object directory, so these builds cannot replace the
# backend's objects while a separate production build is in progress.
foreach ($taskTest in $taskTests) {
& $taskBuildScript -ToolchainRoot $ToolchainRoot -SdkInclude $SdkInclude -OutputName ($taskTest.Name + '.exe') `
-SourceFiles $taskTest.Sources -OutputDirectory $taskTestBin `
-BuildDirectory (Join-Path $taskProject ('build\tests\' + $taskTest.Name))
}
$taskPreviousPath = $env:PATH
$taskPreviousTestExecutable = $env:FREESCAN_TEST_EXECUTABLE
$taskCrt = Join-Path $ToolchainRoot 'msvc\VC\Redist\MSVC\14.44.35112\x64\Microsoft.VC143.CRT'
if (-not (Test-Path -LiteralPath (Join-Path $taskCrt 'msvcp140.dll'))) {
# Release packages carry the same native runtime DLLs beside the backend.
$taskCrt = Join-Path $taskWorkspace 'FreeScanViewer'
}
try {
$env:PATH = $taskCrt + ';' + $env:PATH
foreach ($taskTest in $taskTests) {
& (Join-Path $taskTestBin ($taskTest.Name + '.exe'))
if ($LASTEXITCODE -ne 0) {
throw ('Offline test failed: ' + $taskTest.Name + ' (exit ' + $LASTEXITCODE + ')')
}
}
if ($IncludeHttp) {
$taskBackend = Join-Path $taskProject 'build\bin\FreeScanCpp.exe'
if (-not (Test-Path -LiteralPath $taskBackend)) {
throw 'Build FreeScanCpp.exe with build.ps1 before running -IncludeHttp.'
}
if (-not $NodePath) {
$taskNodeCommand = Get-Command node.exe -ErrorAction SilentlyContinue
if ($taskNodeCommand) {
$NodePath = $taskNodeCommand.Source
} else {
$NodePath = Join-Path $env:LOCALAPPDATA '..\..\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe'
$NodePath = [IO.Path]::GetFullPath($NodePath)
}
}
if (-not (Test-Path -LiteralPath $NodePath)) {
throw 'Node.js was not found. Supply -NodePath with the full path to node.exe.'
}
$env:FREESCAN_TEST_EXECUTABLE = $taskBackend
& $NodePath --test (Join-Path $taskProject 'tests\native-api.test.mjs')
if ($LASTEXITCODE -ne 0) {
throw ('Mock HTTP suite failed (exit ' + $LASTEXITCODE + ')')
}
}
Write-Output ('Native verification passed. HTTP mock included: ' + [bool]$IncludeHttp)
} finally {
$env:PATH = $taskPreviousPath
$env:FREESCAN_TEST_EXECUTABLE = $taskPreviousTestExecutable
}

View File

@ -0,0 +1,113 @@
#pragma once
#include "common.hpp"
namespace freescan::detail {
enum class AutoConnectionAction { none, connect, recycle };
// Owns retry scheduling and operator intent, not SDK resources. All decisions
// run under the supervisor's command gate; this mutex only protects reporting.
class AutoConnectionPolicy {
mutable std::mutex gate;
bool enabled, paused = false, blocked = false, protectedSession = false;
int interval;
uint64_t attempts = 0, restartCount = 0;
int64_t nextAttempt = 0, lastRestart = 0;
bool lastRestartForced = false;
std::string phase, message;
Json lastError = nullptr;
public:
AutoConnectionPolicy(bool active, int seconds)
: enabled(active), interval(seconds), phase(active ? "waiting" : "disabled"),
message(active ? "等待自动连接SDK。" : "自动连接已关闭。") {}
void pause() {
std::lock_guard<std::mutex> hold(gate);
paused = true;
nextAttempt = 0;
phase = enabled ? "paused" : "disabled";
message = "已手动断开或请求停止,自动连接暂停;手动连接可恢复。";
}
void resume() {
std::lock_guard<std::mutex> hold(gate);
paused = blocked = false;
nextAttempt = 0;
phase = enabled ? "waiting" : "disabled";
message = "已请求手动连接。";
}
void protect(bool active = true) {
std::lock_guard<std::mutex> hold(gate);
protectedSession = active;
}
bool may_restart() const {
std::lock_guard<std::mutex> hold(gate);
return enabled && !paused && !blocked && !protectedSession;
}
void restarted(bool forced, int64_t now) {
std::lock_guard<std::mutex> hold(gate);
++restartCount;
lastRestart = now;
lastRestartForced = forced;
}
AutoConnectionAction decide(const Json &status, int64_t now) {
std::lock_guard<std::mutex> hold(gate);
if (!enabled || paused || blocked)
return AutoConnectionAction::none;
if (protectedSession || status.value("projectReady", false) ||
status.value("scanning", false) || status.value("calibrationActive", false)) {
phase = "session_active";
message = "当前有工程或标定会话,保留数据,不自动重连或扫描。";
nextAttempt = 0;
return AutoConnectionAction::none;
}
if (status.value("busy", false))
return AutoConnectionAction::none;
const bool reset = status.value("restartRequired", false) || status.value("stateUncertain", false);
const bool offline = status.contains("deviceOnline") && status["deviceOnline"] == false;
if (status.value("initialized", false) && !reset && !offline) {
phase = "connected";
message = "SDK已连接。";
lastError = nullptr;
nextAttempt = 0;
return AutoConnectionAction::none;
}
if (now < nextAttempt)
return AutoConnectionAction::none;
++attempts;
phase = reset || status.value("initialized", false) ? "recovering" : "connecting";
message = phase == "recovering" ? "正在重启异常SDK后台,HTTP服务保持运行。" : "正在自动连接SDK。";
nextAttempt = 0;
return reset || status.value("initialized", false) ? AutoConnectionAction::recycle
: AutoConnectionAction::connect;
}
void failed(const ApiError &error, int64_t now, bool cleanupUnconfirmed = false) {
std::lock_guard<std::mutex> hold(gate);
if (paused)
return;
blocked = cleanupUnconfirmed;
phase = blocked ? "blocked" : "retry_wait";
message = blocked ? "SDK后台身份或退出无法核验,已停止自动重启,请检查日志。"
: "SDK连接未成功,将按间隔重试;需要时自动重启SDK后台。";
lastError = {{"code", error.code}, {"message", error.what()}, {"httpStatus", error.status}};
nextAttempt = blocked ? 0 : now + int64_t(interval) * 1000;
}
void connected() {
std::lock_guard<std::mutex> hold(gate);
if (paused)
return;
phase = "connected";
message = "SDK已连接。";
lastError = nullptr;
nextAttempt = 0;
}
Json snapshot() const {
std::lock_guard<std::mutex> hold(gate);
return {{"enabled", enabled}, {"paused", paused}, {"state", phase},
{"attempts", attempts}, {"retryIntervalSeconds", interval},
{"restartCount", restartCount},
{"lastRestartUtc", lastRestart ? Json(utc_from_ms(lastRestart)) : Json(nullptr)},
{"lastRestartForced", lastRestart ? Json(lastRestartForced) : Json(nullptr)},
{"nextRetryUtc", nextAttempt ? Json(utc_from_ms(nextAttempt)) : Json(nullptr)},
{"lastError", lastError}, {"message", message}};
}
};
} // namespace freescan::detail

View File

@ -0,0 +1,100 @@
#pragma once
#include "common.hpp"
#include <cctype>
namespace freescan::detail {
struct SdkCompletion {
bool done = false;
std::string error;
};
inline std::string normalized_result(const Json &value) {
if (!value.is_string())
return {};
auto result = value.get<std::string>();
std::transform(result.begin(), result.end(), result.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return result;
}
inline bool nonzero_sdk_code(const Json &value) {
if (value.is_number_integer())
return value != 0;
if (!value.is_string())
return false;
const auto text = value.get<std::string>();
try {
size_t consumed = 0;
const int base = text.size() > 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X') ? 16 : 10;
const auto number = std::stoll(text, &consumed, base);
return consumed == text.size() && number != 0;
} catch (...) { return false; }
}
inline bool zero_sdk_code(const Json &value) {
if (value.is_number_integer())
return value == 0;
if (!value.is_string())
return false;
const auto text = value.get<std::string>();
try {
size_t consumed = 0;
const int base = text.size() > 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X') ? 16 : 10;
const auto number = std::stoll(text, &consumed, base);
return consumed == text.size() && number == 0;
} catch (...) { return false; }
}
inline bool calibration_compute_succeeded(const Json &message) {
const auto result = message.find("calibResult");
if (result == message.end() || (*result != true && normalized_result(*result) != "true"))
return false;
for (const auto *key : {"errorCode", "errCode"}) {
const auto code = message.find(key);
if (code != message.end() && !zero_sdk_code(*code))
return false;
}
return true;
}
inline std::string calibration_compute_error(const Json &message, const std::string &ordinaryError) {
bool failed = !ordinaryError.empty();
for (const auto *key : {"calibResult", "result"}) {
const auto found = message.find(key);
if (found == message.end())
continue;
const auto text = normalized_result(*found);
failed = failed || *found == false || text == "false" || text == "failed" ||
(std::string(key) == "result" && found->is_number_integer() && *found != 0);
}
for (const auto *key : {"errorCode", "errCode"}) {
const auto found = message.find(key);
if (found != message.end())
failed = failed || nonzero_sdk_code(*found);
}
if (!failed)
return {};
std::string error = "SDK标定计算失败";
for (const auto *key : {"cmd", "calibTarget", "calibResult", "errorCode", "errCode", "result", "camErr"}) {
const auto found = message.find(key);
if (found != message.end())
error += std::string("; ") + key + "=" + found->dump().substr(0, 96);
}
if (!ordinaryError.empty())
error += "; " + ordinaryError.substr(0, 192);
return error;
}
inline SdkCompletion sdk_completion(const std::set<std::string> &expected, const Json &message,
const std::string &ordinaryError) {
if (!message.is_object() || !message.contains("cmd") || !message["cmd"].is_string())
return {};
const auto command = message["cmd"].get<std::string>();
const bool computing = expected.count("freeCalibrationComputeFinish") != 0;
if (computing && (command == "calibCalculateResult" || command == "freeCalibrationComputeFinish")) {
auto error = calibration_compute_error(message, ordinaryError);
if (!error.empty())
return {true, std::move(error)};
// The installed SDK also finishes computation through this result
// callback. Both vendor calibration demos use calibResult as the
// outcome; the actual successful device run sends no separate ACK.
if (command == "calibCalculateResult")
return {calibration_compute_succeeded(message), {}};
}
return expected.count(command) ? SdkCompletion{true, ordinaryError} : SdkCompletion{};
}
} // namespace freescan::detail

View File

@ -0,0 +1,66 @@
#pragma once
#include "common.hpp"
#include <cwctype>
namespace freescan::detail {
inline const char *calibration_file_type(std::wstring name) {
for (auto &letter : name)
letter = static_cast<wchar_t>(std::towlower(letter));
for (const auto &kind : {std::pair{L"trackcalibdata.bin", "tracker"},
std::pair{L"scannercalibdata.bin", "scanner"},
std::pair{L"handeyecalibdata.bin", "handEye"}}) {
const std::wstring suffix(kind.first);
if (name.size() <= suffix.size() || name.compare(name.size() - suffix.size(), suffix.size(), suffix))
continue;
const auto prefixLength = name.size() - suffix.size();
if (std::all_of(name.begin(), name.begin() + prefixLength, [](wchar_t letter) {
return (letter >= L'0' && letter <= L'9') || (letter >= L'a' && letter <= L'f');
}))
return kind.second;
}
return nullptr;
}
// The API intentionally reports local file modification times, not a hardware
// readback, a successful-calculation receipt or a device serial-number match.
inline Json snapshot_calibration_files(const fs::path &directory) {
Json result{{"lastCalibrationUtc", nullptr},
{"lastCalibrationSource", "local_calibration_file_modified_time"},
{"calibrationFileTimes", Json::array()}};
if (directory.empty())
return result;
std::error_code error;
fs::directory_iterator entry(directory, error), end;
std::map<std::string, Json> files;
uint64_t latest = 0;
for (; !error && entry != end; entry.increment(error)) {
const auto path = entry->path();
const auto *type = calibration_file_type(path.filename().wstring());
if (!type)
continue;
WIN32_FILE_ATTRIBUTE_DATA attributes{};
if (!GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &attributes) ||
(attributes.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) ||
(!attributes.nFileSizeHigh && !attributes.nFileSizeLow))
continue;
ULARGE_INTEGER ticks{};
ticks.LowPart = attributes.ftLastWriteTime.dwLowDateTime;
ticks.HighPart = attributes.ftLastWriteTime.dwHighDateTime;
constexpr uint64_t epoch = 116444736000000000ull;
SYSTEMTIME time{};
if (ticks.QuadPart < epoch || !FileTimeToSystemTime(&attributes.ftLastWriteTime, &time) ||
time.wYear > 9999)
continue;
const auto modified = utc_from_ms(static_cast<int64_t>((ticks.QuadPart - epoch) / 10000ull));
const auto name = path_string(path.filename());
files.emplace(name, Json{{"type", type}, {"fileName", name}, {"modifiedUtc", modified}});
if (ticks.QuadPart > latest) {
latest = ticks.QuadPart;
result["lastCalibrationUtc"] = modified;
}
}
for (auto &file : files)
result["calibrationFileTimes"].push_back(std::move(file.second));
return result;
}
} // namespace freescan::detail

View File

@ -0,0 +1,18 @@
#pragma once
#include "common.hpp"
namespace freescan::detail {
// Only a positively identified calibration session is eligible. Unknown state
// never authorizes killing a worker or ending a scan project.
inline void validate_calibration_recovery(const Json &info, const std::string &expected, bool force) {
if (!info.is_object() || !info.contains("sessionId") || !info["sessionId"].is_string() ||
info["sessionId"].get<std::string>() != expected)
throw ApiError(409, "session_changed", "标定会话已变化,请刷新状态后重新确认。");
if (info.value("projectReady", true) || info.value("scanning", true))
throw ApiError(409, "project_protected", "当前有扫描工程或正在采集,不能使用标定恢复接口。");
if (!info.value("calibrationSession", false))
throw ApiError(409, "calibration_not_active", "当前没有可恢复的标定会话。");
if (info.value("busy", true) && !force)
throw ApiError(409, "recovery_requires_force", "标定任务仍在执行;若确认中止,请明确使用 force:true。");
}
} // namespace freescan::detail

View File

@ -0,0 +1,39 @@
#pragma once
#include "common.hpp"
#include <cmath>
namespace freescan::detail {
// Only documented SDK callback fields are retained. Commands and workflow
// completion counts never manufacture calibration progress or temperatures.
struct CalibrationTelemetryCache {
Json progress=nullptr, scanner=nullptr, tracker=nullptr;
void clear(){progress=scanner=tracker=nullptr;}
void observe(const Json &message,int64_t received) {
if(!message.is_object()||!message.contains("cmd")||!message["cmd"].is_string())return;
const auto cmd=message["cmd"].get<std::string>();
auto temperature=[&](const char *field,Json &target){
auto value=message.find(field);
if(value!=message.end()&&value->is_number()&&std::isfinite(value->get<double>()))
target={{"value",*value},{"receivedAt",utc_from_ms(received)}};
};
if(cmd=="updateScannerTemperature")temperature("scannerTemperature",scanner);
if(cmd=="updateTrakTemperature")temperature("trakTemperature",tracker);
if(cmd!="handeyeCalibStep"&&cmd!="calibCalculateResult"&&cmd!="sdk_calibFinished"&&cmd!="showProgress"&&cmd!="hideProgress"
&&!message.contains("currentStep")&&!message.contains("totalStep")&&!message.contains("totalSteps"))return;
Json value{{"cmd",cmd},{"receivedAt",utc_from_ms(received)}};
for(const auto *key:{"currentStep","totalStep","totalSteps","totalStepIndex","title","value","visible","calibResult","camErr","calibTarget"}) {
auto field=message.find(key);
if(field!=message.end()&&(field->is_primitive()&&field->dump().size()<=1024))value[key]=*field;
}
if(message.contains("data")&&message["data"].is_object()){
Json data=Json::object();
for(const auto *key:{"title","value","visible","currentStep","totalStep","totalSteps","totalStepIndex"}){
auto field=message["data"].find(key);
if(field!=message["data"].end()&&field->is_primitive()&&field->dump().size()<=1024)data[key]=*field;
}
if(!data.empty())value["data"]=std::move(data);
}
progress=std::move(value);
}
Json snapshot()const{return {{"progress",progress},{"temperatures",{{"scanner",scanner},{"tracker",tracker}}}};}
};
}

View File

@ -0,0 +1,567 @@
#include "calibration_window_capture.hpp"
#include <d3d11.h>
#include <dwmapi.h>
#include <wincodec.h>
#include <windows.graphics.capture.interop.h>
#include <windows.graphics.directx.direct3d11.interop.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Graphics.Capture.h>
#include <winrt/Windows.Graphics.DirectX.Direct3D11.h>
#include <cstring>
#include <limits>
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "windowsapp.lib")
#pragma comment(lib, "windowscodecs.lib")
#pragma comment(lib, "dwmapi.lib")
namespace freescan {
namespace {
using namespace winrt;
using namespace winrt::Windows::Graphics;
using namespace winrt::Windows::Graphics::Capture;
using namespace winrt::Windows::Graphics::DirectX;
using namespace winrt::Windows::Graphics::DirectX::Direct3D11;
constexpr uint64_t freshMs = 2000, captureDeadlineMs = 1500;
constexpr int maxDimension = 8192, maxOutputWidth = 1920;
void retain_capture_runtime() {
// WGC schedules asynchronous COM cleanup beyond Close(). Keep one MTA alive
// across calibration sessions so that pending callbacks and cached factory
// references cannot outlive an unloaded Windows capture component. There is
// one cookie for the process, not one leaked apartment per capture session.
struct RuntimeLifetime {
CO_MTA_USAGE_COOKIE cookie{};
RuntimeLifetime() { check_hresult(CoIncrementMTAUsage(&cookie)); }
~RuntimeLifetime() {
clear_factory_cache();
CoDecrementMTAUsage(cookie);
}
};
static RuntimeLifetime lifetime;
}
uint64_t filetime_number(const FILETIME &value) {
return (uint64_t(value.dwHighDateTime) << 32) | value.dwLowDateTime;
}
int64_t qpc_100ns() {
LARGE_INTEGER counter{}, frequency{};
if (!QueryPerformanceCounter(&counter) || !QueryPerformanceFrequency(&frequency) || !frequency.QuadPart)
throw std::runtime_error("Monotonic capture clock is unavailable.");
return (counter.QuadPart / frequency.QuadPart) * 10000000 +
((counter.QuadPart % frequency.QuadPart) * 10000000) / frequency.QuadPart;
}
bool equal_path(const std::wstring &a, const std::wstring &b) {
return CompareStringOrdinal(a.c_str(), int(a.size()), b.c_str(), int(b.size()), TRUE) == CSTR_EQUAL;
}
std::wstring image_path(HANDLE process) {
std::wstring result(32768, L'\0');
DWORD size = DWORD(result.size());
if (!QueryFullProcessImageNameW(process, 0, result.data(), &size))
throw std::runtime_error("Cannot read the trusted manufacturer process image.");
result.resize(size);
return result;
}
std::wstring canonical_image(const std::wstring &path) {
// Resolving the file handle also resolves junctions and path aliases. This
// occurs only at session binding, never in the frame delivery path.
if (!fs::path(path).is_absolute())
throw std::runtime_error("The trusted manufacturer image must have an absolute path.");
Handle file(CreateFileW(path.c_str(), FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, 0, nullptr));
if (!file)
throw std::runtime_error("Cannot resolve the trusted manufacturer executable.");
std::wstring result(32768, L'\0');
DWORD size = GetFinalPathNameByHandleW(file.get(), result.data(), DWORD(result.size()), FILE_NAME_NORMALIZED);
if (!size || size >= result.size())
throw std::runtime_error("Cannot normalize the trusted manufacturer executable.");
result.resize(size);
if (result.compare(0, 4, L"\\\\?\\") == 0)
result.erase(0, 4);
return result;
}
bool ordinary_window(HWND window) {
RECT rect{};
DWORD cloaked = 0;
return IsWindow(window) && IsWindowVisible(window) && !IsIconic(window) &&
GetAncestor(window, GA_ROOT) == window && !GetWindow(window, GW_OWNER) &&
!(GetWindowLongPtrW(window, GWL_EXSTYLE) & WS_EX_TOOLWINDOW) &&
GetWindowRect(window, &rect) && rect.right > rect.left && rect.bottom > rect.top &&
(FAILED(DwmGetWindowAttribute(window, DWMWA_CLOAKED, &cloaked, sizeof(cloaked))) || !cloaked);
}
struct WindowSearch {
DWORD pid;
std::vector<HWND> windows;
};
BOOL CALLBACK find_window(HWND window, LPARAM context) {
auto &search = *reinterpret_cast<WindowSearch *>(context);
DWORD pid = 0;
GetWindowThreadProcessId(window, &pid);
if (pid == search.pid && ordinary_window(window)) {
// At most two are needed to prove ambiguity; do not inspect titles,
// window contents, or unrelated processes.
search.windows.push_back(window);
if (search.windows.size() == 2)
return FALSE;
}
return TRUE;
}
struct CaptureState {
mutable std::mutex mutex;
std::condition_variable wake;
Handle owner;
DWORD pid = 0;
uint64_t created = 0;
std::wstring rawImage;
Json source = nullptr;
std::string sessionId, state = "starting", message;
std::optional<FrameSnapshot> frame;
uint64_t publishedTick = 0;
HWND window = nullptr;
DWORD windowThread = 0;
ULONG_PTR windowClass = 0;
std::atomic<bool> cancel{false}, closed{false};
bool finished = false;
int64_t startedQpc = 0;
};
bool owner_valid(const CaptureState &state) {
if (!state.owner || GetProcessId(state.owner.get()) != state.pid ||
WaitForSingleObject(state.owner.get(), 0) != WAIT_TIMEOUT)
return false;
FILETIME created{}, ended{}, kernel{}, user{};
if (!GetProcessTimes(state.owner.get(), &created, &ended, &kernel, &user) ||
filetime_number(created) != state.created)
return false;
try {
return equal_path(image_path(state.owner.get()), state.rawImage);
} catch (...) {
return false;
}
}
bool window_valid(const CaptureState &state, HWND window, DWORD thread, ULONG_PTR atom) {
DWORD pid = 0;
return !state.closed.load() && ordinary_window(window) &&
GetWindowThreadProcessId(window, &pid) == thread && pid == state.pid &&
GetClassLongPtrW(window, GCW_ATOM) == atom;
}
void unavailable(const std::shared_ptr<CaptureState> &state, const char *code, const std::string &message) {
std::lock_guard<std::mutex> lock(state->mutex);
state->frame.reset();
state->publishedTick = 0;
if (!state->cancel.load()) {
state->state = code;
state->message = message;
}
}
std::vector<uint8_t> encode_jpeg(IWICImagingFactory *factory, std::vector<uint8_t> &pixels,
int width, int height, int &outputWidth, int &outputHeight) {
com_ptr<IWICBitmap> bitmap;
check_hresult(factory->CreateBitmapFromMemory(width, height, GUID_WICPixelFormat32bppBGRA,
UINT(width * 4), UINT(pixels.size()), pixels.data(), bitmap.put()));
com_ptr<IWICBitmapSource> source = bitmap.as<IWICBitmapSource>();
outputWidth = std::min(width, maxOutputWidth);
outputHeight = std::max(1, int(int64_t(height) * outputWidth / width));
if (outputWidth != width) {
com_ptr<IWICBitmapScaler> scaler;
check_hresult(factory->CreateBitmapScaler(scaler.put()));
check_hresult(scaler->Initialize(source.get(), outputWidth, outputHeight, WICBitmapInterpolationModeFant));
source = scaler.as<IWICBitmapSource>();
}
com_ptr<IWICFormatConverter> converter;
check_hresult(factory->CreateFormatConverter(converter.put()));
check_hresult(converter->Initialize(source.get(), GUID_WICPixelFormat24bppBGR, WICBitmapDitherTypeNone,
nullptr, 0, WICBitmapPaletteTypeCustom));
com_ptr<IStream> stream;
check_hresult(CreateStreamOnHGlobal(nullptr, TRUE, stream.put()));
com_ptr<IWICBitmapEncoder> encoder;
check_hresult(factory->CreateEncoder(GUID_ContainerFormatJpeg, nullptr, encoder.put()));
check_hresult(encoder->Initialize(stream.get(), WICBitmapEncoderNoCache));
com_ptr<IWICBitmapFrameEncode> frame;
com_ptr<IPropertyBag2> properties;
check_hresult(encoder->CreateNewFrame(frame.put(), properties.put()));
PROPBAG2 quality{};
quality.pstrName = const_cast<wchar_t *>(L"ImageQuality");
VARIANT value{};
value.vt = VT_R4;
value.fltVal = 0.90f;
check_hresult(properties->Write(1, &quality, &value));
check_hresult(frame->Initialize(properties.get()));
check_hresult(frame->SetSize(outputWidth, outputHeight));
WICPixelFormatGUID format = GUID_WICPixelFormat24bppBGR;
check_hresult(frame->SetPixelFormat(&format));
if (format != GUID_WICPixelFormat24bppBGR)
throw std::runtime_error("The JPEG encoder did not accept the window pixel format.");
check_hresult(frame->WriteSource(converter.get(), nullptr));
check_hresult(frame->Commit());
check_hresult(encoder->Commit());
STATSTG statistics{};
check_hresult(stream->Stat(&statistics, STATFLAG_NONAME));
if (!statistics.cbSize.QuadPart || statistics.cbSize.QuadPart > 32 * 1024 * 1024)
throw std::runtime_error("The encoded window frame has an invalid size.");
LARGE_INTEGER zero{};
check_hresult(stream->Seek(zero, STREAM_SEEK_SET, nullptr));
std::vector<uint8_t> result(size_t(statistics.cbSize.QuadPart));
ULONG read = 0;
check_hresult(stream->Read(result.data(), ULONG(result.size()), &read));
if (read != result.size())
throw std::runtime_error("The encoded window frame is incomplete.");
return result;
}
bool nonblank(const std::vector<uint8_t> &pixels) {
// Reject clear/blank/protected surfaces. A usable manufacturer GUI contains
// actual variation; a uniform texture is never reported as a successful UI.
uint8_t first[3] = {pixels[0], pixels[1], pixels[2]};
for (size_t i = 0; i < pixels.size(); i += 4)
if (pixels[i] != first[0] || pixels[i + 1] != first[1] || pixels[i + 2] != first[2])
return true;
return false;
}
void capture(const std::shared_ptr<CaptureState> &state) {
retain_capture_runtime();
init_apartment(apartment_type::multi_threaded);
struct Apartment { ~Apartment() { uninit_apartment(); } } apartment;
if (!GraphicsCaptureSession::IsSupported()) {
unavailable(state, "capture_unsupported", "Windows Graphics Capture is unavailable on this host.");
return;
}
const uint64_t windowDeadline = GetTickCount64() + captureDeadlineMs;
HWND window = nullptr;
while (!state->cancel.load() && GetTickCount64() < windowDeadline) {
if (!owner_valid(*state)) {
unavailable(state, "source_changed", "The trusted manufacturer process has exited or changed.");
return;
}
WindowSearch search{state->pid, {}};
EnumWindows(find_window, reinterpret_cast<LPARAM>(&search));
if (search.windows.size() > 1) {
unavailable(state, "window_ambiguous", "More than one manufacturer window is visible; no source was selected.");
return;
}
if (search.windows.size() == 1) {
window = search.windows[0];
break;
}
std::unique_lock<std::mutex> lock(state->mutex);
state->wake.wait_for(lock, std::chrono::milliseconds(25), [&] { return state->cancel.load(); });
}
if (!window || state->cancel.load()) {
unavailable(state, "window_not_found", "The trusted manufacturer has no visible capture window.");
return;
}
const DWORD thread = GetWindowThreadProcessId(window, nullptr);
const ULONG_PTR atom = GetClassLongPtrW(window, GCW_ATOM);
{
std::lock_guard<std::mutex> lock(state->mutex);
state->window = window;
state->windowThread = thread;
state->windowClass = atom;
state->source["windowHandle"] = std::to_string(reinterpret_cast<uintptr_t>(window));
}
if (!owner_valid(*state) || !window_valid(*state, window, thread, atom))
throw std::runtime_error("The manufacturer window changed during capture binding.");
com_ptr<ID3D11Device> device;
com_ptr<ID3D11DeviceContext> context;
D3D_FEATURE_LEVEL level{};
check_hresult(D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, D3D11_CREATE_DEVICE_BGRA_SUPPORT,
nullptr, 0, D3D11_SDK_VERSION, device.put(), &level, context.put()));
auto dxgi = device.as<IDXGIDevice>();
com_ptr<IInspectable> inspectable;
check_hresult(CreateDirect3D11DeviceFromDXGIDevice(dxgi.get(), inspectable.put()));
const auto runtimeDevice = inspectable.as<IDirect3DDevice>();
auto interop = get_activation_factory<GraphicsCaptureItem, IGraphicsCaptureItemInterop>();
GraphicsCaptureItem item{nullptr};
check_hresult(interop->CreateForWindow(window, guid_of<GraphicsCaptureItem>(), put_abi(item)));
auto closed = item.Closed(auto_revoke, [weak = std::weak_ptr<CaptureState>(state)](auto &&, auto &&) {
if (auto retained = weak.lock()) {
retained->closed.store(true);
unavailable(retained, "window_closed", "The captured manufacturer window has closed.");
retained->wake.notify_all();
}
});
SizeInt32 size = item.Size();
if (size.Width <= 0 || size.Height <= 0 || size.Width > maxDimension || size.Height > maxDimension ||
int64_t(size.Width) * size.Height * 4 > 128 * 1024 * 1024)
throw std::runtime_error("The manufacturer window dimensions are unsupported.");
auto pool = Direct3D11CaptureFramePool::CreateFreeThreaded(runtimeDevice, DirectXPixelFormat::B8G8R8A8UIntNormalized, 2, size);
auto session = pool.CreateCaptureSession(item);
// Keep the OS capture indicator and normal capture protection enabled.
// There is no desktop capture fallback and no cursor/keyboard injection.
auto factory = create_instance<IWICImagingFactory>(CLSID_WICImagingFactory);
const int64_t poolStartedQpc = qpc_100ns();
int64_t epochQpc = std::max(poolStartedQpc, state->startedQpc), previousQpc = 0;
uint64_t sequence = 0, progressTick = GetTickCount64(), nextEncode = 0;
session.StartCapture();
while (!state->cancel.load()) {
if (!owner_valid(*state)) {
unavailable(state, "source_changed", "The trusted manufacturer process has exited or changed.");
break;
}
if (state->closed.load() || !IsWindow(window)) {
unavailable(state, "window_closed", "The captured manufacturer window has closed.");
break;
}
if (!window_valid(*state, window, thread, atom)) {
// The HWND is pinned for this session. Restoration may resume this
// same window, but a replacement HWND is never selected implicitly.
unavailable(state, "window_unavailable", "The captured manufacturer window is minimized, hidden, or changed.");
epochQpc = qpc_100ns();
} else {
auto frame = pool.TryGetNextFrame();
for (int i = 0; frame && i < 2; ++i) {
auto newer = pool.TryGetNextFrame();
if (!newer)
break;
frame.Close();
frame = std::move(newer);
}
if (frame) {
const int64_t stamp = frame.SystemRelativeTime().count(), nowQpc = qpc_100ns();
const auto content = frame.ContentSize();
if (content.Width <= 0 || content.Height <= 0 || content.Width > maxDimension ||
content.Height > maxDimension || int64_t(content.Width) * content.Height * 4 > 128 * 1024 * 1024) {
frame.Close();
unavailable(state, "frame_invalid", "The manufacturer window returned invalid dimensions.");
} else if (content.Width != size.Width || content.Height != size.Height) {
frame.Close();
size = content;
unavailable(state, "window_resizing", "Waiting for a new frame at the current window size.");
epochQpc = qpc_100ns();
pool.Recreate(runtimeDevice, DirectXPixelFormat::B8G8R8A8UIntNormalized, 2, size);
progressTick = GetTickCount64();
} else if (stamp <= epochQpc || stamp <= previousQpc || stamp > nowQpc ||
nowQpc - stamp > int64_t(freshMs * 10000)) {
frame.Close();
} else if (GetTickCount64() >= nextEncode) {
previousQpc = stamp;
const uint64_t operationStart = GetTickCount64();
auto access = frame.Surface().as<::Windows::Graphics::DirectX::Direct3D11::IDirect3DDxgiInterfaceAccess>();
com_ptr<ID3D11Texture2D> texture;
check_hresult(access->GetInterface(__uuidof(ID3D11Texture2D), texture.put_void()));
D3D11_TEXTURE2D_DESC desc{};
texture->GetDesc(&desc);
if (desc.Width < UINT(size.Width) || desc.Height < UINT(size.Height) ||
desc.Format != DXGI_FORMAT_B8G8R8A8_UNORM)
throw std::runtime_error("The captured GPU surface does not match the current window.");
desc.Width = size.Width;
desc.Height = size.Height;
desc.MipLevels = desc.ArraySize = 1;
desc.SampleDesc = {1, 0};
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = desc.MiscFlags = 0;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
com_ptr<ID3D11Texture2D> staging;
check_hresult(device->CreateTexture2D(&desc, nullptr, staging.put()));
D3D11_BOX box{0, 0, 0, UINT(size.Width), UINT(size.Height), 1};
context->CopySubresourceRegion(staging.get(), 0, 0, 0, 0, texture.get(), 0, &box);
context->Flush();
D3D11_MAPPED_SUBRESOURCE mapped{};
HRESULT result = DXGI_ERROR_WAS_STILL_DRAWING;
while (!state->cancel.load() && GetTickCount64() - operationStart < captureDeadlineMs) {
result = context->Map(staging.get(), 0, D3D11_MAP_READ, D3D11_MAP_FLAG_DO_NOT_WAIT, &mapped);
if (result != DXGI_ERROR_WAS_STILL_DRAWING)
break;
std::unique_lock<std::mutex> lock(state->mutex);
state->wake.wait_for(lock, std::chrono::milliseconds(5), [&] { return state->cancel.load(); });
}
if (result == DXGI_ERROR_WAS_STILL_DRAWING) {
frame.Close();
unavailable(state, "capture_timeout", "The window GPU readback exceeded its deadline.");
continue;
}
check_hresult(result);
std::vector<uint8_t> pixels(size_t(size.Width) * size.Height * 4);
for (int y = 0; y < size.Height; ++y)
std::memcpy(pixels.data() + size_t(y) * size.Width * 4,
static_cast<const uint8_t *>(mapped.pData) + size_t(y) * mapped.RowPitch,
size_t(size.Width) * 4);
context->Unmap(staging.get(), 0);
frame.Close();
if (!nonblank(pixels)) {
unavailable(state, "frame_blank", "The manufacturer window returned an empty or protected surface.");
continue;
}
FrameSnapshot output;
output.sourceWidth = size.Width;
output.sourceHeight = size.Height;
output.capturedMs = unix_ms() - std::max<int64_t>(0, (qpc_100ns() - stamp) / 10000);
const auto encodeStart = std::chrono::steady_clock::now();
output.jpeg = encode_jpeg(factory.get(), pixels, size.Width, size.Height, output.width, output.height);
output.encodedMs = unix_ms();
output.encodeMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - encodeStart).count();
const auto age = std::max<int64_t>(0, (qpc_100ns() - stamp) / 10000);
if (state->cancel.load() || !owner_valid(*state) || !window_valid(*state, window, thread, atom) ||
GetTickCount64() - operationStart >= captureDeadlineMs || age > int64_t(freshMs)) {
unavailable(state, "capture_timeout", "The captured window frame was not current at publication.");
continue;
}
{
std::lock_guard<std::mutex> lock(state->mutex);
if (!state->cancel.load()) {
output.sequence = ++sequence;
state->publishedTick = GetTickCount64() - uint64_t(age);
state->frame = std::move(output);
state->state = "streaming";
state->message.clear();
}
}
progressTick = GetTickCount64();
nextEncode = progressTick + 200;
} else {
frame.Close();
}
}
if (GetTickCount64() - progressTick >= captureDeadlineMs)
unavailable(state, "frame_timeout", "No new manufacturer window frame arrived before the capture deadline.");
}
std::unique_lock<std::mutex> lock(state->mutex);
state->wake.wait_for(lock, std::chrono::milliseconds(20), [&] { return state->cancel.load() || state->closed.load(); });
}
session.Close();
pool.Close();
}
struct View { Json metadata; std::optional<FrameSnapshot> frame; };
View read_state(const std::shared_ptr<CaptureState> &state, bool includeFrame) {
if (!state)
return {{{"source", "sdk_calibration_window"}, {"available", false}, {"state", "stopped"},
{"sessionId", ""}, {"frameSource", nullptr}}, std::nullopt};
std::lock_guard<std::mutex> lock(state->mutex);
bool current = !state->cancel.load() && state->frame && state->publishedTick &&
GetTickCount64() - state->publishedTick <= freshMs && owner_valid(*state) &&
window_valid(*state, state->window, state->windowThread, state->windowClass);
Json metadata = {{"source", "sdk_calibration_window"}, {"sessionId", state->sessionId},
{"available", current}, {"state", current ? "streaming" : state->state},
{"message", state->message}, {"frameSource", state->source},
{"frameSequence", current ? state->frame->sequence : 0},
{"capturedAtMs", current ? state->frame->capturedMs : 0},
{"maxFrameAgeMs", freshMs}, {"captureDeadlineMs", captureDeadlineMs}};
if (!current && state->state == "streaming") {
metadata["state"] = "source_unavailable";
metadata["message"] = "The manufacturer window frame is stale or its source is no longer valid.";
}
return {std::move(metadata), current && includeFrame ? state->frame : std::nullopt};
}
} // namespace
struct CalibrationWindowCapture::Impl {
mutable std::mutex control;
std::shared_ptr<CaptureState> current, retiring;
std::thread worker;
void stop_locked() {
if (!current)
return;
current->cancel.store(true);
{
std::lock_guard<std::mutex> lock(current->mutex);
current->frame.reset();
current->publishedTick = 0;
current->state = "stopped";
current->message.clear();
}
current->wake.notify_all();
if (!worker.joinable())
return;
bool finished = false;
{
std::unique_lock<std::mutex> lock(current->mutex);
finished = current->wake.wait_for(lock, std::chrono::milliseconds(750), [&] { return current->finished; });
}
if (finished)
worker.join();
else {
// A blocked display driver/COM call cannot hold the SDK worker or
// HTTP shutdown. Its shared state stays alive, publication is
// revoked, and another capture is refused until it finishes.
retiring = current;
worker.detach();
}
}
};
CalibrationWindowCapture::CalibrationWindowCapture() : impl_(std::make_unique<Impl>()) {}
CalibrationWindowCapture::~CalibrationWindowCapture() { stop(); }
void CalibrationWindowCapture::stop() {
std::lock_guard<std::mutex> lock(impl_->control);
impl_->stop_locked();
}
bool CalibrationWindowCapture::start(const std::string &sessionId, const Json &identity, std::string *error) {
std::lock_guard<std::mutex> lock(impl_->control);
impl_->stop_locked();
try {
if (impl_->retiring) {
std::lock_guard<std::mutex> stateLock(impl_->retiring->mutex);
if (!impl_->retiring->finished)
throw std::runtime_error("A previous capture is still shutting down; no new source can be bound.");
}
impl_->retiring.reset();
if (sessionId.empty() || !identity.is_object())
throw std::runtime_error("A current calibration session and trusted SDK process identity are required.");
const auto pid = identity.at("processId").get<uint64_t>();
const std::string creation = identity.at("startedFileTime").get<std::string>();
if (!pid || pid == GetCurrentProcessId() || pid > std::numeric_limits<DWORD>::max() || creation.empty() ||
creation.find_first_not_of("0123456789") != std::string::npos)
throw std::runtime_error("The trusted manufacturer identity is invalid.");
auto state = std::make_shared<CaptureState>();
state->pid = DWORD(pid);
state->created = std::stoull(creation);
state->sessionId = sessionId;
state->owner.reset(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, FALSE, state->pid));
if (!state->owner)
throw std::runtime_error("Cannot retain the trusted manufacturer process.");
state->rawImage = image_path(state->owner.get());
const auto actual = canonical_image(state->rawImage);
const auto expected = canonical_image(wide(identity.value("executable", identity.value("imagePath", std::string{}))));
if (!equal_path(actual, expected) || !owner_valid(*state))
throw std::runtime_error("The manufacturer PID, creation time, and executable do not match the SDK session.");
state->source = {{"kind", "sdk_calibration_window"}, {"processId", state->pid},
{"startedFileTime", std::to_string(state->created)}, {"executable", utf8(actual)},
{"windowHandle", nullptr}, {"sessionId", sessionId}};
state->startedQpc = qpc_100ns();
impl_->current = state;
impl_->worker = std::thread([state] {
try {
capture(state);
} catch (const winrt::hresult_error &exception) {
unavailable(state, "capture_failed", "Windows could not capture the verified manufacturer window (HRESULT " +
std::to_string(uint32_t(exception.code().value)) + ").");
} catch (const std::exception &exception) {
unavailable(state, "capture_failed", exception.what());
} catch (...) {
unavailable(state, "capture_failed", "The manufacturer window capture failed.");
}
{
std::lock_guard<std::mutex> stateLock(state->mutex);
state->finished = true;
}
state->wake.notify_all();
});
return true;
} catch (const std::exception &exception) {
if (error)
*error = exception.what();
return false;
}
}
Json CalibrationWindowCapture::metadata() const {
std::shared_ptr<CaptureState> state;
{ std::lock_guard<std::mutex> lock(impl_->control); state = impl_->current; }
return read_state(state, false).metadata;
}
std::optional<FrameSnapshot> CalibrationWindowCapture::latestFrame() const {
std::shared_ptr<CaptureState> state;
{ std::lock_guard<std::mutex> lock(impl_->control); state = impl_->current; }
return read_state(state, true).frame;
}
Json CalibrationWindowCapture::snapshot() const {
std::shared_ptr<CaptureState> state;
{ std::lock_guard<std::mutex> lock(impl_->control); state = impl_->current; }
auto view = read_state(state, true);
view.metadata["frame"] = view.frame ? frame_to_json(*view.frame) : Json(nullptr);
return std::move(view.metadata);
}
} // namespace freescan

View File

@ -0,0 +1,27 @@
#pragma once
#include "common.hpp"
#include <optional>
namespace freescan {
// A read-only, session-bound capture of one verified manufacturer window. The
// caller supplies the identity retained after SDK initialization; HTTP clients
// must never be allowed to supply it. No SDK or input-control calls occur here.
class CalibrationWindowCapture {
public:
CalibrationWindowCapture();
~CalibrationWindowCapture();
CalibrationWindowCapture(const CalibrationWindowCapture &) = delete;
CalibrationWindowCapture &operator=(const CalibrationWindowCapture &) = delete;
bool start(const std::string &sessionId, const Json &trustedProcessIdentity, std::string *error = nullptr);
void stop();
Json metadata() const;
std::optional<FrameSnapshot> latestFrame() const;
// Metadata and frame are copied under the same lock. frame is null whenever
// the source has ended, changed, minimized, timed out, or become stale.
Json snapshot() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace freescan

View File

@ -0,0 +1,160 @@
#include "common.hpp"
#include <objbase.h>
#include <wincrypt.h>
#include <cmath>
#include <cctype>
#include <cstdio>
#include <iomanip>
#include <sstream>
namespace freescan {
std::wstring wide(const std::string &value) {
if (value.empty())
return {};
int size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value.data(),
static_cast<int>(value.size()), nullptr, 0);
if (!size)
throw ApiError(400, "invalid_utf8", "文本不是有效的 UTF-8。");
std::wstring out(size, L'\0');
MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value.data(), static_cast<int>(value.size()),
out.data(), size);
return out;
}
std::string utf8(const std::wstring &value) {
if (value.empty())
return {};
int size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, value.data(),
static_cast<int>(value.size()), nullptr, 0, nullptr, nullptr);
if (!size)
throw ApiError(500, "invalid_text", "Windows 文本编码无效。");
std::string out(size, '\0');
WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, value.data(), static_cast<int>(value.size()),
out.data(), size, nullptr, nullptr);
return out;
}
std::string path_string(const fs::path &value) {
return utf8(value.wstring());
}
int64_t unix_ms() {
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
}
std::string utc_from_ms(int64_t value) {
ULARGE_INTEGER ticks{};
ticks.QuadPart = static_cast<uint64_t>(value) * 10000ull + 116444736000000000ull;
FILETIME time{ticks.LowPart, ticks.HighPart};
SYSTEMTIME utc{};
FileTimeToSystemTime(&time, &utc);
char out[40];
snprintf(out, sizeof(out), "%04u-%02u-%02uT%02u:%02u:%02u.%03uZ", utc.wYear, utc.wMonth, utc.wDay,
utc.wHour, utc.wMinute, utc.wSecond, utc.wMilliseconds);
return out;
}
std::string utc_now() {
return utc_from_ms(unix_ms());
}
std::string new_id() {
GUID value{};
if (FAILED(CoCreateGuid(&value)))
throw ApiError(500, "random_unavailable", "无法生成会话编号。");
wchar_t out[40];
StringFromGUID2(value, out, 40);
std::string text = utf8(out), id;
for (char c : text)
if (c != '{' && c != '}' && c != '-')
id += static_cast<char>(tolower(static_cast<unsigned char>(c)));
return id;
}
std::string base64_encode(const std::vector<uint8_t> &value) {
if (value.empty())
return {};
DWORD size = 0;
CryptBinaryToStringA(value.data(), static_cast<DWORD>(value.size()),
CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, nullptr, &size);
std::string out(size, '\0');
if (!CryptBinaryToStringA(value.data(), static_cast<DWORD>(value.size()),
CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, out.data(), &size))
throw ApiError(500, "frame_encoding_error", "图像传输编码失败。");
while (!out.empty() && out.back() == '\0')
out.pop_back();
return out;
}
std::vector<uint8_t> base64_decode(const std::string &value) {
if (value.size() > 12 * 1024 * 1024)
throw ApiError(502, "worker_protocol_error", "后台图像超过传输限制。");
DWORD size = 0;
if (!CryptStringToBinaryA(value.data(), static_cast<DWORD>(value.size()),
CRYPT_STRING_BASE64 | CRYPT_STRING_STRICT, nullptr, &size, nullptr, nullptr))
throw ApiError(502, "worker_protocol_error", "后台图像编码无效。");
std::vector<uint8_t> out(size);
if (size &&
!CryptStringToBinaryA(value.data(), static_cast<DWORD>(value.size()),
CRYPT_STRING_BASE64 | CRYPT_STRING_STRICT, out.data(), &size, nullptr, nullptr))
throw ApiError(502, "worker_protocol_error", "后台图像编码无效。");
return out;
}
Json read_json(const fs::path &path) {
std::ifstream in(path, std::ios::binary);
if (!in)
throw ApiError(503, "configuration_missing", "无法读取配置文件:" + path_string(path));
try {
return Json::parse(in);
} catch (const Json::exception &) {
throw ApiError(503, "invalid_configuration", "配置文件必须是有效的 UTF-8 JSON 对象。");
}
}
void write_json(const fs::path &path, const Json &value) {
std::ofstream out(path, std::ios::binary | std::ios::trunc);
if (!out)
throw ApiError(500, "file_write_failed", "无法写入文件:" + path_string(path));
out << value.dump(2) << "\n";
if (!out)
throw ApiError(500, "file_write_failed", "写入文件失败。");
}
void log_line(const fs::path &path, const std::string &message) {
static std::mutex gate;
std::lock_guard<std::mutex> hold(gate);
std::ofstream out(path, std::ios::app | std::ios::binary);
if (out)
out << utc_now() << " " << message << "\n";
}
Json error_json(const std::exception &exception) {
auto known = dynamic_cast<const ApiError *>(&exception);
return Json{{"code", known ? known->code : "internal_error"},
{"message", exception.what()},
{"httpStatus", known ? known->status : 500}};
}
Json frame_to_json(const FrameSnapshot &value) {
return Json{{"jpeg", base64_encode(value.jpeg)},
{"width", value.width},
{"height", value.height},
{"sourceWidth", value.sourceWidth},
{"sourceHeight", value.sourceHeight},
{"sequence", value.sequence},
{"capturedMs", value.capturedMs},
{"encodedMs", value.encodedMs},
{"encodeMs", value.encodeMs}};
}
FrameSnapshot frame_from_json(const Json &value) {
FrameSnapshot out;
try {
out.jpeg = base64_decode(value.at("jpeg").get<std::string>());
out.width = value.at("width").get<int>();
out.height = value.at("height").get<int>();
out.sourceWidth = value.at("sourceWidth").get<int>();
out.sourceHeight = value.at("sourceHeight").get<int>();
out.sequence = value.at("sequence").get<uint64_t>();
out.capturedMs = value.at("capturedMs").get<int64_t>();
out.encodedMs = value.at("encodedMs").get<int64_t>();
out.encodeMs = value.at("encodeMs").get<double>();
} catch (const Json::exception &) {
throw ApiError(502, "worker_protocol_error", "后台图像字段无效。");
}
if (out.jpeg.size() < 4 || out.jpeg.size() > 8 * 1024 * 1024 || out.width < 1 || out.width > 16384 ||
out.height < 1 || out.height > 16384 || out.sourceWidth < 1 || out.sourceHeight < 1 ||
out.encodeMs < 0 || !std::isfinite(out.encodeMs))
throw ApiError(502, "worker_protocol_error", "后台图像尺寸或编码无效。");
return out;
}
} // namespace freescan

View File

@ -0,0 +1,92 @@
#pragma once
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <fstream>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
#include "../third_party/json.hpp"
namespace freescan {
using Json = nlohmann::json;
namespace fs = std::filesystem;
struct ApiError : std::runtime_error {
int status;
std::string code;
ApiError(int value, std::string name, std::string message)
: std::runtime_error(std::move(message)), status(value), code(std::move(name)) {}
};
std::wstring wide(const std::string &value);
std::string utf8(const std::wstring &value);
std::string path_string(const fs::path &value);
std::string utc_now();
std::string utc_from_ms(int64_t value);
int64_t unix_ms();
std::string new_id();
std::string base64_encode(const std::vector<uint8_t> &value);
std::vector<uint8_t> base64_decode(const std::string &value);
Json read_json(const fs::path &path);
void write_json(const fs::path &path, const Json &value);
void log_line(const fs::path &path, const std::string &message);
Json error_json(const std::exception &exception);
struct FrameSnapshot {
std::vector<uint8_t> jpeg;
int width = 0, height = 0, sourceWidth = 0, sourceHeight = 0;
uint64_t sequence = 0;
int64_t capturedMs = 0, encodedMs = 0;
double encodeMs = 0;
};
Json frame_to_json(const FrameSnapshot &frame);
FrameSnapshot frame_from_json(const Json &value);
class Handle {
HANDLE handle_ = INVALID_HANDLE_VALUE;
public:
Handle() = default;
explicit Handle(HANDLE value) : handle_(value) {}
~Handle() {
reset();
}
Handle(const Handle &) = delete;
Handle &operator=(const Handle &) = delete;
Handle(Handle &&other) noexcept : handle_(other.release()) {}
Handle &operator=(Handle &&other) noexcept {
if (this != &other)
reset(other.release());
return *this;
}
HANDLE get() const {
return handle_;
}
explicit operator bool() const {
return handle_ && handle_ != INVALID_HANDLE_VALUE;
}
HANDLE release() {
HANDLE value = handle_;
handle_ = INVALID_HANDLE_VALUE;
return value;
}
void reset(HANDLE value = INVALID_HANDLE_VALUE) {
if (*this)
CloseHandle(handle_);
handle_ = value;
}
};
} // namespace freescan

View File

@ -0,0 +1,717 @@
#include "contracts.hpp"
#include <array>
#include <climits>
#include <cmath>
#include <iomanip>
#include <sstream>
namespace freescan::contracts {
namespace {
using Route = std::pair<const char *, const char *>;
const Route action_routes[] = {{"/api/v1/device/connect", "connect"},
{"/api/v1/projects", "createProject"},
{"/api/v1/device/disconnect", "disconnect"},
{"/api/v1/device/reconnect", "reconnect"},
{"/api/v1/preview/start", "startPreview"},
{"/api/v1/preview/stop", "stopPreview"},
{"/api/v1/scan/start", "startScan"},
{"/api/v1/scan/stop", "stopScan"},
{"/api/v1/scan/type", "setScanType"},
{"/api/v1/framework/import", "importFramework"},
{"/api/v1/framework/optimize", "optimizeFramework"},
{"/api/v1/parameters", "parameters"},
{"/api/v1/mesh", "mesh"},
{"/api/v1/mesh/confirm", "meshConfirm"},
{"/api/v1/mesh/undo", "meshUndo"},
{"/api/v1/align", "align"},
{"/api/v1/edit", "edit"},
{"/api/v1/clip-plane", "clipPlane"},
{"/api/v1/exports", "export"},
{"/api/v1/data/snapshots", "dataSnapshot"},
{"/api/v1/calibration/enter", "calibrationEnter"},
{"/api/v1/calibration/setMode", "calibrationSetMode"},
{"/api/v1/calibration/start", "calibrationStart"},
{"/api/v1/calibration/setTrakType", "calibrationSetTrakType"},
{"/api/v1/calibration/startSystem", "calibrationStartSystem"},
{"/api/v1/calibration/setFree", "calibrationSetFree"},
{"/api/v1/calibration/capturePose", "calibrationCapturePose"},
{"/api/v1/calibration/compute", "calibrationCompute"},
{"/api/v1/calibration/setAdvanced", "calibrationSetAdvanced"},
{"/api/v1/calibration/applyLast", "calibrationApplyLast"},
{"/api/v1/calibration/recover", "calibrationRecover"}};
const char *formats[] = {"ASCW", "ASCS", "STL", "OBJ", "PLY", "P3", "3MF",
"TXT", "CSV", "ASCG", "TGF", "STP", "IGS", "ASC"};
[[noreturn]] void invalid(const std::string &message) {
throw ApiError(400, "invalid_parameter", message);
}
bool member(const std::string &value, std::initializer_list<const char *> choices) {
for (const auto *choice : choices)
if (value == choice)
return true;
return false;
}
void fields(const Json &body, std::initializer_list<const char *> allowed) {
for (const auto &item : body.items())
if (!member(item.key(), allowed))
throw ApiError(400, "unknown_parameter", u8"未知参数:" + item.key());
}
// Generated from .NET Framework Char.GetUnicodeCategory / Char.IsWhiteSpace,
// the same BMP categories used by the original Regex [\p{L}\p{Nd}_-].
// Surrogate pairs remain excluded: the original regex counts UTF-16 code units.
using Range = std::pair<uint32_t, uint32_t>;
const Range name_ranges[] = {
{0x0030, 0x0039}, {0x0041, 0x005A}, {0x0061, 0x007A}, {0x00AA, 0x00AA}, {0x00B5, 0x00B5},
{0x00BA, 0x00BA}, {0x00C0, 0x00D6}, {0x00D8, 0x00F6}, {0x00F8, 0x02C1}, {0x02C6, 0x02D1},
{0x02E0, 0x02E4}, {0x02EC, 0x02EC}, {0x02EE, 0x02EE}, {0x0370, 0x0374}, {0x0376, 0x0377},
{0x037A, 0x037D}, {0x037F, 0x037F}, {0x0386, 0x0386}, {0x0388, 0x038A}, {0x038C, 0x038C},
{0x038E, 0x03A1}, {0x03A3, 0x03F5}, {0x03F7, 0x0481}, {0x048A, 0x052F}, {0x0531, 0x0556},
{0x0559, 0x0559}, {0x0561, 0x0587}, {0x05D0, 0x05EA}, {0x05F0, 0x05F2}, {0x0620, 0x064A},
{0x0660, 0x0669}, {0x066E, 0x066F}, {0x0671, 0x06D3}, {0x06D5, 0x06D5}, {0x06E5, 0x06E6},
{0x06EE, 0x06FC}, {0x06FF, 0x06FF}, {0x0710, 0x0710}, {0x0712, 0x072F}, {0x074D, 0x07A5},
{0x07B1, 0x07B1}, {0x07C0, 0x07EA}, {0x07F4, 0x07F5}, {0x07FA, 0x07FA}, {0x0800, 0x0815},
{0x081A, 0x081A}, {0x0824, 0x0824}, {0x0828, 0x0828}, {0x0840, 0x0858}, {0x08A0, 0x08B4},
{0x0904, 0x0939}, {0x093D, 0x093D}, {0x0950, 0x0950}, {0x0958, 0x0961}, {0x0966, 0x096F},
{0x0971, 0x0980}, {0x0985, 0x098C}, {0x098F, 0x0990}, {0x0993, 0x09A8}, {0x09AA, 0x09B0},
{0x09B2, 0x09B2}, {0x09B6, 0x09B9}, {0x09BD, 0x09BD}, {0x09CE, 0x09CE}, {0x09DC, 0x09DD},
{0x09DF, 0x09E1}, {0x09E6, 0x09F1}, {0x0A05, 0x0A0A}, {0x0A0F, 0x0A10}, {0x0A13, 0x0A28},
{0x0A2A, 0x0A30}, {0x0A32, 0x0A33}, {0x0A35, 0x0A36}, {0x0A38, 0x0A39}, {0x0A59, 0x0A5C},
{0x0A5E, 0x0A5E}, {0x0A66, 0x0A6F}, {0x0A72, 0x0A74}, {0x0A85, 0x0A8D}, {0x0A8F, 0x0A91},
{0x0A93, 0x0AA8}, {0x0AAA, 0x0AB0}, {0x0AB2, 0x0AB3}, {0x0AB5, 0x0AB9}, {0x0ABD, 0x0ABD},
{0x0AD0, 0x0AD0}, {0x0AE0, 0x0AE1}, {0x0AE6, 0x0AEF}, {0x0AF9, 0x0AF9}, {0x0B05, 0x0B0C},
{0x0B0F, 0x0B10}, {0x0B13, 0x0B28}, {0x0B2A, 0x0B30}, {0x0B32, 0x0B33}, {0x0B35, 0x0B39},
{0x0B3D, 0x0B3D}, {0x0B5C, 0x0B5D}, {0x0B5F, 0x0B61}, {0x0B66, 0x0B6F}, {0x0B71, 0x0B71},
{0x0B83, 0x0B83}, {0x0B85, 0x0B8A}, {0x0B8E, 0x0B90}, {0x0B92, 0x0B95}, {0x0B99, 0x0B9A},
{0x0B9C, 0x0B9C}, {0x0B9E, 0x0B9F}, {0x0BA3, 0x0BA4}, {0x0BA8, 0x0BAA}, {0x0BAE, 0x0BB9},
{0x0BD0, 0x0BD0}, {0x0BE6, 0x0BEF}, {0x0C05, 0x0C0C}, {0x0C0E, 0x0C10}, {0x0C12, 0x0C28},
{0x0C2A, 0x0C39}, {0x0C3D, 0x0C3D}, {0x0C58, 0x0C5A}, {0x0C60, 0x0C61}, {0x0C66, 0x0C6F},
{0x0C85, 0x0C8C}, {0x0C8E, 0x0C90}, {0x0C92, 0x0CA8}, {0x0CAA, 0x0CB3}, {0x0CB5, 0x0CB9},
{0x0CBD, 0x0CBD}, {0x0CDE, 0x0CDE}, {0x0CE0, 0x0CE1}, {0x0CE6, 0x0CEF}, {0x0CF1, 0x0CF2},
{0x0D05, 0x0D0C}, {0x0D0E, 0x0D10}, {0x0D12, 0x0D3A}, {0x0D3D, 0x0D3D}, {0x0D4E, 0x0D4E},
{0x0D5F, 0x0D61}, {0x0D66, 0x0D6F}, {0x0D7A, 0x0D7F}, {0x0D85, 0x0D96}, {0x0D9A, 0x0DB1},
{0x0DB3, 0x0DBB}, {0x0DBD, 0x0DBD}, {0x0DC0, 0x0DC6}, {0x0DE6, 0x0DEF}, {0x0E01, 0x0E30},
{0x0E32, 0x0E33}, {0x0E40, 0x0E46}, {0x0E50, 0x0E59}, {0x0E81, 0x0E82}, {0x0E84, 0x0E84},
{0x0E87, 0x0E88}, {0x0E8A, 0x0E8A}, {0x0E8D, 0x0E8D}, {0x0E94, 0x0E97}, {0x0E99, 0x0E9F},
{0x0EA1, 0x0EA3}, {0x0EA5, 0x0EA5}, {0x0EA7, 0x0EA7}, {0x0EAA, 0x0EAB}, {0x0EAD, 0x0EB0},
{0x0EB2, 0x0EB3}, {0x0EBD, 0x0EBD}, {0x0EC0, 0x0EC4}, {0x0EC6, 0x0EC6}, {0x0ED0, 0x0ED9},
{0x0EDC, 0x0EDF}, {0x0F00, 0x0F00}, {0x0F20, 0x0F29}, {0x0F40, 0x0F47}, {0x0F49, 0x0F6C},
{0x0F88, 0x0F8C}, {0x1000, 0x102A}, {0x103F, 0x1049}, {0x1050, 0x1055}, {0x105A, 0x105D},
{0x1061, 0x1061}, {0x1065, 0x1066}, {0x106E, 0x1070}, {0x1075, 0x1081}, {0x108E, 0x108E},
{0x1090, 0x1099}, {0x10A0, 0x10C5}, {0x10C7, 0x10C7}, {0x10CD, 0x10CD}, {0x10D0, 0x10FA},
{0x10FC, 0x1248}, {0x124A, 0x124D}, {0x1250, 0x1256}, {0x1258, 0x1258}, {0x125A, 0x125D},
{0x1260, 0x1288}, {0x128A, 0x128D}, {0x1290, 0x12B0}, {0x12B2, 0x12B5}, {0x12B8, 0x12BE},
{0x12C0, 0x12C0}, {0x12C2, 0x12C5}, {0x12C8, 0x12D6}, {0x12D8, 0x1310}, {0x1312, 0x1315},
{0x1318, 0x135A}, {0x1380, 0x138F}, {0x13A0, 0x13F5}, {0x13F8, 0x13FD}, {0x1401, 0x166C},
{0x166F, 0x167F}, {0x1681, 0x169A}, {0x16A0, 0x16EA}, {0x16F1, 0x16F8}, {0x1700, 0x170C},
{0x170E, 0x1711}, {0x1720, 0x1731}, {0x1740, 0x1751}, {0x1760, 0x176C}, {0x176E, 0x1770},
{0x1780, 0x17B3}, {0x17D7, 0x17D7}, {0x17DC, 0x17DC}, {0x17E0, 0x17E9}, {0x1810, 0x1819},
{0x1820, 0x1877}, {0x1880, 0x18A8}, {0x18AA, 0x18AA}, {0x18B0, 0x18F5}, {0x1900, 0x191E},
{0x1946, 0x196D}, {0x1970, 0x1974}, {0x1980, 0x19AB}, {0x19B0, 0x19C9}, {0x19D0, 0x19D9},
{0x1A00, 0x1A16}, {0x1A20, 0x1A54}, {0x1A80, 0x1A89}, {0x1A90, 0x1A99}, {0x1AA7, 0x1AA7},
{0x1B05, 0x1B33}, {0x1B45, 0x1B4B}, {0x1B50, 0x1B59}, {0x1B83, 0x1BA0}, {0x1BAE, 0x1BE5},
{0x1C00, 0x1C23}, {0x1C40, 0x1C49}, {0x1C4D, 0x1C7D}, {0x1CE9, 0x1CEC}, {0x1CEE, 0x1CF1},
{0x1CF5, 0x1CF6}, {0x1D00, 0x1DBF}, {0x1E00, 0x1F15}, {0x1F18, 0x1F1D}, {0x1F20, 0x1F45},
{0x1F48, 0x1F4D}, {0x1F50, 0x1F57}, {0x1F59, 0x1F59}, {0x1F5B, 0x1F5B}, {0x1F5D, 0x1F5D},
{0x1F5F, 0x1F7D}, {0x1F80, 0x1FB4}, {0x1FB6, 0x1FBC}, {0x1FBE, 0x1FBE}, {0x1FC2, 0x1FC4},
{0x1FC6, 0x1FCC}, {0x1FD0, 0x1FD3}, {0x1FD6, 0x1FDB}, {0x1FE0, 0x1FEC}, {0x1FF2, 0x1FF4},
{0x1FF6, 0x1FFC}, {0x2071, 0x2071}, {0x207F, 0x207F}, {0x2090, 0x209C}, {0x2102, 0x2102},
{0x2107, 0x2107}, {0x210A, 0x2113}, {0x2115, 0x2115}, {0x2119, 0x211D}, {0x2124, 0x2124},
{0x2126, 0x2126}, {0x2128, 0x2128}, {0x212A, 0x212D}, {0x212F, 0x2139}, {0x213C, 0x213F},
{0x2145, 0x2149}, {0x214E, 0x214E}, {0x2183, 0x2184}, {0x2C00, 0x2C2E}, {0x2C30, 0x2C5E},
{0x2C60, 0x2CE4}, {0x2CEB, 0x2CEE}, {0x2CF2, 0x2CF3}, {0x2D00, 0x2D25}, {0x2D27, 0x2D27},
{0x2D2D, 0x2D2D}, {0x2D30, 0x2D67}, {0x2D6F, 0x2D6F}, {0x2D80, 0x2D96}, {0x2DA0, 0x2DA6},
{0x2DA8, 0x2DAE}, {0x2DB0, 0x2DB6}, {0x2DB8, 0x2DBE}, {0x2DC0, 0x2DC6}, {0x2DC8, 0x2DCE},
{0x2DD0, 0x2DD6}, {0x2DD8, 0x2DDE}, {0x2E2F, 0x2E2F}, {0x3005, 0x3006}, {0x3031, 0x3035},
{0x303B, 0x303C}, {0x3041, 0x3096}, {0x309D, 0x309F}, {0x30A1, 0x30FA}, {0x30FC, 0x30FF},
{0x3105, 0x312D}, {0x3131, 0x318E}, {0x31A0, 0x31BA}, {0x31F0, 0x31FF}, {0x3400, 0x4DB5},
{0x4E00, 0x9FD5}, {0xA000, 0xA48C}, {0xA4D0, 0xA4FD}, {0xA500, 0xA60C}, {0xA610, 0xA62B},
{0xA640, 0xA66E}, {0xA67F, 0xA69D}, {0xA6A0, 0xA6E5}, {0xA717, 0xA71F}, {0xA722, 0xA788},
{0xA78B, 0xA7AD}, {0xA7B0, 0xA7B7}, {0xA7F7, 0xA801}, {0xA803, 0xA805}, {0xA807, 0xA80A},
{0xA80C, 0xA822}, {0xA840, 0xA873}, {0xA882, 0xA8B3}, {0xA8D0, 0xA8D9}, {0xA8F2, 0xA8F7},
{0xA8FB, 0xA8FB}, {0xA8FD, 0xA8FD}, {0xA900, 0xA925}, {0xA930, 0xA946}, {0xA960, 0xA97C},
{0xA984, 0xA9B2}, {0xA9CF, 0xA9D9}, {0xA9E0, 0xA9E4}, {0xA9E6, 0xA9FE}, {0xAA00, 0xAA28},
{0xAA40, 0xAA42}, {0xAA44, 0xAA4B}, {0xAA50, 0xAA59}, {0xAA60, 0xAA76}, {0xAA7A, 0xAA7A},
{0xAA7E, 0xAAAF}, {0xAAB1, 0xAAB1}, {0xAAB5, 0xAAB6}, {0xAAB9, 0xAABD}, {0xAAC0, 0xAAC0},
{0xAAC2, 0xAAC2}, {0xAADB, 0xAADD}, {0xAAE0, 0xAAEA}, {0xAAF2, 0xAAF4}, {0xAB01, 0xAB06},
{0xAB09, 0xAB0E}, {0xAB11, 0xAB16}, {0xAB20, 0xAB26}, {0xAB28, 0xAB2E}, {0xAB30, 0xAB5A},
{0xAB5C, 0xAB65}, {0xAB70, 0xABE2}, {0xABF0, 0xABF9}, {0xAC00, 0xD7A3}, {0xD7B0, 0xD7C6},
{0xD7CB, 0xD7FB}, {0xF900, 0xFA6D}, {0xFA70, 0xFAD9}, {0xFB00, 0xFB06}, {0xFB13, 0xFB17},
{0xFB1D, 0xFB1D}, {0xFB1F, 0xFB28}, {0xFB2A, 0xFB36}, {0xFB38, 0xFB3C}, {0xFB3E, 0xFB3E},
{0xFB40, 0xFB41}, {0xFB43, 0xFB44}, {0xFB46, 0xFBB1}, {0xFBD3, 0xFD3D}, {0xFD50, 0xFD8F},
{0xFD92, 0xFDC7}, {0xFDF0, 0xFDFB}, {0xFE70, 0xFE74}, {0xFE76, 0xFEFC}, {0xFF10, 0xFF19},
{0xFF21, 0xFF3A}, {0xFF41, 0xFF5A}, {0xFF66, 0xFFBE}, {0xFFC2, 0xFFC7}, {0xFFCA, 0xFFCF},
{0xFFD2, 0xFFD7}, {0xFFDA, 0xFFDC}};
const Range white_ranges[] = {{0x0009, 0x000D}, {0x0020, 0x0020}, {0x0085, 0x0085}, {0x00A0, 0x00A0},
{0x1680, 0x1680}, {0x2000, 0x200A}, {0x2028, 0x2029}, {0x202F, 0x202F},
{0x205F, 0x205F}, {0x3000, 0x3000}};
template <size_t N> bool in_ranges(uint32_t cp, const Range (&ranges)[N]) {
const auto *range =
std::lower_bound(std::begin(ranges), std::end(ranges), cp,
[](const Range &item, uint32_t value) { return item.second < value; });
return range != std::end(ranges) && cp >= range->first;
}
std::vector<uint32_t> codepoints(const std::string &value) {
std::vector<uint32_t> result;
for (size_t i = 0; i < value.size();) {
unsigned char first = static_cast<unsigned char>(value[i++]);
uint32_t cp = 0, minimum = 0;
size_t remaining = 0;
if (first < 0x80)
cp = first;
else if (first >= 0xC2 && first <= 0xDF) {
cp = first & 0x1F;
remaining = 1;
minimum = 0x80;
} else if (first >= 0xE0 && first <= 0xEF) {
cp = first & 0x0F;
remaining = 2;
minimum = 0x800;
} else if (first >= 0xF0 && first <= 0xF4) {
cp = first & 0x07;
remaining = 3;
minimum = 0x10000;
} else
invalid(u8"字符串必须为有效 UTF-8。");
if (remaining > value.size() - i)
invalid(u8"字符串必须为有效 UTF-8。");
for (size_t n = 0; n < remaining; ++n) {
unsigned char next = static_cast<unsigned char>(value[i++]);
if ((next & 0xC0) != 0x80)
invalid(u8"字符串必须为有效 UTF-8。");
cp = (cp << 6) | (next & 0x3F);
}
if (cp < minimum || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF))
invalid(u8"字符串必须为有效 UTF-8。");
result.push_back(cp);
}
return result;
}
std::string text(const Json &body, const std::string &key, bool required = true) {
if (!body.contains(key)) {
if (required)
invalid(u8"缺少 " + key);
return {};
}
const auto &value = body.at(key);
if (!value.is_string())
invalid(key + u8" 必须是非空字符串。");
const auto result = value.get<std::string>();
const auto chars = codepoints(result);
if (chars.empty() ||
std::all_of(chars.begin(), chars.end(), [](uint32_t cp) { return in_ranges(cp, white_ranges); }))
invalid(key + u8" 必须是非空字符串。");
return result;
}
void name(const Json &body, const char *key, size_t maximum = 40, bool nullable = false) {
if (!body.contains(key) || (nullable && body.at(key).is_null()))
return;
const auto chars = codepoints(text(body, key));
if (chars.empty() || chars.size() > maximum || std::any_of(chars.begin(), chars.end(), [](uint32_t cp) {
return cp != '_' && cp != '-' && !in_ranges(cp, name_ranges);
}))
invalid(std::string(key) +
u8" 只允许限定长度内的 Unicode 字母、十进制数字、下划线或短横线,不能包含文件路径。");
}
void boolean(const Json &body, const char *key, bool required = false) {
if (!body.contains(key)) {
if (required)
invalid(u8"缺少 " + std::string(key));
return;
}
if (!body.at(key).is_boolean())
invalid(std::string(key) + u8" 必须是布尔值。");
}
void confirm(const Json &body) {
if (!body.contains("confirm") || !body.at("confirm").is_boolean() || !body.at("confirm").get<bool>())
throw ApiError(400, "confirmation_required",
u8"该操作会改变数据或标定状态,请核对后显式提供 confirm:true。");
}
bool integer_between(const Json &value, int64_t minimum, int64_t maximum) {
if (value.is_number_unsigned())
return value.get<uint64_t>() <= static_cast<uint64_t>(maximum) &&
(minimum <= 0 || value.get<uint64_t>() >= static_cast<uint64_t>(minimum));
if (!value.is_number_integer())
return false;
const auto number = value.get<int64_t>();
return number >= minimum && number <= maximum;
}
void integer(const Json &body, const char *key, int32_t minimum, int32_t maximum, bool nullable = false,
bool required = false) {
if (!body.contains(key)) {
if (required)
invalid(u8"缺少 " + std::string(key));
return;
}
const auto &value = body.at(key);
if (nullable && value.is_null())
return;
if (!integer_between(value, minimum, maximum))
invalid(std::string(key) + u8" 必须是限定范围内的整数(不接受布尔或小数)。");
}
double numeric(const Json &value, const std::string &key, double minimum = -100000000,
double maximum = 100000000) {
if (!value.is_number())
invalid(key + u8" 必须是数值。");
const double number = value.get<double>();
if (!std::isfinite(number) || number < minimum || number > maximum)
invalid(key + u8" 超出软件允许范围。");
return number;
}
void number(const Json &body, const char *key, double minimum, double maximum) {
if (body.contains(key))
numeric(body.at(key), key, minimum, maximum);
}
const Json &array(const Json &body, const char *key, bool required, size_t maximum) {
static const Json empty = Json::array();
if (!body.contains(key)) {
if (required)
invalid(u8"缺少 " + std::string(key));
return empty;
}
const auto &value = body.at(key);
if (!value.is_array() || value.size() > maximum)
invalid(std::string(key) + u8" 必须为数量不超过限制的数组。");
return value;
}
std::array<double, 3> vector(const Json &body, const char *key) {
const auto &values = array(body, key, true, 3);
if (values.size() != 3)
invalid(std::string(key) + u8" 必须包含 3 个坐标。");
return {numeric(values[0], key), numeric(values[1], key), numeric(values[2], key)};
}
size_t vectors(const Json &body, const char *key, size_t maximum) {
const auto &values = array(body, key, false, maximum);
for (const auto &row : values) {
if (!row.is_array() || row.size() != 3)
invalid(std::string(key) + u8" 每项必须包含 3 个坐标。");
for (const auto &coordinate : row)
numeric(coordinate, key);
}
return values.size();
}
size_t ids(const Json &body, const char *key, size_t maximum) {
const auto &values = array(body, key, false, maximum);
for (const auto &value : values)
if (!integer_between(value, 0, INT64_MAX))
invalid(std::string(key) + u8" 必须为非负 int64 整数标识数组。");
return values.size();
}
bool hex(char value) {
return value >= '0' && value <= '9' || value >= 'a' && value <= 'f' || value >= 'A' && value <= 'F';
}
std::string guid_hex_form(const std::string &value) {
size_t at = 0;
const auto consume = [&](char c) {
if (at >= value.size() || value[at] != c)
return false;
++at;
return true;
};
const auto component = [&](uint32_t maximum, uint32_t &result) {
if (at + 2 > value.size() || value[at] != '0' || (value[at + 1] != 'x' && value[at + 1] != 'X'))
return false;
at += 2;
size_t start = at;
result = 0;
while (at < value.size() && hex(value[at])) {
const auto c = value[at++];
uint32_t digit = c <= '9' ? c - '0' : c <= 'F' ? c - 'A' + 10 : c - 'a' + 10;
if (result > (maximum - digit) / 16)
return false;
result = result * 16 + digit;
}
return at > start;
};
uint32_t first = 0, second = 0, third = 0;
std::array<uint32_t, 8> tail{};
if (!consume('{') || !component(UINT32_MAX, first) || !consume(',') || !component(UINT16_MAX, second) ||
!consume(',') || !component(UINT16_MAX, third) || !consume(',') || !consume('{'))
return {};
for (size_t i = 0; i < tail.size(); ++i)
if (!component(UINT8_MAX, tail[i]) || (i < 7 && !consume(',')))
return {};
if (!consume('}') || !consume('}') || at != value.size())
return {};
std::ostringstream normalized;
normalized << std::hex << std::setfill('0') << std::setw(8) << first << std::setw(4) << second
<< std::setw(4) << third;
for (const auto byte : tail)
normalized << std::setw(2) << byte;
return normalized.str();
}
std::string guid_normalized(const std::string &raw) {
auto chars = codepoints(raw);
size_t begin = 0, end = chars.size();
while (begin < end && in_ranges(chars[begin], white_ranges))
++begin;
while (end > begin && in_ranges(chars[end - 1], white_ranges))
--end;
std::string value, compact;
for (size_t i = begin; i < end; ++i)
if (!in_ranges(chars[i], white_ranges)) {
if (chars[i] > 127)
return {};
compact.push_back(static_cast<char>(chars[i]));
}
const bool hexForm = compact.rfind("{0x", 0) == 0 || compact.rfind("{0X", 0) == 0;
if (hexForm)
value = compact;
else
for (size_t i = begin; i < end; ++i) {
if (chars[i] > 127)
return {};
value.push_back(static_cast<char>(chars[i]));
}
std::string result;
if (value.size() == 32 && std::all_of(value.begin(), value.end(), hex))
result = value;
else {
if (value.size() == 38 &&
(value.front() == '{' && value.back() == '}' || value.front() == '(' && value.back() == ')'))
value = value.substr(1, 36);
if (value.size() == 36 && value[8] == '-' && value[13] == '-' && value[18] == '-' &&
value[23] == '-') {
for (size_t i = 0; i < value.size(); ++i) {
if (i == 8 || i == 13 || i == 18 || i == 23)
continue;
if (!hex(value[i]))
return {};
result.push_back(value[i]);
}
} else {
// X form strips whitespace like Guid.TryParse. Parse iteratively so
// long untrusted strings cannot exhaust a std::regex call stack.
result = guid_hex_form(value);
}
}
std::transform(result.begin(), result.end(), result.begin(),
[](char c) { return static_cast<char>(c >= 'A' && c <= 'F' ? c + ('a' - 'A') : c); });
if (result.size() != 32 || result == std::string(32, '0'))
return {};
return result;
}
std::string uuid(const Json &body, const char *key, bool required) {
if (!body.contains(key)) {
if (required)
invalid(u8"缺少 " + std::string(key));
return {};
}
auto result = guid_normalized(text(body, key));
if (result.empty())
invalid(std::string(key) + u8" 必须为非空 GUID。");
return result;
}
void device_type(const Json &body) {
if (body.contains("deviceType") && (!integer_between(body.at("deviceType"), 3, 4)))
invalid(u8"deviceType 必须为整数 3 或 4。");
}
void lifecycle(const std::string &action, const Json &body) {
if (action == "reconnect")
fields(body, {"confirm", "discardProject", "expectedProjectId", "expectedSessionId", "deviceType"});
else
fields(body, {"confirm", "discardProject", "expectedProjectId", "expectedSessionId"});
confirm(body);
boolean(body, "discardProject");
name(body, "expectedProjectId", 160, true);
if (body.contains("expectedSessionId") && !body.at("expectedSessionId").is_null()) {
const auto id = text(body, "expectedSessionId");
if (id.size() != 32 || !std::all_of(id.begin(), id.end(), hex))
invalid(u8"expectedSessionId 必须是 32 位十六进制会话标识,或未连接时的 null。");
}
if (action == "reconnect")
device_type(body);
}
void parameters(const Json &b) {
for (const auto *key :
{"frameworkBrightness", "cloudShowMode", "scanAlignType", "workingDistance", "workingRange"})
if (b.contains(key))
throw ApiError(422, "unsupported_for_trak", std::string(key) + u8" 不适用于当前 Trak 封装范围。");
fields(b, {"pointDistance", "brightness", "lightSourceMode", "scanFrameRate", "highSpeedMode",
"addMarkerMode", "viewLock", "localEnlargedView", "qualityColor", "strongLight", "preScanMode",
"markerDiameters"});
if (b.empty())
invalid(u8"至少提供一个需要修改的扫描参数。");
number(b, "pointDistance", 0.001, 10);
integer(b, "brightness", 0, 17);
integer(b, "lightSourceMode", 0, 2);
integer(b, "scanFrameRate", 1, 120);
for (const auto *key : {"highSpeedMode", "addMarkerMode", "viewLock", "localEnlargedView", "qualityColor",
"strongLight", "preScanMode"})
boolean(b, key);
if (b.contains("markerDiameters")) {
const auto &values = array(b, "markerDiameters", true, 16);
if (values.empty())
invalid(u8"markerDiameters 不能为空。");
for (const auto &value : values)
if (!integer_between(value, 1, 50))
invalid(u8"markerDiameters 必须包含 1–16 个 1–50 的整数。");
}
}
void mesh(const Json &b) {
for (const auto *key : {"meshType", "qualityType", "simplificationByCurvature", "deleteNeighborhoodAreas",
"cornerOptimization"})
if (b.contains(key))
throw ApiError(422, "unsupported_for_trak",
std::string(key) + u8" 不适用于当前 Trak 或非红外模式。");
fields(b, {"filterLevel", "smoothLevel", "removeSmallFloatingParts", "cutMeshEdgeOptimization",
"cutMeshEdgeValue", "holeOptimization", "boundaryOptimization", "maxTriangles",
"fillSmallHole", "removeSpikes", "fillMarkerHoles", "rememberChoice"});
integer(b, "filterLevel", 0, 3);
integer(b, "smoothLevel", 0, 3);
integer(b, "removeSmallFloatingParts", 0, 100000000);
number(b, "cutMeshEdgeValue", 0, 1000);
integer(b, "maxTriangles", 1, 100000000, true);
integer(b, "fillSmallHole", 1, 1000000, true);
for (const auto *key : {"cutMeshEdgeOptimization", "holeOptimization", "boundaryOptimization",
"removeSpikes", "fillMarkerHoles", "rememberChoice"})
boolean(b, key);
}
void align(const Json &b) {
const auto action = text(b, "action");
if (!member(action, {"enter", "apply", "next", "cancel", "exit"}))
invalid(u8"align.action 无效。");
if (action != "apply") {
fields(b, {"action", "confirm"});
if (action == "exit")
confirm(b);
else
boolean(b, "confirm");
return;
}
fields(b, {"action", "mode", "fixedProjectUuid", "movingProjectUuid", "fixedPoints", "movingPoints",
"fixedMarkerIds", "movingMarkerIds", "fixedMarkerPoints", "movingMarkerPoints", "confirm"});
const auto mode = text(b, "mode");
if (!member(mode, {"featureAuto", "markerAuto", "featureManual", "markerManual"}))
invalid(u8"align.mode 无效。");
const auto fixed = uuid(b, "fixedProjectUuid", true), moving = uuid(b, "movingProjectUuid", true);
if (fixed == moving)
invalid(u8"固定和移动工程不能相同。");
const auto fc = vectors(b, "fixedPoints", 256), mc = vectors(b, "movingPoints", 256),
fm = vectors(b, "fixedMarkerPoints", 256), mm = vectors(b, "movingMarkerPoints", 256);
const auto fi = ids(b, "fixedMarkerIds", 256), mi = ids(b, "movingMarkerIds", 256);
if (fc != mc || fm != mm || fi != mi)
invalid(u8"固定和移动对应数组的数量必须一致。");
if (mode == "featureManual" && fc < 3)
invalid(u8"手动特征拼接至少需要 3 对点。");
if (mode == "markerManual" && (fi < 3 || fm != fi))
invalid(u8"手动标志点拼接至少需要 3 对 ID 和坐标,且各数组数量一致。");
boolean(b, "confirm");
}
void edit(const Json &b) {
fields(b, {"projectUuid", "cloudUuid", "pointIds", "markerIds", "points", "normals", "confirm"});
confirm(b);
uuid(b, "projectUuid", true);
uuid(b, "cloudUuid", false);
const auto pointCount = ids(b, "pointIds", 4096), markers = ids(b, "markerIds", 4096),
points = vectors(b, "points", 4096), normals = vectors(b, "normals", 4096);
if (pointCount == 0 && markers == 0)
invalid(u8"编辑必须提供 pointIds 或 markerIds,不能只凭坐标删除数据。");
if (pointCount > 0 && !b.contains("cloudUuid"))
invalid(u8"删除点云数据必须提供 cloudUuid。");
if (points > 0 && points != pointCount || normals > 0 && normals != pointCount)
invalid(u8"points、normals 与 pointIds 的数量必须一致。");
}
void calibration(const std::string &action, const Json &b) {
if (action == "calibrationRecover") {
fields(b, {"confirm", "force", "expectedSessionId"});
confirm(b);
boolean(b, "force");
if (!b.contains("expectedSessionId") || !b.at("expectedSessionId").is_string())
invalid(u8"expectedSessionId 必须为当前状态返回的 32 位十六进制会话标识。");
const auto id = b.at("expectedSessionId").get<std::string>();
if (id.size() != 32 || !std::all_of(id.begin(), id.end(), hex))
invalid(u8"expectedSessionId 必须为当前状态返回的 32 位十六进制会话标识。");
return;
}
if (action == "calibrationEnter") {
fields(b, {});
return;
}
if (action == "calibrationSetMode") {
fields(b, {"mode"});
integer(b, "mode", 0, 3, false, true);
return;
}
if (action == "calibrationSetTrakType") {
fields(b, {"trakType", "confirm"});
confirm(b);
integer(b, "trakType", 0, 3, false, true);
return;
}
if (action == "calibrationSetFree" || action == "calibrationSetAdvanced") {
fields(b, {"enabled", "confirm"});
confirm(b);
boolean(b, "enabled", true);
return;
}
if (action == "calibrationApplyLast") {
fields(b, {"mode", "confirm"});
confirm(b);
integer(b, "mode", 0, 3, false, true);
return;
}
fields(b, {"confirm"});
confirm(b);
}
} // namespace
std::string action_for_path(const std::string &path) {
for (const auto &route : action_routes)
if (path == route.first)
return route.second;
return {};
}
Json export_formats() {
Json result = Json::array();
for (const auto *format : formats)
result.push_back(format);
return result;
}
Json routes() {
Json result = {"GET /api/v1/health", "GET /api/v1/status", "GET /api/v1/capabilities",
"GET /api/v1/device/battery",
"GET /api/v1/calibration/view", "GET /api/v1/calibration/view/image", "GET /api/v1/calibration/view/stream",
"GET /api/v1/tasks/{taskId}", "GET /api/v1/preview/image", "GET /api/v1/preview/stream",
"GET /api/v1/preview/metrics", "GET /api/v1/data/scene", "GET /api/v1/files/{fileId}",
"POST /api/v1/framework/files"};
for (const auto &route : action_routes)
result.push_back(std::string("POST ") + route.first);
return result;
}
size_t maximum_body_bytes(const std::string &action) {
return action == "align" || action == "edit" ? 1024u * 1024u : 16u * 1024u;
}
std::string normalize_guid(const std::string &value) {
const auto id = guid_normalized(value);
if (id.empty())
invalid(u8"必须提供有效的非空 GUID。");
return id.substr(0, 8) + "-" + id.substr(8, 4) + "-" + id.substr(12, 4) + "-" + id.substr(16, 4) + "-" +
id.substr(20);
}
void validate(const std::string &action, const Json &body) {
if (!body.is_object())
invalid(u8"请求体必须是 JSON 对象。");
bool known = false;
for (const auto &route : action_routes)
if (action == route.second) {
known = true;
break;
}
if (!known)
throw ApiError(404, "unknown_action", u8"没有该设备控制动作。");
if (action == "connect") {
fields(body, {"deviceType"});
device_type(body);
return;
}
if (action == "createProject") {
fields(body, {"mode", "name"});
name(body, "name");
if (body.contains("mode") &&
(!body.at("mode").is_string() || !member(body.at("mode").get<std::string>(), {"trak", "laser"})))
invalid(u8"mode 必须为 trak 或 laser。");
return;
}
if (action == "setScanType") {
fields(body, {"scanType", "device", "confirm"});
if (!member(text(body, "scanType"), {"photogrammetry", "mesh", "markers"}))
invalid(u8"scanType 必须为 photogrammetry、mesh 或 markers。");
if (body.contains("device") && !member(text(body, "device"), {"tracker", "scanner"}))
invalid(u8"device 必须为 tracker(UE Nova)或 scanner(TE Nova)。");
boolean(body, "confirm");
return;
}
if (action == "importFramework") {
fields(body, {"fileIds", "confirm"});
confirm(body);
const auto &values = array(body, "fileIds", true, 8);
if (values.empty())
invalid(u8"fileIds 不能为空;请先上传框架文件。");
std::set<std::string> used;
for (const auto &value : values) {
if (!value.is_string())
invalid(u8"fileIds 必须是已上传文件的 32 位小写十六进制 ID 数组。");
const auto id = value.get<std::string>();
if (id.size() != 32 || !std::all_of(id.begin(), id.end(), [](unsigned char c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
}) || !used.insert(id).second)
invalid(u8"fileIds 包含无效或重复 ID;不能传入本机文件路径。");
}
return;
}
if (member(action, {"startScan", "stopScan", "startPreview", "stopPreview", "meshConfirm", "meshUndo",
"optimizeFramework"})) {
fields(body, {});
return;
}
if (action == "disconnect" || action == "reconnect") {
lifecycle(action, body);
return;
}
if (action == "parameters") {
parameters(body);
return;
}
if (action == "mesh") {
mesh(body);
return;
}
if (action == "align") {
align(body);
return;
}
if (action == "edit") {
edit(body);
return;
}
if (action == "export") {
fields(body, {"name", "formats"});
name(body, "name");
const auto &values = array(body, "formats", true, 14);
std::set<std::string> used;
if (values.empty())
invalid(u8"formats 不能为空。");
for (const auto &value : values) {
if (!value.is_string())
invalid(u8"formats 必须为受支持的大写格式名数组。");
const auto format = value.get<std::string>();
if (std::find(std::begin(formats), std::end(formats), format) == std::end(formats) ||
!used.insert(format).second)
invalid(u8"formats 包含未知或重复格式;MAT 未提供已验证的格式位。");
}
return;
}
if (action == "dataSnapshot") {
fields(body, {"maxPoints", "include", "pauseAcquisition"});
integer(body, "maxPoints", 1, 1000000);
boolean(body, "pauseAcquisition");
if (body.contains("include")) {
const auto &values = array(body, "include", true, 3);
std::set<std::string> used;
if (values.empty())
invalid(u8"include 不能为空。");
for (const auto &value : values)
if (!value.is_string() ||
!member(value.get<std::string>(), {"points", "markers", "meshes"}) ||
!used.insert(value.get<std::string>()).second)
invalid(u8"include 必须为 points、markers、meshes 中不重复的非空数组。");
}
return;
}
if (action == "clipPlane") {
fields(body, {"center", "normal", "deleteBelowPoints", "deleteBelowMarkers", "confirm"});
confirm(body);
vector(body, "center");
const auto normal = vector(body, "normal");
if (std::all_of(normal.begin(), normal.end(), [](double coordinate) { return coordinate == 0; }))
invalid(u8"normal 不能为零向量。");
boolean(body, "deleteBelowPoints");
boolean(body, "deleteBelowMarkers");
if (body.contains("deleteBelowPoints") && !body.at("deleteBelowPoints").get<bool>() &&
(!body.contains("deleteBelowMarkers") || !body.at("deleteBelowMarkers").get<bool>()))
invalid(u8"至少选择一种裁剪对象。");
return;
}
calibration(action, body);
}
} // namespace freescan::contracts

View File

@ -0,0 +1,12 @@
#pragma once
#include "common.hpp"
namespace freescan::contracts {
std::string action_for_path(const std::string &path);
Json routes();
Json export_formats();
void validate(const std::string &action, const Json &body);
size_t maximum_body_bytes(const std::string &action);
// Shared with SDK marshaling: accepts legacy .NET N/D/B/P/X forms and returns D.
std::string normalize_guid(const std::string &value);
} // namespace freescan::contracts

View File

@ -0,0 +1,86 @@
#pragma once
#include "common.hpp"
#include <charconv>
#include <limits>
#include <optional>
namespace freescan::detail {
// Owned by one SDK session; callers hold the worker state mutex.
// SDK indexes are retained without guessing physical battery slots.
class DeviceBatteryCache {
static std::optional<int> integer(const Json &value) {
if (value.is_number_unsigned()) {
auto n = value.get<uint64_t>();
return n <= static_cast<uint64_t>((std::numeric_limits<int>::max)())
? std::optional<int>(static_cast<int>(n)) : std::nullopt;
}
if (value.is_number_integer()) {
auto n = value.get<int64_t>();
return n >= (std::numeric_limits<int>::min)() && n <= (std::numeric_limits<int>::max)()
? std::optional<int>(static_cast<int>(n)) : std::nullopt;
}
if (!value.is_string()) return std::nullopt;
const auto &s = value.get_ref<const std::string &>();
if (s.empty() || s.size() > 11) return std::nullopt;
int n = 0;
auto result = std::from_chars(s.data(), s.data() + s.size(), n);
if (result.ec != std::errc{} || result.ptr != s.data() + s.size()) return std::nullopt;
return n;
}
struct Reading {
std::optional<int> raw;
int64_t updated = 0;
void update(const Json &value, int64_t now) { raw = integer(value); updated = now; }
Json snapshot(bool active, int64_t now) const {
const bool fresh = active && updated > 0 && now >= updated && now - updated <= freshnessLimitMs;
const bool available = fresh && raw && *raw >= 0 && *raw <= 100;
return {{"percent", available ? Json(*raw) : Json(nullptr)},
{"rawValue", raw ? Json(*raw) : Json(nullptr)},
{"available", available}, {"fresh", fresh},
{"updatedUtc", updated > 0 ? Json(utc_from_ms(updated)) : Json(nullptr)}};
}
};
Reading scanner_;
std::map<std::string, Reading> tracker_;
static std::optional<std::string> channel(const Json &message) {
if (!message.contains("index") || message["index"].is_null()) return std::string();
if (message["index"].is_string()) {
const auto &s = message["index"].get_ref<const std::string &>();
if (s.empty() || s.find_first_not_of("0123456789") != std::string::npos)
return std::nullopt;
}
auto n = integer(message["index"]);
if (!n || *n < 0) return std::nullopt;
return std::to_string(*n);
}
public:
static constexpr int64_t freshnessLimitMs = 30000;
bool update(const Json &message, int64_t now) {
if (!message.is_object() || !message.contains("cmd") || message["cmd"] != "sdkDeviceStatus" ||
!message.contains("type") || message["type"] != "information" || now <= 0) return false;
bool changed = false;
if (message.contains("scannerBattery")) { scanner_.update(message["scannerBattery"], now); changed = true; }
if (message.contains("trakBattery")) {
auto index = channel(message);
if (index) {
auto it = tracker_.find(*index);
if (it != tracker_.end() || tracker_.size() < 16) {
tracker_[*index].update(message["trakBattery"], now); changed = true;
}
}
}
return changed;
}
void clear() { scanner_ = {}; tracker_.clear(); }
Json snapshot(bool active, int64_t now) const {
Json channels = Json::array();
for (const auto &entry : tracker_) {
Json reading = entry.second.snapshot(active, now);
reading["index"] = entry.first.empty() ? Json(nullptr) : Json(entry.first);
channels.push_back(std::move(reading));
}
return {{"source", "sdkDeviceStatus"}, {"freshnessLimitMs", freshnessLimitMs},
{"scanner", scanner_.snapshot(active, now)}, {"tracker", {{"channels", std::move(channels)}}}};
}
};
} // namespace freescan::detail

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,20 @@
#pragma once
#include "common.hpp"
namespace freescan {
class HttpServer {
struct Impl;
std::shared_ptr<Impl> impl_;
public:
HttpServer(fs::path dataRoot, Json config, std::function<Json()> status, std::function<Json(std::string, Json, uint64_t)> execute,
std::function<Json(std::string, Json)> query,
std::function<std::shared_ptr<const FrameSnapshot>()> frame, std::function<Json()> metrics,
std::function<uint64_t()> generation, bool simulated = false);
~HttpServer();
HttpServer(const HttpServer &) = delete;
HttpServer &operator=(const HttpServer &) = delete;
void start();
void stop();
};
} // namespace freescan

View File

@ -0,0 +1,185 @@
#include "supervisor.hpp"
#include "http_server.hpp"
#include <objbase.h>
#include <iostream>
namespace freescan {
namespace {
HANDLE hostStopEvent = nullptr;
BOOL WINAPI console_control(DWORD kind) {
if (kind == CTRL_C_EVENT || kind == CTRL_BREAK_EVENT || kind == CTRL_CLOSE_EVENT ||
kind == CTRL_SHUTDOWN_EVENT) {
if (hostStopEvent)
SetEvent(hostStopEvent);
return TRUE;
}
return FALSE;
}
uint64_t started_at(HANDLE process) {
FILETIME created{}, ended{}, kernel{}, user{};
if (!GetProcessTimes(process, &created, &ended, &kernel, &user))
throw ApiError(503, "process_identity_error", "无法读取进程身份。");
ULARGE_INTEGER out{};
out.LowPart = created.dwLowDateTime;
out.HighPart = created.dwHighDateTime;
return out.QuadPart;
}
fs::path own_executable() {
std::vector<wchar_t> path(32768);
DWORD count = GetModuleFileNameW(nullptr, path.data(), static_cast<DWORD>(path.size()));
if (!count || count >= path.size())
throw ApiError(500, "path_error", "无法获取运行目录。");
return fs::path(std::wstring(path.data(), count));
}
Json options(int argc, wchar_t **argv) {
Json out = Json::object();
for (int i = 1; i < argc; ++i) {
std::string arg = utf8(argv[i]);
if (arg == "--mock" || arg == "--api-no-auto-connect" || arg == "--stop") {
out[arg] = true;
continue;
}
if (arg == "--worker" || arg == "--data-root" || arg == "--parent" || arg == "--parent-start") {
if (++i >= argc)
throw ApiError(400, "invalid_argument", "启动参数缺少值:" + arg);
out[arg] = utf8(argv[i]);
continue;
}
throw ApiError(400, "invalid_argument", "未知启动参数:" + arg);
}
return out;
}
int request_stop(const fs::path &root) {
fs::path path = root / L".native-service.json";
if (!fs::exists(path)) {
std::cout << "没有找到由本程序记录的 C++ 设备服务。" << std::endl;
return 0;
}
Json record = read_json(path);
DWORD id = record.at("processId").get<DWORD>();
Handle process(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, FALSE, id));
if (!process || WaitForSingleObject(process.get(), 0) == WAIT_OBJECT_0) {
std::cout << "记录中的 C++ 服务已经退出。" << std::endl;
return 0;
}
std::vector<wchar_t> image(32768);
DWORD count = static_cast<DWORD>(image.size());
if (!QueryFullProcessImageNameW(process.get(), 0, image.data(), &count) ||
_wcsicmp(own_executable().c_str(), std::wstring(image.data(), count).c_str()) != 0 ||
started_at(process.get()) != record.at("startedFileTime").get<uint64_t>())
throw ApiError(409, "process_identity_changed", "服务进程记录已失效,没有关闭任何程序。");
try {
PipeClient(wide(record.at("controlPipe").get<std::string>())).call("stop", Json::object(), 5000);
} catch (const ApiError &error) {
if (error.code != "worker_unavailable" && error.code != "worker_timeout" &&
error.code != "shutting_down")
throw;
}
if (WaitForSingleObject(process.get(), 20000) != WAIT_OBJECT_0)
throw ApiError(409, "service_still_running",
"停止请求已发送,但服务尚未退出。请检查是否有未结束任务或 SDK 清理提示。");
std::cout << "C++ 设备服务已正常停止。" << std::endl;
return 0;
}
} // namespace
} // namespace freescan
int wmain(int argc, wchar_t **argv) {
using namespace freescan;
SetConsoleOutputCP(CP_UTF8);
SetConsoleCP(CP_UTF8);
try {
Json opts = options(argc, argv);
fs::path root = opts.contains("--data-root") ? fs::path(wide(opts["--data-root"].get<std::string>()))
: own_executable().parent_path();
root = fs::canonical(root);
if (opts.value("--stop", false))
return request_stop(root);
Json config = load_configuration(root);
if (opts.value("--api-no-auto-connect", false))
config["autoConnect"] = false;
bool simulated = opts.value("--mock", false);
if (simulated && config.value("prefix", std::string()) != "http://127.0.0.1:18889/")
throw ApiError(400, "simulation_port_required",
"模拟模式只允许显式测试目录及 127.0.0.1:18889,不可用于正式接口端口。");
if (opts.contains("--worker")) {
std::string pipe = opts["--worker"];
if (pipe.rfind("FreeScanCpp_", 0) != 0 || pipe.size() != 44 ||
pipe.substr(12).find_first_not_of("0123456789abcdef") != std::string::npos)
throw ApiError(400, "invalid_worker_name", "后台启动名称无效。");
if (!opts.contains("--parent") || !opts.contains("--parent-start"))
throw ApiError(400, "missing_parent", "扫描后台必须由父进程启动。");
return run_worker(root, config, wide(pipe),
static_cast<DWORD>(std::stoul(opts["--parent"].get<std::string>())),
std::stoull(opts["--parent-start"].get<std::string>()), simulated);
}
if (!config.value("enabled", true)) {
std::cout << "HTTP API 已在配置中停用。" << std::endl;
return 0;
}
CoInitializeEx(nullptr, COINIT_MULTITHREADED);
auto service = std::make_shared<Supervisor>(root, config, simulated);
HttpServer http(
root, config, [service] { return service->status(); },
[service](const std::string &action, const Json &body, uint64_t generation) {
return action == "calibrationRecover" ? service->recover(body) : service->execute(action, body, generation);
},
[service](const std::string &action, const Json &body) { return service->query(action, body); },
[service] { return service->frame(); }, [service] { return service->metrics(); },
[service] { return service->command_generation(); }, simulated);
Handle stopEvent(CreateEventW(nullptr, TRUE, FALSE, nullptr));
hostStopEvent = stopEvent.get();
SetConsoleCtrlHandler(console_control, TRUE);
// Publish HTTP only after the empty SDK worker is ready to accept commands.
service->start();
http.start();
std::wstring controlName = wide("FreeScanCppControl_" + new_id());
PipeServer control(controlName,
[service, stop = stopEvent.get()](const std::string &action, const Json &args) {
if (action != "stop" || !args.empty())
throw ApiError(404, "unknown_control", "服务控制命令无效。");
service->pause_auto_connection();
Json status = service->status();
if (status.value("busy", false))
throw ApiError(409, "device_busy", "设备任务尚未完成,请等待后停止服务。");
SetEvent(stop);
return Json{{"accepted", true}};
});
control.start();
Json record{{"processId", GetCurrentProcessId()},
{"startedFileTime", started_at(GetCurrentProcess())},
{"executable", path_string(own_executable())},
{"controlPipe", utf8(controlName)},
{"implementation", "C++17"},
{"simulated", simulated}};
write_json(root / L".native-service.json", record);
std::cout << "FreeScan C++ HTTP backend: " << config.value("prefix", std::string()) << "api/v1/"
<< std::endl;
if (simulated)
std::cout << "OFFLINE_TEST_FIXTURE: simulated SDK, no hardware." << std::endl;
service->start_auto_connection();
while (true) {
WaitForSingleObject(stopEvent.get(), INFINITE);
if (service->stop())
break;
ResetEvent(stopEvent.get());
std::cerr << "设备后台尚未确认退出,服务保持运行;请检查本地日志。" << std::endl;
}
http.stop();
control.stop();
hostStopEvent = nullptr;
SetConsoleCtrlHandler(console_control, FALSE);
try {
if (fs::exists(root / L".native-service.json")) {
auto current = read_json(root / L".native-service.json");
if (current.value("processId", 0u) == GetCurrentProcessId())
fs::remove(root / L".native-service.json");
}
} catch (const std::exception &) {
}
CoUninitialize();
return 0;
} catch (const std::exception &ex) {
std::cerr << "C++ backend failed: " << ex.what() << std::endl;
return 1;
}
}

View File

@ -0,0 +1,234 @@
#include "pipe_rpc.hpp"
#include <sddl.h>
#include <cstring>
namespace freescan {
namespace {
constexpr uint32_t limit = 12 * 1024 * 1024;
std::wstring address(const std::wstring &name) {
if (name.empty() || name.size() > 128 ||
name.find_first_not_of(L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-") !=
std::wstring::npos)
throw ApiError(500, "invalid_pipe_name", "内部通信名称无效。");
return L"\\\\.\\pipe\\" + name;
}
void transfer(HANDLE pipe, void *buffer, DWORD size, bool write, int64_t deadline, HANDLE stop = nullptr) {
auto bytes = static_cast<uint8_t *>(buffer);
DWORD offset = 0;
while (offset < size) {
Handle event(CreateEventW(nullptr, TRUE, FALSE, nullptr));
OVERLAPPED overlap{};
overlap.hEvent = event.get();
DWORD moved = 0;
BOOL result = write ? WriteFile(pipe, bytes + offset, size - offset, &moved, &overlap)
: ReadFile(pipe, bytes + offset, size - offset, &moved, &overlap);
if (!result) {
DWORD error = GetLastError();
if (error != ERROR_IO_PENDING)
throw ApiError(503, "worker_unavailable", "设备后台通信已断开。");
HANDLE handles[2] = {event.get(), stop};
DWORD remaining = static_cast<DWORD>(std::max<int64_t>(1, deadline - unix_ms()));
DWORD wait = WaitForMultipleObjects(stop ? 2 : 1, handles, FALSE, remaining);
if (wait != WAIT_OBJECT_0) {
CancelIoEx(pipe, &overlap);
GetOverlappedResult(pipe, &overlap, &moved, TRUE);
throw ApiError(wait == WAIT_TIMEOUT ? 504 : 503,
wait == WAIT_TIMEOUT ? "worker_timeout" : "shutting_down",
wait == WAIT_TIMEOUT ? "设备后台通信等待超时;请查询状态并保留任务编号。"
: "设备后台正在关闭。");
}
if (!GetOverlappedResult(pipe, &overlap, &moved, FALSE))
throw ApiError(503, "worker_unavailable", "设备后台通信已断开。");
}
if (!moved)
throw ApiError(503, "worker_unavailable", "设备后台提前结束通信。");
offset += moved;
}
}
void send(HANDLE pipe, const Json &value, int64_t deadline, HANDLE stop = nullptr) {
std::string data = value.dump(-1, ' ', false, Json::error_handler_t::strict);
if (data.empty() || data.size() > limit)
throw ApiError(502, "worker_protocol_error", "后台消息超过传输限制。");
uint32_t size = static_cast<uint32_t>(data.size());
uint8_t head[4] = {static_cast<uint8_t>(size), static_cast<uint8_t>(size >> 8),
static_cast<uint8_t>(size >> 16), static_cast<uint8_t>(size >> 24)};
transfer(pipe, head, 4, true, deadline, stop);
transfer(pipe, data.data(), size, true, deadline, stop);
}
Json receive(HANDLE pipe, int64_t deadline, HANDLE stop = nullptr) {
uint8_t head[4];
transfer(pipe, head, 4, false, deadline, stop);
uint32_t size = static_cast<uint32_t>(head[0]) | (static_cast<uint32_t>(head[1]) << 8) |
(static_cast<uint32_t>(head[2]) << 16) | (static_cast<uint32_t>(head[3]) << 24);
if (!size || size > limit)
throw ApiError(502, "worker_protocol_error", "后台消息长度无效。");
std::string data(size, '\0');
transfer(pipe, data.data(), size, false, deadline, stop);
try {
auto value = Json::parse(data);
if (!value.is_object())
throw ApiError(502, "worker_protocol_error", "后台消息必须是 JSON 对象。");
return value;
} catch (const Json::exception &) {
throw ApiError(502, "worker_protocol_error", "后台消息 JSON 无效。");
}
}
} // namespace
Json PipeClient::call(const std::string &action, const Json &args, int timeoutMs) const {
if (timeoutMs < 1)
throw ApiError(500, "invalid_timeout", "后台通信期限无效。");
int64_t deadline = unix_ms() + timeoutMs;
std::wstring path = address(name_);
Handle pipe;
do {
pipe.reset(CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED, nullptr));
if (pipe)
break;
DWORD error = GetLastError();
if (error != ERROR_PIPE_BUSY && error != ERROR_FILE_NOT_FOUND)
throw ApiError(503, "worker_unavailable", "无法连接本账户的设备后台。");
if (unix_ms() >= deadline)
throw ApiError(504, "worker_timeout", "设备后台尚未就绪。");
WaitNamedPipeW(path.c_str(), 100);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
} while (true);
send(pipe.get(), Json{{"action", action}, {"arguments", args}}, deadline);
Json reply = receive(pipe.get(), deadline);
uint8_t acknowledgement = 0x06;
try {
transfer(pipe.get(), &acknowledgement, 1, true, std::min(deadline, unix_ms() + 1000));
} catch (const ApiError &) { /* The complete framed reply has already been consumed. */
}
if (!reply.contains("ok") || !reply["ok"].is_boolean())
throw ApiError(502, "worker_protocol_error", "后台回复协议无效。");
if (!reply["ok"].get<bool>()) {
auto error = reply.value("error", Json::object());
throw ApiError(error.value("httpStatus", 502), error.value("code", "worker_error"),
error.value("message", "设备后台执行失败。"));
}
return reply.value("result", Json());
}
struct PipeServer::Impl : std::enable_shared_from_this<PipeServer::Impl> {
std::wstring path;
std::function<Json(const std::string &, const Json &)> handler;
Handle stopEvent;
std::thread accept;
std::mutex gate;
std::set<std::shared_ptr<Handle>> pipes;
std::atomic<bool> running{false};
PSECURITY_DESCRIPTOR security = nullptr;
Impl(std::wstring name, std::function<Json(const std::string &, const Json &)> fn)
: path(address(name)), handler(std::move(fn)),
stopEvent(CreateEventW(nullptr, TRUE, FALSE, nullptr)) {
HANDLE raw = nullptr;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &raw))
throw ApiError(500, "pipe_security_error", "无法读取当前用户身份。");
Handle token(raw);
DWORD bytes = 0;
GetTokenInformation(token.get(), TokenUser, nullptr, 0, &bytes);
std::vector<uint8_t> data(bytes);
if (!GetTokenInformation(token.get(), TokenUser, data.data(), bytes, &bytes))
throw ApiError(500, "pipe_security_error", "无法读取当前用户标识。");
LPWSTR sid = nullptr;
if (!ConvertSidToStringSidW(reinterpret_cast<TOKEN_USER *>(data.data())->User.Sid, &sid))
throw ApiError(500, "pipe_security_error", "无法创建用户访问权限。");
std::wstring sddl = L"D:P(A;;GA;;;" + std::wstring(sid) + L")";
LocalFree(sid);
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(), SDDL_REVISION_1, &security,
nullptr))
throw ApiError(500, "pipe_security_error", "无法保护内部通信权限。");
}
~Impl() {
if (security)
LocalFree(security);
}
void serve(const std::shared_ptr<Handle> &pipe) {
try {
auto request = receive(pipe->get(), unix_ms() + 10000, stopEvent.get());
if (request.size() != 2 || !request.contains("action") || !request["action"].is_string() ||
!request.contains("arguments") || !request["arguments"].is_object())
throw ApiError(400, "invalid_rpc_arguments", "后台通信参数无效。");
Json reply;
try {
reply = Json{{"ok", true},
{"result", handler(request["action"].get<std::string>(), request["arguments"])}};
} catch (const std::exception &ex) {
reply = Json{{"ok", false}, {"error", error_json(ex)}};
}
send(pipe->get(), reply, unix_ms() + 15000, stopEvent.get());
uint8_t acknowledgement = 0;
transfer(pipe->get(), &acknowledgement, 1, false, unix_ms() + 5000, stopEvent.get());
} catch (const std::exception &) {
}
std::lock_guard<std::mutex> hold(gate);
DisconnectNamedPipe(pipe->get());
pipes.erase(pipe);
}
void loop() {
while (running) {
SECURITY_ATTRIBUTES attrs{sizeof(attrs), security, FALSE};
auto pipe = std::make_shared<Handle>(
CreateNamedPipeW(path.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
16, 65536, 65536, 0, &attrs));
if (!*pipe) {
std::this_thread::sleep_for(std::chrono::milliseconds(30));
continue;
}
{
std::lock_guard<std::mutex> hold(gate);
pipes.insert(pipe);
}
Handle event(CreateEventW(nullptr, TRUE, FALSE, nullptr));
OVERLAPPED overlap{};
overlap.hEvent = event.get();
BOOL result = ConnectNamedPipe(pipe->get(), &overlap);
DWORD error = result ? ERROR_SUCCESS : GetLastError();
bool connected = result || error == ERROR_PIPE_CONNECTED;
if (error == ERROR_IO_PENDING) {
HANDLE events[2] = {event.get(), stopEvent.get()};
DWORD wait = WaitForMultipleObjects(2, events, FALSE, INFINITE);
if (wait == WAIT_OBJECT_0) {
DWORD moved = 0;
connected = !!GetOverlappedResult(pipe->get(), &overlap, &moved, FALSE);
} else {
CancelIoEx(pipe->get(), &overlap);
DWORD moved = 0;
GetOverlappedResult(pipe->get(), &overlap, &moved, TRUE);
}
}
if (!running || !connected) {
std::lock_guard<std::mutex> hold(gate);
pipes.erase(pipe);
continue;
}
auto self = shared_from_this();
std::thread([self, pipe] { self->serve(pipe); }).detach();
}
}
};
PipeServer::PipeServer(std::wstring name, std::function<Json(const std::string &, const Json &)> handler)
: impl_(std::make_shared<Impl>(std::move(name), std::move(handler))) {}
PipeServer::~PipeServer() {
stop();
}
void PipeServer::start() {
bool expected = false;
if (!impl_->running.compare_exchange_strong(expected, true))
return;
auto self = impl_;
impl_->accept = std::thread([self] { self->loop(); });
}
void PipeServer::stop() {
if (!impl_ || !impl_->running.exchange(false))
return;
SetEvent(impl_->stopEvent.get());
{
std::lock_guard<std::mutex> hold(impl_->gate);
for (auto &pipe : impl_->pipes)
CancelIoEx(pipe->get(), nullptr);
}
if (impl_->accept.joinable())
impl_->accept.join();
}
} // namespace freescan

View File

@ -0,0 +1,22 @@
#pragma once
#include "common.hpp"
namespace freescan {
class PipeClient {
std::wstring name_;
public:
explicit PipeClient(std::wstring name) : name_(std::move(name)) {}
Json call(const std::string &action, const Json &arguments = Json::object(),
int timeoutMs = 120000) const;
};
class PipeServer {
struct Impl;
std::shared_ptr<Impl> impl_;
public:
PipeServer(std::wstring name, std::function<Json(const std::string &, const Json &)> handler);
~PipeServer();
void start();
void stop();
};
} // namespace freescan

View File

@ -0,0 +1,204 @@
#pragma once
#include "common.hpp"
#include <array>
#include <cstring>
#include <utility>
namespace freescan::detail {
inline void preview_atomic_max(std::atomic<uint64_t> &target, uint64_t value) noexcept {
auto previous = target.load(std::memory_order_relaxed);
while (previous < value && !target.compare_exchange_weak(previous, value, std::memory_order_relaxed)) {
}
}
struct PreviewRawFrame {
std::vector<uint8_t> pixels;
int w = 0, h = 0;
int64_t captured = 0;
uint64_t epoch = 0;
};
// Each slot has exactly one owner, whether it is being copied, queued or encoded.
// Returning a lease never needs the frame/state mutexes, including on a dropped
// callback. Pixel capacity is retained until the worker itself is destroyed.
class PreviewFramePool {
public:
static constexpr size_t capacity = 3;
class Lease {
friend class PreviewFramePool;
PreviewFramePool *pool_ = nullptr;
size_t slot_ = 0;
Lease(PreviewFramePool *pool, size_t slot) noexcept : pool_(pool), slot_(slot) {}
public:
Lease() noexcept = default;
Lease(const Lease &) = delete;
Lease &operator=(const Lease &) = delete;
Lease(Lease &&other) noexcept : pool_(other.pool_), slot_(other.slot_) { other.pool_ = nullptr; }
Lease &operator=(Lease &&other) noexcept {
if (this != &other) {
reset();
pool_ = other.pool_;
slot_ = other.slot_;
other.pool_ = nullptr;
}
return *this;
}
~Lease() { reset(); }
explicit operator bool() const noexcept { return pool_ != nullptr; }
PreviewRawFrame *get() const noexcept { return pool_ ? &pool_->slots_[slot_].frame : nullptr; }
PreviewRawFrame *operator->() const noexcept { return get(); }
PreviewRawFrame &operator*() const noexcept { return *get(); }
void reset() noexcept {
if (!pool_)
return;
pool_->inUse_.fetch_sub(1, std::memory_order_relaxed);
pool_->slots_[slot_].claimed.store(false, std::memory_order_release);
pool_ = nullptr;
}
};
Lease try_acquire() noexcept {
for (size_t index = 0; index < slots_.size(); ++index) {
bool expected = false;
if (slots_[index].claimed.compare_exchange_strong(expected, true, std::memory_order_acquire,
std::memory_order_relaxed)) {
const auto count = inUse_.fetch_add(1, std::memory_order_relaxed) + 1;
preview_atomic_max(peakInUse_, count);
return Lease(this, index);
}
}
exhausted_.fetch_add(1, std::memory_order_relaxed);
return {};
}
void prepare(Lease &lease, int width, int height) {
if (lease.pool_ != this || width <= 0 || height <= 0 || width > 16384 || height > 16384 ||
uint64_t(width) * uint64_t(height) * 4 > 256 * 1024 * 1024)
throw std::invalid_argument("Invalid preview frame buffer request.");
auto &frame = *lease;
const auto previous = frame.pixels.capacity();
frame.pixels.resize(size_t(width) * height * 4);
const auto current = frame.pixels.capacity();
if (current > previous) {
allocations_.fetch_add(1, std::memory_order_relaxed);
capacityBytes_.fetch_add(current - previous, std::memory_order_relaxed);
if (!previous)
allocatedSlots_.fetch_add(1, std::memory_order_relaxed);
} else {
reuses_.fetch_add(1, std::memory_order_relaxed);
}
frame.w = width;
frame.h = height;
}
Json snapshot() const {
return {{"capacity", capacity},
{"allocatedSlots", allocatedSlots_.load(std::memory_order_relaxed)},
{"inUse", inUse_.load(std::memory_order_relaxed)},
{"peakInUse", peakInUse_.load(std::memory_order_relaxed)},
{"allocations", allocations_.load(std::memory_order_relaxed)},
{"reuses", reuses_.load(std::memory_order_relaxed)},
{"capacityBytes", capacityBytes_.load(std::memory_order_relaxed)},
{"exhausted", exhausted_.load(std::memory_order_relaxed)}};
}
private:
struct Slot {
std::atomic<bool> claimed{false};
PreviewRawFrame frame;
};
std::array<Slot, capacity> slots_{};
std::atomic<uint64_t> inUse_{0}, peakInUse_{0}, allocatedSlots_{0}, allocations_{0}, reuses_{0},
capacityBytes_{0}, exhausted_{0};
};
// The SDK buffer is bottom-up. Keep the callback to one contiguous memcpy and
// perform this transformation only after the encoder owns an exclusive lease.
inline void flip_preview_rows(PreviewRawFrame &frame) {
const size_t row = size_t(frame.w) * 4;
for (int y = 0; y < frame.h / 2; ++y) {
auto first = frame.pixels.begin() + size_t(y) * row;
auto opposite = frame.pixels.begin() + size_t(frame.h - 1 - y) * row;
std::swap_ranges(first, first + row, opposite);
}
}
struct PreviewCallbackDiagnostics {
std::atomic<uint64_t> entries{0}, completed{0}, inFlight{0}, accepted{0}, invalidParameters{0},
inactiveState{0}, stateLockBusy{0}, copyLockBusy{0}, frameLockBusy{0}, throttled{0},
poolUnavailable{0}, staleEpoch{0}, lifecycleRejected{0}, exceptions{0}, copySamples{0},
copyTotalUs{0}, copyMaxUs{0}, callbackTotalUs{0}, callbackMaxUs{0};
std::atomic<int64_t> lastEntryMs{0};
std::atomic<int> lastWidth{0}, lastHeight{0}, lastChannels{0};
struct Observation {
PreviewCallbackDiagnostics &owner;
std::chrono::steady_clock::time_point started = std::chrono::steady_clock::now();
bool finished = false;
Observation(PreviewCallbackDiagnostics &value, int width, int height, int channels, int64_t now)
: owner(value) {
owner.entries.fetch_add(1, std::memory_order_relaxed);
owner.inFlight.fetch_add(1, std::memory_order_relaxed);
owner.lastWidth.store(width, std::memory_order_relaxed);
owner.lastHeight.store(height, std::memory_order_relaxed);
owner.lastChannels.store(channels, std::memory_order_relaxed);
owner.lastEntryMs.store(now, std::memory_order_relaxed);
}
Observation(const Observation &) = delete;
Observation &operator=(const Observation &) = delete;
~Observation() { finish(); }
void finish() noexcept {
if (finished)
return;
finished = true;
const auto elapsed = uint64_t(std::max<int64_t>(0,
std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - started).count()));
owner.callbackTotalUs.fetch_add(elapsed, std::memory_order_relaxed);
preview_atomic_max(owner.callbackMaxUs, elapsed);
owner.completed.fetch_add(1, std::memory_order_relaxed);
owner.inFlight.fetch_sub(1, std::memory_order_relaxed);
}
};
void record_copy(std::chrono::steady_clock::time_point started) noexcept {
const auto elapsed = uint64_t(std::max<int64_t>(0,
std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - started).count()));
copyTotalUs.fetch_add(elapsed, std::memory_order_relaxed);
preview_atomic_max(copyMaxUs, elapsed);
copySamples.fetch_add(1, std::memory_order_relaxed);
}
Json snapshot(int64_t now) const {
const auto finished = completed.load(std::memory_order_relaxed);
const auto copied = copySamples.load(std::memory_order_relaxed);
const auto last = lastEntryMs.load(std::memory_order_relaxed);
return {{"callbackEntries", entries.load(std::memory_order_relaxed)},
{"completedCallbacks", finished},
{"callbacksInFlight", inFlight.load(std::memory_order_relaxed)},
{"acceptedFrames", accepted.load(std::memory_order_relaxed)},
{"lastCallbackUnixMs", last ? Json(last) : Json(nullptr)},
{"lastCallbackAgeMs", last ? Json(std::max<int64_t>(0, now - last)) : Json(nullptr)},
{"lastWidth", lastWidth.load(std::memory_order_relaxed)},
{"lastHeight", lastHeight.load(std::memory_order_relaxed)},
{"lastChannels", lastChannels.load(std::memory_order_relaxed)},
{"invalidParameters", invalidParameters.load(std::memory_order_relaxed)},
{"inactiveState", inactiveState.load(std::memory_order_relaxed)},
{"stateLockBusy", stateLockBusy.load(std::memory_order_relaxed)},
{"copyLockBusy", copyLockBusy.load(std::memory_order_relaxed)},
{"frameLockBusy", frameLockBusy.load(std::memory_order_relaxed)},
{"throttled", throttled.load(std::memory_order_relaxed)},
{"poolUnavailable", poolUnavailable.load(std::memory_order_relaxed)},
{"staleEpoch", staleEpoch.load(std::memory_order_relaxed)},
{"lifecycleRejected", lifecycleRejected.load(std::memory_order_relaxed)},
{"exceptions", exceptions.load(std::memory_order_relaxed)},
{"copySamples", copied},
{"averageCopyMs", copied ? copyTotalUs.load(std::memory_order_relaxed) / (1000.0 * copied) : 0.0},
{"maxCopyMs", copyMaxUs.load(std::memory_order_relaxed) / 1000.0},
{"averageCallbackMs", finished ? callbackTotalUs.load(std::memory_order_relaxed) / (1000.0 * finished) : 0.0},
{"maxCallbackMs", callbackMaxUs.load(std::memory_order_relaxed) / 1000.0}};
}
};
} // namespace freescan::detail

View File

@ -0,0 +1,25 @@
#pragma once
#include <utility>
namespace freescan::detail {
// The SDK may publish the whole scene while Pause is executing, before its
// completion reply. The receiver and raw-data mode must be ready first.
// This flow never resumes acquisition; restoring image preview is separate.
template <class Prepare, class Pause, class Wait, class Write>
void capture_scene_snapshot(bool pauseAcquisition, Prepare &&prepare, Pause &&pause, Wait &&wait,
Write &&write) {
std::forward<Prepare>(prepare)();
if (pauseAcquisition)
std::forward<Pause>(pause)();
std::forward<Wait>(wait)();
std::forward<Write>(write)();
}
// With pauseAcquisition and meshes selected, an incremental update can precede
// the whole-scene notification. Keep waiting instead of exporting that fragment.
inline bool accepts_scene_snapshot(bool pauseAcquisition, int mask, unsigned int datatype,
bool wholeMeshPresent) {
constexpr unsigned int wholeMesh = 1U << 3;
return !pauseAcquisition || !(mask & 4) || ((datatype & wholeMesh) && wholeMeshPresent);
}
} // namespace freescan::detail

View File

@ -0,0 +1,59 @@
#pragma once
#include "common.hpp"
#include <regex>
namespace freescan::detail {
struct SdkLocation {
fs::path library, serviceDirectory;
};
// Pure filesystem discovery, shared by SDK loading and file metadata queries.
// This function never loads a vendor DLL or starts/connects the device service.
inline SdkLocation locate_sdk_installation(const fs::path &root, const fs::path &app,
const Json &config) {
std::vector<fs::path> candidates;
if (config.contains("sdkPath") && config["sdkPath"].is_string())
candidates.emplace_back(wide(config["sdkPath"].get<std::string>()));
for (const auto &settings : {root / L"settings.xml", app / L"settings.xml",
root.parent_path() / L"FreeScanViewer" / L"settings.xml"}) {
std::ifstream in(settings, std::ios::binary);
const std::string content(std::istreambuf_iterator<char>(in), {});
std::smatch match;
if (std::regex_search(content, match, std::regex("<SdkPath>([^<]+)</SdkPath>")))
candidates.emplace_back(wide(match[1].str()));
}
candidates.emplace_back(L"C:\\Program Files\\Shining3d\\FreeTrak_TRAK\\sdk\\bin\\SDKCWrapper.dll");
candidates.emplace_back(L"C:\\Shining3D\\FreeScanTrak\\sdk\\bin\\SDKCWrapper.dll");
for (auto candidate : candidates) {
if (fs::is_directory(candidate)) {
if (fs::exists(candidate / L"sdk" / L"bin" / L"SDKCWrapper.dll"))
candidate /= L"sdk/bin/SDKCWrapper.dll";
else
candidate /= L"SDKCWrapper.dll";
}
if (!fs::is_regular_file(candidate))
continue;
const auto bin = candidate.parent_path();
if (!fs::exists(bin / L"Sn3DSDKCore.dll") || !fs::exists(bin / L"Sn3DSDKDataLib.dll") ||
!fs::is_directory(bin / L"Qt"))
continue;
const auto qt = bin / L"Qt";
const auto prefix = fs::exists(qt / L"Qt6Core.dll") ? L"Qt6" : L"Qt5";
bool valid = true;
for (auto component : {L"Core.dll", L"Gui.dll", L"Widgets.dll"})
if (!fs::exists(qt / (std::wstring(prefix) + component)))
valid = false;
if (!fs::exists(qt / L"platforms" / L"qwindows.dll"))
valid = false;
if (!valid)
continue;
auto current = bin;
for (int depth = 0; depth <= 4 && !current.empty(); depth++, current = current.parent_path())
if (fs::is_regular_file(current / L"FreeScan Trak.exe"))
return {fs::absolute(candidate), fs::absolute(current)};
}
throw ApiError(503, "sdk_unavailable",
"A complete matching FreeScan Trak SDK/Qt/service installation is required; "
"SDKCWrapper.dll alone is insufficient.");
}
} // namespace freescan::detail

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,26 @@
#pragma once
#include "common.hpp"
namespace freescan {
// One instance owns one SDK initialization attempt. Replace the entire worker
// process after disconnect; the vendor DLL and callback owners are never unloaded.
class WorkerService {
struct Impl;
std::shared_ptr<Impl> impl_;
public:
WorkerService(fs::path dataRoot, Json config, bool simulate = false);
~WorkerService();
WorkerService(const WorkerService &) = delete;
WorkerService &operator=(const WorkerService &) = delete;
Json status();
Json recovery_info(); // Internal parent/worker RPC only; never an HTTP query.
Json execute(const std::string &action, const Json &body);
Json query(const std::string &action, const Json &arguments);
Json files();
Json frame();
Json calibration_view(bool includeFrame=false);
bool can_close(bool shutdown);
void shutdown();
};
} // namespace freescan

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,27 @@
#pragma once
#include "common.hpp"
#include "pipe_rpc.hpp"
namespace freescan {
class Supervisor {
struct Impl;
std::shared_ptr<Impl> impl_;
public:
Supervisor(fs::path dataRoot, Json config, bool simulated = false);
~Supervisor();
void start();
void start_auto_connection();
void pause_auto_connection();
bool stop();
Json status();
uint64_t command_generation() const;
Json execute(const std::string &action, const Json &body, uint64_t expectedGeneration = UINT64_MAX);
Json recover(const Json &body);
Json query(const std::string &action, const Json &args);
std::shared_ptr<const FrameSnapshot> frame();
Json metrics();
};
Json load_configuration(const fs::path &dataRoot);
int run_worker(const fs::path &root, const Json &config, const std::wstring &pipe, DWORD parentPid,
uint64_t parentStarted, bool simulated);
} // namespace freescan

View File

@ -0,0 +1,204 @@
#include "../src/device_battery.hpp"
#include <iostream>
#include <limits>
// OFFLINE ONLY: these are synthetic callback messages with a controlled clock.
// No scanner service, vendor DLL, SDK connection or historical log is used.
using freescan::Json;
using freescan::detail::DeviceBatteryCache;
namespace {
size_t passed = 0;
constexpr int64_t now = 1700000000000;
void check(bool condition, const std::string &message) {
if (!condition)
throw std::runtime_error(message);
++passed;
}
Json message() {
return {{"cmd", "sdkDeviceStatus"}, {"type", "information"}};
}
Json scanner(const Json &value) {
auto result = message();
result["scannerBattery"] = value;
return result;
}
Json tracker(const Json &value, const Json &index) {
auto result = message();
result["trakBattery"] = value;
result["index"] = index;
return result;
}
const Json &channel(const Json &snapshot, const Json &index) {
for (const auto &item : snapshot.at("tracker").at("channels"))
if (item.at("index") == index)
return item;
throw std::runtime_error("Missing tracker channel " + index.dump());
}
void unavailable(const Json &reading, bool fresh, const std::string &label) {
check(reading.at("percent").is_null(), label + ": no percentage is invented.");
check(reading.at("available") == false, label + ": unavailable is explicit.");
check(reading.at("fresh") == fresh, label + ": freshness is independent of a valid percentage.");
}
void defaults_and_filtering() {
DeviceBatteryCache cache;
auto initial = cache.snapshot(false, now);
check(initial.at("source") == "sdkDeviceStatus", "The reading source names the actual SDK message.");
check(initial.at("freshnessLimitMs") == 30000 && DeviceBatteryCache::freshnessLimitMs == 30000,
"The documented freshness window is thirty seconds.");
unavailable(initial.at("scanner"), false, "Never-received scanner");
check(initial.at("scanner").at("rawValue").is_null() &&
initial.at("scanner").at("updatedUtc").is_null(),
"An empty cache has no fabricated SDK timestamp or raw value.");
check(initial.at("tracker").at("channels").empty(), "No tracker channel exists before an SDK report.");
for (const auto &ignored : std::vector<Json>{nullptr, Json::array(), "text", 17, Json::object(),
{{"cmd", "other"}, {"type", "information"}, {"scannerBattery", 66}},
{{"cmd", "sdkDeviceStatus"}, {"type", "request"}, {"scannerBattery", 66}},
{{"cmd", "sdkDeviceStatus"}, {"scannerBattery", 66}},
{{"cmd", 1}, {"type", "information"}, {"scannerBattery", 66}},
message()}) {
check(!cache.update(ignored, now), "Only a device-status information message with a battery field updates.");
check(cache.snapshot(false, now) == initial, "Ignored messages preserve the cache.");
}
}
void values_and_freshness() {
DeviceBatteryCache cache;
for (const auto &value : std::vector<Json>{0, "0", 100, "100", "0017", "-0", 66, "66"}) {
check(cache.update(scanner(value), now), "Integer and strict integer-string reports are accepted.");
const int expected = value.is_string() ? std::stoi(value.get<std::string>()) : value.get<int>();
const auto result = cache.snapshot(true, now).at("scanner");
check(result.at("percent") == expected && result.at("rawValue") == expected &&
result.at("available") == true && result.at("fresh") == true,
"Zero through one hundred are valid battery percentages, including zero.");
check(result.at("updatedUtc") == freescan::utc_from_ms(now), "Report time uses the supplied clock.");
}
cache.update(scanner(66), now);
check(cache.snapshot(true, now + 30000).at("scanner").at("percent") == 66,
"A reading exactly at the freshness boundary remains available.");
const auto stale = cache.snapshot(true, now + 30001).at("scanner");
unavailable(stale, false, "Expired scanner");
check(stale.at("rawValue") == 66 && stale.at("updatedUtc") == freescan::utc_from_ms(now),
"Expired readings retain diagnostic raw data and their original timestamp.");
unavailable(cache.snapshot(true, now - 1).at("scanner"), false, "Clock before report");
const auto offline = cache.snapshot(false, now).at("scanner");
unavailable(offline, false, "Inactive SDK session");
check(offline.at("rawValue") == 66, "Inactive snapshots retain raw diagnostics without exposing current percent.");
for (const auto &value : std::vector<Json>{-1, "-1", -10, 101, "101",
(std::numeric_limits<int>::min)(),
(std::numeric_limits<int>::max)(),
"-2147483648", "2147483647"}) {
cache.update(scanner(value), now);
const auto result = cache.snapshot(true, now).at("scanner");
unavailable(result, true, "Unknown or out-of-range battery report");
const auto expected = value.is_string() ? std::stoll(value.get<std::string>()) : value.get<int64_t>();
check(result.at("rawValue") == expected, "Out-of-range integer reports preserve their exact raw value.");
}
for (const auto &invalid : std::vector<Json>{nullptr, true, false, 17.0, 17.5, "", " ", " 17", "17 ",
"+17", "17.0", "17%", "1e2", "--1", "-", "0x11",
"2147483648", "-2147483649", "9223372036854775808", "-9223372036854775809",
(std::numeric_limits<int64_t>::max)(),
(std::numeric_limits<int64_t>::min)(),
(std::numeric_limits<uint64_t>::max)(), Json::object(), Json::array()}) {
cache.update(scanner(66), now);
check(cache.update(scanner(invalid), now + 1), "An invalid received field invalidates the previous reading.");
const auto result = cache.snapshot(true, now + 1).at("scanner");
unavailable(result, true, "Malformed battery report");
check(result.at("rawValue").is_null(), "Malformed input cannot leave a previous valid raw value.");
check(result.at("updatedUtc") == freescan::utc_from_ms(now + 1),
"Malformed but received reports still update the diagnostic report time.");
}
}
void independent_devices_and_channels() {
DeviceBatteryCache cache;
check(cache.update(scanner("66"), now), "The scanner report is accepted.");
check(cache.update(tracker("25", "000"), now + 1), "A tracker string index is accepted.");
check(cache.update(tracker(75, 1), now + 2), "A tracker integer index is accepted.");
auto result = cache.snapshot(true, now + 2);
check(result.at("scanner").at("percent") == 66 &&
result.at("scanner").at("updatedUtc") == freescan::utc_from_ms(now),
"Tracker messages do not overwrite the scanner reading or its timestamp.");
check(result.at("tracker").at("channels").size() == 2, "Different tracker indices remain separate.");
check(channel(result, "0").at("percent") == 25 && channel(result, "1").at("percent") == 75,
"Tracker indices zero and one retain their own battery percentages.");
cache.update(tracker(-1, 0), now + 3);
result = cache.snapshot(true, now + 3);
unavailable(channel(result, "0"), true, "Unknown tracker channel zero");
check(channel(result, "0").at("rawValue") == -1 && channel(result, "1").at("percent") == 75,
"An unknown channel does not erase another tracker channel.");
auto noIndex = message();
noIndex["trakBattery"] = "40";
cache.update(noIndex, now + 4);
result = cache.snapshot(true, now + 4);
check(channel(result, nullptr).at("percent") == 40 && result.at("tracker").at("channels").size() == 3,
"An omitted index is retained as a distinct null-index reading.");
cache.update(tracker("41", nullptr), now + 4);
result = cache.snapshot(true, now + 4);
check(channel(result, nullptr).at("percent") == 41 && result.at("tracker").at("channels").size() == 3,
"An explicit null index updates the same unindexed tracker channel.");
for (const auto &invalid : std::vector<Json>{true, false, -1, 1.0, 1.5, "", "-1", "-0", "+1", " 1", "1 ",
"1.0", Json::array(), Json::object()}) {
auto update = tracker(99, invalid);
check(!cache.update(update, now + 5), "An invalid explicit tracker index is ignored.");
check(cache.snapshot(true, now + 5).at("tracker") == result.at("tracker"),
"Invalid indices cannot overwrite or invent a tracker channel.");
update["scannerBattery"] = 55;
check(cache.update(update, now + 5), "An invalid tracker index does not reject an independent scanner field.");
check(cache.snapshot(true, now + 5).at("scanner").at("percent") == 55,
"A combined report still updates the scanner with an invalid tracker index.");
}
cache.update(scanner(12), now + 6);
check(cache.snapshot(true, now + 6).at("tracker") == result.at("tracker"),
"Scanner-only reports preserve all tracker readings and timestamps.");
const auto expired = cache.snapshot(true, now + 30003);
check(expired.at("scanner").at("percent") == 12, "A newer scanner report has its own freshness deadline.");
unavailable(channel(expired, "0"), true, "Channel zero exactly at its freshness boundary");
unavailable(channel(expired, "1"), false, "Older tracker channel expires independently");
check(channel(expired, nullptr).at("percent") == 41, "A newer unindexed tracker report remains fresh.");
}
void channel_limit_and_session_reset() {
DeviceBatteryCache cache;
for (int i = 0; i < 16; ++i)
check(cache.update(tracker(i, i), now), "Each of the first sixteen tracker channels is accepted.");
check(cache.snapshot(true, now).at("tracker").at("channels").size() == 16,
"The tracker cache reaches its documented bounded channel count.");
check(!cache.update(tracker(88, "16"), now + 1), "A seventeenth distinct channel is ignored.");
check(cache.snapshot(true, now + 1).at("tracker").at("channels").size() == 16,
"Untrusted indices cannot grow the channel cache without bound.");
check(cache.update(tracker(88, "0001"), now + 1), "Existing normalized indices update even at capacity.");
check(channel(cache.snapshot(true, now + 1), "1").at("percent") == 88,
"Normalization prevents duplicate channels for integer and padded string indices.");
auto combined = tracker(77, "17");
combined["scannerBattery"] = 33;
cache.update(combined, now + 2);
check(cache.snapshot(true, now + 2).at("scanner").at("percent") == 33,
"A full tracker cache cannot block the scanner battery update.");
cache.clear();
auto cleared = cache.snapshot(true, now + 2);
unavailable(cleared.at("scanner"), false, "Cleared SDK session");
check(cleared.at("scanner").at("rawValue").is_null() &&
cleared.at("scanner").at("updatedUtc").is_null() &&
cleared.at("tracker").at("channels").empty(),
"Session clearing drops readings, channels and report times.");
check(cache.update(tracker(10, "16"), now + 3), "A new session starts with an empty channel capacity.");
}
void no_vendor_dll() {
check(GetModuleHandleW(L"SDKCWrapper.dll") == nullptr &&
GetModuleHandleW(L"FreeScanNativeBridge.dll") == nullptr,
"Battery cache tests must never load vendor SDK or bridge DLLs.");
}
} // namespace
int main() {
try {
no_vendor_dll();
defaults_and_filtering();
values_and_freshness();
independent_devices_and_channels();
channel_limit_and_session_reset();
no_vendor_dll();
std::cout << "OFFLINE_TEST_FIXTURE: C++ battery tests passed: " << passed
<< "; synthetic callbacks only, no SDK, device or HTTP listener.\n";
return 0;
} catch (const std::exception &error) {
std::cerr << "FAIL (OFFLINE ONLY): " << error.what() << "\n";
return 1;
}
}

View File

@ -0,0 +1,214 @@
#include "../src/calibration_files.hpp"
#include <iostream>
// OFFLINE ONLY: every file belongs to a newly created temporary fixture.
// These tests never inspect an installed SDK, connect a device or bind HTTP.
using freescan::Json;
namespace fs = std::filesystem;
using freescan::detail::snapshot_calibration_files;
namespace {
size_t passed = 0;
void check(bool condition, const std::string &message) {
if (!condition)
throw std::runtime_error(message);
++passed;
}
struct Fixture {
fs::path parent, directory;
const std::wstring prefix = L"freescan_calibration_files_offline_";
Fixture() {
parent = fs::canonical(fs::temp_directory_path());
directory = parent / (prefix + freescan::wide(freescan::new_id()));
if (!fs::create_directory(directory))
throw std::runtime_error("Cannot create a unique calibration-file fixture.");
}
Fixture(const Fixture &) = delete;
Fixture &operator=(const Fixture &) = delete;
~Fixture() {
std::error_code error;
const auto absolute = fs::weakly_canonical(directory, error);
// Never recursively delete a path until its absolute parent and unique
// test prefix have both been checked against the original fixture.
if (error || !absolute.is_absolute() || absolute.parent_path() != parent ||
absolute.filename().wstring().rfind(prefix, 0) != 0 || absolute != directory) {
std::cerr << "Refusing cleanup of an unverified fixture path.\n";
return;
}
fs::remove_all(absolute, error);
if (error)
std::cerr << "Calibration-file fixture cleanup failed: " << error.message() << "\n";
}
fs::path write(const std::wstring &name, bool nonempty = true) const {
const auto path = directory / name;
std::ofstream output(path, std::ios::binary);
if (nonempty)
output << "synthetic calibration metadata fixture";
output.close();
if (!output)
throw std::runtime_error("Cannot write a calibration-file fixture.");
return path;
}
};
void set_modified_ticks(const fs::path &path, uint64_t fileTimeTicks) {
freescan::Handle file(CreateFileW(path.c_str(), FILE_WRITE_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr));
if (!file)
throw std::runtime_error("Cannot open a fixture to set its file time.");
ULARGE_INTEGER ticks{};
ticks.QuadPart = fileTimeTicks;
const FILETIME modified{ticks.LowPart, ticks.HighPart};
if (!SetFileTime(file.get(), nullptr, nullptr, &modified))
throw std::runtime_error("Cannot set a fixture file time.");
}
void set_modified(const fs::path &path, int64_t unixMs) {
set_modified_ticks(path, static_cast<uint64_t>(unixMs) * 10000ull + 116444736000000000ull);
}
void empty(const Json &value, const std::string &context) {
check(value.at("lastCalibrationSource") == "local_calibration_file_modified_time",
context + ": the source remains explicit when no file is available.");
check(value.at("lastCalibrationUtc").is_null(), context + ": no time is invented.");
check(value.at("calibrationFileTimes").is_array() && value.at("calibrationFileTimes").empty(),
context + ": file details are an empty array.");
}
const Json &entry(const Json &value, const std::string &name) {
for (const auto &item : value.at("calibrationFileTimes"))
if (item.at("fileName") == name)
return item;
throw std::runtime_error("Missing fixture metadata: " + name);
}
void no_vendor_dll() {
check(GetModuleHandleW(L"SDKCWrapper.dll") == nullptr &&
GetModuleHandleW(L"FreeScanNativeBridge.dll") == nullptr,
"Calibration-file tests never load the vendor SDK or bridge.");
}
void missing_and_empty_paths() {
Fixture fixture;
empty(snapshot_calibration_files(fs::path{}), "An unspecified path");
empty(snapshot_calibration_files(fixture.directory), "An empty directory");
empty(snapshot_calibration_files(fixture.directory / L"missing"), "A missing directory");
const auto ordinaryFile = fixture.write(L"ordinary.txt");
empty(snapshot_calibration_files(ordinaryFile), "A file used as the directory");
empty(snapshot_calibration_files(ordinaryFile / L"not-a-directory"), "A path below a regular file");
}
void exact_timestamps_and_all_components() {
Fixture fixture;
const auto tracker = fixture.write(L"aTrackCalibData.bin");
const auto scanner = fixture.write(L"0BScannerCalibData.bin");
const auto handEye = fixture.write(L"c04f0edf600db332HandEyeCalibData.bin");
set_modified(tracker, 1700000000123LL);
set_modified(scanner, 1700000001456LL);
set_modified(handEye, 1700000002789LL);
const auto value = snapshot_calibration_files(fixture.directory);
check(value.at("lastCalibrationSource") == "local_calibration_file_modified_time",
"The snapshot identifies local file metadata rather than hardware readback.");
check(value.at("lastCalibrationUtc") == "2023-11-14T22:13:22.789Z",
"The combined time is the newest component's exact UTC millisecond time.");
check(value.at("calibrationFileTimes").size() == 3, "All three calibration-file types are retained.");
const auto &trackerResult = entry(value, "aTrackCalibData.bin");
const auto &scannerResult = entry(value, "0BScannerCalibData.bin");
const auto &handEyeResult = entry(value, "c04f0edf600db332HandEyeCalibData.bin");
check(trackerResult.at("type") == "tracker" &&
trackerResult.at("modifiedUtc") == "2023-11-14T22:13:20.123Z",
"Tracker metadata uses UTC with the original milliseconds.");
check(scannerResult.at("type") == "scanner" &&
scannerResult.at("modifiedUtc") == "2023-11-14T22:13:21.456Z",
"Scanner metadata uses UTC with the original milliseconds.");
check(handEyeResult.at("type") == "handEye" &&
handEyeResult.at("modifiedUtc") == "2023-11-14T22:13:22.789Z",
"Hand-eye metadata uses UTC with the original milliseconds.");
std::vector<std::string> names;
for (const auto &item : value.at("calibrationFileTimes"))
names.push_back(item.at("fileName").get<std::string>());
check(std::is_sorted(names.begin(), names.end()), "File metadata has deterministic filename ordering.");
}
void multiple_devices_and_case_insensitive_names() {
Fixture fixture;
const auto first = fixture.write(L"1TrackCalibData.bin");
const auto second = fixture.write(L"abcdef01234567890123456789ABCDEFtRaCkCaLiBdAtA.BIN");
const auto scanner = fixture.write(L"ABCscannerCALIBdata.BiN");
const auto handEye = fixture.write(L"FeHaNdEyEcAlIbDaTa.bIN");
set_modified(first, 1700000000000LL);
set_modified(second, 1700000000999LL);
set_modified(scanner, 1700000000001LL);
set_modified(handEye, 1700000000002LL);
const auto value = snapshot_calibration_files(fixture.directory);
check(value.at("calibrationFileTimes").size() == 4,
"Multiple file prefixes of the same type are all retained without choosing a device.");
check(entry(value, "1TrackCalibData.bin").at("type") == "tracker" &&
entry(value, "abcdef01234567890123456789ABCDEFtRaCkCaLiBdAtA.BIN").at("type") == "tracker",
"Nonempty hexadecimal prefixes have no fixed length and suffix matching ignores case.");
check(entry(value, "ABCscannerCALIBdata.BiN").at("type") == "scanner" &&
entry(value, "FeHaNdEyEcAlIbDaTa.bIN").at("type") == "handEye",
"All accepted suffixes are case insensitive.");
check(value.at("lastCalibrationUtc") == "2023-11-14T22:13:20.999Z",
"A second device's newer file contributes to the directory-wide latest time.");
}
void filtering_and_live_file_changes() {
Fixture fixture;
const auto accepted = fixture.write(L"123HandEyeCalibData.bin");
set_modified(accepted, 1700000000123LL);
for (const auto &name : {L"123TrackCalibData.asc", L"123ScannerCalibData.bin.bak",
L"backup123ScannerCalibData.bin", L"12_3TrackCalibData.bin",
L"12-3HandEyeCalibData.bin", L"TrackCalibData.bin",
L"xyzTrackCalibData.bin", L"123UnknownCalibData.bin"})
fixture.write(name);
fixture.write(L"123ScannerCalibData.bin", false);
fs::create_directory(fixture.directory / L"456TrackCalibData.bin");
fs::create_directory(fixture.directory / L"nested");
const auto nested = fixture.write(L"nested/789ScannerCalibData.bin");
set_modified(nested, 1800000000999LL);
auto value = snapshot_calibration_files(fixture.directory);
check(value.at("calibrationFileTimes").size() == 1,
"Empty files, geometry, backups, invalid prefixes, directories and nested files are excluded.");
check(value.at("lastCalibrationUtc") == "2023-11-14T22:13:20.123Z",
"Rejected newer files cannot change the latest calibration time.");
set_modified(accepted, 1700000004567LL);
value = snapshot_calibration_files(fixture.directory);
check(value.at("lastCalibrationUtc") == "2023-11-14T22:13:24.567Z" &&
entry(value, "123HandEyeCalibData.bin").at("modifiedUtc") == "2023-11-14T22:13:24.567Z",
"A subsequent snapshot reflects updated file metadata without restarting a service.");
check(fs::remove(accepted), "The accepted fixture file can be deleted.");
empty(snapshot_calibration_files(fixture.directory), "After deleting the final accepted file");
}
void timestamp_boundaries_and_truncation() {
Fixture fixture;
const auto epochFile = fixture.write(L"0TrackCalibData.bin");
const auto tooOld = fixture.write(L"1ScannerCalibData.bin");
const auto tooNew = fixture.write(L"2HandEyeCalibData.bin");
constexpr uint64_t epoch = 116444736000000000ull;
set_modified_ticks(epochFile, epoch);
set_modified_ticks(tooOld, epoch - 1);
set_modified(tooNew, 253402300800000LL); // 10000-01-01 UTC is outside RFC3339's four-digit year.
auto value = snapshot_calibration_files(fixture.directory);
check(value.at("calibrationFileTimes").size() == 1 &&
value.at("lastCalibrationUtc") == "1970-01-01T00:00:00.000Z",
"The Unix epoch is accepted, while pre-epoch and five-digit-year timestamps are excluded.");
check(entry(value, "0TrackCalibData.bin").at("modifiedUtc") == "1970-01-01T00:00:00.000Z",
"An exact epoch timestamp is a real value rather than a missing-time sentinel.");
set_modified_ticks(epochFile, epoch + 1700000000123ull * 10000ull + 9999ull);
value = snapshot_calibration_files(fixture.directory);
check(value.at("lastCalibrationUtc") == "2023-11-14T22:13:20.123Z" &&
entry(value, "0TrackCalibData.bin").at("modifiedUtc") == "2023-11-14T22:13:20.123Z",
"Sub-millisecond FILETIME precision is truncated rather than rounded or shifted by a clock epoch.");
check(fs::remove(epochFile), "The valid boundary fixture can be deleted.");
empty(snapshot_calibration_files(fixture.directory), "When only invalid-time files remain");
}
} // namespace
int main() {
try {
no_vendor_dll();
missing_and_empty_paths();
exact_timestamps_and_all_components();
multiple_devices_and_case_insensitive_names();
filtering_and_live_file_changes();
timestamp_boundaries_and_truncation();
no_vendor_dll();
std::cout << "OFFLINE_TEST_FIXTURE: C++ calibration-file tests passed: " << passed
<< "; temporary files only, no installed SDK, device or HTTP listener.\n";
return 0;
} catch (const std::exception &error) {
std::cerr << "FAIL (OFFLINE ONLY): " << error.what() << "\n";
return 1;
}
}

View File

@ -0,0 +1,66 @@
#include "../src/calibration_recovery.hpp"
#include <iostream>
using freescan::Json;
namespace {
int passed = 0;
void check(bool value, const char *message) {
if (!value)
throw std::runtime_error(message);
++passed;
}
const std::string reviewed = "0123456789abcdef0123456789abcdef";
Json idle() {
return {{"sessionId", reviewed}, {"projectReady", false}, {"scanning", false},
{"calibrationSession", true}, {"busy", false}, {"restartRequired", false}};
}
void rejected(const Json &info, const std::string &session, bool force, const char *code) {
bool denied = false;
try { freescan::detail::validate_calibration_recovery(info, session, force); }
catch (const freescan::ApiError &error) {
denied = error.code == code;
}
check(denied, code);
}
} // namespace
int main() {
try {
auto info = idle();
freescan::detail::validate_calibration_recovery(info, reviewed, false);
check(true, "Idle calibration is eligible for normal release.");
info["busy"] = true;
rejected(info, reviewed, false, "recovery_requires_force");
freescan::detail::validate_calibration_recovery(info, reviewed, true);
check(true, "Explicit force admits busy calibration.");
info["restartRequired"] = true;
freescan::detail::validate_calibration_recovery(info, reviewed, true);
check(true, "Timeout latch does not trap the recovery path.");
rejected(info, "ffffffffffffffffffffffffffffffff", true, "session_changed");
info["projectReady"] = true;
rejected(info, reviewed, true, "project_protected");
info = idle(); info["scanning"] = true;
rejected(info, reviewed, true, "project_protected");
info = idle(); info["calibrationSession"] = false;
rejected(info, reviewed, true, "calibration_not_active");
info = idle(); info.erase("projectReady");
rejected(info, reviewed, true, "project_protected");
info = idle(); info.erase("scanning");
rejected(info, reviewed, true, "project_protected");
info = idle(); info.erase("calibrationSession");
rejected(info, reviewed, true, "calibration_not_active");
info = idle(); info.erase("busy");
rejected(info, reviewed, false, "recovery_requires_force");
info = idle(); info["sessionId"] = nullptr;
rejected(info, reviewed, true, "session_changed");
rejected(Json::object(), reviewed, true, "session_changed");
rejected(Json::array(), reviewed, true, "session_changed");
check(GetModuleHandleW(L"SDKCWrapper.dll") == nullptr &&
GetModuleHandleW(L"FreeScanNativeBridge.dll") == nullptr,
"Safety tests never load the SDK or bridge.");
std::cout << "Calibration recovery safety checks passed: " << passed << "\n";
return 0;
} catch (const std::exception &error) {
std::cerr << "Calibration recovery safety test failed: " << error.what() << "\n";
return 1;
}
}

View File

@ -0,0 +1,428 @@
#include "../src/contracts.hpp"
#include <cmath>
#include <iostream>
#include <limits>
using freescan::ApiError;
using freescan::Json;
namespace api = freescan::contracts;
namespace {
size_t passed = 0;
const std::string a = "11111111-1111-4111-8111-111111111111", b = "22222222-2222-4222-8222-222222222222";
void check(bool condition, const std::string &label) {
if (!condition)
throw std::runtime_error(label);
++passed;
}
void ok(const std::string &action, const Json &body, const std::string &label = "") {
try {
api::validate(action, body);
++passed;
} catch (const std::exception &error) {
throw std::runtime_error("Unexpected rejection " + action + " " + label + ": " + error.what());
}
}
void bad(const std::string &action, const Json &body, int status = 400,
const std::string &code = "invalid_parameter") {
try {
api::validate(action, body);
} catch (const ApiError &error) {
check(error.status == status && error.code == code, "Wrong error for " + action + ": " + error.code);
return;
}
throw std::runtime_error("Unexpected acceptance " + action + " " + body.dump());
}
Json triplets(size_t count) {
Json result = Json::array();
for (size_t i = 0; i < count; ++i)
result.push_back({0, 1, -1});
return result;
}
Json identifiers(size_t count) {
Json result = Json::array();
for (size_t i = 0; i < count; ++i)
result.push_back(static_cast<int64_t>(i));
return result;
}
Json repeated(size_t count, const Json &value) {
Json result = Json::array();
for (size_t i = 0; i < count; ++i)
result.push_back(value);
return result;
}
Json alignment(const char *mode = "featureAuto") {
return {{"action", "apply"}, {"mode", mode}, {"fixedProjectUuid", a}, {"movingProjectUuid", b}};
}
Json deletion() {
return {{"projectUuid", a}, {"markerIds", Json::array({0})}, {"confirm", true}};
}
Json clip() {
return {{"center", {0, 0, 0}}, {"normal", {0, 1, 0}}, {"confirm", true}};
}
void routes_and_all_actions() {
check(api::routes().size() == 45, "All original routes plus independent calibration window metadata/image/stream must exist.");
check(api::export_formats() == Json({"ASCW", "ASCS", "STL", "OBJ", "PLY", "P3", "3MF", "TXT", "CSV",
"ASCG", "TGF", "STP", "IGS", "ASC"}),
"The exact 14 vendor format names/order must remain stable.");
std::map<std::string, Json> actions = {{"connect", Json::object()},
{"createProject", Json::object()},
{"startScan", Json::object()},
{"stopScan", Json::object()},
{"setScanType", {{"scanType", "mesh"}}},
{"importFramework", {{"fileIds", {std::string(32, 'a')}}, {"confirm", true}}},
{"optimizeFramework", Json::object()},
{"disconnect", {{"confirm", true}}},
{"reconnect", {{"confirm", true}}},
{"startPreview", Json::object()},
{"stopPreview", Json::object()},
{"parameters", {{"viewLock", false}}},
{"mesh", Json::object()},
{"meshConfirm", Json::object()},
{"meshUndo", Json::object()},
{"align", {{"action", "enter"}}},
{"edit", deletion()},
{"clipPlane", clip()},
{"export", {{"formats", {"STL"}}}},
{"dataSnapshot", Json::object()},
{"calibrationEnter", Json::object()},
{"calibrationSetMode", {{"mode", 0}}},
{"calibrationSetTrakType", {{"trakType", 3}, {"confirm", true}}},
{"calibrationStart", {{"confirm", true}}},
{"calibrationStartSystem", {{"confirm", true}}},
{"calibrationSetFree", {{"enabled", false}, {"confirm", true}}},
{"calibrationCapturePose", {{"confirm", true}}},
{"calibrationCompute", {{"confirm", true}}},
{"calibrationSetAdvanced", {{"enabled", true}, {"confirm", true}}},
{"calibrationApplyLast", {{"mode", 3}, {"confirm", true}}},
{"calibrationRecover", {{"confirm", true}, {"expectedSessionId", std::string(32, 'a')}}}};
std::set<std::string> seen;
for (const auto &route : api::routes()) {
const auto line = route.get<std::string>();
if (line.rfind("POST ", 0) != 0)
continue;
if (line == "POST /api/v1/framework/files")
continue; // Synchronous upload is handled by the HTTP layer, not the SDK worker.
const auto action = api::action_for_path(line.substr(5));
check(!action.empty() && seen.insert(action).second,
"POST routes must resolve to distinct registered actions.");
ok(action, actions.at(action));
auto unknown = actions.at(action);
unknown["unknownField"] = true;
bad(action, unknown, 400, "unknown_parameter");
check(api::maximum_body_bytes(action) == (action == "align" || action == "edit" ? 1048576u : 16384u),
"Payload limit mismatch.");
}
check(seen.size() == actions.size(), "Every declared action needs a working exact route.");
for (const auto *route :
{"/api/v1/device/Connect", "/api/v1/projects/", "/api/v1/align/anything",
"/api/v1/calibration/invalid", "/api/v1/projects?name=test", "/api/v1/files/../../file"})
check(api::action_for_path(route).empty(), "Unknown paths cannot acquire a mutation action.");
bad("unknown", Json::object(), 404, "unknown_action");
bad("calibrationUnknown", Json::object(), 404, "unknown_action");
bad("mesh", nullptr);
bad("mesh", Json::array());
bad("mesh", true);
bad("mesh", "text");
}
void primitive_types_and_names() {
for (const Json value : {Json(true), Json(false), Json(3.0), Json("3"), Json(nullptr),
Json(int64_t(2147483648)), Json(uint64_t(18446744073709551615ull))})
bad("connect", {{"deviceType", value}});
ok("connect", {{"deviceType", 3}});
ok("connect", {{"deviceType", 4}});
bad("connect", {{"deviceType", 2}});
ok("createProject", {{"mode", "laser"}, {"name", u8"扫描_Αβ١2-项目"}});
ok("createProject", {{"name", u8"DžȻ中文"}});
std::string forty;
for (size_t i = 0; i < 40; ++i)
forty += u8"测";
ok("createProject", {{"name", forty}});
bad("createProject", {{"name", forty + u8"测"}});
for (const auto *value :
{"", "../scan", "scan/result", "scan\\result", "A B", "A\nB", u8"é", u8"Ⅷ", u8"𠀀", u8"📷",
"a\xE2\x80\xAE"
"b"})
bad("createProject", {{"name", value}});
bad("createProject", {{"name", std::string(1, static_cast<char>(0xFF))}});
bad("createProject", {{"name", nullptr}});
bad("createProject", {{"mode", "TRAK"}});
bad("createProject", {{"mode", true}});
bad("export", {{"name", "../out"}, {"formats", {"PLY"}}});
bad("disconnect", Json::object(), 400, "confirmation_required");
bad("disconnect", {{"confirm", false}}, 400, "confirmation_required");
bad("disconnect", {{"confirm", 1}}, 400, "confirmation_required");
ok("disconnect", {{"confirm", true},
{"discardProject", false},
{"expectedProjectId", nullptr},
{"expectedSessionId", nullptr}});
ok("reconnect", {{"confirm", true},
{"discardProject", true},
{"expectedProjectId", u8"工程_١"},
{"expectedSessionId", std::string(32, 'A')},
{"deviceType", 4}});
bad("disconnect", {{"confirm", true}, {"discardProject", 0}});
bad("disconnect", {{"confirm", true}, {"expectedProjectId", "../scan"}});
bad("disconnect", {{"confirm", true}, {"expectedProjectId", std::string(161, 'a')}});
bad("disconnect", {{"confirm", true}, {"expectedSessionId", a}});
bad("disconnect", {{"confirm", true}, {"expectedSessionId", std::string(32, 'g')}});
bad("reconnect", {{"confirm", true}, {"deviceType", 3.0}});
ok("disconnect", {{"confirm", true}, {"expectedProjectId", std::string(160, 'a')}});
}
void parameters_mesh_and_exports() {
ok("parameters", {{"pointDistance", 0.001},
{"brightness", 0},
{"lightSourceMode", 0},
{"scanFrameRate", 1},
{"highSpeedMode", false},
{"addMarkerMode", true},
{"viewLock", false},
{"localEnlargedView", true},
{"qualityColor", false},
{"strongLight", true},
{"preScanMode", false},
{"markerDiameters", {1, 50}}});
ok("parameters", {{"pointDistance", 10},
{"brightness", 17},
{"lightSourceMode", 2},
{"scanFrameRate", 120},
{"markerDiameters", repeated(16, 1)}});
bad("parameters", Json::object());
bad("parameters", {{"brightness", 1.0}});
bad("parameters", {{"brightness", true}});
bad("parameters", {{"brightness", 18}});
bad("parameters", {{"lightSourceMode", 3}});
bad("parameters", {{"scanFrameRate", 0}});
bad("parameters", {{"scanFrameRate", 121}});
bad("parameters", {{"pointDistance", 0.000999}});
bad("parameters", {{"pointDistance", 10.001}});
for (const double number :
{std::numeric_limits<double>::infinity(), -std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::quiet_NaN()})
bad("parameters", {{"pointDistance", number}});
for (const auto *key : {"highSpeedMode", "addMarkerMode", "viewLock", "localEnlargedView", "qualityColor",
"strongLight", "preScanMode"})
bad("parameters", {{key, 0}});
for (const auto *key :
{"frameworkBrightness", "cloudShowMode", "scanAlignType", "workingDistance", "workingRange"})
bad("parameters", {{key, 1}}, 422, "unsupported_for_trak");
for (const Json values : {Json::array(), Json::array({0}), Json::array({51}), Json::array({1.0}),
Json::array({true}), repeated(17, 1), Json(nullptr)})
bad("parameters", {{"markerDiameters", values}});
ok("mesh", {{"filterLevel", 0},
{"smoothLevel", 3},
{"removeSmallFloatingParts", 100000000},
{"cutMeshEdgeOptimization", false},
{"cutMeshEdgeValue", 1000},
{"holeOptimization", true},
{"boundaryOptimization", false},
{"maxTriangles", nullptr},
{"fillSmallHole", nullptr},
{"removeSpikes", false},
{"fillMarkerHoles", true},
{"rememberChoice", false}});
ok("mesh", {{"maxTriangles", 100000000}, {"fillSmallHole", 1000000}});
for (const auto *key : {"meshType", "qualityType", "simplificationByCurvature", "deleteNeighborhoodAreas",
"cornerOptimization"})
bad("mesh", {{key, 0}}, 422, "unsupported_for_trak");
bad("mesh", {{"filterLevel", 4}});
bad("mesh", {{"smoothLevel", -1}});
bad("mesh", {{"removeSmallFloatingParts", 100000001}});
bad("mesh", {{"cutMeshEdgeValue", 1000.1}});
bad("mesh", {{"maxTriangles", 0}});
bad("mesh", {{"fillSmallHole", 1000001}});
bad("mesh", {{"maxTriangles", 1.0}});
bad("mesh", {{"removeSpikes", 1}});
ok("export", {{"formats", api::export_formats()}});
bad("export", Json::object());
bad("export", {{"formats", Json::array()}});
bad("export", {{"formats", {"STL", "STL"}}});
bad("export", {{"formats", {"MAT"}}});
bad("export", {{"formats", {"stl"}}});
bad("export", {{"formats", {true}}});
ok("dataSnapshot", {{"maxPoints", 1000000}, {"include", {"points", "markers", "meshes"}}});
ok("dataSnapshot", {{"pauseAcquisition", true}});
ok("dataSnapshot", {{"pauseAcquisition", false}});
for (const Json value : {Json(0), Json(1), Json(1.0), Json("true"), Json("false"), Json(nullptr)})
bad("dataSnapshot", {{"pauseAcquisition", value}});
bad("dataSnapshot", {{"maxPoints", 0}});
bad("dataSnapshot", {{"maxPoints", 1000001}});
bad("dataSnapshot", {{"maxPoints", 1.0}});
bad("dataSnapshot", {{"maxPoints", true}});
for (const Json values : {Json::array(), Json::array({"points", "points"}), Json::array({"camera"}),
Json(nullptr), Json("points")})
bad("dataSnapshot", {{"include", values}});
}
void guid_alignment_edit_and_clip() {
const std::vector<std::string> guids = {
a,
"11111111111141118111111111111111",
"{11111111-1111-4111-8111-111111111111}",
"(11111111-1111-4111-8111-111111111111)",
"{0x11111111,0x1111,0x4111,{0x81,0x11,0x11,0x11,0x11,0x11,0x11,0x11}}",
u8" 11111111-1111-4111-8111-111111111111 "};
for (const auto &guid : guids) {
check(api::normalize_guid(guid) == a, "SDK GUID normalization must match static alias comparison.");
auto value = alignment();
value["fixedProjectUuid"] = guid;
ok("align", value);
value["movingProjectUuid"] = a;
bad("align", value);
}
check(api::normalize_guid("{0X1,0X2,0X3,{0X4,0X5,0X6,0X7,0X8,0X9,0XA,0XB}}") ==
"00000001-0002-0003-0405-060708090a0b",
"Short uppercase X components normalize like Guid.TryParse.");
check(api::normalize_guid(u8"{0x1, 0x2,0x3,{0x4,0x5,0x6,0x7,0x8,0x9,0xa,0xb}}") ==
"00000001-0002-0003-0405-060708090a0b",
"X form accepts Unicode whitespace like Guid.TryParse.");
auto overflow = alignment();
overflow["fixedProjectUuid"] = "{0x100000000,0x2,0x3,{0x4,0x5,0x6,0x7,0x8,0x9,0xa,0xb}}";
bad("align", overflow);
for (const auto *guid :
{"00000000-0000-0000-0000-000000000000", "00000000000000000000000000000000",
"{00000000-0000-0000-0000-000000000000}", "{0x0,0x0,0x0,{0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0}}",
"{11111111111141118111111111111111}", "not-a-guid"}) {
auto value = alignment();
value["fixedProjectUuid"] = guid;
bad("align", value);
}
auto manual = alignment("featureManual");
manual["fixedPoints"] = triplets(3);
manual["movingPoints"] = triplets(3);
ok("align", manual);
manual["movingPoints"] = triplets(2);
bad("align", manual);
manual["movingPoints"] = triplets(257);
bad("align", manual);
manual["fixedPoints"] = triplets(256);
manual["movingPoints"] = triplets(256);
ok("align", manual);
manual["fixedPoints"][0][0] = 100000001;
bad("align", manual);
manual["fixedPoints"][0][0] = true;
bad("align", manual);
manual = alignment("markerManual");
manual["fixedMarkerIds"] = identifiers(3);
manual["movingMarkerIds"] = identifiers(3);
manual["fixedMarkerPoints"] = triplets(3);
manual["movingMarkerPoints"] = triplets(3);
ok("align", manual);
manual["movingMarkerIds"][0] = 9223372036854775807ll;
ok("align", manual);
manual["movingMarkerIds"][0] = uint64_t(9223372036854775808ull);
bad("align", manual);
manual["movingMarkerIds"][0] = 1.0;
bad("align", manual);
manual["movingMarkerIds"][0] = true;
bad("align", manual);
manual["movingMarkerIds"][0] = -1;
bad("align", manual);
bad("align", {{"action", "exit"}}, 400, "confirmation_required");
ok("align", {{"action", "exit"}, {"confirm", true}});
ok("align", {{"action", "cancel"}, {"confirm", false}});
bad("align", {{"action", "enter"}, {"mode", "featureAuto"}}, 400, "unknown_parameter");
auto value = deletion();
ok("edit", value);
value.erase("markerIds");
value["points"] = triplets(1);
bad("edit", value);
value["pointIds"] = identifiers(1);
bad("edit", value);
value["cloudUuid"] = b;
ok("edit", value);
value["normals"] = triplets(2);
bad("edit", value);
value["pointIds"] = identifiers(4096);
value["points"] = triplets(4096);
value["normals"] = triplets(4096);
ok("edit", value);
value["pointIds"] = identifiers(4097);
bad("edit", value);
value = deletion();
value["markerIds"] = Json::array({uint64_t(9223372036854775808ull)});
bad("edit", value);
value = clip();
ok("clipPlane", value);
value["deleteBelowMarkers"] = false;
ok("clipPlane", value);
value["deleteBelowPoints"] = false;
bad("clipPlane", value);
value["deleteBelowMarkers"] = true;
ok("clipPlane", value);
value = clip();
value["normal"] = {0, -0.0, 0};
bad("clipPlane", value);
value["normal"] = {0, 0};
bad("clipPlane", value);
value["normal"] = {true, 0, 0};
bad("clipPlane", value);
value["normal"] = {std::numeric_limits<double>::infinity(), 0, 0};
bad("clipPlane", value);
}
void calibration_limits() {
const Json recovery{{"confirm", true}, {"expectedSessionId", std::string(32, 'a')}};
ok("calibrationRecover", recovery);
auto request = recovery;
request["force"] = true;
ok("calibrationRecover", request);
request["force"] = false;
ok("calibrationRecover", request);
request["force"] = "true";
bad("calibrationRecover", request);
request = recovery;
request["confirm"] = false;
bad("calibrationRecover", request, 400, "confirmation_required");
request = recovery;
request.erase("expectedSessionId");
bad("calibrationRecover", request);
for (const Json value : {Json(nullptr), Json(1), Json(""), Json("../worker"), Json(std::string(31, 'a')), Json(std::string(32, 'z'))}) {
request = recovery;
request["expectedSessionId"] = value;
bad("calibrationRecover", request);
}
bad("calibrationEnter", {{"confirm", true}}, 400, "unknown_parameter");
bad("calibrationSetMode", Json::object());
for (const Json value : {Json(true), Json(1.0), Json(-1), Json(4), Json(nullptr), Json("1")})
bad("calibrationSetMode", {{"mode", value}});
bad("calibrationSetTrakType", {{"trakType", 3}}, 400, "confirmation_required");
bad("calibrationSetFree", {{"confirm", true}});
bad("calibrationSetAdvanced", {{"confirm", true}, {"enabled", 0}});
bad("calibrationApplyLast", {{"confirm", true}, {"mode", 4}});
bad("calibrationStartSystem", {{"confirm", false}}, 400, "confirmation_required");
}
void framework_limits() {
ok("setScanType", {{"scanType", "photogrammetry"}, {"device", "tracker"}, {"confirm", true}});
ok("setScanType", {{"scanType", "markers"}, {"device", "scanner"}, {"confirm", false}});
bad("setScanType", Json::object());
bad("setScanType", {{"scanType", "FRAME"}});
bad("setScanType", {{"scanType", 0}});
bad("setScanType", {{"scanType", "mesh"}, {"device", "TENOVA"}});
bad("setScanType", {{"scanType", "mesh"}, {"confirm", 1}});
const std::string id(32, 'a');
ok("importFramework", {{"fileIds", {id}}, {"confirm", true}});
bad("importFramework", {{"fileIds", {id}}}, 400, "confirmation_required");
bad("importFramework", {{"fileIds", {id}}, {"confirm", false}}, 400, "confirmation_required");
bad("importFramework", {{"fileIds", Json::array()}, {"confirm", true}});
bad("importFramework", {{"fileIds", {id, id}}, {"confirm", true}});
bad("importFramework", {{"fileIds", {std::string(32, 'A')}}, {"confirm", true}});
bad("importFramework", {{"fileIds", {"../outside.p3"}}, {"confirm", true}});
bad("importFramework", {{"fileIds", {true}}, {"confirm", true}});
bad("importFramework", {{"fileIds", repeated(9, id)}, {"confirm", true}});
bad("importFramework", {{"fileIds", {id}}, {"paths", {"C:/secret.p3"}}, {"confirm", true}},
400, "unknown_parameter");
}
} // namespace
int main() {
try {
routes_and_all_actions();
primitive_types_and_names();
parameters_mesh_and_exports();
guid_alignment_edit_and_clip();
calibration_limits();
framework_limits();
std::cout << "C++ contract tests passed: " << passed << "\n";
return 0;
} catch (const std::exception &error) {
std::cerr << "FAIL: " << error.what() << "\n";
return 1;
}
}

View File

@ -0,0 +1,110 @@
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { dirname, resolve, join } from 'node:path';
import { setTimeout as sleep } from 'node:timers/promises';
import { MjpegParser, boundaryFromContentType } from '../../FreeScanWeb/public/preview-pipeline.js';
// Explicit read-only real-device transport measurement. This file is outside
// *.test.mjs and sends GET requests only; no device action can be submitted.
const workspace = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
const settings = JSON.parse(await readFile(join(workspace, 'FreeScanViewer', 'api-settings.json'), 'utf8'));
const base = new URL(settings.prefix);
if (base.protocol !== 'http:' || base.hostname !== '127.0.0.1' || base.port !== '18888') throw new Error('Read-only real-device measurement requires the configured 127.0.0.1:18888 endpoint.');
const headers = { 'X-Api-Key': settings.apiKey };
const seconds = 10;
const round = value => Math.round(value * 100) / 100;
async function get(path) {
const response = await fetch(new URL(path, base), { headers, signal: AbortSignal.timeout(7000), cache: 'no-store' });
if (!response.ok) throw new Error(`Read-only GET ${path} returned HTTP ${response.status}`);
return response;
}
async function json(path) { return (await get(path)).json(); }
function summary(values) {
const sorted = values.filter(Number.isFinite).toSorted((a, b) => a - b);
if (!sorted.length) return { samples: 0, minimum: null, median: null, p95: null, maximum: null };
const middle = sorted.length >> 1;
return { samples: sorted.length, minimum: round(sorted[0]), median: round(sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2),
p95: round(sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * .95) - 1)]), maximum: round(sorted.at(-1)) };
}
function dimensions(jpeg) {
const bytes = Buffer.from(jpeg); if (bytes.readUInt16BE(0) !== 0xffd8) throw new Error('Live preview was not a JPEG.');
let offset = 2;
while (offset + 4 < bytes.length) {
if (bytes[offset++] !== 0xff) throw new Error('Invalid JPEG marker.');
while (bytes[offset] === 0xff) offset++;
const marker = bytes[offset++]; if (marker === 0xd9 || marker === 0xda) break;
if (marker === 0x01 || marker >= 0xd0 && marker <= 0xd7) continue;
const length = bytes.readUInt16BE(offset);
if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker)) return { width: bytes.readUInt16BE(offset + 5), height: bytes.readUInt16BE(offset + 3) };
if (length < 2) break; offset += length;
}
throw new Error('Live JPEG did not contain a SOF dimension marker.');
}
const [beforeStatus, beforeMetrics] = await Promise.all([json('api/v1/status'), json('api/v1/preview/metrics')]);
if (!beforeStatus.initialized || !beforeStatus.projectReady || !beforeStatus.previewEnabled || beforeStatus.simulated) throw new Error('A real initialized project with preview enabled is required; no control action was sent.');
const controller = new AbortController();
const response = await fetch(new URL('api/v1/preview/stream', base), { headers, signal: controller.signal, cache: 'no-store' });
if (!response.ok) throw new Error(`Read-only live MJPEG returned HTTP ${response.status}`);
const arrived = [], ages = [], sizes = [], sequences = [], imageHeaderAges = [], headerFailures = [];
const encodedDimensions = new Set(), sourceDimensions = new Set();
const startedUtc = new Date().toISOString(), startedAt = performance.now();
const parser = new MjpegParser(boundaryFromContentType(response.headers.get('content-type') || ''), frame => {
arrived.push(performance.now()); sizes.push(frame.bytes.byteLength); sequences.push(Number(frame.sequence));
ages.push(Date.now() - Date.parse(frame.capturedUtc));
const size = dimensions(frame.bytes); encodedDimensions.add(`${size.width}x${size.height}`);
sourceDimensions.add(`${frame.sourceWidth}x${frame.sourceHeight}`);
});
const sampler = (async () => {
while (!controller.signal.aborted) {
try {
const image = await fetch(new URL('api/v1/preview/image', base), { headers, signal: controller.signal, cache: 'no-store' });
if (!image.ok) throw new Error(`Image HTTP ${image.status}`);
imageHeaderAges.push(Number(image.headers.get('x-frame-age-ms')));
await image.arrayBuffer();
} catch (error) { if (!controller.signal.aborted) headerFailures.push(error.message); }
try { await sleep(500, undefined, { signal: controller.signal }); } catch { break; }
}
})();
const timer = setTimeout(() => controller.abort(), seconds * 1000);
const reader = response.body.getReader();
try {
for (;;) { const { done, value } = await reader.read(); if (done) break; parser.push(value); }
} catch (error) { if (!controller.signal.aborted) throw error; }
finally { clearTimeout(timer); controller.abort(); await reader.cancel().catch(() => {}); await sampler; }
const measuredMs = performance.now() - startedAt;
const [afterStatus, afterMetrics] = await Promise.all([json('api/v1/status'), json('api/v1/preview/metrics')]);
const counterNames = ['offeredFrames', 'encodedFrames', 'replacedFrames', 'throttledFrames', 'encodingFailures'];
const counterDelta = Object.fromEntries(counterNames.filter(name => Number.isFinite(beforeMetrics[name]) && Number.isFinite(afterMetrics[name])).map(name => [name, afterMetrics[name] - beforeMetrics[name]]));
const report = {
mode: 'real_device_read_only_transport', implementation: afterStatus.implementation || afterMetrics.implementation || 'C++17',
endpoint: base.href,
startedUtc, finishedUtc: new Date().toISOString(), requestedSeconds: seconds, measuredMs: round(measuredMs),
frames: arrived.length,
framesPerWindowSecond: round(arrived.length * 1000 / measuredMs),
observedIntervalFps: arrived.length > 1 ? round((arrived.length - 1) * 1000 / (arrived.at(-1) - arrived[0])) : 0,
receivedFrameAgeMs: summary(ages),
xFrameAgeHeaderMs: summary(imageHeaderAges),
streamInitialXFrameAgeMs: Number(response.headers.get('x-frame-age-ms')),
xFrameAgeSampling: 'GET preview/image at 2 Hz; real X-Frame-Age-Ms header, independent of MJPEG frame arrival age',
jpegBytes: summary(sizes), encodedDimensions: [...encodedDimensions], sourceDimensions: [...sourceDimensions],
sequence: { first: sequences[0] ?? null, last: sequences.at(-1) ?? null, uniqueFrames: new Set(sequences).size, monotonic: sequences.every((value, index) => index === 0 || value > sequences[index - 1]) },
statusBefore: beforeStatus, statusAfter: afterStatus, metricsBefore: beforeMetrics, metricsAfter: afterMetrics, metricCounterDelta: counterDelta,
counterResetObserved: Object.values(counterDelta).some(value => value < 0), headerSampleFailures: headerFailures,
sessionPreserved: beforeStatus.sessionId === afterStatus.sessionId, projectPreserved: beforeStatus.projectId === afterStatus.projectId,
acquisitionStatePreserved: beforeStatus.scanning === afterStatus.scanning,
notes: [
'All requests were GET. No connection/project/acquisition/preview control, restart or deployment was performed.',
'MJPEG was decoded with the existing shared FreeScanWeb MjpegParser; JPEG markers were inspected for dimensions without image recompression.',
'MJPEG multipart headers do not repeat X-Frame-Age-Ms; receivedFrameAgeMs is arrival time minus each frame X-Frame-Captured-Utc.',
'averageEncodedFps is the worker lifetime cumulative average including initialization and periods without a project; observedIntervalFps and framesPerWindowSecond measure this window.',
'This measures HTTP transport and managed/native receipt timestamps, excluding browser JPEG decoding, display latency and hardware exposure time.',
],
};
const output = join(workspace, 'FreeScanCpp', 'verification', 'real-preview-window.json');
await mkdir(dirname(output), { recursive: true }); await writeFile(output, JSON.stringify(report, null, 2) + '\n');
console.log(JSON.stringify({ output, frames: report.frames, observedIntervalFps: report.observedIntervalFps, measuredMs: report.measuredMs,
xFrameAgeHeaderMs: report.xFrameAgeHeaderMs, receivedFrameAgeMs: report.receivedFrameAgeMs, encodedDimensions: report.encodedDimensions,
sourceDimensions: report.sourceDimensions, metricCounterDelta: report.metricCounterDelta, sessionPreserved: report.sessionPreserved,
projectPreserved: report.projectPreserved, acquisitionStatePreserved: report.acquisitionStatePreserved }, null, 2));

View File

@ -0,0 +1,769 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { spawn } from 'node:child_process';
import { randomBytes, createHash } from 'node:crypto';
import { mkdtemp, writeFile, readFile, readdir, stat, unlink } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, resolve, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { setTimeout as delay } from 'node:timers/promises';
import { MjpegParser, boundaryFromContentType } from './support/preview-pipeline.js';
// This suite only uses the native executable's explicit mock mode on 18889.
// Fixture images and export files are never evidence of real scanner output.
const workspace = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
const executable = process.env.FREESCAN_TEST_EXECUTABLE
? resolve(process.env.FREESCAN_TEST_EXECUTABLE)
: join(workspace, 'FreeScanViewer', 'FreeScanCpp.exe');
const base = 'http://127.0.0.1:18889';
const key = randomBytes(32).toString('hex');
const sockets = new Set();
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
function request(path, { method = 'GET', body, raw, authenticated = true, headers = {}, timeout = 5000 } = {}) {
const payload = raw ?? (body === undefined ? undefined : Buffer.from(JSON.stringify(body)));
return new Promise((resolveReply, reject) => {
const req = http.request(base + path, {
method, agent: false,
headers: {
...(authenticated ? { Authorization: `Bearer ${key}` } : {}),
...(payload !== undefined ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) } : {}),
...headers,
},
}, res => {
const chunks = [];
res.on('data', chunk => chunks.push(chunk));
res.on('end', () => {
const bytes = Buffer.concat(chunks); let json;
try { json = JSON.parse(bytes.toString('utf8')); } catch { }
resolveReply({ status: res.statusCode, headers: res.headers, bytes, json });
});
res.on('error', reject);
});
req.on('error', reject);
req.setTimeout(timeout, () => req.destroy(new Error(`HTTP timeout ${method} ${path}`)));
if (payload !== undefined) req.write(payload);
req.end();
});
}
async function until(probe, message, timeout = 10000) {
const deadline = Date.now() + timeout; let failure;
while (Date.now() < deadline) {
try { const value = await probe(); if (value) return value; } catch (error) { failure = error; }
await delay(35);
}
throw new Error(message, { cause: failure });
}
async function state() { const result = await request('/api/v1/status'); assert.equal(result.status, 200); return result.json; }
function assertUnknownBattery(battery) {
assert.equal(battery.source, 'sdkDeviceStatus');
assert.equal(battery.freshnessLimitMs, 30000);
assert.deepEqual(battery.scanner, {
percent: null, rawValue: null, available: false, fresh: false, updatedUtc: null,
}, 'An HTTP mock without actual SDK battery reports cannot fabricate a scanner percentage or timestamp.');
assert.deepEqual(battery.tracker, { channels: [] }, 'Tracker channels appear only after actual callback reports.');
}
function confirmation(status) {
return { confirm: true, expectedSessionId: status.sessionId ?? null, expectedProjectId: status.projectId ?? null, discardProject: !!status.projectReady };
}
async function submit(path, body = {}) {
const accepted = await request(path, { method: 'POST', body });
assert.equal(accepted.status, 202, JSON.stringify(accepted.json));
assert.match(accepted.json.taskId, /^[a-f0-9]{32}$/);
assert.equal(accepted.json.statusUrl, `/api/v1/tasks/${accepted.json.taskId}`);
assert.equal(accepted.headers.location, accepted.json.statusUrl);
return accepted.json;
}
async function terminal(task, expected = 'succeeded', timeout = 20000) {
const result = await until(async () => {
const reply = await request(task.statusUrl);
assert.equal(reply.status, 200);
return ['succeeded', 'failed'].includes(reply.json.state) ? reply.json : null;
}, `Task ${task.taskId} did not finish`, timeout);
assert.equal(result.state, expected, JSON.stringify(result));
for (const name of ['taskId', 'action', 'state', 'createdUtc', 'startedUtc', 'finishedUtc', 'result', 'error']) assert.ok(Object.hasOwn(result, name), `Missing task field ${name}`);
for (const name of ['createdUtc', 'startedUtc', 'finishedUtc']) assert.ok(Number.isFinite(Date.parse(result[name])));
return result;
}
async function command(path, body = {}) { return terminal(await submit(path, body)); }
function jpegDimensions(bytes) {
assert.equal(bytes.readUInt16BE(0), 0xffd8, 'The mock preview must be a valid JPEG, not a JSON or PNG placeholder.');
let offset = 2;
while (offset + 4 < bytes.length) {
assert.equal(bytes[offset++], 0xff);
while (bytes[offset] === 0xff) offset++;
const marker = bytes[offset++];
if (marker === 0xd9 || marker === 0xda) break;
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue;
const length = bytes.readUInt16BE(offset);
if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker)) return { width: bytes.readUInt16BE(offset + 5), height: bytes.readUInt16BE(offset + 3) };
assert.ok(length >= 2 && offset + length <= bytes.length); offset += length;
}
throw new Error('JPEG has no supported SOF marker.');
}
function openStream() {
return new Promise((resolveStream, reject) => {
const req = http.get(base + '/api/v1/preview/stream', { agent: false, headers: { Authorization: `Bearer ${key}` } }, res => {
if (res.statusCode !== 200) {
const chunks = []; res.on('data', b => chunks.push(b)); res.on('end', () => reject(new Error(`Stream returned ${res.statusCode}: ${Buffer.concat(chunks)}`))); return;
}
const stream = { req, res, count: 0, frames: [], error: null, closed: false, close() { this.closed = true; sockets.delete(this); req.destroy(); res.destroy(); } };
const parser = new MjpegParser(boundaryFromContentType(res.headers['content-type']), frame => { stream.count++; stream.frames.push(frame); if (stream.frames.length > 3) stream.frames.shift(); });
res.on('data', chunk => {
try {
// Exercise the actual shared browser/relay parser with unrelated
// network fragmentation, after Node removes HTTP chunk framing.
let offset = 0, index = 0; const sizes = [1, 7, 311, 4096];
while (offset < chunk.length) { const end = Math.min(chunk.length, offset + sizes[index++ % sizes.length]); parser.push(chunk.subarray(offset, end)); offset = end; }
} catch (error) { stream.error = error; stream.close(); }
});
res.on('error', error => { if (!stream.closed) stream.error = error; });
sockets.add(stream); resolveStream(stream);
});
req.on('error', reject); req.setTimeout(7000, () => req.destroy(new Error('MJPEG stream fixture timed out.')));
});
}
function slowBody() {
let requestHandle; const started = Date.now();
const done = new Promise((resolveReply, reject) => {
let settled = false;
requestHandle = http.request(base + '/api/v1/device/connect', {
method: 'POST', agent: false, headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json', 'Content-Length': 100 },
}, res => {
const chunks = []; res.on('data', b => chunks.push(b)); res.on('end', () => { settled = true; resolveReply({ status: res.statusCode, json: JSON.parse(Buffer.concat(chunks).toString('utf8')), elapsed: Date.now() - started }); }); res.on('error', reject);
});
requestHandle.on('error', error => { if (!settled) reject(error); });
requestHandle.setTimeout(13000, () => requestHandle.destroy(new Error('Slow-body fixture exceeded 13 seconds.')));
requestHandle.flushHeaders(); requestHandle.write('{');
});
return { done, close: () => requestHandle.destroy() };
}
async function filesUnder(directory) {
const found = [];
for (const item of await readdir(directory, { withFileTypes: true })) {
const path = join(directory, item.name);
if (item.isDirectory()) found.push(...await filesUnder(path)); else if (item.isFile()) found.push(path);
}
return found;
}
test('native C++ HTTP API with explicit simulated SDK fixture on isolated port 18889', { skip: process.platform !== 'win32', timeout: 240000 }, async t => {
assert.ok((await stat(executable)).isFile(), 'Build FreeScanViewer/FreeScanCpp.exe before running native API tests.');
let occupied = false;
try { await request('/', { authenticated: false, timeout: 400 }); occupied = true; } catch { }
assert.equal(occupied, false, 'Port 18889 is occupied; this test will not stop an unrelated service.');
const directory = await mkdtemp(join(tmpdir(), 'freescan-native-offline-'));
await writeFile(join(directory, 'api-settings.json'), JSON.stringify({ enabled: true, prefix: base + '/', apiKey: key, previewFps: 20, previewMaxWidth: 1280, previewJpegQuality: 75,
sdkPath: join(directory, 'NO_REAL_SDK', 'SDKCWrapper.dll'), bridgePath: join(directory, 'NO_REAL_BRIDGE.dll') }));
const child = spawn(executable, ['--data-root', directory, '--mock', '--api-no-auto-connect'], { cwd: directory, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
let output = '', spawnError; const append = bytes => { output = (output + bytes.toString('utf8')).slice(-32000); };
child.stdout.on('data', append); child.stderr.on('data', append); child.on('error', error => { spawnError = error; });
const exited = new Promise(resolveExit => child.once('exit', (code, signal) => resolveExit({ code, signal })));
t.diagnostic(`OFFLINE TEST ONLY: ${directory}`);
let savedExport, savedBytes, connectedTask, exportTask, disconnectTask;
try {
await until(async () => {
if (spawnError) throw spawnError;
if (child.exitCode !== null) throw new Error(`Native mock exited ${child.exitCode}: ${output}`);
const current = await state();
return current.simulated === true && !current.busy && output.includes('OFFLINE_TEST_FIXTURE') ? current : null;
}, 'Explicit native mock fixture did not become ready', 18000);
await t.test('metadata, authentication, exact host and query rules preserve the external protocol', async () => {
const metadata = await request('/', { authenticated: false }); assert.equal(metadata.status, 200); assert.equal(metadata.json.implementation, 'C++17');
const health = await request('/api/v1/health'); assert.equal(health.status, 200); assert.equal(health.json.implementation, 'C++17');
assert.equal((await request('/api/v1/health', { authenticated: false })).status, 401);
assert.equal((await request('/api/v1/health', { headers: { Authorization: 'Bearer wrong-key' } })).status, 401);
assert.equal((await request('/api/v1/health', { authenticated: false, headers: { 'X-Api-Key': key } })).status, 200);
assert.equal((await request('/api/v1/health', { headers: { Host: 'localhost:18889' } })).status, 400);
assert.equal((await request('/api/v1/health?ignored=1')).status, 400);
assert.equal((await request(`/api/v1/health?apiKey=${key}`, { authenticated: false })).status, 401);
const capabilities = await request('/api/v1/capabilities'); assert.equal(capabilities.status, 200); assert.equal(capabilities.json.implementation, 'C++17'); assert.equal(capabilities.json.simulated, true);
assert.equal((await state()).autoConnection.enabled, false, '--api-no-auto-connect preserves explicit manual operation.');
for (const route of ['POST /api/v1/device/connect', 'POST /api/v1/device/disconnect', 'POST /api/v1/device/reconnect', 'POST /api/v1/preview/start', 'POST /api/v1/preview/stop']) assert.ok(capabilities.json.routes.includes(route));
for (const [name, value] of [['x-content-type-options', 'nosniff'], ['cache-control', 'no-store']]) assert.equal(health.headers[name], value);
assert.match(health.headers['content-security-policy'], /default-src 'none'/);
assert.equal((await request('/api/v1/device/connect')).status, 405);
assert.equal((await request('/api/v1/not-an-endpoint')).status, 404);
});
await t.test('calibration enum choices are readable without SDK initialization and never select a mode', async () => {
const before = await state();
const reply = await request('/api/v1/capabilities');
assert.equal(reply.status, 200);
assert.equal(reply.json.initialized, false);
assert.equal(reply.json.calibration, null);
assert.deepEqual(reply.json.calibrationModes, [
{ mode: 0, modeName: '跟踪仪标定' },
{ mode: 1, modeName: '系统标定' },
{ mode: 2, modeName: '探针标定' },
{ mode: 3, modeName: 'UE Nova 激光标定' },
]);
assert.equal((await request('/api/v1/capabilities', { authenticated: false })).status, 401);
const after = await state();
for (const field of ['initialized','sessionId','projectId','projectReady','scanning','calibrationActive']) {
assert.deepEqual(after[field], before[field], `Reading enum choices must not change ${field}`);
}
});
await t.test('last calibration time uses local file metadata and mock mode never reads the actual SDK files', async () => {
const before = await state();
assert.equal(before.lastCalibrationUtc, null);
assert.equal(before.lastCalibrationSource, 'local_calibration_file_modified_time');
assert.deepEqual(before.calibrationFileTimes, []);
const after = await state();
assert.equal(after.lastCalibrationUtc, null);
assert.deepEqual(after.calibrationFileTimes, []);
for (const field of ['initialized', 'sessionId', 'calibrationActive', 'scanning', 'projectReady']) {
assert.equal(after[field], before[field], `Reading file metadata must preserve ${field}`);
}
});
await t.test('battery is an authenticated read-only query with honest unknown values before connection', async () => {
const path = '/api/v1/device/battery';
assert.equal((await request(path, { authenticated: false })).status, 401);
assert.equal((await request(path, { headers: { Authorization: 'Bearer wrong-key' } })).status, 401);
const reply = await request(path);
assert.equal(reply.status, 200);
assert.equal(reply.headers['cache-control'], 'no-store');
assertUnknownBattery(reply.json);
assert.deepEqual((await state()).battery, reply.json, 'Status embeds the same battery object as the dedicated query.');
assert.equal((await request(path, { authenticated: false, headers: { 'X-Api-Key': key } })).status, 200);
assert.equal((await request(path + '?ignored=1')).status, 400);
const mutation = await request(path, { method: 'POST', body: {} });
assert.equal(mutation.status, 405);
assert.equal(mutation.headers.allow, 'GET');
assert.equal((await state()).initialized, false, 'Reading battery never connects the SDK.');
const capabilities = await request('/api/v1/capabilities');
assert.ok(capabilities.json.routes.includes('GET /api/v1/device/battery'));
});
await t.test('invalid JSON, unknown fields, depth and body limits fail before a device task is accepted', async () => {
const cases = [
['/api/v1/device/connect', { body: { deviceType: true } }, 400], ['/api/v1/device/connect', { body: { deviceType: 99 } }, 400],
['/api/v1/device/connect', { body: { unused: true } }, 400], ['/api/v1/projects', { body: { path: 'C:/not-allowed' } }, 400],
['/api/v1/preview/start', { body: { extra: true } }, 400], ['/api/v1/device/disconnect', { body: {} }, 400],
['/api/v1/device/connect', { raw: Buffer.from('[]') }, 400], ['/api/v1/device/connect', { raw: Buffer.from('{') }, 400],
['/api/v1/device/connect', { raw: Buffer.from([0xc0, 0x80]) }, 400],
['/api/v1/device/connect', { raw: Buffer.from('{"x":' + '['.repeat(40) + '0' + ']'.repeat(40) + '}') }, 400],
['/api/v1/device/connect', { raw: Buffer.alloc(16385, 0x20) }, 413], ['/api/v1/align', { raw: Buffer.alloc(1024 * 1024 + 1, 0x20) }, 413],
['/api/v1/device/connect', { raw: Buffer.from('{}'), headers: { 'Content-Type': 'text/plain' } }, 415],
];
for (const [path, options, expected] of cases) {
const reply = await request(path, { method: 'POST', ...options }); assert.equal(reply.status, expected, `${path}: ${reply.bytes}`); assert.ok(reply.json?.error?.code); assert.equal(reply.json.taskId, undefined);
}
assert.equal((await state()).initialized, false);
const unknown = await request('/api/v1/tasks/' + 'f'.repeat(32)); assert.equal(unknown.status, 404);
});
await t.test('an incomplete body times out after eight seconds without blocking health requests', async () => {
const slow = slowBody();
try {
await delay(200); const started = Date.now(); assert.equal((await request('/api/v1/health', { timeout: 2000 })).status, 200); assert.ok(Date.now() - started < 2000);
const result = await slow.done; assert.equal(result.status, 408); assert.equal(result.json.error.code, 'request_timeout'); assert.ok(result.elapsed >= 7000 && result.elapsed < 12000, `Slow body elapsed ${result.elapsed}ms`);
} finally { slow.close(); }
assert.equal((await state()).initialized, false);
});
await t.test('connect returns a 202 task and creating a project publishes a genuine JPEG fixture', async () => {
const accepted = await submit('/api/v1/device/connect', { deviceType: 3 }); connectedTask = accepted;
const first = await request(accepted.statusUrl); assert.equal(first.status, 200); assert.ok(['queued', 'running', 'succeeded'].includes(first.json.state));
const done = await terminal(accepted); assert.equal(done.result.simulated, true);
const connected = await state(); assert.equal(connected.initialized, true); assert.match(connected.sessionId, /^[a-f0-9]{32}$/); assert.equal(connected.projectReady, false);
assertUnknownBattery(connected.battery);
const battery = await request('/api/v1/device/battery'); assert.equal(battery.status, 200); assertUnknownBattery(battery.json);
assert.deepEqual(battery.json, connected.battery, 'A mock connection cannot turn historical or synthetic data into current battery readings.');
const created = await command('/api/v1/projects', { mode: 'trak', name: 'OFFLINE_API_Test' }); assert.equal(created.result.simulated, true);
const image = await until(async () => { const result = await request('/api/v1/preview/image'); return result.status === 200 ? result : null; }, 'Mock JPEG did not arrive');
assert.match(image.headers['content-type'], /^image\/jpeg/); assert.deepEqual(jpegDimensions(image.bytes), { width: 640, height: 360 });
assert.ok(Number(image.headers['x-frame-sequence']) > 0); assert.ok(Number.isFinite(Date.parse(image.headers['x-frame-captured-utc']))); assert.ok(Number(image.headers['x-frame-age-ms']) <= 2000);
const metrics = await request('/api/v1/preview/metrics'); assert.equal(metrics.status, 200);
assert.equal(metrics.json.encoderRunning, true);
assert.equal(metrics.json.metricSource, 'worker_encoder_cache');
assert.ok(metrics.json.offeredFrames >= metrics.json.encodedFrames);
assert.ok(metrics.json.captureDiagnostics.callbackEntries > 0);
assert.equal(metrics.json.captureDiagnostics.lastChannels, 4);
assert.equal(metrics.json.captureDiagnostics.exceptions, 0);
assert.equal(metrics.json.bufferPool.capacity, 3);
assert.ok(metrics.json.bufferPool.allocatedSlots <= 3);
assert.equal((await state()).scanning, false);
});
await t.test('framework files are bounded authenticated binary uploads and only registered IDs can be imported', async () => {
const bytes = Buffer.from('OFFLINE_TEST_FIXTURE\nThis is not a valid manufacturer framework.\n');
const upload = (raw = bytes, headers = {}, authenticated = true) => request('/api/v1/framework/files', {
method: 'POST', raw, authenticated,
headers: { 'Content-Type': 'application/octet-stream', 'X-File-Name': encodeURIComponent('离线框架.p3'), ...headers },
});
assert.equal((await request('/api/v1/framework/files')).status, 405);
assert.equal((await upload(bytes, {}, false)).status, 401);
for (const [raw, headers, status] of [
[bytes, { 'Content-Type': 'application/json' }, 415],
[bytes, { 'X-File-Name': 'model.stl' }, 415],
[bytes, { 'X-File-Name': '%2e%2e%2fescape.p3' }, 400],
[bytes, { 'X-File-Name': 'bad%xx.p3' }, 400],
[bytes, { 'X-File-Name': '%FF.p3' }, 400],
[Buffer.alloc(0), {}, 400],
[Buffer.alloc(0), { 'Content-Length': 16 * 1024 * 1024 + 1 }, 413],
]) {
const reply = await upload(raw, headers); assert.equal(reply.status, status, `${JSON.stringify(headers)}: ${reply.bytes}`);
assert.equal(reply.json.taskId, undefined);
}
const uploaded = await upload();
assert.equal(uploaded.status, 201); assert.match(uploaded.json.fileId, /^[a-f0-9]{32}$/);
assert.equal(uploaded.json.name, '离线框架.p3'); assert.equal(uploaded.json.size, bytes.length);
assert.ok(Number.isFinite(Date.parse(uploaded.json.uploadedUtc)));
assert.deepEqual(Object.keys(uploaded.json).sort(), ['fileId', 'name', 'size', 'uploadedUtc']);
assert.deepEqual(await readFile(join(directory, 'FrameworkUploads', uploaded.json.fileId + '.p3')), bytes);
assert.equal((await request('/api/v1/framework/import', { method: 'POST', body: { fileIds: [uploaded.json.fileId] } })).status, 400);
const unknown = await request('/api/v1/framework/import', { method: 'POST', body: { fileIds: ['f'.repeat(32)], confirm: true } });
assert.equal(unknown.status, 404); assert.equal(unknown.json.error.code, 'framework_file_not_found'); assert.equal(unknown.json.taskId, undefined);
const imported = await command('/api/v1/framework/import', { fileIds: [uploaded.json.fileId], confirm: true });
assert.equal(imported.result.frameworkImported, true); assert.equal(imported.result.frameworkFileCount, 1); assert.equal(imported.result.simulated, true);
const current = await state(); assert.equal(current.frameworkImported, true); assert.equal(current.scanType, 'mesh'); assert.equal(current.scanDevice, 'scanner'); assert.equal(current.scanning, false);
const blocked = await terminal(await submit('/api/v1/scan/type', { scanType: 'photogrammetry', confirm: true }), 'failed');
assert.equal(blocked.error.code, 'project_data_present');
await command('/api/v1/scan/start');
const activeImport = await terminal(await submit('/api/v1/framework/import', { fileIds: [uploaded.json.fileId], confirm: true }), 'failed');
assert.equal(activeImport.error.code, 'scan_active');
const activeType = await terminal(await submit('/api/v1/scan/type', { scanType: 'mesh' }), 'failed');
assert.equal(activeType.error.code, 'scan_active');
await command('/api/v1/scan/stop');
await command('/api/v1/projects', { mode: 'trak', name: 'OFFLINE_Photo_Test' });
});
await t.test('photogrammetry selects the correct device, optimizes marker data, and saves P3 without requiring a mesh', async () => {
const missingConfirm = await terminal(await submit('/api/v1/scan/type', { scanType: 'photogrammetry' }), 'failed');
assert.equal(missingConfirm.error.code, 'confirmation_required');
const changed = await command('/api/v1/scan/type', { scanType: 'photogrammetry', device: 'tracker', confirm: true });
assert.equal(changed.result.scanType, 'photogrammetry'); assert.equal(changed.result.sdkScanDeviceType, 0); assert.equal(changed.result.sdkScanType, 0);
const ready = await state(); assert.equal(ready.scanDevice, 'tracker'); assert.equal(ready.scanning, false); assert.equal(ready.frameworkImported, false);
const empty = await terminal(await submit('/api/v1/framework/optimize'), 'failed'); assert.ok(empty.error.code);
await command('/api/v1/scan/start'); await command('/api/v1/scan/stop');
const optimized = await command('/api/v1/framework/optimize'); assert.equal(optimized.result.frameworkOptimized, true);
assert.equal((await state()).meshState, 'none');
const exported = await command('/api/v1/exports', { name: 'OFFLINE_Framework', formats: ['P3'] });
assert.equal(exported.result.simulated, true); assert.equal(exported.result.files.length, 1);
const saved = await request(exported.result.files[0].downloadUrl);
assert.match(saved.bytes.toString('utf8'), /OFFLINE_TEST_FIXTURE/); assert.match(saved.bytes.toString('utf8'), /not valid scanner geometry/);
const mixed = await terminal(await submit('/api/v1/exports', { formats: ['P3', 'STL'] }), 'failed'); assert.ok(mixed.error.code);
await command('/api/v1/scan/type', { scanType: 'mesh' }); assert.equal((await state()).scanDevice, 'tracker');
const noSwitch = await terminal(await submit('/api/v1/scan/type', { scanType: 'mesh', device: 'scanner', confirm: true }), 'failed');
assert.equal(noSwitch.error.code, 'project_data_present');
await command('/api/v1/projects', { mode: 'laser', name: 'OFFLINE_Markers_Test' });
const photo = await terminal(await submit('/api/v1/scan/type', { scanType: 'photogrammetry', confirm: true }), 'failed'); assert.equal(photo.error.code, 'unsupported_scan_type');
const markers = await command('/api/v1/scan/type', { scanType: 'markers' }); assert.equal(markers.result.sdkScanType, 3);
await command('/api/v1/projects', { mode: 'trak', name: 'OFFLINE_API_Test' });
const reset = await state(); assert.equal(reset.scanType, 'mesh'); assert.equal(reset.scanDevice, 'scanner'); assert.equal(reset.frameworkImported, false); assert.equal(reset.frameworkOptimized, false);
});
await t.test('preview controls preserve scan acquisition, and stopping scan preserves project and preview', async () => {
await command('/api/v1/scan/start'); const before = await state(); assert.equal(before.scanning, true);
await command('/api/v1/preview/stop'); const stopped = await state(); assert.equal(stopped.previewEnabled, false); assert.equal(stopped.scanning, true); assert.equal(stopped.projectId, before.projectId);
assert.equal((await request('/api/v1/preview/image')).status, 503);
await command('/api/v1/preview/start'); const resumed = await state(); assert.equal(resumed.previewEnabled, true); assert.equal(resumed.scanning, true); assert.equal(resumed.projectId, before.projectId);
await until(async () => (await request('/api/v1/preview/image')).status === 200, 'Preview did not resume');
await command('/api/v1/scan/stop'); const paused = await state(); assert.equal(paused.scanning, false); assert.equal(paused.projectReady, true); assert.equal(paused.previewEnabled, true);
});
await t.test('MJPEG uses the unchanged shared browser parser and enforces four independent stream slots', async () => {
const streams = [];
try {
for (let i = 0; i < 4; i++) {
const stream = await openStream(); streams.push(stream); await until(() => { if (stream.error) throw stream.error; return stream.count >= 2; }, 'MJPEG frame did not parse');
assert.deepEqual(jpegDimensions(Buffer.from(stream.frames.at(-1).bytes)), { width: 640, height: 360 });
assert.ok(Number.isFinite(Date.parse(stream.frames.at(-1).capturedUtc))); assert.ok(Number(stream.frames.at(-1).sequence) > 0);
assert.notEqual(stream.frames.at(-1).ageMs, null, 'Each production MJPEG part needs its own duration header for LAN viewers.');
assert.ok(Number(stream.frames.at(-1).ageMs) >= 0 && Number(stream.frames.at(-1).ageMs) <= 2000);
}
const fifth = await request('/api/v1/preview/stream'); assert.equal(fifth.status, 429); assert.equal(fifth.json.error.code, 'stream_limit');
assert.equal((await request('/api/v1/health')).status, 200);
const first = streams[0], previous = Number(first.frames.at(-1).sequence); await until(() => Number(first.frames.at(-1)?.sequence) > previous, 'Stream sequences did not advance');
} finally { for (const stream of streams) stream.close(); }
await delay(120); const replacement = await openStream(); try { await until(() => replacement.count >= 1, 'Stream slot was not released'); } finally { replacement.close(); }
});
await t.test('opt-in snapshots pause acquisition and preserve the current project and preview', async () => {
await command('/api/v1/scan/start');
const before = await state();
const unchanged = await command('/api/v1/data/snapshots', { include: ['meshes'] });
assert.equal(unchanged.result.pauseAcquisition, false);
assert.equal(unchanged.result.scanning, true);
const stopped = await command('/api/v1/data/snapshots', { include: ['meshes'], pauseAcquisition: true });
assert.equal(stopped.result.pauseAcquisition, true);
assert.equal(stopped.result.scanning, false);
assert.equal(stopped.result.simulated, true);
const after = await state();
assert.equal(after.scanning, false);
assert.equal(after.previewEnabled, true);
assert.equal(after.projectId, before.projectId);
assert.equal(stopped.result.files.length, 1);
const manifest = await request(stopped.result.files[0].downloadUrl);
assert.equal(manifest.status, 200);
assert.equal(manifest.json.simulated, true);
assert.equal(manifest.json.available, false);
});
await t.test('the HTTP task slot rejects a second control operation while mesh is running', async () => {
const mesh = await submit('/api/v1/mesh');
const second = await request('/api/v1/scan/stop', { method: 'POST', body: {} }); assert.equal(second.status, 409); assert.equal(second.json.error.code, 'busy'); assert.equal(second.json.taskId, undefined);
await terminal(mesh); await command('/api/v1/mesh/confirm'); assert.equal((await state()).meshState, 'confirmed');
exportTask = await submit('/api/v1/exports', { name: 'OFFLINE_ONLY', formats: ['PLY'] }); const exported = await terminal(exportTask);
assert.equal(exported.result.simulated, true); assert.equal(exported.result.files.length, 1); savedExport = exported.result.files[0];
assert.match(savedExport.name, /SIMULATED_.*\.fixture\.txt$/);
const download = await request(savedExport.downloadUrl); assert.equal(download.status, 200); savedBytes = download.bytes; assert.match(savedBytes.toString('utf8'), /OFFLINE_TEST_FIXTURE/); assert.match(savedBytes.toString('utf8'), /not valid scanner geometry/);
assert.match(download.headers['content-disposition'], /attachment; filename=download; filename\*=UTF-8''/);
const disk = (await filesUnder(join(directory, 'Exports'))).find(path => path.endsWith(savedExport.name)); assert.ok(disk); assert.equal(hash(await readFile(disk)), hash(savedBytes));
assert.equal((await request(savedExport.downloadUrl, { authenticated: false })).status, 401);
assert.equal((await request('/api/v1/files/not-a-file-id')).status, 400);
assert.equal((await request('/api/v1/files/' + 'e'.repeat(32))).status, 404);
});
await t.test('confirmation guards reject stale targets, and worker rotations retain HTTP tasks and downloads', async () => {
const before = await state(), oldSession = before.sessionId;
const stale = await terminal(await submit('/api/v1/device/reconnect', { ...confirmation(before), expectedSessionId: '0'.repeat(32) }), 'failed'); assert.equal(stale.error.code, 'session_changed'); assert.equal((await state()).sessionId, oldSession);
const wrongProject = await terminal(await submit('/api/v1/device/disconnect', { ...confirmation(before), expectedProjectId: 'another_project' }), 'failed'); assert.equal(wrongProject.error.code, 'project_changed');
const noDiscard = await terminal(await submit('/api/v1/device/disconnect', { ...confirmation(before), discardProject: false }), 'failed'); assert.equal(noDiscard.error.code, 'project_discard_confirmation_required');
disconnectTask = await submit('/api/v1/device/disconnect', confirmation(await state())); await terminal(disconnectTask);
const disconnected = await state(); assert.equal(disconnected.initialized, false); assert.equal(disconnected.projectReady, false); assert.equal(disconnected.scanning, false); assert.equal(disconnected.previewEnabled, false); assert.equal(disconnected.sessionId, null);
assertUnknownBattery(disconnected.battery);
assertUnknownBattery((await request('/api/v1/device/battery')).json);
assert.equal((await request('/api/v1/health')).status, 200); assert.equal(hash((await request(savedExport.downloadUrl)).bytes), hash(savedBytes));
await command('/api/v1/device/reconnect', confirmation(disconnected)); const reconnected = await state();
assert.equal(reconnected.initialized, true); assert.notEqual(reconnected.sessionId, oldSession); assert.equal(reconnected.projectReady, false); assert.equal(reconnected.scanning, false);
assertUnknownBattery(reconnected.battery);
assertUnknownBattery((await request('/api/v1/device/battery')).json);
for (const accepted of [connectedTask, exportTask, disconnectTask]) assert.equal((await request(accepted.statusUrl)).json.state, 'succeeded');
assert.equal(hash((await request(savedExport.downloadUrl)).bytes), hash(savedBytes));
const metrics = await request('/api/v1/preview/metrics'); assert.equal(metrics.status, 200); assert.equal(metrics.json.implementation, 'C++17');
const record = JSON.parse(await readFile(join(directory, '.native-service.json'), 'utf8')); assert.equal(record.processId, child.pid); assert.equal(record.simulated, true); assert.equal(record.implementation, 'C++17');
});
await t.test('calibration names extend task results without changing numeric requests or existing fields', async () => {
await command('/api/v1/calibration/enter', {});
const names = ['跟踪仪标定', '系统标定', '探针标定', 'UE Nova 激光标定'];
for (let mode = 0; mode < names.length; mode++) {
for (const [path, action, body] of [
['/api/v1/calibration/setMode', 'calibrationSetMode', { mode }],
['/api/v1/calibration/applyLast', 'calibrationApplyLast', { mode, confirm: true }],
]) {
const task = await command(path, body);
assert.equal(task.action, action);
assert.equal(task.result.action, action);
assert.equal(task.result.status, 'confirmed');
assert.equal(task.result.calibrationActive, true);
assert.equal(task.result.mode, mode);
assert.equal(typeof task.result.mode, 'number');
assert.equal(task.result.modeName, names[mode]);
const caps = (await request('/api/v1/capabilities')).json;
assert.equal(caps.calibration.mode, mode);
assert.equal(caps.calibration.modeName, names[mode]);
}
}
assert.equal((await request('/api/v1/calibration/setMode', { method: 'POST', body: { mode: '跟踪仪标定' } })).status, 400);
assert.equal((await request('/api/v1/calibration/setMode', { method: 'POST', body: { mode: 0, modeName: names[0] } })).status, 400);
assert.equal((await state()).projectReady, false);
assert.equal((await state()).scanning, false);
});
await t.test('SDK calibration calculation callbacks complete HTTP tasks with the actual result and preserve the reusable session', async () => {
const callbackFixture = join(directory, 'OFFLINE_TEST_CALIBRATION_COMPUTE_REPLY');
await command('/api/v1/calibration/setMode', { mode:1 });
await command('/api/v1/calibration/setFree', { enabled:true, confirm:true });
await command('/api/v1/calibration/capturePose', { confirm:true });
const before = await state();
const assertSessionPreserved = async () => {
const current = await state();
assert.equal(current.sessionId, before.sessionId);
assert.equal(current.initialized, true);
assert.equal(current.busy, false);
assert.equal(current.restartRequired, false);
assert.equal(current.calibrationActive, true);
};
const computeWithCallback = async (callback, expected = 'succeeded') => {
await writeFile(callbackFixture, JSON.stringify(callback));
const started = Date.now();
const result = await terminal(await submit('/api/v1/calibration/compute', { confirm:true }), expected);
assert.ok(Date.now() - started < 2000,
`A definitive SDK calculation result must finish promptly without the 300-second timeout: ${JSON.stringify(callback)}`);
assert.equal(result.action, 'calibrationCompute');
await assertSessionPreserved();
return result;
};
// Preserve the real negative callback regression: an explicit failure
// must remain failed instead of being mistaken for a successful receipt.
const rejected = await computeWithCallback({ cmd:'calibCalculateResult', type:'rep', calibTarget:'5',
calibResult:'false', camErr:'0', errorCode:'0x00000001', result:'failed' }, 'failed');
assert.equal(rejected.error.code, 'sdk_error');
assert.equal(rejected.error.httpStatus, 502);
assert.match(rejected.error.message, /0x00000001/);
assert.match(rejected.error.message, /calibTarget="5"/);
assert.equal(rejected.result, null);
// This is the actual successful SDK reply from the completed 56-pose
// calibration, whose previous HTTP task incorrectly timed out.
const calculated = { cmd:'calibCalculateResult', type:'rep', calibResult:'true', calibTarget:'6',
camErr:'0.004910327805427969', errorCode:'0x00000000', isTrinity:'true', result:'success' };
const succeeded = await computeWithCallback(calculated);
assert.equal(succeeded.error, null);
assert.equal(succeeded.result.action, 'calibrationCompute');
assert.equal(succeeded.result.calibrationActive, true);
assert.equal(succeeded.result.status, 'confirmed');
assert.deepEqual(succeeded.result.sdkResult, calculated,
'Return the actual callback with its original fields and string values, including the residual.');
// The documented completion ACK is still supported. Its task must retain
// this callback, without leaking the preceding calculation's fields.
const acknowledged = { cmd:'freeCalibrationComputeFinish', type:'rep', result:'success' };
const legacy = await computeWithCallback(acknowledged);
assert.equal(legacy.error, null);
assert.equal(legacy.result.action, 'calibrationCompute');
assert.equal(legacy.result.calibrationActive, true);
assert.equal(legacy.result.status, 'confirmed');
assert.deepEqual(legacy.result.sdkResult, acknowledged);
await command('/api/v1/calibration/capturePose', { confirm:true });
await assertSessionPreserved();
assert.deepEqual((await request(`/api/v1/tasks/${rejected.taskId}`)).json, rejected);
assert.deepEqual((await request(`/api/v1/tasks/${succeeded.taskId}`)).json, succeeded,
'A later callback and command must not overwrite the completed calculation result.');
assert.deepEqual((await request(`/api/v1/tasks/${legacy.taskId}`)).json, legacy);
});
await t.test('calibration recovery validates targets, releases an idle session and preserves HTTP tasks and downloads', async () => {
const before = await state();
assert.equal(before.calibrationActive, true);
const oldRecord = JSON.parse(await readFile(join(directory, '.native-service.json'), 'utf8'));
const target = { confirm:true, expectedSessionId:before.recoverySessionId || before.sessionId };
assert.equal((await request('/api/v1/calibration/recover', { method:'POST', body:{ confirm:true } })).status, 400);
const rejected = await terminal(await submit('/api/v1/calibration/recover', { ...target, force:true, expectedSessionId:'0'.repeat(32) }), 'failed');
assert.equal(rejected.error.code, 'session_changed');
assert.equal((await state()).sessionId, before.sessionId, 'A stale recovery request cannot abort another session.');
const recovered = await terminal(await submit('/api/v1/calibration/recover', target), 'succeeded', 60000);
assert.equal(recovered.result.recovered, true);
assert.equal(recovered.result.reconnected, true);
assert.equal(recovered.result.calibrationAborted, true);
assert.equal(recovered.result.forced, false);
const after = await state();
assert.equal(after.initialized, true); assert.equal(after.calibrationActive, false);
assert.equal(after.scanning, false); assert.equal(after.projectReady, false);
assert.notEqual(after.sessionId, before.sessionId);
const newRecord = JSON.parse(await readFile(join(directory, '.native-service.json'), 'utf8'));
assert.equal(newRecord.processId, oldRecord.processId);
assert.equal(newRecord.startedFileTime, oldRecord.startedFileTime, 'Recovery must keep the HTTP supervisor alive.');
assert.deepEqual((await request(`/api/v1/tasks/${recovered.taskId}`)).json, recovered);
assert.equal(hash((await request(savedExport.downloadUrl)).bytes), hash(savedBytes));
const notCalibrating = await terminal(await submit('/api/v1/calibration/recover', { confirm:true, force:true, expectedSessionId:after.sessionId }), 'failed');
assert.equal(notCalibrating.error.code, 'calibration_not_active');
});
await t.test('an independent recovery task can abort a blocked calibration without restarting HTTP or accepting duplicate recovery', async () => {
await command('/api/v1/calibration/enter', {});
await command('/api/v1/calibration/setMode', { mode:1 });
const before = await state();
const fixture = join(directory, 'OFFLINE_TEST_CALIBRATION_START_HANG');
await writeFile(fixture, 'OFFLINE_TEST_FIXTURE\n');
const blocked = await submit('/api/v1/calibration/startSystem', { confirm:true });
await until(async () => (await state()).busy, 'The offline calibration did not block.');
const busyCaps = await request('/api/v1/capabilities');
assert.equal(busyCaps.status, 200);
assert.ok(busyCaps.json.routes.includes('POST /api/v1/calibration/recover'));
const target = { confirm:true, expectedSessionId:before.sessionId };
const ordinary = await terminal(await submit('/api/v1/calibration/recover', target), 'failed');
assert.equal(ordinary.error.code, 'recovery_requires_force');
assert.equal((await request(blocked.statusUrl)).json.state, 'running', 'Normal release cannot implicitly abort a running calibration.');
const recovering = await submit('/api/v1/calibration/recover', { ...target, force:true });
const duplicate = await request('/api/v1/calibration/recover', { method:'POST', body:{ ...target, force:true } });
assert.equal(duplicate.status, 409); assert.equal(duplicate.json.error.code, 'recovery_in_progress');
assert.equal((await request('/api/v1/health')).status, 200);
assert.equal((await request('/api/v1/device/connect', { method:'POST', body:{} })).status, 409);
await unlink(fixture);
const finished = await terminal(recovering, 'succeeded', 60000);
assert.equal(finished.result.forced, true);
const aborted = await terminal(blocked, 'failed');
assert.equal(aborted.error.code, 'calibration_aborted');
const after = await state();
assert.equal(after.initialized, true); assert.equal(after.calibrationActive, false);
assert.equal(after.busy, false); assert.equal(after.restartRequired, false);
assert.notEqual(after.sessionId, before.sessionId);
await delay(150);
assert.deepEqual((await request(blocked.statusUrl)).json, aborted, 'Late results cannot overwrite the aborted task.');
});
await t.test('a queued calibration command cannot execute against the replacement SDK after recovery', async () => {
await command('/api/v1/calibration/enter', {});
const before = await state();
const fixture = join(directory, 'OFFLINE_TEST_HTTP_DELAY_CALIBRATION_DISPATCH');
await writeFile(fixture, 'OFFLINE_TEST_FIXTURE\n');
const delayed = await submit('/api/v1/calibration/setMode', { mode:1 });
await until(async () => {
try { return JSON.parse(await readFile(join(directory, 'OFFLINE_TEST_HTTP_DISPATCH_WAITING'), 'utf8')).taskId === delayed.taskId; }
catch { return false; }
}, 'The mock HTTP calibration dispatch did not pause.');
const recovered = await terminal(await submit('/api/v1/calibration/recover', { confirm:true, force:true, expectedSessionId:before.sessionId }), 'succeeded', 60000);
assert.equal(recovered.result.recovered, true);
await unlink(fixture);
const aborted = await terminal(delayed, 'failed');
assert.equal(aborted.error.code, 'calibration_aborted');
await delay(250);
const caps = (await request('/api/v1/capabilities')).json;
assert.equal((await state()).calibrationActive, false, 'A delayed old HTTP request cannot re-enter calibration or modify the new session.');
assert.equal(caps.calibration.lastConfirmedAction, 'none');
assert.deepEqual((await request(delayed.statusUrl)).json, aborted);
});
await t.test('a failed normal release remains explicitly retryable with the original recovery identity', async () => {
await command('/api/v1/calibration/enter', {});
const before = await state();
await writeFile(join(directory, 'OFFLINE_TEST_RECOVERY_CLOSE_FAIL_ONCE'), 'OFFLINE_TEST_FIXTURE\n');
const target = { confirm:true, expectedSessionId:before.recoverySessionId || before.sessionId };
const refused = await terminal(await submit('/api/v1/calibration/recover', target), 'failed', 60000);
assert.equal(refused.error.code, 'recovery_requires_force');
assert.equal((await state()).recoverySessionId, target.expectedSessionId);
const retry = await terminal(await submit('/api/v1/calibration/recover', { ...target, force:true }), 'succeeded', 60000);
assert.equal(retry.result.recovered, true);
assert.equal((await state()).restartRequired, false);
});
await t.test('failure while connecting a replacement worker can be retried without reviving the old calibration', async () => {
await command('/api/v1/calibration/enter', {});
const before = await state();
await writeFile(join(directory, 'OFFLINE_TEST_RECOVERY_CONNECT_FAIL_ONCE'), 'OFFLINE_TEST_FIXTURE\n');
const target = { confirm:true, force:true, expectedSessionId:before.recoverySessionId || before.sessionId };
const failed = await terminal(await submit('/api/v1/calibration/recover', target), 'failed', 60000);
assert.equal(failed.error.code, 'recovery_connect_failed');
const fault = await state();
assert.equal(fault.recoverySessionId, target.expectedSessionId);
const retry = await terminal(await submit('/api/v1/calibration/recover', { ...target, expectedSessionId:fault.recoverySessionId }), 'succeeded', 60000);
assert.equal(retry.result.recovered, true);
assert.equal((await state()).calibrationActive, false);
assert.equal((await state()).restartRequired, false);
});
await t.test('a timed-out calibration exposes a recoverable session identity and can be recovered past restart_required', async () => {
await command('/api/v1/calibration/enter', {});
await command('/api/v1/calibration/setMode', { mode:1 });
const before = await state();
const fixture = join(directory, 'OFFLINE_TEST_CALIBRATION_START_TIMEOUT');
await writeFile(fixture, 'OFFLINE_TEST_FIXTURE\n');
const timedOut = await terminal(await submit('/api/v1/calibration/startSystem', { confirm:true }), 'failed');
assert.equal(timedOut.error.code, 'sdk_timeout');
const fault = await state();
assert.equal(fault.restartRequired, true);
assert.equal(fault.recoverySessionId, before.sessionId);
const faultCaps = await request('/api/v1/capabilities');
assert.equal(faultCaps.status, 200);
assert.ok(faultCaps.json.routes.includes('POST /api/v1/calibration/recover'));
await unlink(fixture);
const recovered = await terminal(await submit('/api/v1/calibration/recover', {
confirm:true, force:true, expectedSessionId:fault.recoverySessionId || fault.sessionId,
}), 'succeeded', 60000);
assert.equal(recovered.result.recovered, true);
assert.equal((await state()).restartRequired, false);
await command('/api/v1/projects', { mode:'trak', name:'OFFLINE_Recovery_Project_Guard' });
const project = await state();
const refused = await terminal(await submit('/api/v1/calibration/recover', { confirm:true, force:true, expectedSessionId:project.sessionId }), 'failed');
assert.equal(refused.error.code, 'project_protected');
assert.equal((await state()).projectId, project.projectId);
});
} catch (error) {
error.message += `\nNative mock output:\n${output}\nFixture directory: ${directory}`; throw error;
} finally {
for (const stream of [...sockets]) stream.close();
if (child.exitCode === null && !spawnError) {
const stop = spawn(executable, ['--stop', '--data-root', directory], { cwd: directory, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
let stopOutput = ''; stop.stdout.on('data', bytes => { stopOutput += bytes; }); stop.stderr.on('data', bytes => { stopOutput += bytes; });
const result = await Promise.race([new Promise(resolveStop => { stop.once('exit', code => resolveStop({ code })); stop.once('error', error => resolveStop({ error })); }), delay(26000, undefined, { ref: false }).then(() => ({ timeout: true }))]);
assert.equal(result.code, 0, `Native test shutdown was not confirmed: ${stopOutput} ${JSON.stringify(result)}; test will not kill an unknown service.`);
}
const ended = await Promise.race([exited, delay(5000, undefined, { ref: false }).then(() => ({ timeout: true }))]); assert.equal(ended.code, 0, `Native mock did not exit cleanly: ${JSON.stringify(ended)}\n${output}`);
}
});
test('SDK automatically restarts after failed initialization/cleanup while HTTP, tasks and protected sessions survive', { skip: process.platform !== 'win32', timeout: 80000 }, async () => {
let occupied = false;
try { await request('/', { authenticated: false, timeout: 400 }); occupied = true; } catch { }
assert.equal(occupied, false, 'Auto-connect fixture will not stop an unrelated HTTP service.');
const directory = await mkdtemp(join(tmpdir(), 'freescan-auto-offline-'));
await writeFile(join(directory, 'api-settings.json'), JSON.stringify({
enabled: true, prefix: base + '/', apiKey: key, previewFps: 20, previewMaxWidth: 1280, previewJpegQuality: 75,
autoConnect: true, autoConnectRetrySeconds: 5,
sdkPath: join(directory, 'NO_REAL_SDK', 'SDKCWrapper.dll'), bridgePath: join(directory, 'NO_REAL_BRIDGE.dll'),
}));
await writeFile(join(directory, 'OFFLINE_TEST_FAIL_INITIALIZE_ONCE'), 'OFFLINE_TEST_FIXTURE\n');
const child = spawn(executable, ['--data-root', directory, '--mock'], { cwd: directory, windowsHide: true, stdio: ['ignore','pipe','pipe'] });
let output = '';
const append = bytes => { output = (output + bytes.toString('utf8')).slice(-16000); };
child.stdout.on('data', append); child.stderr.on('data', append);
const ended = new Promise(resolveExit => { child.once('exit', code => resolveExit(code)); child.once('error', error => resolveExit(error)); });
try {
const failed = await until(async () => {
const current = await state();
return current.simulated && current.autoConnection.state === 'retry_wait' ? current : null;
}, 'Mock initialization failure was not reported', 18000);
assert.equal(failed.initialized, false);
assert.equal(failed.autoConnection.lastError.code, 'sdk_timeout');
const originalRecord = JSON.parse(await readFile(join(directory, '.native-service.json'), 'utf8'));
const failedTask = await terminal(await submit('/api/v1/scan/start', {}), 'failed');
let observedRecovering = false;
const connected = await until(async () => {
const current = await state();
if (current.autoConnection.state === 'recovering') observedRecovering = true;
return current.simulated && current.initialized && !current.busy && current.autoConnection.state === 'connected' ? current : null;
}, 'Automatic mock SDK did not restart and initialize', 30000);
assert.equal(connected.projectReady, false);
assert.equal(connected.scanning, false);
assert.equal(connected.autoConnection.enabled, true);
assert.equal(connected.autoConnection.retryIntervalSeconds, 5);
assert.equal(connected.autoConnection.attempts, 2);
assert.equal(connected.autoConnection.restartCount, 1);
assert.equal(connected.autoConnection.lastRestartForced, true);
assert.ok(Number.isFinite(Date.parse(connected.autoConnection.lastRestartUtc)));
assert.ok(observedRecovering, 'HTTP status must remain readable during SDK restart.');
assert.deepEqual(JSON.parse(await readFile(join(directory, '.native-service.json'), 'utf8')), originalRecord,
'SDK recovery must preserve the same HTTP parent PID and identity.');
assert.deepEqual((await request(`/api/v1/tasks/${failedTask.taskId}`)).json, failedTask,
'SDK restart must retain the original HTTP task table.');
assert.match(output, /SDK工作进程已重启/);
await command('/api/v1/device/disconnect', confirmation(connected));
await delay(2200);
const disconnected = await state();
assert.equal(disconnected.initialized, false);
assert.equal(disconnected.autoConnection.paused, true);
assert.equal(disconnected.autoConnection.state, 'paused');
await command('/api/v1/device/connect', {});
await until(async () => (await state()).autoConnection.state === 'connected', 'Manual connect did not resume automatic monitoring');
const reconnected = await state();
assert.notEqual(reconnected.sessionId, connected.sessionId);
await command('/api/v1/projects', { name:'Protected', mode:'trak' });
const project = await state();
await command('/api/v1/scan/start', {});
await delay(1200);
assert.equal((await state()).scanning, true);
await command('/api/v1/scan/stop', {});
await delay(1200);
const paused = await state();
assert.equal(paused.sessionId, project.sessionId);
assert.equal(paused.projectId, project.projectId);
assert.equal(paused.projectReady, true);
assert.equal(paused.scanning, false, 'The automatic connector must never resume acquisition.');
assert.equal(paused.autoConnection.state, 'session_active');
assert.equal(paused.autoConnection.restartCount, 1, 'Project/scanning/paused sessions must not trigger SDK replacement.');
} catch (error) {
error.message += '\n' + output; throw error;
} finally {
if (child.exitCode === null) {
const stop = spawn(executable, ['--stop','--data-root',directory], { cwd:directory, windowsHide:true, stdio:['ignore','pipe','pipe'] });
const stopped = await Promise.race([new Promise(resolveStop => { stop.once('exit', code=>resolveStop(code)); stop.once('error', resolveStop); }), delay(25000, undefined, { ref:false }).then(()=> 'timeout')]);
assert.equal(stopped, 0, `Automatic fixture did not stop normally: ${output}`);
}
assert.equal(await Promise.race([ended,delay(5000, undefined, { ref:false }).then(()=> 'timeout')]), 0);
}
});

View File

@ -0,0 +1,306 @@
#include "../src/preview_capture.hpp"
#include <algorithm>
#include <array>
#include <climits>
#include <future>
#include <iostream>
#include <type_traits>
// OFFLINE ONLY: exercise the production buffer/row conversion helpers with
// synthetic BGRA pixels. No WorkerService, SDK DLL, HTTP listener or device.
using freescan::Json;
using freescan::detail::PreviewCallbackDiagnostics;
using freescan::detail::PreviewFramePool;
using freescan::detail::PreviewRawFrame;
using freescan::detail::flip_preview_rows;
namespace {
size_t passed = 0;
void check(bool condition, const std::string &message) {
if (!condition)
throw std::runtime_error(message);
++passed;
}
template <class F> void invalid(F operation, const std::string &message) {
try {
operation();
} catch (const std::invalid_argument &) {
check(true, message);
return;
}
throw std::runtime_error(message);
}
uint64_t count(const Json &value, const char *name) { return value.at(name).get<uint64_t>(); }
void no_vendor_dll() {
check(GetModuleHandleW(L"SDKCWrapper.dll") == nullptr, "Offline pool test must not load the SDK DLL.");
check(GetModuleHandleW(L"FreeScanNativeBridge.dll") == nullptr,
"Offline pool test must not load the scene bridge DLL.");
}
void capacity_and_ownership() {
static_assert(!std::is_copy_constructible_v<PreviewFramePool::Lease>);
static_assert(!std::is_copy_assignable_v<PreviewFramePool::Lease>);
static_assert(std::is_nothrow_move_constructible_v<PreviewFramePool::Lease>);
static_assert(std::is_nothrow_move_assignable_v<PreviewFramePool::Lease>);
PreviewFramePool pool;
auto initial = pool.snapshot();
check(count(initial, "capacity") == 3 && count(initial, "allocatedSlots") == 0 &&
count(initial, "inUse") == 0 && count(initial, "capacityBytes") == 0,
"A new pool is bounded to three slots without allocating pixel storage.");
std::array<PreviewFramePool::Lease, PreviewFramePool::capacity> leases;
for (auto &lease : leases) {
lease = pool.try_acquire();
check(bool(lease), "Each of the three unclaimed slots is available.");
pool.prepare(lease, 16, 8);
}
check(leases[0].get() != leases[1].get() && leases[0].get() != leases[2].get() &&
leases[1].get() != leases[2].get(),
"Three simultaneous leases have three distinct frame owners.");
std::fill(leases[0]->pixels.begin(), leases[0]->pixels.end(), uint8_t(73));
auto *encodingFrame = leases[0].get();
auto attempt = std::async(std::launch::async, [&pool] { return bool(pool.try_acquire()); });
const auto prompt = attempt.wait_for(std::chrono::seconds(1)) == std::future_status::ready;
// Release before reporting failure so a regression cannot deadlock cleanup.
if (!prompt)
for (auto &lease : leases)
lease.reset();
const bool fourthSucceeded = attempt.get();
check(prompt && !fourthSucceeded, "Pool exhaustion returns without waiting for an encoder-held slot.");
check(count(pool.snapshot(), "inUse") == 3 && count(pool.snapshot(), "peakInUse") == 3 &&
count(pool.snapshot(), "exhausted") >= 1,
"Exhaustion preserves every existing lease and records the bounded occupancy.");
auto *releasedFrame = leases[1].get();
leases[1].reset();
auto replacement = pool.try_acquire();
check(replacement.get() == releasedFrame && replacement.get() != encodingFrame,
"Only the released slot can be reused while the encoder retains its frame.");
std::fill(replacement->pixels.begin(), replacement->pixels.end(), uint8_t(191));
check(std::all_of(encodingFrame->pixels.begin(), encodingFrame->pixels.end(),
[](uint8_t pixel) { return pixel == 73; }),
"Writing a newly leased producer slot cannot overwrite an encoder-owned frame.");
auto moved = std::move(replacement);
check(!replacement && moved.get() == releasedFrame && count(pool.snapshot(), "inUse") == 3,
"Moving a lease transfers ownership without claiming another slot.");
moved = std::move(leases[2]);
check(!leases[2] && moved && count(pool.snapshot(), "inUse") == 2,
"Move assignment releases the former destination slot exactly once.");
moved.reset();
moved.reset();
leases[0].reset();
check(count(pool.snapshot(), "inUse") == 0,
"Reset is idempotent and every lease returns its slot after ownership transfers.");
{
auto automatic = pool.try_acquire();
check(automatic && count(pool.snapshot(), "inUse") == 1, "A released pool remains usable.");
}
check(count(pool.snapshot(), "inUse") == 0, "Lease destruction returns a slot without explicit cleanup.");
}
void reuse_and_dimensions() {
PreviewFramePool pool;
std::array<PreviewFramePool::Lease, PreviewFramePool::capacity> leases;
std::array<uint8_t *, PreviewFramePool::capacity> storage{};
uint64_t totalCapacity = 0;
for (size_t slot = 0; slot < leases.size(); ++slot) {
leases[slot] = pool.try_acquire();
pool.prepare(leases[slot], 32, 24);
storage[slot] = leases[slot]->pixels.data();
totalCapacity += leases[slot]->pixels.capacity();
}
const auto warmed = pool.snapshot();
check(count(warmed, "allocatedSlots") == 3 && count(warmed, "allocations") == 3 &&
count(warmed, "capacityBytes") == totalCapacity,
"Warmup allocates pixel storage once for each of the three slots.");
for (size_t slot = 0; slot < leases.size(); ++slot) {
for (int iteration = 0; iteration < 40; ++iteration)
pool.prepare(leases[slot], 32, 24);
check(leases[slot]->pixels.data() == storage[slot] && leases[slot]->pixels.size() == 32 * 24 * 4,
"Repeated same-resolution callbacks preserve the warmed pixel allocation.");
pool.prepare(leases[slot], 8, 8);
check(leases[slot]->pixels.data() == storage[slot] && leases[slot]->pixels.size() == 8 * 8 * 4,
"A smaller frame changes logical size without discarding reusable capacity.");
leases[slot].reset();
}
auto reused = pool.try_acquire();
pool.prepare(reused, 32, 24);
const auto repeated = pool.snapshot();
check(reused->pixels.data() == storage[0] && count(repeated, "allocations") == 3 &&
count(repeated, "capacityBytes") == totalCapacity && count(repeated, "reuses") >= 124,
"Returning and reacquiring a warmed slot does not allocate another frame buffer.");
auto *original = reused->pixels.data();
const auto oldSize = reused->pixels.size();
for (const auto dimensions : std::array<std::pair<int, int>, 10>{
{{0, 1}, {1, 0}, {-1, 1}, {1, -1}, {16385, 1}, {1, 16385},
{16384, 4097}, {4097, 16384}, {INT_MAX, 1}, {1, INT_MAX}}}) {
invalid([&] { pool.prepare(reused, dimensions.first, dimensions.second); },
"Invalid dimensions or an oversized BGRA request must be rejected before allocation.");
check(reused->pixels.data() == original && reused->pixels.size() == oldSize &&
reused->w == 32 && reused->h == 24,
"Rejecting a malformed frame preserves the last valid buffer and dimensions.");
}
PreviewFramePool::Lease empty;
invalid([&] { pool.prepare(empty, 1, 1); }, "An empty lease cannot prepare a frame.");
PreviewFramePool other;
auto foreign = other.try_acquire();
invalid([&] { pool.prepare(foreign, 1, 1); }, "A lease from another pool cannot prepare this pool's slot.");
pool.prepare(reused, 16384, 1);
check(reused->w == 16384 && reused->h == 1 && reused->pixels.size() == 65536,
"The documented width boundary is accepted without a large image allocation.");
pool.prepare(reused, 1, 16384);
check(reused->w == 1 && reused->h == 16384 && reused->pixels.size() == 65536,
"The documented height boundary is accepted without a large image allocation.");
pool.prepare(reused, 1, 1);
check(reused->pixels.size() == 4, "A one-pixel BGRA frame remains valid after resolution changes.");
}
void row_orientation() {
for (const auto dimensions : std::array<std::pair<int, int>, 5>{
{{1, 1}, {1, 2}, {2, 3}, {3, 4}, {7, 5}}}) {
PreviewRawFrame frame;
frame.w = dimensions.first;
frame.h = dimensions.second;
frame.epoch = 29;
frame.captured = 1234567;
frame.pixels.resize(size_t(frame.w) * frame.h * 4);
for (int y = 0; y < frame.h; ++y)
for (int x = 0; x < frame.w; ++x)
for (int channel = 0; channel < 4; ++channel)
frame.pixels[(size_t(y) * frame.w + x) * 4 + channel] =
uint8_t(y * 41 + x * 7 + channel);
const auto bottomUp = frame.pixels;
flip_preview_rows(frame);
bool correct = true;
const size_t row = size_t(frame.w) * 4;
for (int y = 0; y < frame.h; ++y)
correct = correct && std::equal(frame.pixels.begin() + size_t(y) * row,
frame.pixels.begin() + size_t(y + 1) * row,
bottomUp.begin() + size_t(frame.h - 1 - y) * row);
check(correct, "Encoder-side row conversion preserves every BGRA channel and corrects bottom-up orientation.");
check(frame.w == dimensions.first && frame.h == dimensions.second && frame.epoch == 29 &&
frame.captured == 1234567,
"Row conversion cannot change source dimensions, epoch or capture timestamp.");
if (frame.h % 2) {
const size_t middle = size_t(frame.h / 2) * row;
check(std::equal(frame.pixels.begin() + middle, frame.pixels.begin() + middle + row,
bottomUp.begin() + middle),
"An odd-height image retains its middle row exactly.");
}
flip_preview_rows(frame);
check(frame.pixels == bottomUp, "Two row flips recover the complete original synthetic frame.");
}
}
void concurrent_producers_and_encoder() {
PreviewFramePool pool;
std::array<PreviewFramePool::Lease, PreviewFramePool::capacity> warm;
std::array<PreviewRawFrame *, PreviewFramePool::capacity> frames{};
for (size_t slot = 0; slot < warm.size(); ++slot) {
warm[slot] = pool.try_acquire();
pool.prepare(warm[slot], 32, 16);
frames[slot] = warm[slot].get();
}
for (auto &lease : warm)
lease.reset();
std::array<std::atomic<unsigned>, PreviewFramePool::capacity> owners{};
std::atomic<unsigned> ready{0}, finished{0}, acquired{0}, duplicates{0}, corruption{0};
std::atomic<bool> begin{false};
constexpr unsigned threads = 8, iterations = 1500;
std::array<std::thread, threads> work;
for (unsigned thread = 0; thread < threads; ++thread)
work[thread] = std::thread([&, thread] {
ready.fetch_add(1);
while (!begin.load())
std::this_thread::yield();
for (unsigned iteration = 0; iteration < iterations; ++iteration) {
auto lease = pool.try_acquire();
if (!lease) {
std::this_thread::yield();
continue;
}
size_t slot = 0;
while (slot < frames.size() && frames[slot] != lease.get())
++slot;
unsigned empty = 0;
if (slot == frames.size() || !owners[slot].compare_exchange_strong(empty, thread + 1)) {
duplicates.fetch_add(1);
continue;
}
pool.prepare(lease, 32, 16);
const auto marker = uint8_t(thread * 19 + iteration);
std::fill(lease->pixels.begin(), lease->pixels.end(), marker);
if (iteration % 8 == 0)
std::this_thread::yield();
if (!std::all_of(lease->pixels.begin(), lease->pixels.end(),
[marker](uint8_t value) { return value == marker; }))
corruption.fetch_add(1);
acquired.fetch_add(1);
owners[slot].store(0);
lease.reset();
}
finished.fetch_add(1);
});
while (ready.load() != threads)
std::this_thread::yield();
begin.store(true);
for (auto &thread : work)
thread.join();
const auto final = pool.snapshot();
check(finished.load() == threads && acquired.load() > 0,
"All concurrent producers complete a bounded set of acquisition attempts.");
check(duplicates.load() == 0 && corruption.load() == 0,
"Concurrent producers and retained frames never share an owner or corrupt another frame's pixels.");
check(count(final, "inUse") == 0 && count(final, "peakInUse") <= 3,
"Concurrent lease churn returns every slot and never exceeds the three-buffer limit.");
check(count(final, "allocations") == 3 && count(final, "allocatedSlots") == 3,
"Concurrent warmed callbacks reuse only the three allocated pixel buffers.");
check(std::all_of(owners.begin(), owners.end(), [](const auto &owner) { return owner.load() == 0; }),
"No thread leaves a stale external owner after lease destruction.");
}
void callback_diagnostics() {
struct SyntheticCallbackFailure {};
PreviewCallbackDiagnostics diagnostics;
const auto empty = diagnostics.snapshot(1000);
check(empty.at("lastCallbackUnixMs").is_null() && empty.at("lastCallbackAgeMs").is_null() &&
count(empty, "callbackEntries") == 0 && count(empty, "callbacksInFlight") == 0,
"Diagnostics distinguish a missing callback from an old callback.");
{
PreviewCallbackDiagnostics::Observation first(diagnostics, 32, 16, 4, 1200);
check(count(diagnostics.snapshot(1200), "callbacksInFlight") == 1,
"An active callback is visible before it completes.");
try {
PreviewCallbackDiagnostics::Observation nested(diagnostics, 64, 24, 4, 1210);
diagnostics.record_copy(std::chrono::steady_clock::now());
check(count(diagnostics.snapshot(1210), "callbacksInFlight") == 2,
"Overlapping callback scopes retain their own in-flight accounting.");
throw SyntheticCallbackFailure{};
} catch (const SyntheticCallbackFailure &) {
}
check(count(diagnostics.snapshot(1220), "callbacksInFlight") == 1 &&
count(diagnostics.snapshot(1220), "completedCallbacks") == 1,
"Exception unwinding completes one callback without clearing the other active callback.");
}
const auto final = diagnostics.snapshot(1260);
check(count(final, "callbackEntries") == 2 && count(final, "completedCallbacks") == 2 &&
count(final, "callbacksInFlight") == 0 && count(final, "copySamples") == 1,
"Callback and copy observations finish without leaking an in-flight count.");
check(final.at("lastCallbackUnixMs") == 1210 && final.at("lastCallbackAgeMs") == 50 &&
final.at("lastWidth") == 64 && final.at("lastHeight") == 24 && final.at("lastChannels") == 4,
"Diagnostics retain the latest received callback's timestamp and source dimensions.");
check(diagnostics.snapshot(1100).at("lastCallbackAgeMs") == 0,
"A backwards wall clock cannot produce a negative callback age.");
check(final.at("averageCopyMs").get<double>() >= 0 && final.at("averageCallbackMs").get<double>() >= 0,
"Callback cost diagnostics remain nonnegative without assuming a machine speed.");
}
} // namespace
int main() {
try {
no_vendor_dll();
capacity_and_ownership();
reuse_and_dimensions();
row_orientation();
concurrent_producers_and_encoder();
callback_diagnostics();
no_vendor_dll();
std::cout << "OFFLINE_TEST_FIXTURE: preview capture tests passed: " << passed
<< "; no SDK, device, HTTP or service action.\n";
return 0;
} catch (const std::exception &error) {
std::cerr << "FAIL (OFFLINE ONLY): " << error.what() << '\n';
return 1;
}
}

View File

@ -0,0 +1,122 @@
// Shared by the browser and the local relay. Network reads never wait for JPEG decoding.
const decoder = new TextDecoder();
const HEADER_END = new Uint8Array([13, 10, 13, 10]);
class ByteQueue {
constructor() { this.chunks = []; this.head = 0; this.offset = 0; this.length = 0; }
append(bytes) {
if (!(bytes instanceof Uint8Array)) throw new TypeError('Expected binary stream data.');
if (bytes.length) { this.chunks.push(bytes); this.length += bytes.length; }
}
indexOf(marker) {
let matched = 0, position = 0;
for (let c = this.head; c < this.chunks.length; c++) {
const chunk = this.chunks[c];
for (let i = c === this.head ? this.offset : 0; i < chunk.length; i++, position++) {
// The header delimiter has only a one-byte overlap (CR LF CR LF).
if (chunk[i] !== marker[matched]) matched = chunk[i] === marker[0] ? 1 : 0;
else matched++;
if (matched === marker.length) return position - marker.length + 1;
}
}
return -1;
}
read(length) {
if (!Number.isSafeInteger(length) || length < 0 || length > this.length) throw new RangeError('Incomplete stream data.');
const result = new Uint8Array(length);
let written = 0;
while (written < length) {
const chunk = this.chunks[this.head];
const count = Math.min(length - written, chunk.length - this.offset);
result.set(chunk.subarray(this.offset, this.offset + count), written);
written += count; this.offset += count; this.length -= count;
if (this.offset === chunk.length) { this.head++; this.offset = 0; }
}
if (this.head === this.chunks.length) { this.chunks = []; this.head = 0; }
else if (this.head >= 32) { this.chunks = this.chunks.slice(this.head); this.head = 0; }
return result;
}
}
export class MjpegParser {
constructor(boundary, onFrame, { maxFrameBytes = 16 * 1024 * 1024, maxHeaderBytes = 16384 } = {}) {
if (typeof boundary !== 'string' || !/^[\x21-\x7e]{1,150}$/.test(boundary) || /[\r\n]/.test(boundary)) throw new Error('Invalid MJPEG boundary.');
this.boundary = '--' + boundary; this.onFrame = onFrame;
this.maxFrameBytes = maxFrameBytes; this.maxHeaderBytes = maxHeaderBytes;
this.queue = new ByteQueue(); this.expected = null; this.metadata = null; this.frames = 0;
}
push(bytes) {
this.queue.append(bytes);
for (;;) {
if (this.expected === null) {
const at = this.queue.indexOf(HEADER_END);
if (at < 0) {
if (this.queue.length > this.maxHeaderBytes) throw new Error('实时流头部超过限制。');
return;
}
if (at > this.maxHeaderBytes) throw new Error('实时流头部超过限制。');
const header = decoder.decode(this.queue.read(at + HEADER_END.length)).replace(/^\r\n/, '');
if (!header.startsWith(this.boundary + '\r\n')) throw new Error('实时流边界无效。');
const lengths = [...header.matchAll(/(?:^|\r\n)Content-Length:\s*(\d+)\s*(?=\r\n)/ig)];
if (lengths.length !== 1) throw new Error('实时图像缺少有效长度信息。');
const size = Number(lengths[0][1]);
if (!Number.isSafeInteger(size) || size <= 0 || size > this.maxFrameBytes) throw new Error('实时图像长度超过限制。');
const field = name => header.match(new RegExp('(?:^|\\r\\n)' + name + ':\\s*([^\\r\\n]+)', 'i'))?.[1]?.trim() || null;
this.expected = size;
this.metadata = { capturedUtc: field('X-Frame-Captured-Utc'), sequence: field('X-Frame-Sequence'),
sourceWidth: field('X-Frame-Source-Width'), sourceHeight: field('X-Frame-Source-Height'),
encodedUtc: field('X-Frame-Encoded-Utc'), encodeMs: field('X-Frame-Encode-Ms'),
ageMs: field('X-Frame-Age-Ms'), headerReceivedAt: performance.now() };
}
if (this.queue.length < this.expected) return;
const jpeg = this.queue.read(this.expected);
const metadata = this.metadata; this.expected = null; this.metadata = null; this.frames++;
this.onFrame({ bytes: jpeg, ...metadata });
}
}
finish() {
if (this.expected !== null) throw new Error('实时图像在接收完成前已断开。');
}
}
// Exactly one frame is being decoded and at most one newest frame is waiting.
// Replacing the pending frame intentionally loses frames to keep control latency low.
export class LatestFrameScheduler {
constructor(render, onError = () => {}) {
this.render = render; this.onError = onError;
this.pending = null; this.active = false; this.closed = false; this.waiters = [];
this.stats = { received: 0, rendered: 0, dropped: 0, decodeErrors: 0, renderMs: 0 };
}
push(frame) {
if (this.closed) return;
this.stats.received++;
if (this.pending) this.stats.dropped++;
this.pending = frame;
if (!this.active) this.pump();
}
async pump() {
this.active = true;
try {
while (!this.closed && this.pending) {
const frame = this.pending; this.pending = null;
const started = performance.now();
try {
if (await this.render(frame) !== false && !this.closed) this.stats.rendered++;
} catch (error) { this.stats.decodeErrors++; this.onError(error); }
this.stats.renderMs = performance.now() - started;
}
} finally {
this.active = false;
for (const resolve of this.waiters.splice(0)) resolve();
}
}
stop() { this.closed = true; this.pending = null; }
idle() { return this.active ? new Promise(resolve => this.waiters.push(resolve)) : Promise.resolve(); }
metrics() { return { ...this.stats, decoding: this.active, pendingFrames: this.pending ? 1 : 0 }; }
}
export function boundaryFromContentType(contentType) {
const match = contentType.match(/boundary\s*=\s*(?:"([^"]+)"|([^;\s]+))/i);
if (!match) throw new Error('实时流格式无效。');
return match[1] || match[2];
}

View File

@ -0,0 +1,885 @@
#include "../src/sdk_worker.hpp"
#include "../src/contracts.hpp"
#include "../src/scene_snapshot_flow.hpp"
#include "../src/auto_connection.hpp"
#include "../src/calibration_completion.hpp"
#include <objbase.h>
#include <gdiplus.h>
#include <future>
#include <iostream>
// OFFLINE ONLY: every WorkerService below receives simulate=true and nonexistent
// SDK paths. It never starts HTTP, calls SDK LoadLibrary, or addresses a device.
// Synthetic UUID/ID syntax is used only to verify rejection gates, never as
// evidence of existing scanner geometry or hardware identifiers.
using namespace freescan;
namespace {
std::atomic<size_t> passed{0};
void check(bool condition, const std::string &message) {
if (!condition)
throw std::runtime_error(message);
++passed;
}
template <class F> void rejects(F operation, int status, const std::string &code) {
try {
operation();
} catch (const ApiError &error) {
check(error.status == status && error.code == code,
"Unexpected rejection: " + error.code + " (wanted " + code + ")");
return;
}
throw std::runtime_error("Expected rejection: " + code);
}
void rejected(WorkerService &worker, const std::string &action, const Json &body, const std::string &code,
int status = 409) {
rejects([&] { worker.execute(action, body); }, status, code);
}
Json run(WorkerService &worker, const std::string &action, const Json &body = Json::object()) {
auto result = worker.execute(action, body);
check(result.is_object() && result.value("simulated", false),
"Mock results must explicitly identify simulation: " + action);
return result;
}
struct TemporaryRoot {
fs::path base, path;
TemporaryRoot() {
base = fs::canonical(fs::temp_directory_path());
path = base / wide("FreeScanCpp_worker_test_" + new_id());
if (!fs::create_directory(path))
throw std::runtime_error("Refusing to reuse an existing test root.");
path = fs::canonical(path);
}
~TemporaryRoot() {
try {
// Verify the absolute target immediately before recursive cleanup.
const auto target = fs::canonical(path);
if (target.parent_path() == base &&
target.filename().wstring().rfind(L"FreeScanCpp_worker_test_", 0) == 0)
fs::remove_all(target);
} catch (const std::exception &) {
}
}
};
Json configuration() {
return {{"previewFps", 20},
{"previewMaxWidth", 1280},
{"previewJpegQuality", 75},
{"sdkPath", "C:/OFFLINE_TEST_DO_NOT_LOAD/SDKCWrapper.dll"},
{"bridgePath", "C:/OFFLINE_TEST_DO_NOT_LOAD/FreeScanNativeBridge.dll"}};
}
void calibration_completion_replies() {
const std::set<std::string> computing{"freeCalibrationComputeFinish"};
Json actual{{"cmd", "calibCalculateResult"}, {"type", "rep"}, {"calibTarget", "5"},
{"calibResult", "false"}, {"camErr", "0"}, {"errorCode", "0x00000001"}, {"result", "failed"}};
auto failure = detail::sdk_completion(computing, actual, "result=failed");
check(failure.done && failure.error.find("0x00000001") != std::string::npos &&
failure.error.find("calibTarget=\"5\"") != std::string::npos &&
failure.error.find("calibResult=\"false\"") != std::string::npos,
"Actual per-target SDK failure promptly ends the pending compute with diagnostic fields.");
for (const auto *expected : {"freeCalibrationCapturePoseFinish", "startCalibrationFinish",
"startSystemCalibrationFinish", "setCalibrationModeFinish"})
check(!detail::sdk_completion({expected}, actual, "result=failed").done,
"A compute failure cannot complete an unrelated SDK request.");
for (const auto &code : std::vector<Json>{1, "1", "0x00000001", "0X01"}) {
Json reply{{"cmd", "calibCalculateResult"}, {"errorCode", code}};
check(detail::sdk_completion(computing, reply, "").done,
"Decimal and hexadecimal nonzero SDK errors are terminal compute failures.");
}
for (const auto &code : std::vector<Json>{0, "0", "0x00000000"}) {
Json reply{{"cmd", "calibCalculateResult"}, {"errorCode", code}, {"calibResult", "true"}};
const auto completed = detail::sdk_completion(computing, reply, "");
check(completed.done && completed.error.empty(),
"An explicit successful calculation with a valid zero code finishes without a second ACK.");
}
for (const auto &value : std::vector<Json>{true, "true", "TRUE"}) {
const auto completed = detail::sdk_completion(computing,
Json{{"cmd", "calibCalculateResult"}, {"calibResult", value}}, "");
check(completed.done && completed.error.empty(),
"Vendor boolean and string successful results finish the active computation.");
}
for (const auto &code : std::vector<Json>{"0x01trailing", "", "unknown", false, nullptr}) {
Json reply{{"cmd", "calibCalculateResult"}, {"errorCode", code}, {"calibResult", "true"}};
check(!detail::sdk_completion(computing, reply, "").done,
"An invalid SDK error code cannot be interpreted as explicit successful calculation.");
}
for (const auto &value : std::vector<Json>{nullptr, 1, "unknown", ""}) {
check(!detail::sdk_completion(computing,
Json{{"cmd", "calibCalculateResult"}, {"calibResult", value}, {"result", "success"}}, "").done,
"An ambiguous result cannot finish computation merely because the command was accepted.");
}
for (const auto &value : std::vector<Json>{false, "false", "FALSE"}) {
check(detail::sdk_completion(computing, Json{{"cmd", "calibCalculateResult"}, {"calibResult", value}}, "").done,
"Boolean and string false calibration results end computation without waiting for timeout.");
}
auto success = detail::sdk_completion(computing, Json{{"cmd", "freeCalibrationComputeFinish"}, {"result", "success"}}, "");
check(success.done && success.error.empty(), "The documented successful ACK remains supported.");
Json actualSuccess{{"cmd", "calibCalculateResult"}, {"type", "rep"}, {"calibTarget", "6"},
{"calibResult", "true"}, {"camErr", "0.004910327805427969"},
{"errorCode", "0x00000000"}, {"isTrinity", "true"}, {"result", "success"}};
success = detail::sdk_completion(computing, actualSuccess, "");
check(success.done && success.error.empty(),
"The actual 56-capture successful SDK result must not become a five-minute timeout.");
for (const auto *expected : {"freeCalibrationCapturePoseFinish", "startCalibrationFinish",
"startSystemCalibrationFinish", "setCalibrationModeFinish"})
check(!detail::sdk_completion({expected}, actualSuccess, "").done,
"Successful computation cannot finish an unrelated SDK request.");
for (const auto *field : {"errorCode", "errCode"}) {
auto contradictory = actualSuccess;
contradictory[field] = "0x00000001";
const auto rejected = detail::sdk_completion(computing, contradictory, "");
check(rejected.done && !rejected.error.empty(),
"A nonzero SDK error takes precedence over a contradictory successful result.");
}
auto contradictory = actualSuccess;
contradictory["result"] = "failed";
const auto contradictoryResult = detail::sdk_completion(computing, contradictory, "result=failed");
check(contradictoryResult.done && !contradictoryResult.error.empty(),
"An explicit failed command result takes precedence over calibResult=true.");
auto explicitFailure = detail::sdk_completion(computing, Json{{"cmd", "freeCalibrationComputeFinish"}, {"errorCode", "0x00000001"}}, "");
check(explicitFailure.done && !explicitFailure.error.empty(), "The normal ACK also honors hexadecimal calculation errors.");
check(!detail::sdk_completion(computing, Json{{"cmd", "putSceneData"}, {"result", "failed"}}, "result=failed").done,
"Scene updates cannot complete or fail a calculation request.");
check(!detail::sdk_completion(computing, Json{{"cmd", 17}}, "").done,
"Malformed command identifiers do not match a pending computation.");
}
void calibration_compute_failure_workflow(const fs::path &root) {
WorkerService worker(root, configuration(), true);
run(worker, "connect");
run(worker, "calibrationEnter");
run(worker, "calibrationSetMode", {{"mode", 1}});
run(worker, "calibrationSetFree", {{"enabled", true}, {"confirm", true}});
run(worker, "calibrationCapturePose", {{"confirm", true}});
const auto previous = worker.status();
write_json(root / L"OFFLINE_TEST_CALIBRATION_COMPUTE_REPLY",
Json{{"cmd", "calibCalculateResult"}, {"type", "rep"}, {"calibTarget", "5"},
{"calibResult", "false"}, {"camErr", "0"}, {"errorCode", "0x00000001"}, {"result", "failed"}});
const auto started = std::chrono::steady_clock::now();
try {
worker.execute("calibrationCompute", {{"confirm", true}});
throw std::runtime_error("The failed SDK result was reported as success.");
} catch (const ApiError &error) {
check(error.status == 502 && error.code == "sdk_error" &&
std::string(error.what()).find("0x00000001") != std::string::npos,
"The same worker message callback surfaces the actual SDK failure immediately.");
}
check(std::chrono::steady_clock::now() - started < std::chrono::seconds(1),
"A known negative calculation result must not become a five-minute callback timeout.");
const auto after = worker.status();
check(after.at("sessionId") == previous.at("sessionId") && after.at("initialized") == true &&
after.at("calibrationActive") == true && after.at("restartRequired") == false && after.at("busy") == false,
"An explicit SDK calculation rejection keeps the session reusable without flagging a timeout or restart.");
const Json actualSuccess{{"cmd", "calibCalculateResult"}, {"type", "rep"}, {"calibTarget", "6"},
{"calibResult", "true"}, {"camErr", "0.004910327805427969"},
{"errorCode", "0x00000000"}, {"isTrinity", "true"}, {"result", "success"}};
write_json(root / L"OFFLINE_TEST_CALIBRATION_COMPUTE_REPLY", actualSuccess);
const auto successStarted = std::chrono::steady_clock::now();
const auto actualResult = run(worker, "calibrationCompute", {{"confirm", true}});
check(std::chrono::steady_clock::now() - successStarted < std::chrono::seconds(1) &&
actualResult.at("sdkResult") == actualSuccess && actualResult.at("status") == "confirmed" &&
actualResult.at("calibrationActive") == true,
"The actual successful SDK callback completes promptly and is returned without losing residual fields.");
check(worker.status().at("restartRequired") == false && worker.status().at("busy") == false,
"A successful calculation never introduces a false timeout or restart flag.");
auto contradictoryReply = actualSuccess;
contradictoryReply["success"] = false;
write_json(root / L"OFFLINE_TEST_CALIBRATION_COMPUTE_REPLY", contradictoryReply);
rejects([&] { worker.execute("calibrationCompute", {{"confirm", true}}); }, 502, "sdk_error");
const Json legacyReply{{"cmd", "freeCalibrationComputeFinish"}, {"type", "rep"}, {"result", "success"}};
write_json(root / L"OFFLINE_TEST_CALIBRATION_COMPUTE_REPLY", legacyReply);
check(run(worker, "calibrationCompute", {{"confirm", true}}).at("sdkResult") == legacyReply,
"Legacy completion callbacks remain successful and preserve their raw SDK fields.");
check(worker.status().at("sessionId") == previous.at("sessionId"),
"A subsequent calculation can use the same SDK session after a handled negative result.");
worker.shutdown();
}
void automatic_connection_policy() {
using detail::AutoConnectionAction;
Json idle{{"initialized", false}, {"deviceOnline", nullptr}, {"busy", false},
{"projectReady", false}, {"scanning", false}, {"calibrationActive", false},
{"restartRequired", false}, {"stateUncertain", false}};
detail::AutoConnectionPolicy off(false, 15);
check(off.decide(idle, 1000) == AutoConnectionAction::none &&
off.snapshot().at("state") == "disabled", "Explicit manual mode never connects automatically.");
detail::AutoConnectionPolicy policy(true, 15);
check(policy.decide(idle, 1000) == AutoConnectionAction::connect,
"An idle disconnected SDK can connect without creating a project.");
policy.failed(ApiError(409, "service_in_use", "Other app owns service"), 2000);
check(policy.decide(idle, 16999) == AutoConnectionAction::none &&
policy.snapshot().at("attempts") == 1,
"A failed connect waits the configured interval rather than spamming SDK initialization.");
check(policy.decide(idle, 17000) == AutoConnectionAction::connect,
"A pre-initialization failure can retry when its deadline arrives.");
auto failed = idle;
failed["restartRequired"] = failed["stateUncertain"] = true;
policy.failed(ApiError(504, "sdk_timeout", "Initialize unconfirmed"), 18000);
check(policy.decide(failed, 33000) == AutoConnectionAction::recycle,
"An attempted/uncertain SDK is replaced through verified cleanup, never reinitialized in place.");
check(policy.may_restart(), "Only an enabled, unpaused and unprotected policy permits worker replacement.");
policy.restarted(true, 33500);
check(policy.snapshot().at("restartCount") == 1 &&
policy.snapshot().at("lastRestartForced") == true &&
policy.snapshot().at("lastRestartUtc") == utc_from_ms(33500),
"Confirmed SDK worker restarts record their count, time and forced-exit fallback.");
policy.failed(ApiError(504, "worker_exit_timeout", "Old worker did not exit"), 34000, true);
check(policy.decide(idle, 999999) == AutoConnectionAction::none &&
policy.snapshot().at("state") == "blocked" && policy.snapshot().at("nextRetryUtc").is_null(),
"Unverified worker identity or exit stops recovery instead of starting a second owner.");
check(!policy.may_restart(), "Blocked identity/exit checks cannot force replacement.");
policy.resume();
auto connected = idle;
connected["initialized"] = true;
connected["deviceOnline"] = true;
check(policy.decide(connected, 35000) == AutoConnectionAction::none &&
policy.snapshot().at("state") == "connected", "An existing healthy SDK session is reused.");
connected["deviceOnline"] = nullptr;
check(policy.decide(connected, 36000) == AutoConnectionAction::none,
"Unknown/stale online status alone must not destroy an initialized session.");
connected["deviceOnline"] = false;
check(policy.decide(connected, 37000) == AutoConnectionAction::recycle,
"Confirmed offline status permits recovery only when there is no active session data.");
for (const auto *field : {"projectReady", "scanning", "calibrationActive", "busy"}) {
auto guarded = failed;
guarded[field] = true;
check(policy.decide(guarded, 999999) == AutoConnectionAction::none,
std::string("Automatic recovery preserves ") + field);
}
policy.protect();
check(!policy.may_restart(), "Project/calibration protection forbids a forced SDK restart.");
check(policy.decide(failed, 999999) == AutoConnectionAction::none,
"Even a missing/crashed worker cannot erase the protected project/calibration latch.");
policy.protect(false);
policy.pause();
check(!policy.may_restart(), "Operator pause forbids a forced SDK restart.");
policy.failed(ApiError(504, "sdk_timeout", "An earlier attempt finished late"), 1000000);
policy.connected();
check(policy.decide(idle, 2000000) == AutoConnectionAction::none &&
policy.snapshot().at("state") == "paused" && policy.snapshot().at("paused") == true,
"Manual disconnect/stop wins over late automatic completion and retry scheduling.");
policy.resume();
check(policy.decide(idle, 2000001) == AutoConnectionAction::connect,
"A new manual connect request resumes the automatic connection policy.");
}
Json confirmation(const Json &status, bool discard = false) {
return {
{"confirm", true},
{"discardProject", discard},
{"expectedProjectId", status.value("projectReady", false) ? status.at("projectId") : Json(nullptr)},
{"expectedSessionId", status.at("sessionId")}};
}
Json syntactic_edit() {
return {{"confirm", true}, {"projectUuid", "11111111-1111-4111-8111-111111111111"}, {"markerIds", {0}}};
}
Json clip_request() {
return {{"confirm", true}, {"center", {0, 0, 0}}, {"normal", {0, 1, 0}}};
}
std::string bytes(const fs::path &path) {
std::ifstream input(path, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(input), {});
}
void no_vendor_dll() {
check(GetModuleHandleW(L"SDKCWrapper.dll") == nullptr,
"Offline tests must not load the manufacturer SDK DLL.");
check(GetModuleHandleW(L"FreeScanNativeBridge.dll") == nullptr,
"Offline tests must not load the scene bridge DLL.");
}
void pause_snapshot_flow() {
// OFFLINE event fixture: this SDK stand-in only notifies during Pause.
// It exercises the production ordering helper, without loading a DLL.
bool receiverReady = false, rawModeReady = false, notified = false, scanning = true, written = false;
detail::capture_scene_snapshot(
true,
[&] {
receiverReady = true;
rawModeReady = true;
},
[&] {
check(receiverReady && rawModeReady, "The scene receiver and raw mode must precede Pause.");
scanning = false;
notified = true; // The SDK may notify before Pause returns.
},
[&] { check(notified, "A scene published inside Pause must survive until the wait step."); },
[&] { written = true; });
check(written && !scanning, "A pause snapshot writes data and never resumes acquisition.");
bool paused = false;
detail::capture_scene_snapshot(false, [] {}, [&] { paused = true; }, [] {}, [] {});
check(!paused, "Existing snapshot requests must not start pausing acquisition implicitly.");
for (int failAt = 0; failAt < 4; ++failAt) {
int reached = -1;
auto step = [&](int stage) {
reached = stage;
if (stage == failAt)
throw std::runtime_error("offline scene phase failed");
};
bool failed = false;
try {
detail::capture_scene_snapshot(
true, [&] { step(0); }, [&] { step(1); }, [&] { step(2); }, [&] { step(3); });
} catch (const std::runtime_error &) {
failed = true;
}
check(failed && reached == failAt, "Failed scene phases must stop before later SDK/write actions.");
}
check(!detail::accepts_scene_snapshot(true, 7, 4, false),
"An incremental mesh must not satisfy a pause snapshot that requests meshes.");
check(!detail::accepts_scene_snapshot(true, 7, 3, false),
"Points or markers alone cannot satisfy a pause request that also requires a whole mesh.");
check(!detail::accepts_scene_snapshot(true, 4, 8, false),
"A whole-mesh flag without actual mesh data cannot satisfy a pause snapshot.");
check(detail::accepts_scene_snapshot(true, 7, 8, true),
"An actual whole mesh can satisfy the paused scene request.");
check(detail::accepts_scene_snapshot(true, 1, 2, false) &&
detail::accepts_scene_snapshot(true, 2, 1, false),
"Point/marker-only requests do not require a mesh.");
check(detail::accepts_scene_snapshot(false, 7, 4, false),
"Non-pausing snapshots continue to permit incremental data.");
no_vendor_dll();
}
void disconnected_gates(const fs::path &root) {
WorkerService worker(root, configuration(), true);
const auto status = worker.status();
check(status.value("simulated", false) && !status.value("initialized", true) &&
status.at("sessionId").is_null(),
"Fresh mock worker must be explicitly disconnected.");
check(worker.files().empty() && worker.frame().is_null(),
"Fresh worker cannot invent frame or file data.");
check(worker.can_close(false) && worker.can_close(true), "A fresh empty worker can close safely.");
const auto caps = worker.query("capabilities", Json::object());
check(caps.value("simulated", false) && !caps.value("rawDataAvailable", true),
"Mock must not claim real raw SDK data.");
check(caps.at("routes") == contracts::routes() && caps.at("exportFormats") == contracts::export_formats(),
"Capabilities must expose every migrated route and format.");
const Json expectedModes = {{{"mode", 0}, {"modeName", "跟踪仪标定"}},
{{"mode", 1}, {"modeName", "系统标定"}},
{{"mode", 2}, {"modeName", "探针标定"}},
{{"mode", 3}, {"modeName", "UE Nova 激光标定"}}};
check(caps.at("calibrationModes") == expectedModes && caps.at("calibration").is_null(),
"Disconnected SDK must expose enum choices without inventing a current calibration mode.");
const auto afterChoices = worker.status();
check(afterChoices.at("initialized") == status.at("initialized") &&
afterChoices.at("sessionId") == status.at("sessionId") &&
afterChoices.at("projectId") == status.at("projectId") &&
afterChoices.at("scanning") == status.at("scanning") &&
afterChoices.at("calibrationActive") == status.at("calibrationActive"),
"Reading static calibration choices cannot initialize SDK or change the current session.");
const std::vector<std::pair<std::string, Json>> requests = {
{"createProject", Json::object()},
{"startScan", Json::object()},
{"stopScan", Json::object()},
{"setScanType", {{"scanType", "mesh"}}},
{"importFramework", {{"fileIds", {std::string(32, 'a')}}, {"confirm", true}}},
{"optimizeFramework", Json::object()},
{"startPreview", Json::object()},
{"stopPreview", Json::object()},
{"parameters", {{"brightness", 8}}},
{"mesh", Json::object()},
{"meshConfirm", Json::object()},
{"meshUndo", Json::object()},
{"export", {{"formats", {"PLY"}}}},
{"dataSnapshot", Json::object()},
{"align", {{"action", "enter"}}},
{"align",
{{"action", "apply"},
{"mode", "featureAuto"},
{"fixedProjectUuid", "11111111-1111-4111-8111-111111111111"},
{"movingProjectUuid", "22222222-2222-4222-8222-222222222222"}}},
{"edit", syntactic_edit()},
{"clipPlane", clip_request()},
{"calibrationEnter", Json::object()}};
for (const auto &request : requests)
rejected(worker, request.first, request.second, "not_connected");
rejects([&] { worker.query("sceneInfo", Json::object()); }, 409, "not_connected");
rejects([&] { worker.query("unknown", Json::object()); }, 404, "unknown_query");
rejected(worker, "reconnect", {{"confirm", true}}, "worker_restart_required");
rejected(worker, "connect", {{"deviceType", true}}, "invalid_parameter", 400);
worker.shutdown();
rejected(worker, "connect", Json::object(), "worker_restart_required");
no_vendor_dll();
}
std::string project_and_session_workflow(const fs::path &root) {
WorkerService worker(root, configuration(), true);
auto connected = run(worker, "connect", {{"deviceType", 3}}), initial = worker.status();
const auto originalSession = initial.at("sessionId").get<std::string>();
check(initial.value("initialized", false) && initial.value("deviceOnline", false) &&
originalSession.size() == 32,
"Explicit mock connect establishes an identifiable simulated session.");
check(!worker.can_close(false) && worker.can_close(true),
"Ordinary close cannot retire an active SDK session.");
check(run(worker, "connect", {{"deviceType", 3}}).value("alreadyConnected", false),
"Connect to the same active type is idempotent.");
check(worker.status().at("sessionId") == originalSession,
"Idempotent connect must preserve the reviewed session.");
rejected(worker, "connect", {{"deviceType", 4}}, "device_type_conflict");
rejected(worker, "startPreview", Json::object(), "project_required");
rejected(worker, "disconnect", {{"confirm", true}}, "session_confirmation_required");
auto wrongSession = confirmation(initial);
wrongSession["expectedSessionId"] = std::string(32, 'f');
rejected(worker, "disconnect", wrongSession, "session_changed");
auto project = run(worker, "createProject", {{"name", u8"离线测试"}, {"mode", "trak"}});
const auto firstProject = project.at("projectId");
check(worker.status().value("previewEnabled", false) && !worker.status().value("scanning", true),
"Creating a project enables preview without acquisition.");
auto scene = worker.query("sceneInfo", Json::object());
check(scene.value("simulated", false) && !scene.value("available", true) &&
!scene.value("pointIdsAvailable", true) && !scene.contains("projectUuid") &&
!scene.contains("cloudUuid"),
"Mock scene must not invent geometry, UUIDs or point identifiers.");
run(worker, "startScan");
check(run(worker, "startScan").value("alreadyScanning", false),
"Repeat start reports existing acquisition.");
rejected(worker, "createProject", Json::object(), "scan_active");
rejected(worker, "calibrationEnter", Json::object(), "scan_active");
for (const auto &action : std::vector<std::pair<std::string, Json>>{{"parameters", {{"viewLock", true}}},
{"mesh", Json::object()},
{"export", {{"formats", {"PLY"}}}},
{"align", {{"action", "enter"}}},
{"edit", syntactic_edit()},
{"clipPlane", clip_request()}})
rejected(worker, action.first, action.second, "scan_active");
const auto snapshot =
run(worker, "dataSnapshot", {{"maxPoints", 17}, {"include", {"markers", "meshes"}}});
check(!snapshot.value("pauseAcquisition", true) && snapshot.value("scanning", false),
"Default snapshots preserve ongoing acquisition.");
check(snapshot.at("files").size() == 1,
"Simulation snapshot contains only a manifest, never invented geometry.");
const auto snapshotId = snapshot.at("files").at(0).at("fileId");
const auto descriptor = worker.query("file", {{"fileId", snapshotId}});
const auto manifest = read_json(fs::path(wide(descriptor.at("path").get<std::string>())));
check(manifest.value("simulated", false) &&
manifest.value("fixture", std::string()) == "OFFLINE_TEST_FIXTURE" &&
!manifest.value("available", true) && !manifest.value("pointIdsAvailable", true) &&
manifest.value("maxPoints", 0) == 17,
"Manifest must clearly identify unavailable OFFLINE data.");
auto preview = run(worker, "stopPreview");
check(!preview.value("previewEnabled", true) && preview.value("scanning", false) &&
worker.status().at("projectId") == firstProject,
"Stopping preview preserves acquisition and project identity.");
check(worker.frame().is_null(), "Stopping preview clears the shared frame cache.");
preview = run(worker, "startPreview");
check(preview.value("previewEnabled", false) && preview.value("scanning", false),
"Starting preview does not start or stop acquisition.");
run(worker, "stopScan");
check(!worker.status().value("scanning", true) && worker.status().value("previewEnabled", false),
"Stopping acquisition preserves the project preview.");
run(worker, "startScan");
const auto pausedSnapshot = run(worker, "dataSnapshot", {{"pauseAcquisition", true}});
check(pausedSnapshot.value("pauseAcquisition", false) && !pausedSnapshot.value("scanning", true) &&
!worker.status().value("scanning", true) && worker.status().value("previewEnabled", false) &&
worker.status().at("projectId") == firstProject,
"Opt-in snapshot pauses acquisition and preserves preview and project without restarting scan.");
const Json parameters = {
{"pointDistance", 0.1}, {"brightness", 8}, {"lightSourceMode", 2},
{"scanFrameRate", 30}, {"highSpeedMode", false}, {"addMarkerMode", true},
{"viewLock", false}, {"localEnlargedView", true}, {"qualityColor", false},
{"strongLight", true}, {"preScanMode", false}, {"markerDiameters", {3, 6}}};
run(worker, "parameters", parameters);
const auto caps = worker.query("capabilities", Json::object());
check(caps.at("lastParameterCommands") == parameters,
"Mock cache records submitted fields while preserving explicit false.");
check(caps.at("parameterStateSource").get<std::string>().find("not hardware readback") !=
std::string::npos,
"Command cache must not claim hardware readback.");
rejected(worker, "meshConfirm", Json::object(), "mesh_required");
rejected(worker, "meshUndo", Json::object(), "mesh_required");
rejected(worker, "export", {{"formats", {"STL"}}}, "mesh_confirmation_required");
auto mesh = std::async(std::launch::async, [&] { return run(worker, "mesh"); });
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2);
while (!worker.status().value("busy", false) && std::chrono::steady_clock::now() < deadline)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
check(worker.status().value("busy", false),
"Delayed explicit mock mesh exposes the real dynamic busy gate.");
rejected(worker, "parameters", {{"brightness", 1}}, "device_busy");
check(!worker.can_close(true), "Shutdown cannot overlap an active worker command.");
mesh.get();
check(worker.status().value("meshState", std::string()) == "preview",
"Mesh success transitions to preview stage.");
rejected(worker, "export", {{"formats", {"STL"}}}, "mesh_confirmation_required");
rejected(worker, "startScan", Json::object(), "processing_active");
for (const auto &action : std::vector<std::pair<std::string, Json>>{
{"align", {{"action", "enter"}}}, {"edit", syntactic_edit()}, {"clipPlane", clip_request()}})
rejected(worker, action.first, action.second, "undo_mesh_first");
run(worker, "meshConfirm");
check(worker.status().value("meshState", std::string()) == "confirmed",
"Confirm transitions the mesh to the exportable stage.");
const auto exported =
run(worker, "export", {{"name", u8"离线结果"}, {"formats", contracts::export_formats()}});
check(exported.at("files").size() == 14,
"All 14 format requests map to clearly marked offline fixtures.");
for (const auto &file : exported.at("files")) {
const auto stored = worker.query("file", {{"fileId", file.at("fileId")}});
const auto path = fs::path(wide(stored.at("path").get<std::string>()));
const auto content = bytes(path);
const auto id = file.at("fileId").get<std::string>();
check(id.size() == 32 && file.at("downloadUrl") == "/api/v1/files/" + id,
"Download URLs must use registered identifiers.");
check(path.extension() == L".txt" && path.filename().wstring().rfind(L"SIMULATED_", 0) == 0 &&
content.find("OFFLINE_TEST_FIXTURE") != std::string::npos &&
content.find("not valid scanner geometry") != std::string::npos,
"Fixture exports must never masquerade as real STL/PLY/CAD geometry.");
check(fs::exists(path) &&
fs::absolute(root / L"Exports") == fs::path(wide(stored.at("root").get<std::string>())),
"Artifacts must be registered under this isolated root.");
}
rejects([&] { worker.query("file", {{"fileId", "../unregistered"}}); }, 404, "file_not_found");
run(worker, "meshUndo");
check(worker.status().value("meshState", std::string()) == "none",
"Undo returns to source-data processing stage.");
for (const auto *action : {"enter", "next", "cancel", "exit"}) {
Json body = {{"action", action}};
if (std::string(action) == "exit")
body["confirm"] = true;
check(run(worker, "align", body).at("operation") == action,
"Alignment action mapping must remain exact.");
}
check(run(worker, "clipPlane", clip_request()).value("clipped", false),
"The explicit mock clipping branch is reachable without claiming geometry exists.");
rejected(worker, "calibrationEnter", Json::object(), "project_open");
const auto second = run(worker, "createProject", {{"name", "Second"}}).at("projectId");
check(second != firstProject, "Project replacement changes its identity.");
auto staleProject = confirmation(worker.status(), true);
staleProject["expectedProjectId"] = firstProject;
rejected(worker, "disconnect", staleProject, "project_changed");
auto discard = confirmation(worker.status());
rejected(worker, "disconnect", discard, "project_discard_confirmation_required");
discard = confirmation(worker.status(), true);
discard.erase("expectedProjectId");
rejected(worker, "disconnect", discard, "project_confirmation_required");
const auto fileCount = worker.files().size();
check(fileCount == 16, "Worker registry preserves all export and snapshot descriptors.");
run(worker, "startScan");
const auto ended = run(worker, "disconnect", confirmation(worker.status(), true));
check(ended.value("acquisitionStopped", false) && ended.value("projectSessionClosed", false) &&
ended.at("previousProjectId") == second,
"Disconnect pauses acquisition and ends the reviewed project session.");
const auto final = worker.status();
check(!final.value("initialized", true) && !final.value("scanning", true) &&
!final.value("projectReady", true) && !final.value("previewEnabled", true) &&
final.at("sessionId").is_null(),
"Disconnected status cannot retain a live session or project.");
check(worker.files().size() == fileCount && worker.can_close(false),
"Safe release preserves registered files and permits process retirement.");
check(fs::exists(fs::path(wide(descriptor.at("path").get<std::string>()))),
"Session release must preserve existing artifact files.");
rejected(worker, "connect", Json::object(), "worker_restart_required");
rejected(worker, "disconnect", confirmation(initial), "session_changed");
check(run(worker, "disconnect", confirmation(final)).value("alreadyDisconnected", false),
"Disconnecting an already released worker is idempotent.");
no_vendor_dll();
return originalSession;
}
void replacement_session_aba(const fs::path &root, const std::string &stale) {
WorkerService worker(root, configuration(), true);
run(worker, "connect");
const auto current = worker.status();
check(current.at("sessionId") != stale && !current.value("projectReady", true),
"A replacement worker must establish a fresh session even with identical empty-project flags.");
auto previous = confirmation(current);
previous["expectedSessionId"] = stale;
rejected(worker, "disconnect", previous, "session_changed");
check(worker.status().value("initialized", false) &&
worker.status().at("sessionId") == current.at("sessionId"),
"An ABA confirmation cannot end the replacement worker session.");
run(worker, "disconnect", confirmation(current));
}
void calibration_workflow(const fs::path &root) {
WorkerService worker(root, configuration(), true);
run(worker, "connect");
const std::vector<std::pair<std::string, Json>> steps = {
{"calibrationSetMode", {{"mode", 2}}},
{"calibrationSetTrakType", {{"trakType", 3}, {"confirm", true}}},
{"calibrationSetFree", {{"enabled", true}, {"confirm", true}}},
{"calibrationSetAdvanced", {{"enabled", false}, {"confirm", true}}},
{"calibrationStart", {{"confirm", true}}},
{"calibrationStartSystem", {{"confirm", true}}},
{"calibrationCapturePose", {{"confirm", true}}},
{"calibrationCompute", {{"confirm", true}}},
{"calibrationApplyLast", {{"mode", 1}, {"confirm", true}}}};
for (const auto &step : steps)
rejected(worker, step.first, step.second, "calibration_required");
run(worker, "calibrationEnter");
const std::vector<std::string> modeNames = {"跟踪仪标定", "系统标定", "探针标定", "UE Nova 激光标定"};
for (int mode = 0; mode < 4; ++mode) {
for (const auto &action : {std::string("calibrationSetMode"), std::string("calibrationApplyLast")}) {
Json request{{"mode", mode}};
if (action == "calibrationApplyLast") request["confirm"] = true;
const auto result = run(worker, action, request);
check(result.at("action") == action && result.at("status") == "confirmed" &&
result.at("calibrationActive") == true,
"Adding mode labels must preserve every original calibration result field.");
check(result.at("mode").is_number_integer() && result.at("mode") == mode &&
result.at("modeName") == modeNames[mode],
"Each numeric calibration mode has its corresponding Chinese label.");
const auto cached = worker.query("capabilities", Json::object()).at("calibration");
check(cached.at("mode") == mode && cached.at("modeName") == modeNames[mode],
"Capabilities preserve the numeric receipt and add the same label.");
const auto choices = worker.query("capabilities", Json::object()).at("calibrationModes");
check(choices.size() == 4 && choices.at(mode).at("mode") == mode &&
choices.at(mode).at("modeName") == modeNames[mode],
"Enum choices stay complete and distinct from the currently selected mode.");
}
}
for (const auto &step : steps) {
const auto result = run(worker, step.first, step.second);
check(result.at("action") == step.first && result.value("calibrationActive", false),
"All ten calibration commands must preserve exact action mapping.");
}
check(worker.status().value("calibrationSystemStarted", false) &&
worker.status().value("calibrationFreeEnabled", false),
"Confirmed system/free calibration phases are retained until the SDK session ends.");
rejected(worker, "calibrationStartSystem", {{"confirm", true}}, "calibration_already_started");
const auto recovery = worker.recovery_info();
check(recovery.value("calibrationSession", false) && !recovery.value("projectReady", true) &&
recovery.at("sessionId") == worker.status().at("sessionId") &&
!worker.status().contains("owner"),
"Internal recovery metadata identifies the calibration session without exposing process ownership in public status.");
const auto state = worker.query("capabilities", Json::object()).at("calibration");
check(state.value("mode", -1) == 1 && state.value("modeName", std::string()) == "系统标定" && state.value("trakType", -1) == 3 &&
state.value("lastConfirmedAction", std::string()) == "applyLast" &&
state.value("source", std::string()) == "last_confirmed_command_not_hardware_progress",
"Calibration state is only a receipt cache, never hardware quality or progress.");
run(worker, "createProject");
check(!worker.status().value("calibrationActive", true),
"Creating a project finishes the calibration workflow in the new scan session.");
rejected(worker, "calibrationEnter", Json::object(), "project_open");
worker.shutdown();
no_vendor_dll();
}
void calibration_timeout_recovery_state(const fs::path &root) {
WorkerService worker(root, configuration(), true);
run(worker, "connect");
const auto session = worker.status().at("sessionId");
run(worker, "calibrationEnter");
{ std::ofstream marker(root / L"OFFLINE_TEST_CALIBRATION_START_TIMEOUT"); marker << "offline only"; }
rejected(worker, "calibrationStartSystem", {{"confirm", true}}, "sdk_timeout", 504);
const auto after = worker.status();
check(after.value("restartRequired", false) && after.at("recoverySessionId") == session,
"A timed out calibration retains its original confirmation identity for recovery.");
const auto internal = worker.recovery_info();
check(internal.value("calibrationSession", false) && internal.at("sessionId") == session &&
!internal.value("projectReady", true),
"The independent recovery RPC remains usable after the normal command guard rejects operations.");
rejected(worker, "calibrationStartSystem", {{"confirm", true}}, "restart_required");
check(worker.can_close(true), "Normal shutdown remains available after a calibration completion timeout.");
worker.shutdown();
check(!worker.recovery_info().value("calibrationSession", true), "Release clears the calibration safety latch.");
no_vendor_dll();
}
Json wait_preview_frame(WorkerService &worker, uint64_t after = 0) {
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(4);
while (std::chrono::steady_clock::now() < deadline) {
auto frame = worker.frame();
if (frame.is_object() && frame.at("sequence").get<uint64_t>() > after)
return frame;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
throw std::runtime_error("Offline preview did not publish a fresh JPEG.");
}
void preview_callback_workflow(const fs::path &root) {
WorkerService worker(root, configuration(), true);
run(worker, "connect", {{"deviceType", 3}});
run(worker, "createProject");
auto frame = wait_preview_frame(worker);
const auto snapshot = frame_from_json(frame);
check(snapshot.width == 640 && snapshot.height == 360 && !snapshot.jpeg.empty(),
"Buffered preview preserves the simulated source dimensions and valid JPEG bytes.");
{
IStream *stream = nullptr;
if (FAILED(CreateStreamOnHGlobal(nullptr, TRUE, &stream)))
throw std::runtime_error("Cannot decode offline orientation fixture.");
struct Release { IStream *stream; ~Release() { stream->Release(); } } release{stream};
ULONG written = 0;
if (FAILED(stream->Write(snapshot.jpeg.data(), static_cast<ULONG>(snapshot.jpeg.size()), &written)) ||
written != snapshot.jpeg.size())
throw std::runtime_error("Cannot write offline orientation fixture.");
LARGE_INTEGER zero{};
stream->Seek(zero, STREAM_SEEK_SET, nullptr);
Gdiplus::Bitmap image(stream, FALSE);
check(image.GetLastStatus() == Gdiplus::Ok, "Buffered output is a decodable JPEG.");
auto yellow_pixels = [&](int first, int last) {
size_t count = 0;
for (int y = first; y < last; ++y)
for (int x = 8; x < 400; ++x) {
Gdiplus::Color color;
if (image.GetPixel(x, y, &color) == Gdiplus::Ok && color.GetR() > 150 &&
color.GetG() > 120 && color.GetB() < 160)
++count;
}
return count;
};
check(yellow_pixels(30, 100) > 100 && yellow_pixels(260, 330) < 10,
"Moving vertical flip off the callback keeps the mock label at the top, not upside down.");
}
run(worker, "startScan");
std::vector<std::future<void>> readers;
for (int reader = 0; reader < 3; ++reader)
readers.push_back(std::async(std::launch::async, [&] {
for (int n = 0; n < 100; ++n) {
check(worker.status().at("simulated") == true,
"Concurrent status remains explicitly simulated.");
const auto current = worker.frame();
check(current.is_null() || current.at("jpeg").is_string(),
"Concurrent readers see whole JPEG snapshots, never partially reused storage.");
}
}));
for (int cycle = 0; cycle < 6; ++cycle) {
const auto previous = frame.at("sequence").get<uint64_t>();
run(worker, "stopPreview");
std::this_thread::sleep_for(std::chrono::milliseconds(60));
check(worker.frame().is_null(),
"An old queued or encoding frame cannot republish after stopping preview.");
check(worker.status().at("scanning") == true,
"Preview lifecycle changes preserve the active acquisition state.");
run(worker, "startPreview");
frame = wait_preview_frame(worker, previous);
}
for (auto &reader : readers)
reader.get();
run(worker, "stopScan");
const auto previous = frame.at("sequence").get<uint64_t>();
run(worker, "createProject");
frame = wait_preview_frame(worker, previous);
check(worker.status().at("previewFresh") == true && !frame_from_json(frame).jpeg.empty(),
"A new project publishes a fresh frame after the previous frame epoch is invalidated.");
run(worker, "stopPreview");
std::this_thread::sleep_for(std::chrono::milliseconds(80));
const auto metrics = worker.query("previewMetrics", Json::object());
const auto &capture = metrics.at("captureDiagnostics");
const auto &pool = metrics.at("bufferPool");
check(capture.at("callbackEntries").get<uint64_t>() >= 6 &&
capture.at("callbackEntries") == capture.at("completedCallbacks") &&
capture.at("callbacksInFlight") == 0 && capture.at("lastChannels") == 4,
"Callback diagnostics count the same real entry path used by offline rendering.");
check(capture.at("exceptions") == 0 && capture.at("averageCopyMs").get<double>() >= 0 &&
capture.at("maxCallbackMs").get<double>() >= capture.at("averageCallbackMs").get<double>(),
"Completed callback timings remain valid without synchronous callback logging.");
check(pool.at("capacity") == 3 && pool.at("allocatedSlots").get<uint64_t>() <= 3 &&
pool.at("reuses").get<uint64_t>() > 0 && pool.at("inUse") == 0,
"Preview restarts reuse bounded buffers and release all leases after stopping.");
worker.shutdown();
no_vendor_dll();
}
void framework_workflow(const fs::path &root) {
WorkerService worker(root, configuration(), true);
check(worker.status().at("scanType").is_null() && worker.status().at("scanDevice").is_null(),
"A disconnected worker cannot claim confirmed acquisition settings.");
run(worker, "connect");
rejected(worker, "setScanType", {{"scanType", "mesh"}}, "project_required");
run(worker, "createProject", {{"mode", "trak"}});
auto state = worker.status();
check(state.at("scanType") == "mesh" && state.at("scanDevice") == "scanner" &&
!state.value("frameworkImported", true) && state.value("frameworkFileCount", 99) == 0 &&
!state.value("projectHasAcquisition", true),
"New projects establish mesh/scanner and reset framework data flags.");
auto same = run(worker, "setScanType", {{"scanType", "mesh"}});
check(same.value("alreadyInRequestedState", false) && !same.value("deviceChanged", true) &&
same.value("sdkScanDeviceType", -1) == 1 && !same.value("acquisitionStarted", true),
"Setting the existing mesh type is idempotent and TE Nova uses SDK value 1.");
rejected(worker, "setScanType", {{"scanType", "markers"}}, "unsupported_scan_type");
rejected(worker, "setScanType", {{"scanType", "photogrammetry"}, {"device", "scanner"}},
"unsupported_scan_type");
rejected(worker, "setScanType", {{"scanType", "photogrammetry"}}, "confirmation_required", 400);
auto photo = run(worker, "setScanType", {{"scanType", "photogrammetry"}, {"confirm", true}});
check(photo.value("sdkScanType", -1) == 0 && photo.value("sdkScanDeviceType", -1) == 0 &&
photo.at("scanDevice") == "tracker" && !worker.status().value("scanning", true),
"Photogrammetry selects UE Nova SDK 0 and never starts acquisition automatically.");
rejected(worker, "optimizeFramework", Json::object(), "framework_capture_required");
rejected(worker, "export", {{"formats", {"P3"}}}, "mesh_confirmation_required");
run(worker, "startScan");
rejected(worker, "setScanType", {{"scanType", "mesh"}}, "scan_active");
rejected(worker, "optimizeFramework", Json::object(), "scan_active");
run(worker, "stopScan");
auto optimized = run(worker, "optimizeFramework");
check(optimized.value("frameworkOptimized", false) &&
worker.status().value("frameworkHasAcquisition", false),
"Only confirmed optimization permits saving the acquired framework.");
auto savedFramework = run(worker, "export", {{"formats", {"P3"}}});
check(savedFramework.at("dataKind") == "framework" && savedFramework.at("files").size() == 1 &&
savedFramework.at("files").at(0).at("name").get<std::string>().find(".fixture.txt") != std::string::npos &&
worker.status().at("meshState") == "none",
"Optimized P3-only export requires no mesh and simulation writes only a labeled fixture TXT.");
rejected(worker, "export", {{"formats", {"P3", "STL"}}}, "mesh_confirmation_required");
run(worker, "startScan");
run(worker, "stopScan");
check(!worker.status().value("frameworkOptimized", true),
"Resuming photogrammetry invalidates the previous optimization receipt.");
rejected(worker, "export", {{"formats", {"P3"}}}, "mesh_confirmation_required");
rejected(worker, "setScanType", {{"scanType", "mesh"}, {"device", "scanner"}, {"confirm", true}},
"project_data_present");
auto mesh = run(worker, "setScanType", {{"scanType", "mesh"}});
check(mesh.at("scanDevice") == "tracker" && !mesh.value("deviceChanged", true) &&
worker.status().value("projectHasAcquisition", false),
"Mesh with no device preserves the active UE device and collected framework data.");
const auto id = std::string(32, 'a');
const Json request = {{"fileIds", {id}}, {"confirm", true}};
rejected(worker, "importFramework", request, "framework_mode_required");
run(worker, "createProject");
rejected(worker, "importFramework", request, "framework_file_not_found", 404);
const auto uploads = root / L"FrameworkUploads";
fs::create_directory(uploads);
const auto file = uploads / wide(id + ".p3");
{ std::ofstream fixture(file); fixture << "OFFLINE_TEST_FIXTURE_NOT_VALID_GEOMETRY\n"; }
run(worker, "startScan");
rejected(worker, "importFramework", request, "scan_active");
run(worker, "stopScan");
auto imported = run(worker, "importFramework", request);
check(imported.value("frameworkImported", false) && imported.value("frameworkFileCount", 0) == 1 &&
!imported.value("acquisitionStarted", true) && !worker.status().value("scanning", true),
"A simulated framework import reports only a receipt, without acquisition or fabricated data.");
check(worker.files().size() == 1 && worker.query("sceneInfo", Json::object()).value("simulated", false),
"Import simulation adds no downloadable geometry; only the earlier export fixture exists.");
rejected(worker, "setScanType", {{"scanType", "photogrammetry"}, {"confirm", true}},
"project_data_present");
const auto capability = worker.query("capabilities", Json::object()).at("framework");
check(capability.value("importAvailable", false) && !capability.value("deviceChangeAvailable", true) &&
!capability.value("stationRelocationCommandAvailable", true),
"Capabilities distinguish framework import from native leapfrog commands.");
run(worker, "createProject", {{"mode", "laser"}});
check(!worker.status().value("frameworkImported", true) &&
worker.status().value("frameworkFileCount", 99) == 0,
"Creating another project resets imported-framework state.");
rejected(worker, "setScanType", {{"scanType", "photogrammetry"}, {"confirm", true}},
"unsupported_scan_type");
check(run(worker, "setScanType", {{"scanType", "markers"}}).value("sdkScanType", -1) == 3,
"Laser marker capture uses FRAME SDK 3, not a relocation action.");
rejected(worker, "importFramework", request, "framework_mode_required");
run(worker, "disconnect", confirmation(worker.status(), true));
state = worker.status();
check(state.at("scanType").is_null() && state.at("scanDevice").is_null() &&
!state.value("frameworkImported", true) && !state.value("projectHasAcquisition", true),
"Disconnect resets all confirmed framework acquisition state.");
worker.shutdown();
no_vendor_dll();
}
} // namespace
int main() {
const auto com = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
try {
TemporaryRoot root;
no_vendor_dll();
calibration_completion_replies();
automatic_connection_policy();
pause_snapshot_flow();
disconnected_gates(root.path / L"unconnected");
const auto old = project_and_session_workflow(root.path / L"project");
replacement_session_aba(root.path / L"replacement", old);
calibration_workflow(root.path / L"calibration");
calibration_timeout_recovery_state(root.path / L"calibration_timeout");
calibration_compute_failure_workflow(root.path / L"calibration_compute_failure");
preview_callback_workflow(root.path / L"preview_callback");
framework_workflow(root.path / L"framework");
std::cout << "OFFLINE_TEST_FIXTURE: C++ worker tests passed: " << passed.load()
<< "; no SDK, hardware or HTTP listener.\n";
if (SUCCEEDED(com))
CoUninitialize();
return 0;
} catch (const std::exception &error) {
std::cerr << "FAIL (OFFLINE ONLY): " << error.what() << "\n";
if (SUCCEEDED(com))
CoUninitialize();
return 1;
}
}

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2013-2025 Niels Lohmann
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,9 @@
# 第三方源文件
`json.hpp` 来自 [nlohmann/json v3.12.0 官方发布](https://github.com/nlohmann/json/releases/tag/v3.12.0),许可证为 MIT,完整文本保存在 `LICENSE.nlohmann-json`。
- 官方下载地址:`https://github.com/nlohmann/json/releases/download/v3.12.0/json.hpp`
- 官方发布 SHA-256:`aaf127c04cb31c406e5b04a63f1ae89369fccde6d8fa7cdda1ed4f32dfc5de63`
- 下载后已核对上述散列;构建使用项目内固定头文件,不在构建时下载依赖。
HTTP 监听使用 Windows 自带的 [HTTP Server API](https://learn.microsoft.com/en-us/windows/win32/http/http-server-api-overview),JPEG 编码使用 Windows GDI+。这些 Windows 系统组件不作为第三方源码随包分发。

File diff suppressed because it is too large Load Diff