diff --git a/.gitignore b/.gitignore index ba69f35..a4e11a5 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,8 @@ **/__pycache__/ am-backend/script/ 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 diff --git a/AGENTS.md b/AGENTS.md index 70ccf76..ce14268 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,7 @@ # 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 用户要求坐标系使用只保存名称、按名称调用。GET/APPLY、工作流目标位姿和命名MoveL/MoveJPose、动作队列使用节点忽略历史固定版本;新保存剔除对应版本字段,不改写数据库中的冻结版本及历史执行。UPDATE/DELETE仍保留记录版本并发保护。内部必须继续核对同名最新记录已完整实际应用、实际TCP和运动期间记录身份,不能为按名字调用取消这些检查、自动应用或重发运动。用户本轮明确授权全部平台代码完成验证后提交并推送现有main;不据此重启正式服务或部署边端。 diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerCommandJournal.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerCommandJournal.java index 1ee9ec8..34c5d3c 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerCommandJournal.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerCommandJournal.java @@ -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) .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) { 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); } diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerMonitoringService.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerMonitoringService.java index 9d2ed65..884407f 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerMonitoringService.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerMonitoringService.java @@ -20,6 +20,12 @@ public class ScannerMonitoringService { 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) { + 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) { JsonNode context=journal.latestContext(instId); if(context!=null&&(operation==ScannerOperation.SNAPSHOT||operation==ScannerOperation.EXPORT)) { @@ -51,6 +57,107 @@ public class ScannerMonitoringService { return journal.context(commandKey); } 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) { String key=ScannerService.hash("view-snapshot:"+instId+":"+ScannerService.key(requestedKey)); diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerOperation.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerOperation.java index e739709..0768c35 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerOperation.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerOperation.java @@ -29,6 +29,9 @@ public enum ScannerOperation { SNAPSHOT("POST", "/api/v1/data/snapshots", "创建原始场景快照", "SCANNER_SNAPSHOT"), SCENE("GET", "/api/v1/data/scene", "读取最近场景摘要", "SCANNER_SCENE"), 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_MODE("POST", "/api/v1/calibration/setMode", "选择标定模式", "SCANNER_CALIBRATION_MODE"), 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 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 static ScannerOperation forAction(String action) { return Arrays.stream(values()).filter(op -> op.action!=null && op.action.equals(action)).findFirst().orElse(null); diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerStreamingConfiguration.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerStreamingConfiguration.java index ed99064..8f37835 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerStreamingConfiguration.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerStreamingConfiguration.java @@ -15,6 +15,6 @@ public class ScannerStreamingConfiguration implements WebMvcConfigurer { @Override public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) { 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"); } } diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/cmvr/LabMaintenanceScannerViewController.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/cmvr/LabMaintenanceScannerViewController.java new file mode 100644 index 0000000..bf6ca77 --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/cmvr/LabMaintenanceScannerViewController.java @@ -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 view(@RequestParam String instId){return CommonResult.success(views.view(instId));} + @GetMapping("/execution") public CommonResult execution(@RequestParam String instId){return CommonResult.success(views.execution(instId));} + @GetMapping("/image") public ResponseEntity 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 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());} +} diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabMaintenanceScannerViewService.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabMaintenanceScannerViewService.java new file mode 100644 index 0000000..86cdb9b --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabMaintenanceScannerViewService.java @@ -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(); + 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();} + } +} diff --git a/am-web/src/api/lab/maintenance.ts b/am-web/src/api/lab/maintenance.ts index 0d19b53..29392c6 100644 --- a/am-web/src/api/lab/maintenance.ts +++ b/am-web/src/api/lab/maintenance.ts @@ -1,4 +1,5 @@ import request from '@/cmvr/request' +import platformRequest from '@/config/axios' import { loadMaintenanceDefinition } from '@/views/lab/dimension/maintenance.mjs' interface NativeResult { @@ -54,3 +55,42 @@ export async function getMaintenanceStatus(instId: string, signal: AbortSignal) if (data?.instId !== instId) throw new Error('执行状态暂未同步') return data } + +export async function getMaintenanceExecution(instId: string, signal?: AbortSignal) { + const data = await platformRequest.get({ + 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('/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 | null + temperatures?: { + scanner?: { value: number; receivedAt?: string } | null + tracker?: { value: number; receivedAt?: string } | null + } | null +} diff --git a/am-web/src/api/lab/scan-task/scannerView.ts b/am-web/src/api/lab/scan-task/scannerView.ts index 9602a0e..6a82f65 100644 --- a/am-web/src/api/lab/scan-task/scannerView.ts +++ b/am-web/src/api/lab/scan-task/scannerView.ts @@ -1,10 +1,11 @@ +import type { CalibrationTelemetry } from '@/api/lab/maintenance' import request from '@/config/axios' import { authenticatedFetch } from '@/config/axios/authenticatedFetch' import { readScannerBinary } from '@/views/lab/scan-task/scannerBinary.mjs' import { consumeScannerMjpeg } from '@/cmvr/common/utils/scannerMjpeg.mjs' import { scannerPreviewTarget } from '@/views/lab/scan-task/scannerPreviewTarget.mjs' -export interface ScannerExecutionView { +export interface ScannerExecutionView extends CalibrationTelemetry { executionId: string executionNo?: string taskId?: string @@ -22,22 +23,72 @@ export interface ScannerExecutionView { meshState?: string } 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) - return request.get({ url: target.path + target.view, params: target.params, signal }) + return request.get({ + 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 ScannerSnapshotCommand { commandKey?: string; key?: string; state: string; taskId?: string; error?: string; result?: string } +export interface ScannerAsset { + 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) => request.get({ url: path + '/assets', params: { executionId }, signal }) -export const createScannerSnapshot = (executionId: string | number, commandKey: string, signal?: AbortSignal) => - request.post({ 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({ url: path + '/snapshot-command', params: { executionId, commandKey }, signal }) +export const createScannerSnapshot = ( + executionId: string | number, + commandKey: string, + signal?: AbortSignal +) => + request.post({ + 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({ + url: path + '/snapshot-command', + params: { executionId, commandKey }, + signal + }) -export async function getScannerAsset(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 }) +export async function getScannerAsset( + 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')) { const error = await response.json().catch(() => ({})) 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) { - 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')) { const error = await response.json().catch(() => ({})) throw new Error(error.msg || '扫描画面暂不可用,正在重新核对状态') @@ -54,13 +108,28 @@ export async function getScannerExecutionImage(executionId: string | number, sig 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 query = new URLSearchParams(Object.entries(target.params).map(([key,value]) => [key,String(value)])) - const response = await authenticatedFetch(`${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 query = new URLSearchParams( + Object.entries(target.params).map(([key, value]) => [key, String(value)]) + ) + const response = await authenticatedFetch( + `${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(() => ({})) throw new Error(error.msg || '扫描流暂不可用,正在重新核对状态') } diff --git a/am-web/src/views/lab/dimension/CalibrationMonitor.vue b/am-web/src/views/lab/dimension/CalibrationMonitor.vue new file mode 100644 index 0000000..d905b15 --- /dev/null +++ b/am-web/src/views/lab/dimension/CalibrationMonitor.vue @@ -0,0 +1,288 @@ + + + + + diff --git a/am-web/src/views/lab/dimension/MaintenanceActions.vue b/am-web/src/views/lab/dimension/MaintenanceActions.vue index ffd11a3..98fb485 100644 --- a/am-web/src/views/lab/dimension/MaintenanceActions.vue +++ b/am-web/src/views/lab/dimension/MaintenanceActions.vue @@ -8,6 +8,9 @@ @click="openAction(action)" >{{ action.label }}{{ busy && state.actionKey === action.key ? '(正在执行)' : '' }} + 查看标定过程 扫描仪最后标定时间:{{ calibrationDate }} @@ -75,6 +78,25 @@ > + + + + diff --git a/am-web/src/views/lab/scan-task/calibrationTelemetry.mjs b/am-web/src/views/lab/scan-task/calibrationTelemetry.mjs new file mode 100644 index 0000000..2ef541b --- /dev/null +++ b/am-web/src/views/lab/scan-task/calibrationTelemetry.mjs @@ -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) + } +} diff --git a/am-web/src/views/lab/scan-task/scannerPreviewTarget.mjs b/am-web/src/views/lab/scan-task/scannerPreviewTarget.mjs index e5d1a32..4d2611b 100644 --- a/am-web/src/views/lab/scan-task/scannerPreviewTarget.mjs +++ b/am-web/src/views/lab/scan-task/scannerPreviewTarget.mjs @@ -1,8 +1,27 @@ export function scannerPreviewTarget(scope, id) { - if (scope === 'fixture') return { path: '/lab/master/fixture/framework', params: { recordingId: id }, stream: 'preview-stream', view: '/view' } - if (scope === 'execution') return { path: '/lab/execution/scanner-view', params: { executionId: id }, stream: 'stream', view: '' } - throw new Error('未知扫描预览来源') + if (scope === 'fixture') + return { + 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 = []) { - return history.find(record => record.status === 'RUNNING' && record.id && record.instanceId) + return history.find((record) => record.status === 'RUNNING' && record.id && record.instanceId) } diff --git a/am-web/src/views/lab/scan-task/scannerPreviewTarget.test.mjs b/am-web/src/views/lab/scan-task/scannerPreviewTarget.test.mjs index 62f2280..c5e401b 100644 --- a/am-web/src/views/lab/scan-task/scannerPreviewTarget.test.mjs +++ b/am-web/src/views/lab/scan-task/scannerPreviewTarget.test.mjs @@ -4,6 +4,7 @@ import { scannerPreviewTarget, activeFixtureRecording } from './scannerPreviewTa test('夹具预览按录入记录绑定,普通执行的接口保持原样',()=>{ 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('maintenance','calibration-A'),{path:'/lab/maintenance/scanner-view',params:{instId:'calibration-A'},stream:'stream',view:''}) assert.throws(()=>scannerPreviewTarget('bad',1)) }) test('开始录入自动提供预览,完成、失败与终止均不再预览历史工程',()=>{ diff --git a/deploy/windows11/RELEASE-20261121-calibration-window.md b/deploy/windows11/RELEASE-20261121-calibration-window.md new file mode 100644 index 0000000..67efd01 --- /dev/null +++ b/deploy/windows11/RELEASE-20261121-calibration-window.md @@ -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 窗口及现场弹窗布局仍需部署后验收。 diff --git a/docs/scan-motor-workflow.md b/docs/scan-motor-workflow.md index 0b36091..acf8756 100644 --- a/docs/scan-motor-workflow.md +++ b/docs/scan-motor-workflow.md @@ -84,7 +84,7 @@ 窗口再次打开时复用当前页面中仍适用的上次选择,机器人及设备按实时资源列表重新匹配,失效或新增配置需要补选。弹窗期间若用例重新发布,开始前刷新配置并提示再次核对,不按旧版本静默启动。需要临时输入的业务参数应在开始节点声明,节点内部固定配置仍在用例页面维护。 -沿用资源类型、身份、设备状态和占用校验;取得执行实例后关闭窗口,按钮保持 loading 并跟踪该实例的真实成功、失败或终止状态。扫描仪标定结束后重新获取最后标定时间。 +沿用资源类型、身份、设备状态和占用校验;取得执行实例后关闭执行设置窗口,按钮保持 loading 并跟踪该实例的真实成功、失败或终止状态。扫描仪标定另自动打开画面与步骤监视窗口,结束后重新获取最后标定时间。 ### 结束标定并恢复设备(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”的真实文件路径,当前不能宣称网格化和导出已通过现场验收。 已运行任务保持冻结版本及失败日志。显式运行 `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`。 + +此功能需要同时更新平台和配套扫描仪服务。源代码编译与离线、合成窗口验证不等于已安装或完成厂家真机标定验收;正式替换及现场验证应在用户另行通知更新、设备停稳后进行。 diff --git a/integrations/freescan-service/.clang-format b/integrations/freescan-service/.clang-format new file mode 100644 index 0000000..81d4855 --- /dev/null +++ b/integrations/freescan-service/.clang-format @@ -0,0 +1,8 @@ +BasedOnStyle: LLVM +IndentWidth: 4 +ColumnLimit: 110 +BreakBeforeBraces: Attach +AllowShortFunctionsOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +SortIncludes: Never diff --git a/integrations/freescan-service/CMakeLists.txt b/integrations/freescan-service/CMakeLists.txt new file mode 100644 index 0000000..429e31c --- /dev/null +++ b/integrations/freescan-service/CMakeLists.txt @@ -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() diff --git a/integrations/freescan-service/README.md b/integrations/freescan-service/README.md new file mode 100644 index 0000000..ffbd5a9 --- /dev/null +++ b/integrations/freescan-service/README.md @@ -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)。 diff --git a/integrations/freescan-service/SOURCE-ORIGIN.json b/integrations/freescan-service/SOURCE-ORIGIN.json new file mode 100644 index 0000000..f5cde88 --- /dev/null +++ b/integrations/freescan-service/SOURCE-ORIGIN.json @@ -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" + } + } +} diff --git a/integrations/freescan-service/build.ps1 b/integrations/freescan-service/build.ps1 new file mode 100644 index 0000000..6261a60 --- /dev/null +++ b/integrations/freescan-service/build.ps1 @@ -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} diff --git a/integrations/freescan-service/run-tests.ps1 b/integrations/freescan-service/run-tests.ps1 new file mode 100644 index 0000000..65faf09 --- /dev/null +++ b/integrations/freescan-service/run-tests.ps1 @@ -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 +} diff --git a/integrations/freescan-service/src/auto_connection.hpp b/integrations/freescan-service/src/auto_connection.hpp new file mode 100644 index 0000000..9057fbf --- /dev/null +++ b/integrations/freescan-service/src/auto_connection.hpp @@ -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 hold(gate); + paused = true; + nextAttempt = 0; + phase = enabled ? "paused" : "disabled"; + message = "已手动断开或请求停止,自动连接暂停;手动连接可恢复。"; + } + void resume() { + std::lock_guard hold(gate); + paused = blocked = false; + nextAttempt = 0; + phase = enabled ? "waiting" : "disabled"; + message = "已请求手动连接。"; + } + void protect(bool active = true) { + std::lock_guard hold(gate); + protectedSession = active; + } + bool may_restart() const { + std::lock_guard hold(gate); + return enabled && !paused && !blocked && !protectedSession; + } + void restarted(bool forced, int64_t now) { + std::lock_guard hold(gate); + ++restartCount; + lastRestart = now; + lastRestartForced = forced; + } + AutoConnectionAction decide(const Json &status, int64_t now) { + std::lock_guard 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 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 hold(gate); + if (paused) + return; + phase = "connected"; + message = "SDK已连接。"; + lastError = nullptr; + nextAttempt = 0; + } + Json snapshot() const { + std::lock_guard 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 diff --git a/integrations/freescan-service/src/calibration_completion.hpp b/integrations/freescan-service/src/calibration_completion.hpp new file mode 100644 index 0000000..95d5a81 --- /dev/null +++ b/integrations/freescan-service/src/calibration_completion.hpp @@ -0,0 +1,100 @@ +#pragma once +#include "common.hpp" +#include + +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::transform(result.begin(), result.end(), result.begin(), + [](unsigned char c) { return static_cast(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(); + 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(); + 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 &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(); + 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 diff --git a/integrations/freescan-service/src/calibration_files.hpp b/integrations/freescan-service/src/calibration_files.hpp new file mode 100644 index 0000000..54259b0 --- /dev/null +++ b/integrations/freescan-service/src/calibration_files.hpp @@ -0,0 +1,66 @@ +#pragma once +#include "common.hpp" +#include + +namespace freescan::detail { +inline const char *calibration_file_type(std::wstring name) { + for (auto &letter : name) + letter = static_cast(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 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((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 diff --git a/integrations/freescan-service/src/calibration_recovery.hpp b/integrations/freescan-service/src/calibration_recovery.hpp new file mode 100644 index 0000000..4131848 --- /dev/null +++ b/integrations/freescan-service/src/calibration_recovery.hpp @@ -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() != 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 diff --git a/integrations/freescan-service/src/calibration_telemetry.hpp b/integrations/freescan-service/src/calibration_telemetry.hpp new file mode 100644 index 0000000..7d453d4 --- /dev/null +++ b/integrations/freescan-service/src/calibration_telemetry.hpp @@ -0,0 +1,39 @@ +#pragma once +#include "common.hpp" +#include +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(); + auto temperature=[&](const char *field,Json &target){ + auto value=message.find(field); + if(value!=message.end()&&value->is_number()&&std::isfinite(value->get())) + 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}}}};} +}; +} diff --git a/integrations/freescan-service/src/calibration_window_capture.cpp b/integrations/freescan-service/src/calibration_window_capture.cpp new file mode 100644 index 0000000..46a0131 --- /dev/null +++ b/integrations/freescan-service/src/calibration_window_capture.cpp @@ -0,0 +1,567 @@ +#include "calibration_window_capture.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 windows; +}; +BOOL CALLBACK find_window(HWND window, LPARAM context) { + auto &search = *reinterpret_cast(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 frame; + uint64_t publishedTick = 0; + HWND window = nullptr; + DWORD windowThread = 0; + ULONG_PTR windowClass = 0; + std::atomic 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 &state, const char *code, const std::string &message) { + std::lock_guard lock(state->mutex); + state->frame.reset(); + state->publishedTick = 0; + if (!state->cancel.load()) { + state->state = code; + state->message = message; + } +} + +std::vector encode_jpeg(IWICImagingFactory *factory, std::vector &pixels, + int width, int height, int &outputWidth, int &outputHeight) { + com_ptr bitmap; + check_hresult(factory->CreateBitmapFromMemory(width, height, GUID_WICPixelFormat32bppBGRA, + UINT(width * 4), UINT(pixels.size()), pixels.data(), bitmap.put())); + com_ptr source = bitmap.as(); + outputWidth = std::min(width, maxOutputWidth); + outputHeight = std::max(1, int(int64_t(height) * outputWidth / width)); + if (outputWidth != width) { + com_ptr scaler; + check_hresult(factory->CreateBitmapScaler(scaler.put())); + check_hresult(scaler->Initialize(source.get(), outputWidth, outputHeight, WICBitmapInterpolationModeFant)); + source = scaler.as(); + } + com_ptr converter; + check_hresult(factory->CreateFormatConverter(converter.put())); + check_hresult(converter->Initialize(source.get(), GUID_WICPixelFormat24bppBGR, WICBitmapDitherTypeNone, + nullptr, 0, WICBitmapPaletteTypeCustom)); + com_ptr stream; + check_hresult(CreateStreamOnHGlobal(nullptr, TRUE, stream.put())); + com_ptr encoder; + check_hresult(factory->CreateEncoder(GUID_ContainerFormatJpeg, nullptr, encoder.put())); + check_hresult(encoder->Initialize(stream.get(), WICBitmapEncoderNoCache)); + com_ptr frame; + com_ptr properties; + check_hresult(encoder->CreateNewFrame(frame.put(), properties.put())); + PROPBAG2 quality{}; + quality.pstrName = const_cast(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 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 &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 &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(&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 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 lock(state->mutex); + state->window = window; + state->windowThread = thread; + state->windowClass = atom; + state->source["windowHandle"] = std::to_string(reinterpret_cast(window)); + } + if (!owner_valid(*state) || !window_valid(*state, window, thread, atom)) + throw std::runtime_error("The manufacturer window changed during capture binding."); + + com_ptr device; + com_ptr 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(); + com_ptr inspectable; + check_hresult(CreateDirect3D11DeviceFromDXGIDevice(dxgi.get(), inspectable.put())); + const auto runtimeDevice = inspectable.as(); + auto interop = get_activation_factory(); + GraphicsCaptureItem item{nullptr}; + check_hresult(interop->CreateForWindow(window, guid_of(), put_abi(item))); + auto closed = item.Closed(auto_revoke, [weak = std::weak_ptr(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(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 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 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 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 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(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(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(std::chrono::steady_clock::now() - encodeStart).count(); + const auto age = std::max(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 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 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 frame; }; +View read_state(const std::shared_ptr &state, bool includeFrame) { + if (!state) + return {{{"source", "sdk_calibration_window"}, {"available", false}, {"state", "stopped"}, + {"sessionId", ""}, {"frameSource", nullptr}}, std::nullopt}; + std::lock_guard 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 current, retiring; + std::thread worker; + void stop_locked() { + if (!current) + return; + current->cancel.store(true); + { + std::lock_guard 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 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()) {} +CalibrationWindowCapture::~CalibrationWindowCapture() { stop(); } +void CalibrationWindowCapture::stop() { + std::lock_guard lock(impl_->control); + impl_->stop_locked(); +} +bool CalibrationWindowCapture::start(const std::string &sessionId, const Json &identity, std::string *error) { + std::lock_guard lock(impl_->control); + impl_->stop_locked(); + try { + if (impl_->retiring) { + std::lock_guard 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(); + const std::string creation = identity.at("startedFileTime").get(); + if (!pid || pid == GetCurrentProcessId() || pid > std::numeric_limits::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(); + 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 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 state; + { std::lock_guard lock(impl_->control); state = impl_->current; } + return read_state(state, false).metadata; +} +std::optional CalibrationWindowCapture::latestFrame() const { + std::shared_ptr state; + { std::lock_guard lock(impl_->control); state = impl_->current; } + return read_state(state, true).frame; +} +Json CalibrationWindowCapture::snapshot() const { + std::shared_ptr state; + { std::lock_guard 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 diff --git a/integrations/freescan-service/src/calibration_window_capture.hpp b/integrations/freescan-service/src/calibration_window_capture.hpp new file mode 100644 index 0000000..cbfaecb --- /dev/null +++ b/integrations/freescan-service/src/calibration_window_capture.hpp @@ -0,0 +1,27 @@ +#pragma once +#include "common.hpp" +#include + +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 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_; +}; +} // namespace freescan diff --git a/integrations/freescan-service/src/common.cpp b/integrations/freescan-service/src/common.cpp new file mode 100644 index 0000000..eb18281 --- /dev/null +++ b/integrations/freescan-service/src/common.cpp @@ -0,0 +1,160 @@ +#include "common.hpp" +#include +#include +#include +#include +#include +#include +#include + +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(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(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(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(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::system_clock::now().time_since_epoch()) + .count(); +} +std::string utc_from_ms(int64_t value) { + ULARGE_INTEGER ticks{}; + ticks.QuadPart = static_cast(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(tolower(static_cast(c))); + return id; +} +std::string base64_encode(const std::vector &value) { + if (value.empty()) + return {}; + DWORD size = 0; + CryptBinaryToStringA(value.data(), static_cast(value.size()), + CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, nullptr, &size); + std::string out(size, '\0'); + if (!CryptBinaryToStringA(value.data(), static_cast(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 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(value.size()), + CRYPT_STRING_BASE64 | CRYPT_STRING_STRICT, nullptr, &size, nullptr, nullptr)) + throw ApiError(502, "worker_protocol_error", "后台图像编码无效。"); + std::vector out(size); + if (size && + !CryptStringToBinaryA(value.data(), static_cast(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 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(&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()); + out.width = value.at("width").get(); + out.height = value.at("height").get(); + out.sourceWidth = value.at("sourceWidth").get(); + out.sourceHeight = value.at("sourceHeight").get(); + out.sequence = value.at("sequence").get(); + out.capturedMs = value.at("capturedMs").get(); + out.encodedMs = value.at("encodedMs").get(); + out.encodeMs = value.at("encodeMs").get(); + } 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 diff --git a/integrations/freescan-service/src/common.hpp b/integrations/freescan-service/src/common.hpp new file mode 100644 index 0000000..a8ff1b6 --- /dev/null +++ b/integrations/freescan-service/src/common.hpp @@ -0,0 +1,92 @@ +#pragma once +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#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 &value); +std::vector 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 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 diff --git a/integrations/freescan-service/src/contracts.cpp b/integrations/freescan-service/src/contracts.cpp new file mode 100644 index 0000000..d444818 --- /dev/null +++ b/integrations/freescan-service/src/contracts.cpp @@ -0,0 +1,717 @@ +#include "contracts.hpp" +#include +#include +#include +#include +#include + +namespace freescan::contracts { +namespace { +using Route = std::pair; +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 choices) { + for (const auto *choice : choices) + if (value == choice) + return true; + return false; +} +void fields(const Json &body, std::initializer_list 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; +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 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 codepoints(const std::string &value) { + std::vector result; + for (size_t i = 0; i < value.size();) { + unsigned char first = static_cast(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(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(); + 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()) + 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() <= static_cast(maximum) && + (minimum <= 0 || value.get() >= static_cast(minimum)); + if (!value.is_number_integer()) + return false; + const auto number = value.get(); + 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(); + 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 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 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(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(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(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(); + 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(), {"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 used; + for (const auto &value : values) { + if (!value.is_string()) + invalid(u8"fileIds 必须是已上传文件的 32 位小写十六进制 ID 数组。"); + const auto id = value.get(); + 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 used; + if (values.empty()) + invalid(u8"formats 不能为空。"); + for (const auto &value : values) { + if (!value.is_string()) + invalid(u8"formats 必须为受支持的大写格式名数组。"); + const auto format = value.get(); + 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 used; + if (values.empty()) + invalid(u8"include 不能为空。"); + for (const auto &value : values) + if (!value.is_string() || + !member(value.get(), {"points", "markers", "meshes"}) || + !used.insert(value.get()).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() && + (!body.contains("deleteBelowMarkers") || !body.at("deleteBelowMarkers").get())) + invalid(u8"至少选择一种裁剪对象。"); + return; + } + calibration(action, body); +} +} // namespace freescan::contracts diff --git a/integrations/freescan-service/src/contracts.hpp b/integrations/freescan-service/src/contracts.hpp new file mode 100644 index 0000000..3924f2b --- /dev/null +++ b/integrations/freescan-service/src/contracts.hpp @@ -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 diff --git a/integrations/freescan-service/src/device_battery.hpp b/integrations/freescan-service/src/device_battery.hpp new file mode 100644 index 0000000..fb0e824 --- /dev/null +++ b/integrations/freescan-service/src/device_battery.hpp @@ -0,0 +1,86 @@ +#pragma once +#include "common.hpp" +#include +#include +#include + +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 integer(const Json &value) { + if (value.is_number_unsigned()) { + auto n = value.get(); + return n <= static_cast((std::numeric_limits::max)()) + ? std::optional(static_cast(n)) : std::nullopt; + } + if (value.is_number_integer()) { + auto n = value.get(); + return n >= (std::numeric_limits::min)() && n <= (std::numeric_limits::max)() + ? std::optional(static_cast(n)) : std::nullopt; + } + if (!value.is_string()) return std::nullopt; + const auto &s = value.get_ref(); + 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 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 tracker_; + static std::optional 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(); + 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 diff --git a/integrations/freescan-service/src/http_server.cpp b/integrations/freescan-service/src/http_server.cpp new file mode 100644 index 0000000..1d408fd --- /dev/null +++ b/integrations/freescan-service/src/http_server.cpp @@ -0,0 +1,1284 @@ +#include "http_server.hpp" +#include "contracts.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#pragma comment(lib, "httpapi.lib") +#pragma comment(lib, "bcrypt.lib") +#pragma comment(lib, "ws2_32.lib") + +namespace freescan { +namespace { +using Headers = std::vector>; +std::string lower(std::string text) { + for (auto &c : text) + if (c >= 'A' && c <= 'Z') + c = char(c - 'A' + 'a'); + return text; +} +std::string trim(std::string value) { + auto first = value.find_first_not_of(" \t\r\n"); + if (first == std::string::npos) + return {}; + return value.substr(first, value.find_last_not_of(" \t\r\n") - first + 1); +} +bool id32(const std::string &value) { + return value.size() == 32 && std::all_of(value.begin(), value.end(), [](char c) { + return c >= '0' && c <= '9' || c >= 'a' && c <= 'f'; + }); +} +std::string known_header(const HTTP_REQUEST &request, HTTP_HEADER_ID id) { + const auto &h = request.Headers.KnownHeaders[id]; + return h.pRawValue ? std::string(h.pRawValue, h.RawValueLength) : std::string(); +} +std::string header(const HTTP_REQUEST &request, const std::string &name) { + for (USHORT i = 0; i < request.Headers.UnknownHeaderCount; i++) { + auto &h = request.Headers.pUnknownHeaders[i]; + if (lower(std::string(h.pName, h.NameLength)) == lower(name)) + return std::string(h.pRawValue, h.RawValueLength); + } + return {}; +} +std::array sha256(const std::string &value) { + BCRYPT_ALG_HANDLE algorithm = nullptr; + BCRYPT_HASH_HANDLE hash = nullptr; + std::array result{}; + if (BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM, nullptr, 0) < 0) + throw std::runtime_error("Cannot initialize API authentication hash."); + DWORD objectLength = 0, returned = 0; + std::vector object; + try { + if (BCryptGetProperty(algorithm, BCRYPT_OBJECT_LENGTH, reinterpret_cast(&objectLength), + sizeof(objectLength), &returned, 0) < 0) + throw std::runtime_error("Cannot query API authentication hash."); + object.resize(objectLength); + if (BCryptCreateHash(algorithm, &hash, object.data(), objectLength, nullptr, 0, 0) < 0 || + BCryptHashData(hash, reinterpret_cast(const_cast(value.data())), + ULONG(value.size()), 0) < 0 || + BCryptFinishHash(hash, result.data(), ULONG(result.size()), 0) < 0) + throw std::runtime_error("Cannot calculate API authentication hash."); + } catch (...) { + if (hash) + BCryptDestroyHash(hash); + BCryptCloseAlgorithmProvider(algorithm, 0); + throw; + } + BCryptDestroyHash(hash); + BCryptCloseAlgorithmProvider(algorithm, 0); + return result; +} +Json api_failure(const std::exception &error) { + if (auto known = dynamic_cast(&error)) + return Json{{"code", known->code}, {"message", known->what()}, {"httpStatus", known->status}}; + return Json{{"code", "sdk_error"}, {"message", error.what()}, {"httpStatus", 500}}; +} +std::string uri_escape(const std::string &value) { + std::ostringstream out; + out << std::uppercase << std::hex; + for (unsigned char c : value) { + if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_' || + c == '.' || c == '~') + out << char(c); + else + out << '%' << std::setw(2) << std::setfill('0') << int(c); + } + return out.str(); +} +std::string uri_unescape(const std::string &value) { + auto digit = [](char c) -> int { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; + }; + std::string out; + for (size_t i = 0; i < value.size(); ++i) { + if (value[i] != '%') { out += value[i]; continue; } + if (i + 2 >= value.size() || digit(value[i + 1]) < 0 || digit(value[i + 2]) < 0) + throw ApiError(400, "invalid_file_name", "X-File-Name 必须为有效的百分号编码文件名。"); + out += static_cast(digit(value[i + 1]) * 16 + digit(value[i + 2])); + i += 2; + } + return out; +} +std::string reason(int status) { + switch (status) { + case 200: + return "OK"; + case 201: + return "Created"; + case 202: + return "Accepted"; + case 400: + return "Bad Request"; + case 401: + return "Unauthorized"; + case 403: + return "Forbidden"; + case 404: + return "Not Found"; + case 405: + return "Method Not Allowed"; + case 408: + return "Request Timeout"; + case 409: + return "Conflict"; + case 413: + return "Payload Too Large"; + case 415: + return "Unsupported Media Type"; + case 422: + return "Unprocessable Entity"; + case 429: + return "Too Many Requests"; + case 431: + return "Request Header Fields Too Large"; + case 502: + return "Bad Gateway"; + case 503: + return "Service Unavailable"; + case 504: + return "Gateway Timeout"; + default: + return "Internal Server Error"; + } +} +bool child_path(const fs::path &root, const fs::path &file) { + auto r = root.lexically_normal(), f = file.lexically_normal(); + auto a = r.begin(), b = f.begin(); + for (; a != r.end(); ++a, ++b) + if (b == f.end() || _wcsicmp(a->c_str(), b->c_str()) != 0) + return false; + return b != f.end(); +} +std::wstring final_path(HANDLE file) { + DWORD needed = GetFinalPathNameByHandleW(file, nullptr, 0, FILE_NAME_NORMALIZED); + if (!needed) + throw ApiError(503, "file_unavailable", "无法核验下载文件的最终路径。"); + std::wstring result(needed, L'\0'); + DWORD written = GetFinalPathNameByHandleW(file, &result[0], needed, FILE_NAME_NORMALIZED); + if (!written || written >= needed) + throw ApiError(503, "file_unavailable", "无法核验下载文件的最终路径。"); + result.resize(written); + return result; +} +struct CountGuard { + std::atomic &value; + explicit CountGuard(std::atomic &item) : value(item) {} + ~CountGuard() { + --value; + } +}; +} // namespace + +struct HttpServer::Impl : std::enable_shared_from_this { + Json config; + fs::path dataRoot, frameworkRoot; + struct FrameworkFile { + fs::path path; + Json metadata; + }; + std::mutex uploadGate; + std::map frameworkFiles; + std::atomic uploading{0}; + static constexpr size_t maxFrameworkFile = 16 * 1024 * 1024; + static constexpr uint64_t frameworkQuota = 256ull * 1024 * 1024; + std::function status, metrics; + std::function execute; + std::function query; + std::function generation; + bool simulated = false; + std::function()> frame; + std::wstring prefix; + std::string expectedHost; + std::array keyHash{}; + Handle queue, stopEvent; + bool httpInitialized = false; + std::atomic stopped{true}; + bool everStarted = false; + std::atomic requests{0}, streams{0}, downloads{0}, callbacks{0}; + // Recovery has its own task slot: a blocked calibration must never block + // the only operation that can retire its SDK worker. Both IDs use jobMutex. + std::string activeJobId, recoveryJobId; + fs::path taskLog; + std::mutex stateMutex, jobMutex, multipartMutex; + std::condition_variable stoppedCv; + bool receiveExited = true; + std::set requestIds; + std::map jobs; + std::deque jobOrder; + std::shared_ptr> multipartCache; + uint64_t multipartSequence = 0; + int64_t multipartCaptured = 0; + Impl(fs::path root, Json settings, std::function getStatus, std::function run, + std::function get, + std::function()> getFrame, std::function getMetrics, + std::function getGeneration, bool mock) + : config(std::move(settings)), dataRoot(fs::canonical(root)), frameworkRoot(dataRoot / L"FrameworkUploads"), status(std::move(getStatus)), metrics(std::move(getMetrics)), + execute(std::move(run)), query(std::move(get)), generation(std::move(getGeneration)), simulated(mock), frame(std::move(getFrame)) { + if (!config.is_object() || !status || !execute || !frame || !metrics || !generation) + throw std::invalid_argument("HTTP server configuration and callbacks are required."); + fs::create_directories(dataRoot / L"Logs"); + taskLog = dataRoot / L"Logs" / wide("native_http_tasks_" + new_id() + ".log"); + std::string address = config.value("prefix", std::string("http://127.0.0.1:18888/")); + if (address.rfind("http://", 0) != 0 || address.back() != '/' || + address.find_first_of("?#@\\") != std::string::npos || address.find('/', 7) != address.size() - 1) + throw std::invalid_argument("prefix must be an explicit HTTP root URL ending in '/'."); + std::string authority = address.substr(7, address.size() - 8), host, port; + if (!authority.empty() && authority[0] == '[') { + auto close = authority.find(']'); + if (close == std::string::npos || close + 1 >= authority.size() || authority[close + 1] != ':') + throw std::invalid_argument("IPv6 prefix requires an explicit port."); + host = authority.substr(1, close - 1); + port = authority.substr(close + 2); + } else { + auto colon = authority.rfind(':'); + if (colon == std::string::npos) + throw std::invalid_argument("prefix requires an explicit port."); + host = authority.substr(0, colon); + port = authority.substr(colon + 1); + } + if (port.empty() || + !std::all_of(port.begin(), port.end(), [](char c) { return c >= '0' && c <= '9'; }) || + port.size() > 5) + throw std::invalid_argument("Invalid HTTP port."); + auto number = std::stoul(port); + if (number < 1024 || number > 65535) + throw std::invalid_argument("HTTP port must be between 1024 and 65535."); + IN_ADDR ipv4{}; + IN6_ADDR ipv6{}; + auto hostWide = wide(host); + bool v4 = InetPtonW(AF_INET, hostWide.c_str(), &ipv4) == 1, + v6 = InetPtonW(AF_INET6, hostWide.c_str(), &ipv6) == 1; + IN6_ADDR any6{}; + if (lower(host) != "localhost" && !v4 && !v6 || v4 && ipv4.S_un.S_addr == 0 || + v6 && memcmp(&ipv6, &any6, sizeof(ipv6)) == 0) + throw std::invalid_argument( + "HTTP host must be localhost or an explicit local IP, never a wildcard."); + std::string key = config.value("apiKey", std::string()); + if (key.size() < 32 || key.size() > 4096 || + !std::all_of(key.begin(), key.end(), [](unsigned char c) { return c >= 33 && c <= 126; })) + throw std::invalid_argument("API key requires at least 32 visible ASCII characters."); + keyHash = sha256(key); + prefix = wide(address); + expectedHost = lower(authority); + stopEvent.reset(CreateEventW(nullptr, TRUE, TRUE, nullptr)); + if (!stopEvent) + throw std::runtime_error("Cannot create HTTP stop event."); + } + ~Impl() { + if (queue) + queue.reset(); + if (httpInitialized) + HttpTerminate(HTTP_INITIALIZE_SERVER, nullptr); + } + // Every API buffer/OVERLAPPED stays alive through cancellation completion. + ULONG complete(HANDLE handle, OVERLAPPED &overlap, ULONG initial, DWORD timeout, + DWORD *transferred = nullptr, bool stopAware = true) { + if (initial != ERROR_IO_PENDING) { + if (transferred) { + DWORD count = 0; + GetOverlappedResult(handle, &overlap, &count, FALSE); + *transferred = count; + } + return initial; + } + HANDLE waits[] = {overlap.hEvent, stopEvent.get()}; + DWORD wait = WaitForMultipleObjects(stopAware ? 2 : 1, waits, FALSE, timeout); + if (wait != WAIT_OBJECT_0) { + CancelIoEx(handle, &overlap); + DWORD ignored = 0; + GetOverlappedResult(handle, &overlap, &ignored, TRUE); + return wait == WAIT_TIMEOUT ? ERROR_TIMEOUT : ERROR_OPERATION_ABORTED; + } + DWORD count = 0; + BOOL done = GetOverlappedResult(handle, &overlap, &count, FALSE); + if (transferred) + *transferred = count; + if (!done) + return GetLastError(); + return NO_ERROR; + } + template + ULONG io(F operation, DWORD timeout, DWORD *transferred = nullptr, bool stopAware = true) { + Handle event(CreateEventW(nullptr, TRUE, FALSE, nullptr)); + if (!event) + return ERROR_NOT_ENOUGH_MEMORY; + OVERLAPPED overlap{}; + overlap.hEvent = event.get(); + return complete(queue.get(), overlap, operation(&overlap), timeout, transferred, stopAware); + } + void start() { + std::lock_guard lock(stateMutex); + if (everStarted) + throw std::logic_error("HTTP server can only be started once."); + everStarted = true; + if (!config.value("enabled", true)) + return; + HTTPAPI_VERSION version{1, 0}; + ULONG result = HttpInitialize(version, HTTP_INITIALIZE_SERVER, nullptr); + if (result) + throw ApiError(503, "http_initialize_failed", + "HTTP.sys 初始化失败,Windows " + std::to_string(result)); + httpInitialized = true; + HANDLE raw = INVALID_HANDLE_VALUE; + result = HttpCreateHttpHandle(&raw, 0); + if (result) + throw ApiError(503, "http_queue_failed", + "创建 HTTP 请求队列失败,Windows " + std::to_string(result)); + queue.reset(raw); + result = HttpAddUrl(queue.get(), prefix.c_str(), nullptr); + if (result) + throw ApiError(503, "http_listen_failed", + "HTTP.sys 监听失败,Windows " + std::to_string(result) + + "。请检查端口占用与该地址的 URL 保留访问权限。"); + stopped = false; + receiveExited = false; + ResetEvent(stopEvent.get()); + auto self = shared_from_this(); + std::thread([self] { self->receive_loop(); }).detach(); + } + void stop() { + if (stopped.exchange(true)) + return; + SetEvent(stopEvent.get()); + HttpRemoveUrl(queue.get(), prefix.c_str()); + CancelIoEx(queue.get(), nullptr); + std::vector pending; + { + std::lock_guard lock(stateMutex); + pending.assign(requestIds.begin(), requestIds.end()); + } + for (auto id : pending) + HttpCancelHttpRequest(queue.get(), id, nullptr); + std::unique_lock lock(stateMutex); + stoppedCv.wait_for(lock, std::chrono::seconds(6), + [&] { return receiveExited && requests.load() == 0; }); + // Detached task/callback workers retain Impl until completion, so their + // state cannot dangle even if an external SDK callback ignores its timeout. + } + void receive_loop() { + HTTP_REQUEST_ID next = HTTP_NULL_ID; + size_t size = 16384; + while (!stopped) { + auto buffer = std::make_shared>(size); + auto request = reinterpret_cast(buffer->data()); + DWORD bytes = 0; + ULONG result = io( + [&](OVERLAPPED *ov) { + return HttpReceiveHttpRequest(queue.get(), next, 0, request, ULONG(buffer->size()), + nullptr, ov); + }, + INFINITE, &bytes); + if (stopped) + break; + if (result == ERROR_MORE_DATA) { + next = request->RequestId; + if (bytes <= size || bytes > 131072) { + try { + send_json( + next, 431, + Json{{"error", {{"code", "headers_too_large"}, {"message", "请求头过大。"}}}}, + {}); + } catch (...) { + } + HttpCancelHttpRequest(queue.get(), next, nullptr); + next = HTTP_NULL_ID; + size = 16384; + } else + size = bytes; + continue; + } + next = HTTP_NULL_ID; + size = 16384; + if (result != NO_ERROR) { + if (result == ERROR_OPERATION_ABORTED || result == ERROR_INVALID_HANDLE) + break; + continue; + } + auto id = request->RequestId; + if (requests.fetch_add(1) >= 32) { + --requests; + try { + send_json(id, 429, + Json{{"error", + {{"code", "request_limit"}, {"message", "HTTP 请求过多,请稍后重试。"}}}}, + {}); + } catch (...) { + } + continue; + } + { + std::lock_guard lock(stateMutex); + requestIds.insert(id); + } + auto self = shared_from_this(); + try { + std::thread([self, buffer, id] { + self->handle(*reinterpret_cast(buffer->data())); + { + std::lock_guard lock(self->stateMutex); + self->requestIds.erase(id); + --self->requests; + } + self->stoppedCv.notify_all(); + }).detach(); + } catch (...) { + std::lock_guard lock(stateMutex); + requestIds.erase(id); + --requests; + HttpCancelHttpRequest(queue.get(), id, nullptr); + } + } + { + std::lock_guard lock(stateMutex); + receiveExited = true; + } + stoppedCv.notify_all(); + } + void authenticate(const HTTP_REQUEST &request) { + auto supplied = header(request, "X-Api-Key"), bearer = known_header(request, HttpHeaderAuthorization); + if (lower(bearer.substr(0, 7)) == "bearer ") + supplied = bearer.substr(7); + auto digest = sha256(supplied); + unsigned mismatch = 0; + for (size_t i = 0; i < digest.size(); i++) + mismatch |= digest[i] ^ keyHash[i]; + if (mismatch) + throw ApiError(401, "unauthorized", "缺少或无效的 API 访问密钥。"); + } + Json bounded(std::function callback, int milliseconds, const std::string &code) { + if (callbacks.fetch_add(1) >= 32) { + --callbacks; + throw ApiError(503, "query_limit", "后台查询过多,请等待已有查询结束。"); + } + auto work = std::make_shared>(); + auto future = work->get_future(); + auto self = shared_from_this(); + try { + std::thread([self, work, callback = std::move(callback)] { + try { + work->set_value(callback()); + } catch (...) { + try { + work->set_exception(std::current_exception()); + } catch (...) { + } + } + --self->callbacks; + }).detach(); + } catch (...) { + --callbacks; + throw; + } + auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(milliseconds); + while (future.wait_for(std::chrono::milliseconds(0)) != std::future_status::ready) { + if (stopped) + throw ApiError(503, "shutting_down", "HTTP 服务正在关闭。"); + if (std::chrono::steady_clock::now() >= deadline) + throw ApiError(503, code, "后台查询尚未返回,请检查设备任务并稍后重试。"); + WaitForSingleObject(stopEvent.get(), 10); + } + return future.get(); + } + Json get_query(const std::string &action, const Json &arguments = Json::object()) { + if (!query) + throw ApiError(503, "feature_unavailable", "当前服务未配置该功能后端。"); + auto callback = query; + return bounded([callback, action, arguments] { return callback(action, arguments); }, + action == "sceneInfo" ? 15000 : 5000, "query_timeout"); + } + std::string read_payload(const HTTP_REQUEST &request, size_t maximum, int timeoutSeconds) { + auto length = known_header(request, HttpHeaderContentLength); + if (!length.empty()) { + try { + size_t end = 0; + auto declared = std::stoull(length, &end); + if (end != length.size() || length.find_first_not_of("0123456789") != std::string::npos) + throw ApiError(400, "invalid_content_length", "Content-Length 无效。"); + if (declared > maximum) + throw ApiError(413, "body_too_large", "请求体超过接口允许的字节数。"); + } catch (const ApiError &) { + throw; + } catch (...) { + throw ApiError(400, "invalid_content_length", "Content-Length 无效。"); + } + } + std::string body; + auto append = [&](const char *data, size_t count) { + if (body.size() + count > maximum) + throw ApiError(413, "body_too_large", "请求体超过接口允许的字节数。"); + body.append(data, count); + }; + for (USHORT i = 0; i < request.EntityChunkCount; i++) { + const auto &chunk = request.pEntityChunks[i]; + if (chunk.DataChunkType != HttpDataChunkFromMemory) + throw ApiError(400, "invalid_body", "请求体数据类型无效。"); + append(static_cast(chunk.FromMemory.pBuffer), chunk.FromMemory.BufferLength); + } + auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeoutSeconds); + if (request.Flags & HTTP_REQUEST_FLAG_MORE_ENTITY_BODY_EXISTS) { + for (;;) { + auto remaining = std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now()) + .count(); + if (remaining <= 0) + throw ApiError(408, "request_timeout", "读取请求体超时。"); + std::array chunk{}; + DWORD bytes = 0; + ULONG result = io( + [&](OVERLAPPED *ov) { + return HttpReceiveRequestEntityBody(queue.get(), request.RequestId, 0, chunk.data(), + ULONG(chunk.size()), nullptr, ov); + }, + DWORD(remaining), &bytes); + if (result == ERROR_HANDLE_EOF) { + if (bytes) + append(chunk.data(), bytes); + break; + } + if (result == ERROR_TIMEOUT) + throw ApiError(408, "request_timeout", "读取请求体超时。"); + if (result != NO_ERROR) + throw ApiError(400, "body_read_failed", "请求体连接已关闭或读取失败。"); + append(chunk.data(), bytes); + if (!bytes) + break; + } + } + if (!length.empty() && body.size() != std::stoull(length)) + throw ApiError(400, "body_length_mismatch", "实际上传内容与 Content-Length 不一致。"); + return body; + } + Json read_body(const HTTP_REQUEST &request, size_t maximum) { + auto length = known_header(request, HttpHeaderContentLength); + bool hasBody = (request.Flags & HTTP_REQUEST_FLAG_MORE_ENTITY_BODY_EXISTS) || + request.EntityChunkCount > 0 || (!length.empty() && length != "0"); + auto type = lower(trim(known_header(request, HttpHeaderContentType) + .substr(0, known_header(request, HttpHeaderContentType).find(';')))); + if (hasBody && type != "application/json") + throw ApiError(415, "unsupported_media_type", "请求体应使用 application/json。"); + auto body = read_payload(request, maximum, 8); + if (body.empty()) + return Json::object(); + try { + auto result = Json::parse(body, [](int depth, Json::parse_event_t, Json &) { + if (depth > 32) + throw ApiError(400, "invalid_json", "JSON 嵌套层数过多。"); + return true; + }); + if (!result.is_object()) + throw ApiError(400, "invalid_json", "JSON 请求体必须是对象。"); + return result; + } catch (const ApiError &) { + throw; + } catch (...) { + throw ApiError(400, "invalid_json", "请求体必须为有效的 UTF-8 JSON 对象。"); + } + } + void send_headers(HTTP_REQUEST_ID id, int code, const Headers &additions, const uint8_t *data, + size_t length, bool more, bool disconnect = false) { + Headers values = {{"X-Content-Type-Options", "nosniff"}, + {"Cache-Control", "no-store"}, + {"Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'"}}; + values.insert(values.end(), additions.begin(), additions.end()); + HTTP_RESPONSE response{}; + std::vector headers; + headers.reserve(values.size()); + for (auto &value : values) { + HTTP_HEADER_ID known = HttpHeaderResponseMaximum; + auto name = lower(value.first); + if (name == "content-type") + known = HttpHeaderContentType; + else if (name == "content-length") + known = HttpHeaderContentLength; + else if (name == "transfer-encoding") + known = HttpHeaderTransferEncoding; + else if (name == "location") + known = HttpHeaderLocation; + else if (name == "allow") + known = HttpHeaderAllow; + else if (name == "cache-control") + known = HttpHeaderCacheControl; + if (known != HttpHeaderResponseMaximum) { + auto &h = response.Headers.KnownHeaders[known]; + h.pRawValue = value.second.c_str(); + h.RawValueLength = USHORT(value.second.size()); + } else { + HTTP_UNKNOWN_HEADER h{}; + h.pName = value.first.c_str(); + h.NameLength = USHORT(value.first.size()); + h.pRawValue = value.second.c_str(); + h.RawValueLength = USHORT(value.second.size()); + headers.push_back(h); + } + } + response.Version = {1, 1}; + response.StatusCode = USHORT(code); + auto text = reason(code); + response.pReason = text.c_str(); + response.ReasonLength = USHORT(text.size()); + response.Headers.UnknownHeaderCount = USHORT(headers.size()); + response.Headers.pUnknownHeaders = headers.data(); + HTTP_DATA_CHUNK chunk{}; + if (length) { + chunk.DataChunkType = HttpDataChunkFromMemory; + chunk.FromMemory.pBuffer = const_cast(data); + chunk.FromMemory.BufferLength = ULONG(length); + response.EntityChunkCount = 1; + response.pEntityChunks = &chunk; + } + ULONG flags = (more ? HTTP_SEND_RESPONSE_FLAG_MORE_DATA : 0) | + (disconnect ? HTTP_SEND_RESPONSE_FLAG_DISCONNECT : 0); + ULONG result = io( + [&](OVERLAPPED *ov) { + return HttpSendHttpResponse(queue.get(), id, flags, &response, nullptr, nullptr, nullptr, 0, + ov, nullptr); + }, + 15000); + if (result != NO_ERROR) + throw std::runtime_error("HTTP response write failed: " + std::to_string(result)); + } + void send_json(HTTP_REQUEST_ID id, int code, const Json &value, Headers headers = {}) { + auto text = value.dump(); + headers.emplace_back("Content-Type", "application/json; charset=utf-8"); + headers.emplace_back("Content-Length", std::to_string(text.size())); + send_headers(id, code, headers, reinterpret_cast(text.data()), text.size(), false, + code >= 400); + } + void send_bytes(HTTP_REQUEST_ID id, const uint8_t *data, size_t size, bool final = false, + bool disconnect = false) { + HTTP_DATA_CHUNK chunk{}; + chunk.DataChunkType = HttpDataChunkFromMemory; + chunk.FromMemory.pBuffer = const_cast(data); + chunk.FromMemory.BufferLength = ULONG(size); + ULONG result = io( + [&](OVERLAPPED *ov) { + return HttpSendResponseEntityBody(queue.get(), id, + (final ? 0 : HTTP_SEND_RESPONSE_FLAG_MORE_DATA) | + (disconnect ? HTTP_SEND_RESPONSE_FLAG_DISCONNECT : 0), + size ? 1 : 0, size ? &chunk : nullptr, nullptr, nullptr, 0, + ov, nullptr); + }, + 15000); + if (result != NO_ERROR) + throw std::runtime_error("HTTP body write failed: " + std::to_string(result)); + } + Headers frame_headers(const FrameSnapshot &item) { + return {{"X-Frame-Captured-Utc", utc_from_ms(item.capturedMs)}, + {"X-Frame-Encoded-Utc", utc_from_ms(item.encodedMs)}, + {"X-Frame-Sequence", std::to_string(item.sequence)}, + {"X-Frame-Width", std::to_string(item.width)}, + {"X-Frame-Height", std::to_string(item.height)}, + {"X-Frame-Source-Width", std::to_string(item.sourceWidth)}, + {"X-Frame-Source-Height", std::to_string(item.sourceHeight)}, + {"X-Frame-Age-Ms", std::to_string(std::max(0, unix_ms() - item.capturedMs))}, + {"X-Frame-Encode-Ms", std::to_string(item.encodeMs)}}; + } + std::shared_ptr fresh() { + auto result = frame(); + if (!result || result->jpeg.empty()) + throw ApiError(503, "frame_unavailable", "尚未收到扫描画面,请先连接设备并创建工程。"); + if (unix_ms() - result->capturedMs > 2000) + throw ApiError(503, "frame_stale", "扫描画面已超过 2 秒未更新,请查询设备状态。"); + return result; + } + std::shared_ptr> multipart(const FrameSnapshot &item) { + std::lock_guard lock(multipartMutex); + if (multipartCache && multipartSequence == item.sequence && multipartCaptured == item.capturedMs) + return multipartCache; + std::string head = + "--scanframe\r\nContent-Type: image/jpeg\r\nContent-Length: " + std::to_string(item.jpeg.size()) + + "\r\nX-Frame-Sequence: " + std::to_string(item.sequence) + + "\r\nX-Frame-Captured-Utc: " + utc_from_ms(item.capturedMs) + + "\r\nX-Frame-Encoded-Utc: " + utc_from_ms(item.encodedMs) + + "\r\nX-Frame-Source-Width: " + std::to_string(item.sourceWidth) + + "\r\nX-Frame-Source-Height: " + std::to_string(item.sourceHeight) + "\r\n\r\n"; + auto packet = std::make_shared>(); + packet->reserve(head.size() + item.jpeg.size() + 2); + packet->insert(packet->end(), head.begin(), head.end()); + packet->insert(packet->end(), item.jpeg.begin(), item.jpeg.end()); + packet->push_back('\r'); + packet->push_back('\n'); + multipartSequence = item.sequence; + multipartCaptured = item.capturedMs; + multipartCache = packet; + return packet; + } + void send_stream(const HTTP_REQUEST &request, bool &sent) { + auto first = fresh(); + if (streams.fetch_add(1) >= 4) { + --streams; + throw ApiError(429, "stream_limit", "最多同时连接 4 路实时画面。"); + } + CountGuard guard(streams); + auto headers = frame_headers(*first); + headers.emplace_back("Content-Type", "multipart/x-mixed-replace; boundary=scanframe"); + headers.emplace_back("Transfer-Encoding", "chunked"); + send_headers(request.RequestId, 200, headers, nullptr, 0, true); + sent = true; + uint64_t previous = 0; + bool havePrevious = false; + int fps = std::clamp(config.value("previewFps", 20), 1, 30); + auto chunk = [&](const uint8_t *data, size_t size, bool final, + const std::string &partHeader = std::string()) { + size_t headerPrefix = 0; + if (!partHeader.empty()) { + const uint8_t delimiter[] = {'\r', '\n', '\r', '\n'}; + const auto end = std::search(data, data + size, std::begin(delimiter), std::end(delimiter)); + if (end == data + size) + throw ApiError(500, "stream_header_invalid", "Invalid internal preview headers."); + headerPrefix = size_t(end - data) + 2; + } + std::ostringstream count; + count << std::hex << (size + partHeader.size()); + auto prefix = count.str() + "\r\n"; + std::vector bytes; + bytes.reserve(prefix.size() + size + partHeader.size() + 2 + (final ? 5 : 0)); + bytes.insert(bytes.end(), prefix.begin(), prefix.end()); + if (partHeader.empty()) { + bytes.insert(bytes.end(), data, data + size); + } else { + bytes.insert(bytes.end(), data, data + headerPrefix); + bytes.insert(bytes.end(), partHeader.begin(), partHeader.end()); + bytes.insert(bytes.end(), data + headerPrefix, data + size); + } + bytes.push_back('\r'); + bytes.push_back('\n'); + if (final) { + const char end[] = "0\r\n\r\n"; + bytes.insert(bytes.end(), end, end + 5); + } + send_bytes(request.RequestId, bytes.data(), bytes.size(), final); + }; + while (!stopped) { + auto current = frame(); + if (!current || unix_ms() - current->capturedMs > 2000) + break; + if (!havePrevious || current->sequence != previous) { + auto packet = multipart(*current); + // Duration is computed per send, not stored in the shared JPEG + // cache. LAN viewers must not compare two PCs' wall clocks. + chunk(packet->data(), packet->size(), false, + "X-Frame-Age-Ms: " + std::to_string(std::max(0, unix_ms() - current->capturedMs)) + "\r\n"); + previous = current->sequence; + havePrevious = true; + } + WaitForSingleObject(stopEvent.get(), std::max(5, 500 / fps)); + } + if (!stopped) { + const std::string end = "--scanframe--\r\n"; + chunk(reinterpret_cast(end.data()), end.size(), true); + } + } + struct CalibrationFrame {Json view;FrameSnapshot frame;}; + CalibrationFrame fresh_calibration() { + auto view=get_query("calibrationViewFrame"); + if(!view.is_object()||view.value("source",std::string())!="sdk_calibration_window"||!view.value("available",false)||!view.value("calibrationActive",false)) + throw ApiError(503,view.value("state",std::string("calibration_window_unavailable")),view.value("message",std::string("厂家标定窗口画面暂不可用。"))); + if(!view.value("sessionId",Json(nullptr)).is_string()||view["sessionId"].get().empty()||!view.value("calibrationId",Json(nullptr)).is_string()||view["calibrationId"].get().empty() + ||!view.value("frameSource",Json(nullptr)).is_object()||!view.value("frame",Json(nullptr)).is_object())throw ApiError(502,"calibration_identity_invalid","标定窗口帧缺少身份关联。"); + const auto &source=view["frameSource"]; + if(!source.contains("pid")||!source["pid"].is_number_unsigned()||source["pid"].get()==0 + ||source.value("startedAt",std::string()).empty()||source.value("path",std::string()).empty()||source.value("windowHandle",std::string()).empty()) + throw ApiError(502,"calibration_identity_invalid","标定窗口进程归属不可核对。"); + auto decoded=frame_from_json(view["frame"]);const auto age=unix_ms()-decoded.capturedMs; + if(age<0||age>2000)throw ApiError(503,"frame_stale","厂家标定窗口画面已超过2秒未更新。"); + return {std::move(view),std::move(decoded)}; + } + Headers calibration_headers(const CalibrationFrame &item){ + auto headers=frame_headers(item.frame);const auto &source=item.view["frameSource"]; + headers.emplace_back("X-Frame-Source","sdk_calibration_window"); + headers.emplace_back("X-Frame-Session-Id",item.view["sessionId"].get()); + headers.emplace_back("X-Frame-Calibration-Id",item.view["calibrationId"].get()); + headers.emplace_back("X-Frame-Source-Pid",std::to_string(source["pid"].get())); + headers.emplace_back("X-Frame-Source-Started-At",source["startedAt"].get()); + headers.emplace_back("X-Frame-Window-Handle",source["windowHandle"].get()); + return headers; + } + std::string calibration_identity(const Json &view){return view["sessionId"].dump()+":"+view["calibrationId"].dump()+":"+view["frameSource"].dump();} + void send_calibration_stream(const HTTP_REQUEST &request,bool &sent){ + auto first=fresh_calibration();const auto identity=calibration_identity(first.view); + if(streams.fetch_add(1)>=4){--streams;throw ApiError(429,"stream_limit","最多同时连接4路实时画面。");} + CountGuard guard(streams);auto headers=calibration_headers(first); + headers.emplace_back("Content-Type","multipart/x-mixed-replace; boundary=scanframe");headers.emplace_back("Transfer-Encoding","chunked"); + send_headers(request.RequestId,200,headers,nullptr,0,true);sent=true; + uint64_t previous=0;bool havePrevious=false; + auto chunk=[&](const uint8_t *data,size_t size,bool final){ + std::ostringstream count;count< bytes(prefix.begin(),prefix.end());bytes.insert(bytes.end(),data,data+size);bytes.push_back('\r');bytes.push_back('\n'); + if(final){const std::string end="0\r\n\r\n";bytes.insert(bytes.end(),end.begin(),end.end());} + send_bytes(request.RequestId,bytes.data(),bytes.size(),final); + }; + while(!stopped){ + CalibrationFrame current; + try{current=fresh_calibration();}catch(const std::exception &){break;} + if(calibration_identity(current.view)!=identity)break; + if(!havePrevious||current.frame.sequence!=previous){ + std::string head="--scanframe\r\nContent-Type: image/jpeg\r\nContent-Length: "+std::to_string(current.frame.jpeg.size())+"\r\n"; + for(const auto &header:calibration_headers(current))head+=header.first+": "+header.second+"\r\n"; + head+="\r\n";std::vector packet(head.begin(),head.end());packet.insert(packet.end(),current.frame.jpeg.begin(),current.frame.jpeg.end());packet.push_back('\r');packet.push_back('\n'); + chunk(packet.data(),packet.size(),false);previous=current.frame.sequence;havePrevious=true; + } + WaitForSingleObject(stopEvent.get(),80); + } + if(!stopped){const std::string end="--scanframe--\r\n";chunk(reinterpret_cast(end.data()),end.size(),true);} + } + void send_download(HTTP_REQUEST_ID id, const Json &metadata, bool &sent) { + if (downloads.fetch_add(1) >= 4) { + --downloads; + throw ApiError(429, "download_limit", "最多同时下载 4 个文件。"); + } + CountGuard guard(downloads); + if (!metadata.is_object()) + throw ApiError(404, "file_not_found", "文件不存在或尚未生成。"); + auto root = fs::u8path(metadata.value("root", std::string())), + path = fs::u8path(metadata.value("path", std::string())); + auto name = metadata.value("name", std::string()), + type = metadata.value("contentType", std::string()); + if (!root.is_absolute() || !path.is_absolute() || !child_path(root, path)) + throw ApiError(403, "invalid_download_path", "文件必须位于应用已登记的导出目录内。"); + if (name.empty() || name.size() > 1024 || name.find_first_of("\\/\r\n") != std::string::npos || + std::any_of(name.begin(), name.end(), [](unsigned char c) { return c < 32 || c == 127; })) + throw ApiError(500, "invalid_download_name", "下载文件名无效。"); + auto slash = type.find('/'); + if (slash == std::string::npos || slash == 0 || slash == type.size() - 1 || + !std::all_of(type.begin(), type.end(), + [](unsigned char c) { + return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || + c == '.' || c == '+' || c == '-' || c == '/'; + }) || + type.find('/', slash + 1) != std::string::npos) + throw ApiError(500, "invalid_content_type", "下载媒体类型无效。"); + for (auto inspect = path.lexically_normal(); !inspect.empty();) { + DWORD attributes = GetFileAttributesW(inspect.c_str()); + if (attributes == INVALID_FILE_ATTRIBUTES) + throw ApiError(404, "file_not_found", "文件不存在或暂时无法读取。"); + if (attributes & FILE_ATTRIBUTE_REPARSE_POINT) + throw ApiError(403, "reparse_path", "不允许通过重解析目录或符号链接下载文件。"); + auto parent = inspect.parent_path(); + if (parent == inspect) + break; + inspect = parent; + } + Handle rootHandle(CreateFileW( + root.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr)); + Handle file(CreateFileW( + path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_SEQUENTIAL_SCAN | FILE_FLAG_OVERLAPPED, nullptr)); + if (!file || !rootHandle) + throw ApiError(503, "file_unavailable", "文件正在写入或暂时无法读取,请稍后重试。"); + FILE_ATTRIBUTE_TAG_INFO info{}; + if (!GetFileInformationByHandleEx(file.get(), FileAttributeTagInfo, &info, sizeof(info)) || + (info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) || + !child_path(fs::path(final_path(rootHandle.get())), fs::path(final_path(file.get())))) + throw ApiError(403, "reparse_path", "下载文件的最终路径不在核验目录内。"); + LARGE_INTEGER length{}; + if (!GetFileSizeEx(file.get(), &length) || length.QuadPart < 0) + throw ApiError(503, "file_unavailable", "无法读取下载文件长度。"); + Headers headers = { + {"Content-Type", type}, + {"Content-Length", std::to_string(length.QuadPart)}, + {"Content-Disposition", "attachment; filename=download; filename*=UTF-8''" + uri_escape(name)}}; + send_headers(id, 200, headers, nullptr, 0, length.QuadPart > 0); + sent = true; + uint64_t offset = 0; + std::array bytes{}; + while (!stopped && offset < uint64_t(length.QuadPart)) { + DWORD wanted = DWORD(std::min(bytes.size(), uint64_t(length.QuadPart) - offset)), + got = 0; + Handle event(CreateEventW(nullptr, TRUE, FALSE, nullptr)); + OVERLAPPED overlap{}; + overlap.hEvent = event.get(); + overlap.Offset = DWORD(offset); + overlap.OffsetHigh = DWORD(offset >> 32); + BOOL done = ReadFile(file.get(), bytes.data(), wanted, nullptr, &overlap); + ULONG result = complete(file.get(), overlap, done ? NO_ERROR : GetLastError(), 15000, &got); + if (result != NO_ERROR || !got) + throw std::runtime_error("Registered file read failed."); + offset += got; + send_bytes(id, bytes.data(), got, offset == uint64_t(length.QuadPart)); + } + } + Handle framework_directory(bool create) { + if (create) + fs::create_directories(frameworkRoot); + Handle base(CreateFileW(dataRoot.c_str(), FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, nullptr)); + Handle directory(CreateFileW(frameworkRoot.c_str(), FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr)); + FILE_ATTRIBUTE_TAG_INFO attributes{}; + if (!base || !directory || + !GetFileInformationByHandleEx(directory.get(), FileAttributeTagInfo, &attributes, sizeof(attributes)) || + (attributes.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) || + !child_path(fs::path(final_path(base.get())), fs::path(final_path(directory.get())))) + throw ApiError(403, "framework_storage_unavailable", "框架上传目录无法核验,请检查本机运行目录。"); + return directory; + } + Json upload_framework(const HTTP_REQUEST &request) { + if (lower(trim(known_header(request, HttpHeaderContentType))) != "application/octet-stream") + throw ApiError(415, "unsupported_media_type", "框架文件上传应使用 application/octet-stream 原始二进制。"); + auto encodedName = header(request, "X-File-Name"); + if (encodedName.empty() || encodedName.size() > 2048) + throw ApiError(400, "invalid_file_name", "请用 X-File-Name 提供百分号编码的文件名。"); + auto name = uri_unescape(encodedName); + auto nameWide = wide(name); + if (name.empty() || name.size() > 240 || nameWide.size() > 128 || name.back() == '.' || name.back() == ' ' || + std::any_of(name.begin(), name.end(), [](unsigned char c) { return c < 32 || c == 127; }) || + name.find_first_of("<>:\"/\\|?*") != std::string::npos) + throw ApiError(400, "invalid_file_name", "文件名无效;只提供文件名,不能使用路径。"); + auto extension = lower(path_string(fs::path(nameWide).extension())); + if (name.size() <= extension.size() || (extension != ".p3" && extension != ".txt" && extension != ".asc")) + throw ApiError(415, "unsupported_framework_format", "仅接收厂家格式的 .p3、.txt、.asc 框架文件。"); + if (uploading.fetch_add(1) >= 2) { + --uploading; + throw ApiError(429, "upload_limit", "同时最多上传两个框架文件,请稍后重试。"); + } + CountGuard uploadCount(uploading); + auto bytes = read_payload(request, maxFrameworkFile, 60); + if (bytes.empty()) + throw ApiError(400, "empty_framework_file", "框架文件不能为空。"); + std::lock_guard hold(uploadGate); + if (frameworkFiles.size() >= 64) + throw ApiError(413, "framework_storage_full", "本次服务最多登记 64 个上传文件。"); + auto directory = framework_directory(true); + uint64_t diskBytes = 0; + for (const auto &entry : fs::directory_iterator(frameworkRoot)) { + if (entry.is_symlink()) + throw ApiError(403, "framework_storage_unavailable", "框架上传目录含有未核验的链接。"); + if (entry.is_regular_file()) { + diskBytes += entry.file_size(); + if (diskBytes > frameworkQuota) + break; + } + } + if (diskBytes + bytes.size() > frameworkQuota) + throw ApiError(413, "framework_storage_full", "框架上传目录已达到 256 MiB 配额,请由管理员检查历史文件。"); + auto id = new_id(); + auto path = frameworkRoot / wide(id + extension); + Handle file(CreateFileW(path.c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT, nullptr)); + if (!file) + throw ApiError(503, "framework_file_unavailable", "无法创建框架上传文件。"); + try { + DWORD written = 0; + if (!WriteFile(file.get(), bytes.data(), static_cast(bytes.size()), &written, nullptr) || + written != bytes.size() || !FlushFileBuffers(file.get())) + throw ApiError(503, "framework_file_unavailable", "框架上传文件写入未完成。"); + file.reset(); + Json metadata{{"fileId", id}, {"name", name}, {"size", bytes.size()}, {"uploadedUtc", utc_now()}}; + frameworkFiles.emplace(id, FrameworkFile{path, metadata}); + return metadata; + } catch (...) { + file.reset(); + std::error_code ignored; + fs::remove(path, ignored); + throw; + } + } + std::shared_ptr> lease_framework_files(const Json &body) { + auto lease = std::make_shared>(); + std::lock_guard hold(uploadGate); + for (const auto &value : body.at("fileIds")) { + auto found = frameworkFiles.find(value.get()); + if (found == frameworkFiles.end()) + throw ApiError(404, "framework_file_not_found", "框架文件编号未登记或已随服务重启失效,请重新上传。"); + if (lease->empty()) + lease->push_back(framework_directory(false)); + Handle file(CreateFileW(found->second.path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, + OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_SEQUENTIAL_SCAN, nullptr)); + FILE_ATTRIBUTE_TAG_INFO attributes{}; + LARGE_INTEGER size{}; + if (!file || !GetFileInformationByHandleEx(file.get(), FileAttributeTagInfo, &attributes, sizeof(attributes)) || + (attributes.FileAttributes & (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY)) || + !child_path(fs::path(final_path((*lease)[0].get())), fs::path(final_path(file.get()))) || + !GetFileSizeEx(file.get(), &size) || size.QuadPart <= 0 || uint64_t(size.QuadPart) != found->second.metadata.at("size").get()) + throw ApiError(409, "framework_file_changed", "已上传的框架文件被修改或暂时不可读,请重新上传。"); + lease->push_back(std::move(file)); + } + return lease; + } + void submit(HTTP_REQUEST_ID requestId, const std::string &action, const Json &body, + std::shared_ptr> inputLease = {}) { + const bool recovery = action == "calibrationRecover"; + const uint64_t submittedGeneration = generation(); + std::string id = new_id(); + std::string interruptedId; + Json job = { + {"taskId", id}, {"action", action}, {"state", "queued"}, {"createdUtc", utc_now()}, + {"startedUtc", nullptr}, {"finishedUtc", nullptr}, {"result", nullptr}, {"error", nullptr}}; + { + std::lock_guard lock(jobMutex); + if (!recoveryJobId.empty()) + throw ApiError(409, "recovery_in_progress", "设备正在恢复,请查询恢复任务状态。"); + if (!activeJobId.empty()) { + const auto &active = jobs.at(activeJobId); + if (!recovery || active.at("action").get().rfind("calibration", 0) != 0) + throw ApiError(409, "busy", "已有设备控制任务正在执行,请先查询任务状态。"); + interruptedId = activeJobId; + } + while (jobs.size() >= 128 && !jobOrder.empty()) { + auto expired = std::find_if(jobOrder.begin(), jobOrder.end(), [&](const std::string &candidate) { + return candidate != activeJobId && candidate != recoveryJobId; + }); + if (expired == jobOrder.end()) break; + jobs.erase(*expired); + jobOrder.erase(expired); + } + jobs[id] = job; + jobOrder.push_back(id); + if (recovery) recoveryJobId = id; + else activeJobId = id; + } + auto writeTaskLog = [this](const std::string &message) noexcept { + try { log_line(taskLog, message); } catch (...) {} + }; + writeTaskLog("Accepted " + action + " taskId=" + id); + auto self = shared_from_this(); + try { + std::thread([self, id, action, body, inputLease, recovery, interruptedId, submittedGeneration] { + Json result = nullptr, error = nullptr; + { + std::lock_guard lock(self->jobMutex); + self->jobs[id]["state"] = "running"; + self->jobs[id]["startedUtc"] = utc_now(); + } + try { + // Explicit mock fixture for the queued-before-execute race. + // Real services never read these files or delay dispatch. + if (self->simulated && !recovery && action.rfind("calibration", 0) == 0 && + fs::is_regular_file(self->dataRoot / L"OFFLINE_TEST_HTTP_DELAY_CALIBRATION_DISPATCH")) { + write_json(self->dataRoot / L"OFFLINE_TEST_HTTP_DISPATCH_WAITING", Json{{"taskId", id}}); + const auto deadline = unix_ms() + 10000; + while (unix_ms() < deadline && + fs::is_regular_file(self->dataRoot / L"OFFLINE_TEST_HTTP_DELAY_CALIBRATION_DISPATCH")) + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } + result = self->execute(action, body, submittedGeneration); + } catch (const std::exception &ex) { + error = api_failure(ex); + } catch (...) { + error = { + {"code", "sdk_error"}, {"message", "设备后台发生未知异常。"}, {"httpStatus", 500}}; + } + { + std::lock_guard lock(self->jobMutex); + auto &view = self->jobs[id]; + // A successful recovery may have already retired this task. + // A late SDK reply cannot turn an aborted task into success. + if (view["state"] == "running") { + view["result"] = std::move(result); + view["error"] = error; + view["finishedUtc"] = utc_now(); + view["state"] = error.is_null() ? "succeeded" : "failed"; + } + if (recovery && error.is_null() && !interruptedId.empty()) { + auto old = self->jobs.find(interruptedId); + if (old != self->jobs.end() && (old->second["state"] == "running" || old->second["state"] == "queued")) { + auto &aborted = old->second; + aborted["result"] = nullptr; + aborted["error"] = Json{{"code", "calibration_aborted"}, + {"message", "本次标定已通过恢复设备操作中止。"}, {"httpStatus", 409}}; + aborted["finishedUtc"] = utc_now(); + aborted["state"] = "failed"; + } + if (self->activeJobId == interruptedId) self->activeJobId.clear(); + } + if (recovery) { + if (self->recoveryJobId == id) self->recoveryJobId.clear(); + } else if (self->activeJobId == id) self->activeJobId.clear(); + } + try { + log_line(self->taskLog, action + " taskId=" + id + + (error.is_null() ? " succeeded" : " failed " + error.dump())); + } catch (...) {} + }).detach(); + } catch (...) { + std::lock_guard lock(jobMutex); + if (activeJobId == id) activeJobId.clear(); + if (recoveryJobId == id) recoveryJobId.clear(); + jobs[id]["state"] = "failed"; + jobs[id]["finishedUtc"] = utc_now(); + jobs[id]["error"] = Json{{"code", "task_start_failed"}, {"message", "无法启动设备任务。"}, {"httpStatus", 500}}; + throw; + } + send_json(requestId, 202, + Json{{"taskId", id}, + {"statusUrl", "/api/v1/tasks/" + id}, + {"message", "任务已接收,请查询任务状态;succeeded 才代表操作完成。"}}, + {{"Location", "/api/v1/tasks/" + id}}); + } + void handle(const HTTP_REQUEST &request) { + bool sent = false; + Headers errorHeaders; + try { + if (stopped) + throw ApiError(503, "shutting_down", "HTTP 服务正在关闭。"); + if (lower(trim(known_header(request, HttpHeaderHost))) != expectedHost) + throw ApiError(400, "invalid_host", "请求 Host 必须与配置的监听地址一致。"); + std::string path = utf8( + std::wstring(request.CookedUrl.pAbsPath, request.CookedUrl.AbsPathLength / sizeof(wchar_t))); + bool get = request.Verb == HttpVerbGET, post = request.Verb == HttpVerbPOST; + if (path == "/" && get) { + if (request.CookedUrl.QueryStringLength) + throw ApiError(400, "query_not_supported", "此版本不接受查询参数。"); + send_json(request.RequestId, 200, + Json{{"service", "FreeScan HTTP API"}, + {"version", "v1"}, + {"apiVersion", "1.3"}, + {"implementation", "C++17"}, + {"authentication", "Authorization: Bearer or X-Api-Key"}, + {"routes", contracts::routes()}}); + return; + } + if (path.rfind("/api/v1/", 0) != 0) + throw ApiError(404, "not_found", "接口不存在。"); + authenticate(request); + if (request.CookedUrl.QueryStringLength) + throw ApiError(400, "query_not_supported", "此版本不接受查询参数,访问密钥必须放在请求头。"); + if (get) { + if (path == "/api/v1/health") { + send_json(request.RequestId, 200, + Json{{"service", "FreeScan HTTP API"}, + {"running", true}, + {"utc", utc_now()}, + {"deviceStatusUrl", "/api/v1/status"}, + {"implementation", "C++17"}}); + return; + } + if (path == "/api/v1/status") { + send_json(request.RequestId, 200, bounded(status, 5000, "status_unavailable")); + return; + } + if (path == "/api/v1/device/battery") { + auto current = bounded(status, 5000, "status_unavailable"); + send_json(request.RequestId, 200, current.at("battery")); + return; + } + if (path == "/api/v1/capabilities") { + send_json(request.RequestId, 200, get_query("capabilities")); + return; + } + if (path == "/api/v1/data/scene") { + send_json(request.RequestId, 200, get_query("sceneInfo")); + return; + } + if (path == "/api/v1/preview/metrics") { + send_json(request.RequestId, 200, metrics()); + return; + } + if (path.rfind("/api/v1/tasks/", 0) == 0) { + auto id = path.substr(14); + Json view; + { + std::lock_guard lock(jobMutex); + auto found = jobs.find(id); + if (found == jobs.end()) + throw ApiError(404, "task_not_found", "任务不存在或已过期。"); + view = found->second; + } + send_json(request.RequestId, 200, view); + return; + } + if (path.rfind("/api/v1/files/", 0) == 0) { + auto id = path.substr(14); + if (!id32(id)) + throw ApiError(400, "invalid_file_id", + "fileId 必须为已登记的 32 位小写标识,不能使用路径。"); + send_download(request.RequestId, get_query("file", Json{{"fileId", id}}), sent); + return; + } + if(path=="/api/v1/calibration/view"){send_json(request.RequestId,200,get_query("calibrationView"));return;} + if(path=="/api/v1/calibration/view/image"){ + auto image=fresh_calibration();auto headers=calibration_headers(image);headers.emplace_back("Content-Type","image/jpeg");headers.emplace_back("Content-Length",std::to_string(image.frame.jpeg.size())); + send_headers(request.RequestId,200,headers,image.frame.jpeg.data(),image.frame.jpeg.size(),false);return; + } + if(path=="/api/v1/calibration/view/stream"){send_calibration_stream(request,sent);return;} + if (path == "/api/v1/preview/image") { + auto image = fresh(); + auto headers = frame_headers(*image); + headers.emplace_back("Content-Type", "image/jpeg"); + headers.emplace_back("Content-Length", std::to_string(image->jpeg.size())); + send_headers(request.RequestId, 200, headers, image->jpeg.data(), image->jpeg.size(), + false); + return; + } + if (path == "/api/v1/preview/stream") { + send_stream(request, sent); + return; + } + } + if (path == "/api/v1/framework/files") { + if (!post) { + errorHeaders.emplace_back("Allow", "POST"); + throw ApiError(405, "method_not_allowed", "框架文件上传只支持 POST。"); + } + send_json(request.RequestId, 201, upload_framework(request)); + return; + } + auto action = contracts::action_for_path(path); + if (!action.empty()) { + if (!post) { + errorHeaders.emplace_back("Allow", "POST"); + throw ApiError(405, "method_not_allowed", "该接口只支持 POST。"); + } + auto body = read_body(request, contracts::maximum_body_bytes(action)); + contracts::validate(action, body); + auto inputLease = action == "importFramework" ? lease_framework_files(body) : nullptr; + submit(request.RequestId, action, body, std::move(inputLease)); + return; + } + if (path == "/api/v1/health" || path == "/api/v1/status" || path == "/api/v1/device/battery" || path == "/api/v1/capabilities" || + path == "/api/v1/data/scene" || path == "/api/v1/calibration/view" || path == "/api/v1/calibration/view/image" || path == "/api/v1/calibration/view/stream" || path == "/api/v1/preview/image" || + path == "/api/v1/preview/stream" || path == "/api/v1/preview/metrics" || + path.rfind("/api/v1/tasks/", 0) == 0 || path.rfind("/api/v1/files/", 0) == 0) { + errorHeaders.emplace_back("Allow", "GET"); + throw ApiError(405, "method_not_allowed", "该接口只支持 GET。"); + } + throw ApiError(404, "not_found", "接口不存在。"); + } catch (const std::exception &ex) { + if (!sent && !stopped) { + auto error = api_failure(ex); + try { + send_json(request.RequestId, error["httpStatus"].get(), + Json{{"error", error}, {"utc", utc_now()}}, errorHeaders); + return; + } catch (...) { + } + } + HttpCancelHttpRequest(queue.get(), request.RequestId, nullptr); + } catch (...) { + HttpCancelHttpRequest(queue.get(), request.RequestId, nullptr); + } + } +}; + +HttpServer::HttpServer(fs::path dataRoot, Json config, std::function status, + std::function execute, + std::function query, + std::function()> frame, + std::function metrics, std::function generation, bool simulated) + : impl_(std::make_shared(std::move(dataRoot), std::move(config), std::move(status), std::move(execute), std::move(query), + std::move(frame), std::move(metrics), std::move(generation), simulated)) {} +HttpServer::~HttpServer() { + stop(); +} +void HttpServer::start() { + impl_->start(); +} +void HttpServer::stop() { + if (impl_) + impl_->stop(); +} +} // namespace freescan diff --git a/integrations/freescan-service/src/http_server.hpp b/integrations/freescan-service/src/http_server.hpp new file mode 100644 index 0000000..33558e7 --- /dev/null +++ b/integrations/freescan-service/src/http_server.hpp @@ -0,0 +1,20 @@ +#pragma once +#include "common.hpp" + +namespace freescan { +class HttpServer { + struct Impl; + std::shared_ptr impl_; + + public: + HttpServer(fs::path dataRoot, Json config, std::function status, std::function execute, + std::function query, + std::function()> frame, std::function metrics, + std::function generation, bool simulated = false); + ~HttpServer(); + HttpServer(const HttpServer &) = delete; + HttpServer &operator=(const HttpServer &) = delete; + void start(); + void stop(); +}; +} // namespace freescan diff --git a/integrations/freescan-service/src/main.cpp b/integrations/freescan-service/src/main.cpp new file mode 100644 index 0000000..1ab9edb --- /dev/null +++ b/integrations/freescan-service/src/main.cpp @@ -0,0 +1,185 @@ +#include "supervisor.hpp" +#include "http_server.hpp" +#include +#include + +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 path(32768); + DWORD count = GetModuleFileNameW(nullptr, path.data(), static_cast(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(); + 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 image(32768); + DWORD count = static_cast(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()) + throw ApiError(409, "process_identity_changed", "服务进程记录已失效,没有关闭任何程序。"); + try { + PipeClient(wide(record.at("controlPipe").get())).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())) + : 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(std::stoul(opts["--parent"].get())), + std::stoull(opts["--parent-start"].get()), simulated); + } + if (!config.value("enabled", true)) { + std::cout << "HTTP API 已在配置中停用。" << std::endl; + return 0; + } + CoInitializeEx(nullptr, COINIT_MULTITHREADED); + auto service = std::make_shared(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; + } +} diff --git a/integrations/freescan-service/src/pipe_rpc.cpp b/integrations/freescan-service/src/pipe_rpc.cpp new file mode 100644 index 0000000..b65dad7 --- /dev/null +++ b/integrations/freescan-service/src/pipe_rpc.cpp @@ -0,0 +1,234 @@ +#include "pipe_rpc.hpp" +#include +#include +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(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(std::max(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(data.size()); + uint8_t head[4] = {static_cast(size), static_cast(size >> 8), + static_cast(size >> 16), static_cast(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(head[0]) | (static_cast(head[1]) << 8) | + (static_cast(head[2]) << 16) | (static_cast(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()) { + 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 { + std::wstring path; + std::function handler; + Handle stopEvent; + std::thread accept; + std::mutex gate; + std::set> pipes; + std::atomic running{false}; + PSECURITY_DESCRIPTOR security = nullptr; + Impl(std::wstring name, std::function 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 data(bytes); + if (!GetTokenInformation(token.get(), TokenUser, data.data(), bytes, &bytes)) + throw ApiError(500, "pipe_security_error", "无法读取当前用户标识。"); + LPWSTR sid = nullptr; + if (!ConvertSidToStringSidW(reinterpret_cast(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 &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(), 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 hold(gate); + DisconnectNamedPipe(pipe->get()); + pipes.erase(pipe); + } + void loop() { + while (running) { + SECURITY_ATTRIBUTES attrs{sizeof(attrs), security, FALSE}; + auto pipe = std::make_shared( + 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 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 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 handler) + : impl_(std::make_shared(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 hold(impl_->gate); + for (auto &pipe : impl_->pipes) + CancelIoEx(pipe->get(), nullptr); + } + if (impl_->accept.joinable()) + impl_->accept.join(); +} +} // namespace freescan diff --git a/integrations/freescan-service/src/pipe_rpc.hpp b/integrations/freescan-service/src/pipe_rpc.hpp new file mode 100644 index 0000000..52a6296 --- /dev/null +++ b/integrations/freescan-service/src/pipe_rpc.hpp @@ -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_; + + public: + PipeServer(std::wstring name, std::function handler); + ~PipeServer(); + void start(); + void stop(); +}; +} // namespace freescan diff --git a/integrations/freescan-service/src/preview_capture.hpp b/integrations/freescan-service/src/preview_capture.hpp new file mode 100644 index 0000000..cc00a3c --- /dev/null +++ b/integrations/freescan-service/src/preview_capture.hpp @@ -0,0 +1,204 @@ +#pragma once +#include "common.hpp" +#include +#include +#include + +namespace freescan::detail { + +inline void preview_atomic_max(std::atomic &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 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 claimed{false}; + PreviewRawFrame frame; + }; + std::array slots_{}; + std::atomic 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 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 lastEntryMs{0}; + std::atomic 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(0, + std::chrono::duration_cast(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(0, + std::chrono::duration_cast(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(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 diff --git a/integrations/freescan-service/src/scene_snapshot_flow.hpp b/integrations/freescan-service/src/scene_snapshot_flow.hpp new file mode 100644 index 0000000..44ba79e --- /dev/null +++ b/integrations/freescan-service/src/scene_snapshot_flow.hpp @@ -0,0 +1,25 @@ +#pragma once +#include + +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 +void capture_scene_snapshot(bool pauseAcquisition, Prepare &&prepare, Pause &&pause, Wait &&wait, + Write &&write) { + std::forward(prepare)(); + if (pauseAcquisition) + std::forward(pause)(); + std::forward(wait)(); + std::forward(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 diff --git a/integrations/freescan-service/src/sdk_location.hpp b/integrations/freescan-service/src/sdk_location.hpp new file mode 100644 index 0000000..8f06c36 --- /dev/null +++ b/integrations/freescan-service/src/sdk_location.hpp @@ -0,0 +1,59 @@ +#pragma once +#include "common.hpp" +#include + +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 candidates; + if (config.contains("sdkPath") && config["sdkPath"].is_string()) + candidates.emplace_back(wide(config["sdkPath"].get())); + 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(in), {}); + std::smatch match; + if (std::regex_search(content, match, std::regex("([^<]+)"))) + 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 diff --git a/integrations/freescan-service/src/sdk_worker.cpp b/integrations/freescan-service/src/sdk_worker.cpp new file mode 100644 index 0000000..852730c --- /dev/null +++ b/integrations/freescan-service/src/sdk_worker.cpp @@ -0,0 +1,2797 @@ +#include "sdk_worker.hpp" +#include "contracts.hpp" +#include "scene_snapshot_flow.hpp" +#include "device_battery.hpp" +#include "calibration_completion.hpp" +#include "sdk_location.hpp" +#include "preview_capture.hpp" +#include "calibration_window_capture.hpp" +#include "calibration_telemetry.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#pragma warning(push) +#pragma warning(disable : 4091) // Unnamed trailing typedef in the installed vendor header. +#include "sn3dsdkcorepub.h" +#include "Sn3DSDKDataLibpub.h" +#pragma warning(pop) +#pragma comment(lib, "gdiplus.lib") +#pragma comment(lib, "ole32.lib") + +namespace freescan { +namespace { +using Clock = std::chrono::steady_clock; +const char *calibration_mode_name(int mode) { + switch (mode) { + case 0: return "跟踪仪标定"; + case 1: return "系统标定"; + case 2: return "探针标定"; + case 3: return "UE Nova 激光标定"; + default: return "未知标定模式"; + } +} +std::string lower(std::string value) { + for (auto &c : value) + c = static_cast(std::tolower(static_cast(c))); + return value; +} +bool same_path(const fs::path &a, const fs::path &b) { + return _wcsicmp(fs::absolute(a).lexically_normal().c_str(), fs::absolute(b).lexically_normal().c_str()) == + 0; +} +fs::path executable_directory() { + std::vector b(32768); + DWORD n = GetModuleFileNameW(nullptr, b.data(), static_cast(b.size())); + if (!n || n == b.size()) + throw ApiError(500, "application_path_error", "Cannot resolve worker executable path."); + return fs::path(std::wstring(b.data(), n)).parent_path(); +} +std::string native_path(const fs::path &p) { + auto v = path_string(fs::absolute(p).lexically_normal()); + std::replace(v.begin(), v.end(), '\\', '/'); + return v; +} +std::string read_text(const fs::path &p) { + std::ifstream in(p, std::ios::binary); + if (!in) + return {}; + return std::string(std::istreambuf_iterator(in), {}); +} +void write_text(const fs::path &p, const std::string &value) { + fs::create_directories(p.parent_path()); + std::ofstream out(p, std::ios::binary | std::ios::trunc); + if (!out || !out.write(value.data(), static_cast(value.size()))) + throw ApiError(500, "file_write_failed", "Cannot write application file: " + path_string(p)); +} +std::string guid_d(const std::string &value) { + return contracts::normalize_guid(value); +} +std::vector points(const Json &body, const char *key) { + std::vector out; + if (!body.contains(key)) + return out; + for (const auto &p : body.at(key)) + out.push_back({p.at(0).get(), p.at(1).get(), p.at(2).get()}); + return out; +} +std::vector ids(const Json &body, const char *key) { + if (!body.contains(key)) + return {}; + return body.at(key).get>(); +} +std::string failure(const Json &j) { + if (!j.is_object()) + return {}; + if (j.contains("success") && j["success"].is_boolean() && !j["success"].get()) + return "success=false"; + if (j.contains("result")) { + const auto &r = j["result"]; + if (r.is_string()) { + auto s = lower(r.get()); + if (!s.empty() && s != "success" && s != "ok" && s != "0") + return "result=" + r.get(); + } else if (r.is_boolean() && !r.get()) + return "result=false"; + else if (r.is_number_integer() && r.get() != 0) + return "result=" + r.dump(); + else if (r.is_object()) { + auto s = failure(r); + if (!s.empty()) + return s; + } + } + for (const auto *k : {"errorCode", "errCode"}) + if (j.contains(k)) { + try { + int64_t code = j[k].is_string() ? std::stoll(j[k].get()) : j[k].get(); + if (code) + return std::string(k) + "=" + std::to_string(code); + } catch (...) { + } + } + return j.contains("data") && j["data"].is_object() ? failure(j["data"]) : std::string(); +} +const std::vector parameter_fields = {"pointDistance", "brightness", "lightSourceMode", + "scanFrameRate", "highSpeedMode", "addMarkerMode", + "viewLock", "localEnlargedView", "qualityColor", + "strongLight", "preScanMode", "markerDiameters"}; +const std::vector unsupported = {"frameworkBrightness", "cloudShowMode", "scanAlignType", + "workingDistance", "workingRange"}; +const std::vector formats_lower = {"ascw", "ascs", "stl", "obj", "ply", "p3", "3mf", + "txt", "csv", "ascg", "tgf", "stp", "igs", "asc"}; +static_assert(sizeof(Sn3DStartupConfig) == 32, "SDK startup ABI changed"); +static_assert(sizeof(ProjectInfo) == 32, "SDK project ABI changed"); +static_assert(sizeof(FreeScanMeshPar) == 56 && sizeof(FreeSaveMeshPar) == 96, "SDK mesh/save ABI changed"); +static_assert(sizeof(Sn3DAlignParam) == 104 && sizeof(Sn3DEditParam) == 64 && sizeof(Sn3DClipPlaneData) == 24, + "SDK processing ABI changed"); +} // namespace + +struct WorkerService::Impl : std::enable_shared_from_this { + fs::path root, app, sdkPath, serviceDirectory, logPath; + Json config; + const bool simulated; + std::mutex operation, state, ackGate, callbackGate, sceneGate, frameGate, renderCopyGate, retainedGate; + std::condition_variable callbackDone, sceneDone, encodeWake; + std::atomic busy{false}, retiring{false}, disposed{false}, nativeRunning{false}, + sceneRunning{false}, encoderStop{false}, pollStop{false}; + bool initialized = false, attempted = false, scanning = false, projectReady = false, preview = false, + uncertain = false, restart = false, calibrationActive = false, acquisitionEverStarted = false, + frameworkImported = false, frameworkOptimized = false, frameworkCaptureStarted = false, + calibrationSession = false, calibrationSystemStarted = false, calibrationFreeEnabled = false, + ownerTrustedForForce = false; + size_t frameworkFileCount = 0; + int deviceType = 3, calibrationMode = 0, trakType = 0, callbacks = 0; + int64_t onlineChecked = 0, lastFrameMs = 0; + Json online = nullptr; + detail::DeviceBatteryCache battery; + detail::CalibrationTelemetryCache calibrationTelemetry; + CalibrationWindowCapture calibrationCapture; + std::string calibrationId,calibrationViewError,calibrationViewMessage; + std::string sessionId, projectId, scanMode = "trak", meshState = "none", calibrationAction = "none"; + // Receipt cache only: an empty value means no SDK completion has confirmed it. + std::string scanType, scanDevice; + Json applied = Json::object(), registered = Json::array(); + HMODULE module = nullptr, bridge = nullptr; + void *service = nullptr; + Handle serviceOwner; + DWORD servicePid = 0; + Json serviceOwnerIdentity = nullptr; + std::wstring oldPath, oldDirectory; + bool environmentChanged = false; + std::vector> retained; + struct Pending { + std::mutex mutex; + std::condition_variable cv; + std::set names; + bool done = false; + std::string error; + Json reply = nullptr; + }; + std::vector> pending; + struct SceneRequest { + int maximum = 0, mask = 0; + bool running = false, finished = false, success = false; + bool pauseAcquisition = false; + uint64_t notifications = 0, emptyNotifications = 0, incrementalNotifications = 0; + std::string error, lastError; + }; + std::atomic sceneNotifications{0}; + std::atomic lastSceneNotificationMs{0}; + std::shared_ptr sceneRequest; + using BridgeInt = int(WINAPI *)(); + using BridgeCapture = int(WINAPI *)(HMODULE, int, int); + using BridgeSummary = int(WINAPI *)(char *, int); + using BridgeWrite = int(WINAPI *)(const wchar_t *); + using BridgeClear = void(WINAPI *)(); + using BridgeError = const char *(WINAPI *)(); + BridgeCapture capture = nullptr; + BridgeSummary summary = nullptr; + BridgeWrite writeSnapshot = nullptr; + BridgeClear clearScene = nullptr; + BridgeError bridgeError = nullptr; + std::string bridgeReason = "Native bridge not loaded."; + detail::PreviewFramePool framePool; + detail::PreviewFramePool::Lease raw; + detail::PreviewCallbackDiagnostics captureDiagnostics; + std::shared_ptr latest; + uint64_t frameEpoch = 0, sequence = 0, offered = 0, encoded = 0, replaced = 0, throttled = 0, + encodeFailures = 0; + double encodeTotal = 0; + int fps = 20, maxWidth = 1280, jpegQuality = 75; + Clock::time_point nextOffer{}; + int64_t windowStart = unix_ms(); + std::thread encoder, poller; + ULONG_PTR gdiplusToken = 0; + CLSID jpegClsid{}; + + Impl(fs::path dataRoot, Json cfg, bool mock) + : root(fs::absolute(std::move(dataRoot))), app(executable_directory()), config(std::move(cfg)), + simulated(mock) { + fs::create_directories(root / "Logs"); + logPath = root / "Logs" / ("cpp_worker_" + new_id() + ".log"); + fps = config.value("previewFps", 20); + maxWidth = config.value("previewMaxWidth", 1280); + jpegQuality = config.value("previewJpegQuality", 75); + deviceType = config.value("deviceType", 3); + if (fps < 1 || fps > 30 || maxWidth < 320 || maxWidth > 3840 || jpegQuality < 30 || jpegQuality > 95) + throw ApiError(400, "invalid_configuration", "Invalid preview configuration."); + Gdiplus::GdiplusStartupInput input; + if (Gdiplus::GdiplusStartup(&gdiplusToken, &input, nullptr) != Gdiplus::Ok) + throw ApiError(500, "jpeg_encoder_unavailable", "GDI+ initialization failed."); + UINT count = 0, bytes = 0; + Gdiplus::GetImageEncodersSize(&count, &bytes); + std::vector storage(bytes); + auto *codecs = reinterpret_cast(storage.data()); + if (!bytes || Gdiplus::GetImageEncoders(count, bytes, codecs) != Gdiplus::Ok) + throw ApiError(500, "jpeg_encoder_unavailable", "No GDI+ codecs."); + bool found = false; + for (UINT i = 0; i < count; i++) + if (std::wcscmp(codecs[i].MimeType, L"image/jpeg") == 0) { + jpegClsid = codecs[i].Clsid; + found = true; + break; + } + if (!found) + throw ApiError(500, "jpeg_encoder_unavailable", "JPEG encoder unavailable."); + } + void start_threads() { + auto self = shared_from_this(); + encoder = std::thread([self] { self->encode_loop(); }); + poller = std::thread([self] { self->poll_loop(); }); + } + void log(const std::string &message) noexcept { + try { + log_line(logPath, message); + } catch (...) { + } + } + void retain_owner() { + static auto *roots = new std::vector>; + static auto *mutex = new std::mutex; + std::lock_guard guard(*mutex); + roots->push_back(shared_from_this()); + } + template std::shared_ptr keep(T value) { + auto p = std::make_shared(std::move(value)); + std::lock_guard guard(retainedGate); + retained.push_back(p); + return p; + } + const char *text(const std::string &value) { + return keep(value)->c_str(); + } + template T *array_ptr(const std::shared_ptr> &p) { + return p->empty() ? nullptr : p->data(); + } + void flag_timeout(const std::string &message) { + std::lock_guard guard(state); + uncertain = restart = true; + initialized = false; + battery.clear(); + calibrationTelemetry.clear(); + log(message); + } + FARPROC address(const std::string &name) { + if (!module) + return nullptr; + auto p = GetProcAddress(module, name.c_str()); + if (p) + return p; + static const std::map decorated = { + {"Sn3DSetScanModeSync", "?Sn3DSetScanModeSync@@YAHPEAXW4ScanMode@@H@Z"}, + {"Sn3DCreateProjectSync", "?Sn3DCreateProjectSync@@YAHPEAXPEAUProjectInfo@@H@Z"}, + {"Sn3DSetScanTypeSync", "?Sn3DSetScanTypeSync@@YAHPEAXW4ScanType@@H@Z"}, + {"Sn3DStartScanSync", "?Sn3DStartScanSync@@YAHPEAXH@Z"}, + {"Sn3DPauseScanSync", "?Sn3DPauseScanSync@@YAHPEAXH@Z"}, + {"Sn3DSetMainWindowVisibleSync", "?Sn3DSetMainWindowVisibleSync@@YAHPEAX_NH@Z"}}; + auto i = decorated.find(name); + return i == decorated.end() ? nullptr : GetProcAddress(module, i->second.c_str()); + } + template T function(const std::string &name) { + auto p = address(name); + if (!p) + throw ApiError(503, "sdk_unavailable", "Installed SDK export is missing: " + name); + return reinterpret_cast(p); + } + static void check(int code, const std::string &api) { + if (code == 0x0B) + throw ApiError(504, "sdk_timeout", + api + " 等待厂家服务完成超时(0x0000000B)。请检查厂家窗口、固件与软件版本及 SDK " + "日志;超时不能作为加密狗故障的判断。请正常重启设备服务。"); + if (code) { + std::ostringstream s; + s << api << " returned 0x" << std::hex << std::setw(8) << std::setfill('0') + << static_cast(code); + throw ApiError(502, "sdk_error", s.str()); + } + } + int native(const std::string &name, std::function call, int timeout = 35000) { + bool expected = false; + if (!nativeRunning.compare_exchange_strong(expected, true)) + throw ApiError(409, "device_busy", "A previous native call is still running."); + auto promise = std::make_shared>(); + auto future = promise->get_future(); + auto self = shared_from_this(); + try { + std::thread([self, promise, call = std::move(call)] { + HRESULT com = CoInitializeEx(nullptr, COINIT_MULTITHREADED); + try { + int result = call(); + if (SUCCEEDED(com)) + CoUninitialize(); + self->nativeRunning = false; + promise->set_value(result); + } catch (...) { + if (SUCCEEDED(com)) + CoUninitialize(); + self->nativeRunning = false; + try { + promise->set_exception(std::current_exception()); + } catch (...) { + } + } + }).detach(); + } catch (...) { + nativeRunning = false; + throw; + } + if (future.wait_for(std::chrono::milliseconds(timeout)) != std::future_status::ready) { + flag_timeout(name + " native call timed out; worker restart required."); + throw ApiError(504, "sdk_timeout", + name + " native call has not returned; restart the device service."); + } + int result = future.get(); + if (result == 0x0B) + flag_timeout(name + " returned manufacturer timeout 0x0000000B."); + check(result, name); + return result; + } + std::shared_ptr expect(const std::string &names) { + auto p = std::make_shared(); + std::istringstream stream(names); + std::string name; + while (std::getline(stream, name, '|')) + p->names.insert(name); + std::lock_guard guard(ackGate); + pending.push_back(p); + return p; + } + void forget(const std::shared_ptr &p) { + if (!p) + return; + std::lock_guard guard(ackGate); + pending.erase(std::remove(pending.begin(), pending.end(), p), pending.end()); + } + Json wait(const std::shared_ptr &p, int timeout, const std::string &name) { + std::unique_lock guard(p->mutex); + auto deadline = Clock::now() + std::chrono::milliseconds(timeout); + while (!p->done) { + if (p->cv.wait_until(guard, std::min(deadline, Clock::now() + std::chrono::milliseconds(500))) == + std::cv_status::timeout && + Clock::now() >= deadline) { + guard.unlock(); + flag_timeout(name + " completion callback timed out."); + throw ApiError(504, "sdk_timeout", name + " completion not confirmed; restart required."); + } + guard.unlock(); + health(false); + guard.lock(); + } + if (!p->error.empty()) + throw ApiError(502, "sdk_error", name + ": " + p->error); + return p->reply; + } + Json command(const std::string &api, const std::string &completion, std::function call, + int timeout = 120000) { + auto p = completion.empty() ? nullptr : expect(completion); + try { + log("SDK command: " + api); + native(api, std::move(call)); + Json reply = p ? wait(p, timeout, api) : Json(nullptr); + forget(p); + return reply; + } catch (...) { + forget(p); + throw; + } + } + Json service_command(const std::string &api, const std::string &completion, int timeout = 120000, + bool preferSync = false) { + using Sync = int(WINAPI *)(void *, int); + using Async = int(WINAPI *)(void *); + if (preferSync && address(api + "Sync")) { + auto fn = function(api + "Sync"); + native(api + "Sync", [this, fn] { return fn(service, 30000); }); + return nullptr; + } else { + auto fn = function(api); + return command(api, completion, [this, fn] { return fn(service); }, timeout); + } + } + void int_command(const std::string &api, const std::string &completion, int value, int timeout = 120000, + bool preferSync = false) { + using Fn = int(WINAPI *)(void *, int); + using Sync = int(WINAPI *)(void *, int, int); + if (preferSync && address(api + "Sync")) { + auto fn = function(api + "Sync"); + native(api + "Sync", [this, fn, value] { return fn(service, value, 30000); }); + } else { + auto fn = function(api); + command(api, completion, [this, fn, value] { return fn(service, value); }, timeout); + } + } + void bool_command(const std::string &api, const std::string &completion, bool value) { + auto fn = function(api); + command(api, completion, [this, fn, value] { return fn(service, value); }); + } + template + void pointer_command(const std::string &api, const std::string &completion, const std::shared_ptr &p, + int timeout = 120000) { + auto fn = function(api); + command(api, completion, [this, fn, p] { return fn(service, p.get()); }, timeout); + } + bool enter_callback() { + std::lock_guard guard(callbackGate); + if (disposed || retiring) + return false; + callbacks++; + return true; + } + void leave_callback() { + std::lock_guard guard(callbackGate); + callbacks--; + callbackDone.notify_all(); + } + static void CALLBACK message_callback(int, int, void *data, size_t size, void *owner) { + auto *self = static_cast(owner); + if (!self || !self->enter_callback()) + return; + try { + self->on_message(data, size); + } catch (...) { + self->log("SDK message callback rejected invalid data."); + } + self->leave_callback(); + } + static void CALLBACK render_callback(const unsigned char *data, int w, int h, int c, void *owner) { + auto *self = static_cast(owner); + if (!self) + return; + detail::PreviewCallbackDiagnostics::Observation observed(self->captureDiagnostics, w, h, c, + unix_ms()); + if (!self->enter_callback()) { + self->captureDiagnostics.lifecycleRejected.fetch_add(1, std::memory_order_relaxed); + return; + } + try { + self->on_frame(data, w, h, c); + } catch (...) { + // A callback must never wait for filesystem logging. The poller + // reports persistent stalls with these counters outside SDK code. + self->captureDiagnostics.exceptions.fetch_add(1, std::memory_order_relaxed); + } + // Finish all observation writes before the shutdown callback counter is + // released, so draining callbacks also drains access to this worker. + observed.finish(); + self->leave_callback(); + } + static void CALLBACK scene_callback(void *owner) { + auto *self = static_cast(owner); + if (!self || !self->enter_callback()) + return; + try { + self->on_scene(); + } catch (...) { + self->log("SDK scene callback failed."); + } + self->leave_callback(); + } + void on_message(void *data, size_t bytes) { + if (!data || !bytes || bytes > 4 * 1024 * 1024) + return; + auto *p = static_cast(data); + while (bytes && p[bytes - 1] == 0) + bytes--; + Json j = Json::parse(p, p + bytes, nullptr, false); + if (!j.is_object() || !j.contains("cmd") || !j["cmd"].is_string()) + return; + auto name = j["cmd"].get(); + auto error = failure(j); + { + std::lock_guard guard(state); + if(attempted&&!retiring&&!disposed&&!restart&&!sessionId.empty())calibrationTelemetry.observe(j,unix_ms()); + } + if (name == "sdkDeviceStatus" && error.empty()) { + std::lock_guard guard(state); + if (attempted && !retiring && !disposed && !restart) + battery.update(j, unix_ms()); + } + if (j.value("type", std::string()) != "information" || !error.empty()) + log("SDK " + j.dump()); + if (name == "ScanModeChange" && error.empty()) { + const Json &d = j.contains("scanMode") ? j : j.value("data", Json::object()); + if (d.is_object() && d.contains("scanMode")) { + int v = d["scanMode"].is_string() ? std::stoi(d["scanMode"].get()) + : d["scanMode"].get(); + std::lock_guard guard(state); + if (initialized && !restart && v >= 1 && v <= 5) { + scanning = v == 2 || v == 3; + if (scanning) + acquisitionEverStarted = true; + if (scanning && scanType == "photogrammetry") { + frameworkCaptureStarted = true; + frameworkOptimized = false; + } + if (v == 4 || v == 5) + uncertain = false; + } + } + } + std::vector> list; + { + std::lock_guard guard(ackGate); + list = pending; + } + for (auto &item : list) { + const auto completion = detail::sdk_completion(item->names, j, error); + if (completion.done) { + std::lock_guard guard(item->mutex); + if (!item->done) { + item->done = true; + item->error = completion.error; + item->reply = j; + item->cv.notify_all(); + } + } + } + } + void clear_frames() { + std::lock_guard guard(frameGate); + frameEpoch++; + raw.reset(); + latest.reset(); + nextOffer = {}; + lastFrameMs = 0; + } + void on_frame(const unsigned char *pixels, int w, int h, int channels) { + if (!pixels || w <= 0 || h <= 0 || w > 16384 || h > 16384 || channels != 4 || + uint64_t(w) * h * 4 > 256 * 1024 * 1024) { + captureDiagnostics.invalidParameters.fetch_add(1, std::memory_order_relaxed); + return; + } + std::unique_lock copy(renderCopyGate, std::try_to_lock); + if (!copy.owns_lock()) { + captureDiagnostics.copyLockBusy.fetch_add(1, std::memory_order_relaxed); + return; + } + uint64_t epoch; + auto now = Clock::now(); + { + // Capture the epoch while the corresponding active state is still + // protected. Stop/create cannot clear frames between that state + // check and this epoch read, then have an old callback publish into + // the new generation. Both locks are nonblocking in SDK code. + std::unique_lock current(state, std::try_to_lock); + if (!current.owns_lock()) { + captureDiagnostics.stateLockBusy.fetch_add(1, std::memory_order_relaxed); + return; + } + if (!initialized || !preview || !projectReady || restart || uncertain) { + captureDiagnostics.inactiveState.fetch_add(1, std::memory_order_relaxed); + return; + } + std::unique_lock guard(frameGate, std::try_to_lock); + if (!guard.owns_lock()) { + captureDiagnostics.frameLockBusy.fetch_add(1, std::memory_order_relaxed); + return; + } + offered++; + if (nextOffer != Clock::time_point{} && now < nextOffer) { + throttled++; + captureDiagnostics.throttled.fetch_add(1, std::memory_order_relaxed); + return; + } + auto interval = std::chrono::microseconds(1000000 / fps); + if (nextOffer == Clock::time_point{} || now - nextOffer > std::chrono::seconds(1)) + nextOffer = now + interval; + else { + do { + nextOffer += interval; + } while (nextOffer <= now); + } + epoch = frameEpoch; + } + auto value = framePool.try_acquire(); + if (!value) { + captureDiagnostics.poolUnavailable.fetch_add(1, std::memory_order_relaxed); + return; + } + framePool.prepare(value, w, h); + value->epoch = epoch; + value->captured = unix_ms(); + const auto copyStarted = Clock::now(); + std::memcpy(value->pixels.data(), pixels, value->pixels.size()); + captureDiagnostics.record_copy(copyStarted); + { + std::unique_lock guard(frameGate, std::try_to_lock); + if (!guard.owns_lock()) { + captureDiagnostics.frameLockBusy.fetch_add(1, std::memory_order_relaxed); + return; + } + if (epoch != frameEpoch || retiring || disposed) { + captureDiagnostics.staleEpoch.fetch_add(1, std::memory_order_relaxed); + return; + } + if (raw) + replaced++; + raw = std::move(value); + lastFrameMs = raw->captured; + captureDiagnostics.accepted.fetch_add(1, std::memory_order_relaxed); + } + encodeWake.notify_one(); + } + void encode_loop() { + CoInitializeEx(nullptr, COINIT_MULTITHREADED); + while (!encoderStop) { + detail::PreviewFramePool::Lease image; + { + std::unique_lock guard(frameGate); + encodeWake.wait(guard, [this] { return encoderStop || bool(raw); }); + if (encoderStop) + break; + image = std::move(raw); + } + try { + auto started = Clock::now(); + detail::flip_preview_rows(*image); + int w = std::min(image->w, maxWidth), + h = std::max(1, int(std::lround(double(image->h) * w / image->w))); + Gdiplus::Bitmap source(image->w, image->h, image->w * 4, PixelFormat32bppARGB, + image->pixels.data()); + Gdiplus::Bitmap output(w, h, PixelFormat32bppARGB); + Gdiplus::Graphics g(&output); + g.SetCompositingMode(Gdiplus::CompositingModeSourceCopy); + g.SetInterpolationMode(Gdiplus::InterpolationModeBilinear); + g.DrawImage(&source, Gdiplus::Rect(0, 0, w, h)); + IStream *stream = nullptr; + if (FAILED(CreateStreamOnHGlobal(nullptr, TRUE, &stream))) + throw std::runtime_error("JPEG stream creation failed."); + struct Release { + IStream *p; + ~Release() { + p->Release(); + } + } release{stream}; + Gdiplus::EncoderParameters params{}; + params.Count = 1; + ULONG quality = jpegQuality; + params.Parameter[0] = {Gdiplus::EncoderQuality, 1, Gdiplus::EncoderParameterValueTypeLong, + &quality}; + if (output.Save(stream, &jpegClsid, ¶ms) != Gdiplus::Ok) + throw std::runtime_error("JPEG encoding failed."); + STATSTG stat{}; + if (FAILED(stream->Stat(&stat, STATFLAG_NONAME)) || stat.cbSize.HighPart || + stat.cbSize.LowPart > 8 * 1024 * 1024) + throw std::runtime_error("JPEG size is invalid."); + auto value = std::make_unique(); + value->jpeg.resize(stat.cbSize.LowPart); + LARGE_INTEGER zero{}; + stream->Seek(zero, STREAM_SEEK_SET, nullptr); + ULONG got = 0; + if (FAILED(stream->Read(value->jpeg.data(), static_cast(value->jpeg.size()), &got)) || + got != value->jpeg.size()) + throw std::runtime_error("JPEG stream read failed."); + value->width = w; + value->height = h; + value->sourceWidth = image->w; + value->sourceHeight = image->h; + value->capturedMs = image->captured; + value->encodedMs = unix_ms(); + value->encodeMs = std::chrono::duration(Clock::now() - started).count(); + std::lock_guard guard(frameGate); + if (image->epoch == frameEpoch && !disposed) { + value->sequence = ++sequence; + encoded++; + encodeTotal += value->encodeMs; + latest = std::move(value); + } + } catch (...) { + std::lock_guard guard(frameGate); + encodeFailures++; + } + } + CoUninitialize(); + } + void simulated_frame() { + bool enabled; + { + std::lock_guard guard(state); + enabled = initialized && preview && projectReady; + } + if (!enabled) + return; + const int w = 640, h = 360; + std::vector pixels(size_t(w) * h * 4, 0); + for (int y = 0; y < h; y++) + for (int x = 0; x < w; x++) { + size_t n = (size_t(y) * w + x) * 4; + pixels[n] = 45; + pixels[n + 1] = 55; + pixels[n + 2] = 65; + pixels[n + 3] = 255; + } + Gdiplus::Bitmap image(w, h, w * 4, PixelFormat32bppARGB, pixels.data()); + Gdiplus::Graphics g(&image); + Gdiplus::Font font(L"Arial", 20); + Gdiplus::SolidBrush brush(Gdiplus::Color(255, 255, 220, 80)); + g.DrawString(L"SIMULATED SDK - NO SCANNER DATA", -1, &font, Gdiplus::PointF(8, 40), &brush); + g.Flush(Gdiplus::FlushIntentionSync); + for (int y = 0; y < h / 2; y++) + std::swap_ranges(pixels.begin() + size_t(y) * w * 4, pixels.begin() + size_t(y + 1) * w * 4, + pixels.begin() + size_t(h - 1 - y) * w * 4); + render_callback(pixels.data(), w, h, 4, this); + } + std::vector service_processes(bool requireExpectedPath) { + std::vector result; + Handle snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)); + if (!snapshot) + throw ApiError(502, "service_owner_unverified", + "Cannot enumerate manufacturer service processes."); + PROCESSENTRY32W entry{}; + entry.dwSize = sizeof(entry); + if (Process32FirstW(snapshot.get(), &entry)) + do { + if (_wcsicmp(entry.szExeFile, L"FreeScan Trak.exe") != 0) + continue; + if (!requireExpectedPath) { + result.push_back(entry.th32ProcessID); + continue; + } + Handle p( + OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, FALSE, entry.th32ProcessID)); + if (!p) + throw ApiError(502, "service_owner_unverified", + "Cannot verify manufacturer process ownership."); + wchar_t path[32768]{}; + DWORD length = 32768; + if (!QueryFullProcessImageNameW(p.get(), 0, path, &length)) + throw ApiError(502, "service_owner_unverified", "Cannot read manufacturer process path."); + if (same_path(fs::path(std::wstring(path, length)), serviceDirectory / L"FreeScan Trak.exe")) + result.push_back(entry.th32ProcessID); + } while (Process32NextW(snapshot.get(), &entry)); + return result; + } + void capture_service() { + if (serviceOwner || serviceDirectory.empty()) + return; + auto list = service_processes(true); + if (list.empty()) + return; + if (list.size() != 1) + throw ApiError(502, "service_owner_unverified", + "More than one matching manufacturer service exists."); + HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, FALSE, list[0]); + if (!process) + throw ApiError(502, "service_owner_unverified", + "Cannot retain the manufacturer service process handle."); + serviceOwner.reset(process); + servicePid = list[0]; + FILETIME created{}, ended{}, kernel{}, user{}; + wchar_t image[32768]{}; + DWORD length = 32768; + if (!GetProcessTimes(process, &created, &ended, &kernel, &user) || + !QueryFullProcessImageNameW(process, 0, image, &length) || + !same_path(fs::path(std::wstring(image, length)), serviceDirectory / L"FreeScan Trak.exe")) + throw ApiError(502, "service_owner_unverified", "Cannot verify captured manufacturer identity."); + ULARGE_INTEGER ticks{}; + ticks.LowPart = created.dwLowDateTime; + ticks.HighPart = created.dwHighDateTime; + { + std::lock_guard guard(state); + serviceOwnerIdentity = {{"processId", servicePid}, {"startedFileTime", std::to_string(ticks.QuadPart)}, + {"executable", path_string(fs::path(std::wstring(image, length)))}}; + } + log("Captured manufacturer service PID " + std::to_string(servicePid)); + } + void health(bool required = true) { + if (simulated) + return; + if (serviceOwner && WaitForSingleObject(serviceOwner.get(), 0) == WAIT_OBJECT_0) { + flag_timeout("Captured manufacturer service exited unexpectedly."); + throw ApiError(502, "sdk_error", "Manufacturer service exited; restart the device service."); + } + bool active; + { + std::lock_guard guard(state); + active = initialized; + } + if (required && active && !serviceOwner) { + capture_service(); + if (!serviceOwner) { + flag_timeout("Manufacturer service ownership could not be confirmed."); + throw ApiError(502, "service_owner_unverified", + "Cannot confirm this session's manufacturer service process."); + } + } + } + void ready() { + { + std::lock_guard guard(state); + if (restart) + throw ApiError(409, "restart_required", "SDK state requires restarting the device service."); + if (!initialized || disposed || !service) + throw ApiError(409, "not_connected", "Connect and initialize the SDK first."); + } + health(); + } + void require_project(bool stopped) { + ready(); + std::lock_guard guard(state); + if (uncertain) + throw ApiError(409, "state_uncertain", "Previous operation is unconfirmed."); + if (!projectReady) + throw ApiError(409, "project_required", "Create a scan project first."); + if (calibrationActive) + throw ApiError(409, "calibration_active", + "Complete calibration and create a scan project first."); + if (stopped && scanning) + throw ApiError(409, "scan_active", "Pause acquisition before this operation."); + } + void ensure_bridge() { + if (bridge) + return; + std::vector candidates; + if (config.contains("bridgePath") && config["bridgePath"].is_string()) + candidates.emplace_back(wide(config["bridgePath"].get())); + candidates.push_back(app / L"FreeScanNativeBridge.dll"); + candidates.push_back(root / L"FreeScanNativeBridge.dll"); + auto parent = root; + for (int n = 0; n < 3 && !parent.empty(); n++, parent = parent.parent_path()) + candidates.push_back(parent / L"FreeScanViewer" / L"FreeScanNativeBridge.dll"); + fs::path path; + for (const auto &item : candidates) + if (fs::is_regular_file(item)) { + path = item; + break; + } + if (path.empty()) { + bridgeReason = "FreeScanNativeBridge.dll is missing."; + return; + } + bridge = LoadLibraryExW(path.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); + if (!bridge) { + bridgeReason = "Native bridge load failed: Windows " + std::to_string(GetLastError()); + return; + } + auto get = [this](const char *name) { return GetProcAddress(bridge, name); }; + auto abi = reinterpret_cast(get("FSB_GetAbiVersion")), + size = reinterpret_cast(get("FSB_GetSceneStructSize")); + if (!abi || !size || abi() != 1 || size() != 608) { + bridgeReason = "Native bridge ABI is incompatible."; + return; + } + capture = reinterpret_cast(get("FSB_Capture")); + summary = reinterpret_cast(get("FSB_GetSummary")); + writeSnapshot = reinterpret_cast(get("FSB_WriteSnapshot")); + clearScene = reinterpret_cast(get("FSB_Clear")); + bridgeError = reinterpret_cast(get("FSB_GetLastError")); + if (!capture || !summary || !writeSnapshot || !clearScene || !bridgeError) { + capture = nullptr; + bridgeReason = "Native bridge exports are incomplete."; + return; + } + bridgeReason.clear(); + } + bool raw_available() { + return capture && module && address("Sn3DGetSceneData") && address("Sn3DRegisterDataCallback") && + address("Sn3DSetRealtimeScanDataMode"); + } + fs::path locate_sdk() { + const auto location = detail::locate_sdk_installation(root, app, config); + serviceDirectory = location.serviceDirectory; + return location.library; + } + void prepare_configuration() { + const auto bin = sdkPath.parent_path(); + auto content = read_text(app / L"scansoftwaresdk.ini"); + if (content.empty()) + content = read_text(root / L"scansoftwaresdk.ini"); + if (content.empty()) + content = read_text(bin / L"scansoftwaresdk.ini"); + if (content.empty()) + content = "offscreenRender=1\r\n"; + auto replace_line = [](std::string source, const std::string &key, const std::string &value) { + std::regex line("(^|\\n)[ \\t]*" + key + "[ \\t]*=[^\\r\\n]*"); + if (std::regex_search(source, line)) + return std::regex_replace(source, line, "$1" + key + "=" + value); + return key + "=" + value + "\r\n" + source; + }; + content = replace_line(content, "serviceFile", native_path(serviceDirectory / L"FreeScan Trak.exe")); + content = replace_line(content, "workmode", "1"); + content = replace_line(content, "offscreenRender", "1"); + write_text(app / L"scansoftwaresdk.ini", content); + if (!same_path(root, app)) + write_text(root / L"scansoftwaresdk.ini", content); + for (const auto &target : {app / L"zmq_sdk_config.ini", root / L"zmq_sdk_config.ini"}) + if (!fs::exists(target) && fs::is_regular_file(bin / L"zmq_sdk_config.ini")) + fs::copy_file(bin / L"zmq_sdk_config.ini", target, fs::copy_options::none); + } + void load() { + if (module) + return; + sdkPath = locate_sdk(); + prepare_configuration(); + auto data = read_text(sdkPath); + if (data.size() < 64 || data[0] != 'M' || data[1] != 'Z') + throw ApiError(503, "sdk_unavailable", "Invalid SDK DLL."); + uint32_t offset = 0; + std::memcpy(&offset, data.data() + 0x3c, 4); + uint16_t machine = 0; + if (uint64_t(offset) + 6 > data.size() || std::memcmp(data.data() + offset, "PE\0\0", 4) != 0) + throw ApiError(503, "sdk_unavailable", "Incomplete SDK PE header."); + std::memcpy(&machine, data.data() + offset + 4, 2); + if (machine != 0x8664) + throw ApiError(503, "sdk_unavailable", "SDK DLL must be x64."); + wchar_t current[32768]{}; + DWORD n = GetCurrentDirectoryW(32768, current); + oldDirectory.assign(current, n); + DWORD count = GetEnvironmentVariableW(L"PATH", nullptr, 0); + std::vector env(count + 1); + if (count) + GetEnvironmentVariableW(L"PATH", env.data(), count); + oldPath = env.data(); + const auto bin = sdkPath.parent_path(); + auto newPath = bin.wstring() + L";" + (bin / L"Qt").wstring() + L";" + serviceDirectory.wstring() + + L";" + oldPath; + SetEnvironmentVariableW(L"PATH", newPath.c_str()); + if (!SetCurrentDirectoryW(serviceDirectory.c_str())) + throw ApiError(503, "sdk_unavailable", "Cannot select manufacturer working directory."); + environmentChanged = true; + ensure_bridge(); + module = LoadLibraryExW(sdkPath.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); + if (!module) + throw ApiError(503, "sdk_unavailable", + "SDK load failed: Windows " + std::to_string(GetLastError())); + retain_owner(); + log("Loaded SDK " + path_string(sdkPath)); + } + void restore_environment() { + if (environmentChanged) { + SetEnvironmentVariableW(L"PATH", oldPath.c_str()); + SetCurrentDirectoryW(oldDirectory.c_str()); + environmentChanged = false; + } + } + void connect(int type) { + { + std::lock_guard guard(state); + if (initialized) { + if (type != deviceType) + throw ApiError(409, "device_type_conflict", + "Existing SDK session uses another device type."); + return; + } + if (attempted) + throw ApiError( + 409, "worker_restart_required", + "This process already attempted SDK initialization; replace the worker process."); + if (retiring || disposed) + throw ApiError(409, "worker_restart_required", "This worker was retired."); + } + if (!simulated) { + load(); + if (!service_processes(false).empty()) + throw ApiError(409, "service_in_use", + "Manufacturer service is owned by another session. Save and close that " + "application before connecting."); + } + { + std::lock_guard guard(state); + attempted = true; + battery.clear(); + deviceType = type; + sessionId = new_id(); + calibrationTelemetry.clear();calibrationId.clear();calibrationViewError.clear();calibrationViewMessage.clear(); + } + if (simulated) { + std::lock_guard guard(state); + service = reinterpret_cast(uintptr_t(1)); + // Explicit offline mock only: exercise a failed initialization + // whose first cleanup cannot finish, without loading vendor code. + const auto fixture = root / L"OFFLINE_TEST_FAIL_INITIALIZE_ONCE"; + if (fs::is_regular_file(fixture)) { + fs::rename(fixture, root / L"OFFLINE_TEST_FAILED_INITIALIZE_CONSUMED"); + uncertain = restart = true; + throw ApiError(504, "sdk_timeout", "OFFLINE_TEST_FIXTURE: initialization failed once."); + } + initialized = true; + ownerTrustedForForce = true; + online = true; + onlineChecked = unix_ms(); + return; + } + try { + auto startup = keep(Sn3DStartupConfig{}); + startup->log_dir = text(path_string(root / L"Logs" / L"SDK")); + startup->app_name = text("FreeScanCpp"); + startup->level = static_cast(2); + startup->windowVis = false; + startup->clearService = false; + startup->sdk_performanceLevel = static_cast(1); + fs::create_directories(root / L"Logs" / L"SDK"); + auto set = function("Sn3DSetStartupParam"); + native("Sn3DSetStartupParam", [set, startup] { return set(*startup); }); + auto p = expect("initializeFinish|sdkInitializeFinish|InitializeFinish"); + try { + auto init = function("Sn3DInitialize"); + native("Sn3DInitialize", [this, init, type] { return init(&service, type); }); + if (!service) + throw ApiError(502, "sdk_error", "SDK returned an empty service handle."); + auto reg = + function("Sn3DRegisterMessageCallback"); + native("Sn3DRegisterMessageCallback", + [this, reg] { return reg(service, message_callback, this); }); + wait(p, 90000, "Initialize"); + forget(p); + } catch (...) { + forget(p); + throw; + } + capture_service(); + if (!serviceOwner) + throw ApiError(502, "service_owner_unverified", + "Initialized service process ownership was not confirmed."); + health(false); + { + std::lock_guard guard(state); + initialized = true; + } + poll_online(); + { + std::lock_guard guard(state); + // Merely finding a same-path process after failed Initialize + // cannot authorize terminating somebody else's vendor app. + ownerTrustedForForce = true; + } + } catch (...) { + // Initialization may fail after launching its manufacturer process. + // Keep ownership metadata for a later explicit recovery, without + // changing the original SDK failure or starting another service. + try { capture_service(); } catch (...) { } + std::lock_guard guard(state); + initialized = false; + uncertain = restart = true; + battery.clear(); + throw; + } + } + void poll_online() { + if (simulated) { + std::lock_guard guard(state); + online = true; + onlineChecked = unix_ms(); + return; + } + ready(); + auto data = keep(DeviceStatus{}); + auto fn = function("Sn3DGetDeviceStatus"); + native("Sn3DGetDeviceStatus", [this, fn, data] { return fn(service, data.get()); }, 5000); + std::lock_guard guard(state); + online = !data->offline; + onlineChecked = unix_ms(); + } + void poll_loop() { + int64_t next = 0; + int64_t nextPreviewReport = 0, previewStaleSince = 0; + while (!pollStop) { + try { + if (simulated) { + if (!retiring && !disposed) + simulated_frame(); + } else if (!busy && !retiring && !disposed && unix_ms() >= next) { + std::unique_lock op(operation, std::try_to_lock); + if (op.owns_lock()) { + bool active; + { + std::lock_guard guard(state); + active = initialized && !restart; + } + if (active) { + next = unix_ms() + 3000; + poll_online(); + } + } + } + } catch (const std::exception &e) { + log(std::string("Device status poll: ") + e.what()); + } + // No frame callback performs logging. Sample from this background + // thread at most once per five seconds, and log only sustained + // stalls while an initialized project's preview is requested. + const auto reportNow = unix_ms(); + if (reportNow >= nextPreviewReport) { + nextPreviewReport = reportNow + 5000; + try { + bool active = false, acquiring = false, sampled = false; + int64_t received = 0; + { + std::unique_lock guard(state, std::try_to_lock); + if (guard.owns_lock()) { + std::unique_lock image(frameGate, std::try_to_lock); + if (image.owns_lock()) { + active = initialized && preview && projectReady && !restart && !uncertain && + !retiring && !disposed; + acquiring = scanning; + received = lastFrameMs; + sampled = true; + } + } + } + if (sampled) { + if (active && (!received || reportNow - received > 2000)) { + if (!previewStaleSince) + previewStaleSince = reportNow; + else if (reportNow - previewStaleSince >= 5000) { + Json diagnostic = {{"scanning", acquiring}, + {"lastAcceptedFrameAgeMs", received ? Json(std::max(0, reportNow - received)) : Json(nullptr)}, + {"captureDiagnostics", captureDiagnostics.snapshot(reportNow)}, + {"bufferPool", framePool.snapshot()}}; + log("Preview capture stalled: " + diagnostic.dump()); + } + } else { + previewStaleSince = 0; + } + } + } catch (...) { + // Diagnostic sampling cannot change SDK session state. + } + } + for (int n = 0; n < 5 && !pollStop; n++) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + } + void start_preview() { + ready(); + { + std::lock_guard guard(state); + if (preview) + return; + } + if (!simulated) { + if (address("Sn3DRegisterDataCallback")) { + auto f = function("Sn3DRegisterDataCallback"); + native("Sn3DRegisterDataCallback", [this, f] { return f(scene_callback, this); }, 15000); + } + if (address("Sn3DSetRealtimeScanDataMode")) + int_command("Sn3DSetRealtimeScanDataMode", "", 1); + auto f = function( + "Sn3DRegisterOffscreenRenderCallback"); + native( + "Sn3DRegisterOffscreenRenderCallback", + [this, f] { return f(service, render_callback, this); }, 15000); + } + { + std::lock_guard guard(state); + preview = true; + } + try { + if (!simulated) { + auto f = function("Sn3DStartOffscreenRender"); + native("Sn3DStartOffscreenRender", [f] { return f(); }, 15000); + } + } catch (...) { + { + std::lock_guard guard(state); + preview = false; + } + clear_frames(); + throw; + } + } + void stop_preview(int timeout = 15000) { + bool enabled; + { + std::lock_guard guard(state); + enabled = preview; + } + if (enabled && !simulated) { + auto f = function("Sn3DStopOffscreenRender"); + native("Sn3DStopOffscreenRender", [f] { return f(); }, timeout); + } + { + std::lock_guard guard(state); + preview = false; + } + clear_frames(); + } + void pause() { + ready(); + if (!simulated) + service_command("Sn3DPauseScan", "pauseScanFinish|pauseScanFinish1", 30000, true); + std::lock_guard guard(state); + scanning = false; + uncertain = false; + } + void verify_end(const Json &body) { + if (!body.value("confirm", false)) + throw ApiError(400, "confirmation_required", "Explicit session-end confirmation is required."); + std::lock_guard guard(state); + if (body.contains("expectedSessionId")) { + std::string expected = + body["expectedSessionId"].is_null() ? "" : body["expectedSessionId"].get(); + if (lower(expected) != lower(sessionId)) + throw ApiError(409, "session_changed", "Current session differs from the reviewed session."); + } else if (!sessionId.empty()) + throw ApiError(409, "session_confirmation_required", "Provide the reviewed status.sessionId."); + if (body.contains("expectedProjectId")) { + std::string expected = + body["expectedProjectId"].is_null() ? "" : body["expectedProjectId"].get(); + if (expected != (projectReady ? projectId : "")) + throw ApiError(409, "project_changed", "Current project differs from the reviewed project."); + } + if (projectReady && !body.value("discardProject", false)) + throw ApiError(409, "project_discard_confirmation_required", + "Export required data, then explicitly confirm ending this project session."); + if (projectReady && !body.contains("expectedProjectId")) + throw ApiError(409, "project_confirmation_required", "Provide the reviewed status.projectId."); + } + bool disconnect_inner(bool shuttingDown = false) { + bool wasReady, wasScanning; + { + std::lock_guard guard(state); + wasReady = initialized; + wasScanning = scanning; + } + // Explicit service shutdown follows the vendor's normal Release cleanup, + // including after an earlier timeout. It never submits a new acquisition + // command to an uncertain session. Business disconnect always confirms Pause. + if (wasScanning && !shuttingDown) + pause(); + if (!service && !wasReady && !serviceOwner) { + retiring = true; + disposed = true; + restore_environment(); + return true; + } + if (nativeRunning || sceneRunning) + throw ApiError(409, "device_busy", "A native operation is still active."); + { + std::lock_guard guard(ackGate); + if (!pending.empty()) + throw ApiError(409, "device_busy", "An SDK completion is still pending."); + } + retiring = true; + calibrationCapture.stop(); + { + std::lock_guard guard(state); + initialized = false;calibrationTelemetry.clear(); + battery.clear(); + } + const auto deadline = Clock::now() + std::chrono::seconds(15); + auto remaining = [&] { + return std::max( + 1, + int(std::chrono::duration_cast(deadline - Clock::now()).count())); + }; + try { + if (!simulated && service && !serviceOwner) { + capture_service(); + if (!serviceOwner) + throw ApiError(502, "service_owner_unverified", + "Cannot confirm manufacturer owner; release/reconnect was not attempted."); + } + stop_preview(remaining()); + { + std::unique_lock guard(callbackGate); + if (!callbackDone.wait_until(guard, deadline, [this] { return callbacks == 0; })) + throw ApiError(504, "sdk_timeout", "SDK callbacks have not drained; restart required."); + } + if (clearScene) + clearScene(); + if (!simulated && service) { + auto release = function("Sn3DRelease"); + native("Sn3DRelease", [this, release] { return release(&service); }, remaining()); + service = nullptr; + } + if (!simulated && serviceOwner && + WaitForSingleObject(serviceOwner.get(), remaining()) != WAIT_OBJECT_0) + throw ApiError(504, "sdk_timeout", + "SDK release returned, but manufacturer service exit is unconfirmed."); + restore_environment(); + { + std::lock_guard guard(state); + service = nullptr; + initialized = false; + scanning = projectReady = preview = calibrationActive = false; + calibrationSession = calibrationSystemStarted = calibrationFreeEnabled = false; + ownerTrustedForForce = false; + acquisitionEverStarted = frameworkImported = false; + frameworkOptimized = frameworkCaptureStarted = false; + frameworkFileCount = 0; + scanType.clear(); + scanDevice.clear(); + projectId.clear(); + sessionId.clear(); + meshState = "none"; + uncertain = restart = false; + online = nullptr; + onlineChecked = 0; + } + disposed = true; + clear_frames(); + return false; + } catch (...) { + flag_timeout("SDK release was not confirmed; do not reconnect this worker."); + disposed = true; + throw; + } + } + fs::path artifact_directory(const std::string &prefix) { + auto directory = root / L"Exports" / wide(prefix + "_" + new_id()); + fs::create_directories(directory); + return directory; + } + Json register_artifacts(const fs::path &directory, const std::string &requiredExtension = {}) { + std::vector paths; + size_t dirs = 1; + if (GetFileAttributesW(directory.c_str()) & FILE_ATTRIBUTE_REPARSE_POINT) + throw ApiError(502, "invalid_export_path", "Artifact root is a reparse point."); + for (fs::recursive_directory_iterator i(directory), end; i != end; ++i) { + auto attributes = GetFileAttributesW(i->path().c_str()); + if (attributes == INVALID_FILE_ATTRIBUTES) + throw ApiError(502, "export_unavailable", "Cannot inspect exported artifact."); + if (attributes & FILE_ATTRIBUTE_REPARSE_POINT) + throw ApiError(502, "invalid_export_path", "Artifact path contains a reparse point."); + if (i->is_directory()) { + if (++dirs > 256) + throw ApiError(502, "export_directory_limit", "Too many artifact directories."); + } else if (i->is_regular_file()) { + if (i->path().filename().wstring().size() > 180) + throw ApiError(502, "export_filename_limit", + "导出文件名超过180个字符,请缩短工程或导出名称。"); + if (requiredExtension.empty() || + (lower(i->path().extension().u8string()) == requiredExtension && fs::file_size(i->path()) > 0)) + paths.push_back(i->path()); + if (paths.size() > 256) + throw ApiError(502, "export_file_limit", "Too many artifact files."); + } + } + if (paths.empty()) + throw ApiError(502, requiredExtension.empty() ? "export_empty" : "export_no_files", + "SDK returned successfully but produced no downloadable file. Check data type and " + "selected formats."); + std::sort(paths.begin(), paths.end()); + Json result = Json::array(); + std::lock_guard guard(state); + for (const auto &path : paths) { + std::ifstream test(path, std::ios::binary); + if (!test) + throw ApiError(502, "export_unavailable", "Exported file is not readable."); + std::string id = new_id(), name = path_string(path.filename()), + type = lower(path.extension().u8string()) == ".json" ? "application/json" + : "application/octet-stream"; + registered.push_back({{"fileId", id}, + {"root", path_string(fs::absolute(root / L"Exports"))}, + {"path", path_string(fs::absolute(path))}, + {"name", name}, + {"contentType", type}}); + result.push_back({{"fileId", id}, + {"name", name}, + {"bytes", fs::file_size(path)}, + {"downloadUrl", "/api/v1/files/" + id}}); + } + return result; + } + Json create_project(const Json &body) { + ready(); + std::string mode = body.value("mode", std::string("trak")), label = body.value("name", std::string()); + { + std::lock_guard guard(state); + if (scanning) + throw ApiError(409, "scan_active", "Pause acquisition before creating a project."); + projectReady = false; + } + clear_frames(); + if (clearScene) + clearScene(); + SYSTEMTIME local{}; + GetLocalTime(&local); + char stamp[48]{}; + std::snprintf(stamp, sizeof(stamp), "%04d%02d%02d_%02d%02d%02d_%03d", local.wYear, local.wMonth, + local.wDay, local.wHour, local.wMinute, local.wSecond, local.wMilliseconds); + const std::string id = + std::string("Scan_") + stamp + "_" + new_id().substr(0, 6) + (label.empty() ? "" : "_" + label); + auto directory = root / L"Scans" / wide(id); + fs::create_directories(directory); + if (!simulated) { + service_command("Sn3DEnterScanModePage", "enterScanModePageFinish", 30000, true); + int_command("Sn3DSetScanMode", "setScanModeFinish", mode == "trak" ? 0 : 1, 30000, true); + auto value = keep(ProjectInfo{}); + value->szSlnDirPath = text(native_path(directory)); + value->szSlnFileName = nullptr; + value->irParams.scanSubMode = static_cast(0); + value->irParams.irAlignType = static_cast(100); + value->irParams.irPointDis = 1.0f; + if (address("Sn3DCreateProjectSync")) { + auto f = function("Sn3DCreateProjectSync"); + native("Sn3DCreateProjectSync", [this, f, value] { return f(service, value.get(), 30000); }); + } else + pointer_command("Sn3DCreateProject", "createProjectFinish", value, 30000); + } + { + std::lock_guard guard(state); + projectId = id; + scanMode = mode; + projectReady = true; + scanning = false; + meshState = "none"; + calibrationActive = false; + calibrationSession = calibrationSystemStarted = calibrationFreeEnabled = false; + uncertain = false; + acquisitionEverStarted = frameworkImported = false; + frameworkOptimized = frameworkCaptureStarted = false; + frameworkFileCount = 0; + scanType.clear(); + scanDevice.clear(); + } + // Project creation is already confirmed. Commit each following receipt + // separately so a partial failure never invents a device/type setting. + // UE/TE selection is a Trak option. Laser mode keeps its original SDK + // creation path and its scanner source is fixed by that mode. + if (!simulated && mode == "trak") + int_command("Sn3DSetScanDeviceType", "setScanDeviceTypeFinish", SNSDK_SCANDEVICE_TENOVA, + 30000); + { + std::lock_guard guard(state); + scanDevice = "scanner"; + } + if (!simulated) + int_command("Sn3DSetScanType", "setScanTypeFinish", SNSDK_SCANTYPE_POINTCLOUD, 30000); + { + std::lock_guard guard(state); + scanType = "mesh"; + } + try { + start_preview(); + } catch (const ApiError &error) { + log(std::string("Project exists, preview did not start: ") + error.what()); + std::lock_guard guard(state); + if (restart) + throw; + } + std::lock_guard guard(state); + return {{"projectId", id}, {"mode", mode}, {"previewEnabled", preview}, + {"scanType", scanType}, {"scanDevice", scanDevice}}; + } + Json set_scan_type(const Json &body) { + require_project(true); + const auto requestedType = body.at("scanType").get(); + std::string requestedDevice; + bool deviceChanged, already; + { + std::lock_guard guard(state); + requestedDevice = body.value( + "device", requestedType == "photogrammetry" ? std::string("tracker") + : requestedType == "markers" ? std::string("scanner") + : !scanDevice.empty() ? scanDevice + : std::string("scanner")); + if (meshState != "none") + throw ApiError(409, "processing_active", "Undo mesh processing before changing scan type."); + if ((requestedType == "photogrammetry" && + (scanMode != "trak" || requestedDevice != "tracker")) || + (requestedType == "markers" && + (scanMode != "laser" || requestedDevice != "scanner")) || + (scanMode == "laser" && requestedDevice != "scanner")) + throw ApiError(409, "unsupported_scan_type", + "Photogrammetry requires Trak/UE Nova (tracker); markers require " + "laser/TE Nova (scanner). FRAME is marker capture, not station relocation."); + deviceChanged = scanDevice != requestedDevice; + if (deviceChanged && (acquisitionEverStarted || frameworkImported)) + throw ApiError(409, "project_data_present", + "Changing UE/TE Nova can clear project data. Export required data and " + "create a fresh project before changing the acquisition device."); + if (deviceChanged && !body.value("confirm", false)) + throw ApiError(400, "confirmation_required", + "Changing the acquisition device can clear data; provide confirm:true " + "in an empty project."); + already = !deviceChanged && scanType == requestedType; + } + const int sdkDevice = requestedDevice == "tracker" ? SNSDK_SCANDEVICE_UENOVA + : SNSDK_SCANDEVICE_TENOVA; + const int sdkType = requestedType == "photogrammetry" ? SNSDK_SCANTYPE_PHOTOGRAMMETRY + : requestedType == "markers" ? SNSDK_SCANTYPE_FRAME + : SNSDK_SCANTYPE_POINTCLOUD; + if (deviceChanged) { + if (!simulated) + int_command("Sn3DSetScanDeviceType", "setScanDeviceTypeFinish", sdkDevice, 30000); + std::lock_guard guard(state); + scanDevice = requestedDevice; + // The device change may reset the vendor's current scan type. + scanType.clear(); + } + if (deviceChanged) { + clear_frames(); + if (clearScene) + clearScene(); + } + if (!already) { + if (!simulated) + int_command("Sn3DSetScanType", "setScanTypeFinish", sdkType, 30000); + { + std::lock_guard guard(state); + scanType = requestedType; + } + // Only invalidate this application's old image/scene snapshots. + // FSB_Clear never clears SDK project geometry or framework points. + clear_frames(); + if (clearScene) + clearScene(); + } + return {{"scanType", requestedType}, + {"scanDevice", requestedDevice}, + {"sdkScanType", sdkType}, + {"sdkScanDeviceType", sdkDevice}, + {"deviceChanged", deviceChanged}, + {"alreadyInRequestedState", already}, + {"acquisitionStarted", false}, + {"status", status_json()}}; + } + Json import_framework(const Json &body) { + require_project(true); + { + std::lock_guard guard(state); + if (meshState != "none") + throw ApiError(409, "processing_active", "Undo mesh processing before importing a framework."); + if (scanMode != "trak" || scanType != "mesh" || scanDevice != "scanner") + throw ApiError(409, "framework_mode_required", + "Framework import currently requires Trak, mesh, TE Nova (scanner), " + "and paused acquisition."); + } + const auto directory = root / L"FrameworkUploads"; + const DWORD directoryAttributes = GetFileAttributesW(directory.c_str()); + if (directoryAttributes == INVALID_FILE_ATTRIBUTES || + !(directoryAttributes & FILE_ATTRIBUTE_DIRECTORY) || + (directoryAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) + throw ApiError(404, "framework_file_not_found", "Upload framework files to this service first."); + const auto canonicalDirectory = fs::canonical(directory); + auto fileNames = keep(std::vector()); + auto pinnedFiles = keep(std::vector()); + for (const auto &item : body.at("fileIds")) { + const auto id = item.get(); + fs::path found; + for (const auto *extension : {L".p3", L".txt", L".asc"}) { + const auto candidate = directory / (wide(id) + extension); + const DWORD attributes = GetFileAttributesW(candidate.c_str()); + if (attributes == INVALID_FILE_ATTRIBUTES) + continue; + if (!found.empty() || (attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) || + fs::canonical(candidate).parent_path() != canonicalDirectory) + throw ApiError(400, "invalid_framework_file", "Framework upload is not a unique regular file."); + found = candidate; + } + if (found.empty()) + throw ApiError(404, "framework_file_not_found", "Framework file ID does not exist in this service."); + Handle file(CreateFileW(found.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT, nullptr)); + BY_HANDLE_FILE_INFORMATION information{}; + LARGE_INTEGER bytes{}; + if (!file || !GetFileInformationByHandle(file.get(), &information) || + (information.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) || + !GetFileSizeEx(file.get(), &bytes) || bytes.QuadPart <= 0 || bytes.QuadPart > 16 * 1024 * 1024) + throw ApiError(400, "invalid_framework_file", "Framework file must be readable and between 1 byte and 16 MiB."); + pinnedFiles->push_back(std::move(file)); + fileNames->push_back(native_path(found)); + } + auto pointers = keep(std::vector()); + for (const auto &name : *fileNames) + pointers->push_back(name.c_str()); + if (!simulated) { + auto fn = function("Sn3DImportGlobalMarkers"); + command("Sn3DImportGlobalMarkers", "importGlobalMarkersFinish", + [this, fn, pointers, fileNames, pinnedFiles] { + return fn(service, pointers->data(), static_cast(pointers->size())); + }); + } + pinnedFiles->clear(); // SDK completion confirmed; no write/delete lock is needed afterwards. + { + std::lock_guard guard(state); + frameworkImported = true; + frameworkFileCount = body.at("fileIds").size(); + } + // A freshly imported reference frame makes previous managed snapshots + // stale. This leaves the SDK's actual project and imported points intact. + clear_frames(); + if (clearScene) + clearScene(); + return {{"frameworkImported", true}, + {"frameworkFileCount", body.at("fileIds").size()}, + {"fileIds", body.at("fileIds")}, + {"scanType", "mesh"}, + {"scanDevice", "scanner"}, + {"acquisitionStarted", false}, + {"status", status_json()}}; + } + Json optimize_framework() { + require_project(true); + { + std::lock_guard guard(state); + if (scanMode != "trak" || scanType != "photogrammetry" || scanDevice != "tracker") + throw ApiError(409, "framework_capture_mode_required", + "Framework optimization requires Trak, photogrammetry and UE Nova (tracker)."); + if (meshState != "none") + throw ApiError(409, "processing_active", "Undo mesh processing before framework optimization."); + if (!frameworkCaptureStarted) + throw ApiError(409, "framework_capture_required", + "Acquire and pause photogrammetry data before optimizing the framework."); + } + if (!simulated) + service_command("Sn3DGlobalMarkerOptimize", "globalMarkerOptimizeFinish", 120000); + { + std::lock_guard guard(state); + frameworkOptimized = true; + } + return {{"frameworkOptimized", true}, {"acquisitionStarted", false}, {"status", status_json()}}; + } + Json parameters(const Json &body) { + for (auto item = body.begin(); item != body.end(); ++item) { + const auto &key = item.key(); + const auto &v = item.value(); + if (!simulated) { + if (key == "pointDistance") { + auto f = function("Sn3DSetPointDistance"); + float value = v.get(); + command( + "Sn3DSetPointDistance", "setPointDistanceFinish", + [this, f, value] { return f(service, value); }, 120000); + } else if (key == "markerDiameters") { + auto data = keep(v.get>()); + auto f = function("Sn3DSetMarkerDiameterType"); + command("Sn3DSetMarkerDiameterType", "setMarkerDiameterTypeFinish", [this, f, data] { + return f(service, data->data(), static_cast(data->size())); + }); + } else if (key == "brightness") + int_command("Sn3DSetScanMeshBrightnessLevel", "setScanMeshBrightnessLevelFinish", + v.get()); + else if (key == "lightSourceMode") + int_command("Sn3DSetLightSourceMode", "setLightSourceModeFinish", v.get()); + else if (key == "scanFrameRate") + int_command("Sn3DSetScanFrameRate", "", v.get()); + else { + static const std::map> map = { + {"highSpeedMode", {"Sn3DSetHighSpeedMode", "setHighSpeedModeFinish"}}, + {"addMarkerMode", {"Sn3DSetAddMarkerMode", "setAddMarkerModeFinish"}}, + {"viewLock", {"Sn3DSetViewLockEnable", "setViewLockEnableFinish"}}, + {"localEnlargedView", + {"Sn3DSetLocalEnlargedViewEnable", "setLocalEnlargedViewEnableFinish"}}, + {"qualityColor", {"Sn3DSetQualityColor", "setQualityColorFinish"}}, + {"strongLight", {"Sn3DSetStrongLight", ""}}, + {"preScanMode", {"Sn3DSetPreScanMode", "setPreScanModeFinish"}}}; + auto i = map.find(key); + if (i == map.end()) + throw ApiError(400, "unknown_parameter", "Unknown scan parameter: " + key); + bool_command(i->second.first, i->second.second, v.get()); + } + } + std::lock_guard guard(state); + applied[key] = v; + } + Json fields = Json::array(); + for (auto i = body.begin(); i != body.end(); ++i) + fields.push_back(i.key()); + return {{"appliedFields", fields}, + {"atomic", false}, + {"confirmation", body.contains("strongLight") || body.contains("scanFrameRate") + ? "strongLight and scanFrameRate are SDK-accepted values without " + "completion callbacks; other fields wait for completion." + : "sdk_completion"}}; + } + void mesh(const Json &b) { + if (!simulated) { + auto p = keep(FreeScanMeshPar{}); + p->fileter_level = static_cast(b.value("filterLevel", 0)); + p->smooth_level = static_cast(b.value("smoothLevel", 0)); + p->remove_small_floating_parts = b.value("removeSmallFloatingParts", 0); + p->cut_mesh_edgeOpt_ischeck = b.value("cutMeshEdgeOptimization", false); + p->cut_meshedge_opt_value = b.value("cutMeshEdgeValue", 0.0); + p->detected_hole_opt_ischeck = b.value("holeOptimization", false); + p->boundary_opt_ischeck = b.value("boundaryOptimization", false); + p->remove_spike_ischeck = b.value("removeSpikes", false); + p->marker_hole_filling_ischeck = b.value("fillMarkerHoles", false); + p->isRememberChoice = b.value("rememberChoice", false); + if (b.contains("maxTriangles") && !b["maxTriangles"].is_null()) { + p->max_trianlges_ischeck = true; + p->max_trianlges_value = b["maxTriangles"].get(); + } + if (b.contains("fillSmallHole") && !b["fillSmallHole"].is_null()) { + p->fill_small_hole_ischeck = 1; + p->fill_small_hole_value = b["fillSmallHole"].get(); + } + pointer_command("Sn3DMesh", "meshFinish", p, 300000); + } + std::lock_guard guard(state); + meshState = "preview"; + } + Json export_data(const Json &body, bool frameworkExport = false) { + const std::string name = body.value("name", std::string("ScanResult")); + auto directory = artifact_directory("export"); + auto selected = body.at("formats").get>(); + if (simulated) { + for (auto &format : selected) + write_text(directory / wide("SIMULATED_" + name + "_" + format + ".fixture.txt"), + "OFFLINE_TEST_FIXTURE\nThis is not valid scanner geometry. Requested format: " + + format + "\n"); + } else { + std::set chosen; + for (auto &f : selected) + chosen.insert(lower(f)); + std::string mask(14, '0'); + for (size_t n = 0; n < formats_lower.size(); n++) + if (chosen.count(formats_lower[n])) + mask[n] = '1'; + auto p = keep(FreeSaveMeshPar{}); + p->fileName = text(name); + auto folder = native_path(directory); + while (!folder.empty() && folder.back() == '/') + folder.pop_back(); + p->folderPath = text(folder + "/"); + p->format = text(mask); + p->method = text("save"); + p->postpageVisible = 0; + p->saveAscwFile = chosen.count("ascw") ? 1 : 0; + p->saveAscsFile = chosen.count("ascs") ? 1 : 0; + p->saveStlFile = chosen.count("stl") ? 1 : 0; + p->saveObjFile = chosen.count("obj") ? 1 : 0; + p->savePlyFile = chosen.count("ply") ? 1 : 0; + p->saveP3File = chosen.count("p3") ? 1 : 0; + p->save3MfFile = chosen.count("3mf") ? 1 : 0; + p->saveTxtFile = chosen.count("txt") ? 1 : 0; + p->saveCsvFile = chosen.count("csv") ? 1 : 0; + p->saveAscgFile = chosen.count("ascg") ? 1 : 0; + p->saveTgfFile = chosen.count("tgf") ? 1 : 0; + p->saveStpFile = chosen.count("stp") ? 1 : 0; + p->saveIgsFile = chosen.count("igs") ? 1 : 0; + p->saveAscFile = chosen.count("asc") ? 1 : 0; + pointer_command("Sn3DSaveData", "saveDataFinish", p, 300000); + } + auto files = register_artifacts(directory, frameworkExport && !simulated ? ".p3" : ""); + std::lock_guard guard(state); + return {{"name", name}, {"formats", selected}, {"files", files}, {"projectId", projectId}, + {"dataKind", frameworkExport ? "framework" : "mesh"}}; + } + Json align(const Json &body) { + auto action = body.at("action").get(); + if (!simulated) { + if (action == "enter") + service_command("Sn3DEnterAlign", "enterAlignFinish"); + else if (action == "next") + service_command("Sn3DNextManualAlign", "nextManualAlignFinish"); + else if (action == "cancel") + service_command("Sn3DCancelManualAlign", "cancelManualAlignFinish"); + else if (action == "exit") + service_command("Sn3DExitAlign", "exitAlignFinish"); + else { + auto p = keep(Sn3DAlignParam{}); + std::vector modes = {"featureAuto", "markerAuto", "featureManual", + "markerManual"}; + auto mode = body.at("mode").get(); + p->alignType = static_cast( + std::distance(modes.begin(), std::find(modes.begin(), modes.end(), mode))); + p->fixKey = text(guid_d(body.at("fixedProjectUuid").get())); + p->floatKey = text(guid_d(body.at("movingProjectUuid").get())); + auto fixed = keep(points(body, "fixedPoints")), moving = keep(points(body, "movingPoints")), + fixedMarkers = keep(points(body, "fixedMarkerPoints")), + movingMarkers = keep(points(body, "movingMarkerPoints")); + auto fixedIds = keep(ids(body, "fixedMarkerIds")), + movingIds = keep(ids(body, "movingMarkerIds")); + p->v_fixPosCount = static_cast(fixed->size()); + p->v_fixPos = array_ptr(fixed); + p->v_floatPosCount = static_cast(moving->size()); + p->v_floatPos = array_ptr(moving); + p->fixMarkerCount = static_cast(fixedIds->size()); + p->fixMarkerId = array_ptr(fixedIds); + p->fixMarkerPos = array_ptr(fixedMarkers); + p->floatMarkerCount = static_cast(movingIds->size()); + p->floatMarkerId = array_ptr(movingIds); + p->floatMarkerPos = array_ptr(movingMarkers); + pointer_command("Sn3DApplyMultiProjectAlignParam", "applyMultiProjectAlignParamFinish", p, + 300000); + } + } + return {{"operation", action}, {"sdkCompletion", true}}; + } + Json edit(const Json &body) { + if (!simulated) { + auto p = keep(Sn3DEditParam{}); + p->prjUuid = text(guid_d(body.at("projectUuid").get())); + if (body.contains("cloudUuid")) + p->cloudUuid = text(guid_d(body.at("cloudUuid").get())); + auto pointIds = keep(ids(body, "pointIds")), markerIds = keep(ids(body, "markerIds")); + auto coordinates = keep(points(body, "points")), normals = keep(points(body, "normals")); + p->deleteMarkersCount = markerIds->size(); + p->deleteMarkersId = array_ptr(markerIds); + p->deletePointCount = pointIds->size(); + p->vertex_data = array_ptr(coordinates); + p->norma_data = array_ptr(normals); + p->delelePointID = array_ptr(pointIds); + pointer_command("Sn3DApplyEdit", "applyEditFinish", p); + } + return {{"edited", true}}; + } + Json clip(const Json &body) { + Json packed = {{"centers", Json::array({body.at("center")})}, + {"normals", Json::array({body.at("normal")})}}; + auto center = keep(points(packed, "centers")), normal = keep(points(packed, "normals")); + if (normal->at(0).x == 0 && normal->at(0).y == 0 && normal->at(0).z == 0) + throw ApiError(400, "invalid_parameter", + "Clip plane normal becomes zero in the SDK float representation."); + if (!simulated) { + auto p = keep(Sn3DClipPlaneData{}); + p->center = array_ptr(center); + p->normal = array_ptr(normal); + p->isDeleteBelowPoint = body.value("deleteBelowPoints", true); + p->isDeleteBelowMarker = body.value("deleteBelowMarkers", false); + pointer_command("Sn3DSetClipPlane", "setClipPlaneFinish", p); + } + return {{"clipped", true}}; + } + void begin_calibration_view() { + calibrationCapture.stop(); + Json owner;std::string session; + { + std::lock_guard guard(state); + calibrationId=new_id();calibrationViewError.clear();calibrationViewMessage.clear(); + session=sessionId;owner=serviceOwnerIdentity; + if(simulated){calibrationViewError="simulated_window_unavailable";calibrationViewMessage="离线模拟没有厂家标定窗口,不提供模拟画面。";return;} + if(!initialized||!calibrationActive||!ownerTrustedForForce||!serviceOwner||!owner.is_object()){ + calibrationViewError="service_owner_unverified";calibrationViewMessage="当前SDK标定窗口的进程归属尚未核实。";return; + } + } + try { + // Display only the already initialized SDK service's own GUI. This + // never starts another vendor program, SDK session or scan project. + auto show=function("Sn3DSetMainWindowVisibleSync"); + native("Sn3DSetMainWindowVisibleSync",[this,show]{return show(service,true,10000);},15000); + std::string error; + if(!calibrationCapture.start(session,owner,&error))throw ApiError(503,"calibration_window_unavailable",error.empty()?"厂家标定窗口采集未能启动。":error); + }catch(const ApiError &error){ + std::lock_guard guard(state); + calibrationViewError=error.code;calibrationViewMessage=error.what(); + }catch(const std::exception &error){ + std::lock_guard guard(state); + calibrationViewError="calibration_window_unavailable";calibrationViewMessage=error.what(); + } + } + Json calibration_view(bool includeFrame) { + std::lock_guard guard(state); + bool active=initialized&&calibrationActive&&!retiring&&!disposed&&!restart&&!uncertain; + Json out{{"source","sdk_calibration_window"},{"sessionId",sessionId.empty()?Json(nullptr):Json(sessionId)}, + {"calibrationId",calibrationId.empty()?Json(nullptr):Json(calibrationId)}, + {"calibrationActive",active},{"available",false},{"state","calibration_inactive"}, + {"message","当前未处于已确认的标定会话。"},{"frameSequence",0},{"frameSource",nullptr}, + {"progress",nullptr},{"temperatures",{{"scanner",nullptr},{"tracker",nullptr}}},{"frame",nullptr}}; + if(!active){if(!includeFrame)out.erase("frame");return out;} + out.update(calibrationTelemetry.snapshot()); + if(!calibrationViewError.empty()){ + out["state"]=calibrationViewError;out["message"]=calibrationViewMessage; + }else{ + auto captured=calibrationCapture.snapshot(); + const auto rawSource=captured.value("frameSource",Json(nullptr)); + bool same=rawSource.is_object()&&rawSource.value("sessionId",sessionId)==sessionId; + if(same){ + const auto sourcePid=rawSource.value("processId",rawSource.value("pid",0u)); + const auto sourceStarted=rawSource.value("startedFileTime",rawSource.value("startedAt",std::string())); + const auto sourcePath=rawSource.value("executable",rawSource.value("path",std::string())); + same=serviceOwnerIdentity.is_object()&&sourcePid==serviceOwnerIdentity.value("processId",0u) + &&sourceStarted==serviceOwnerIdentity.value("startedFileTime",std::string()) + &&same_path(fs::weakly_canonical(fs::u8path(sourcePath)),fs::weakly_canonical(fs::u8path(serviceOwnerIdentity.value("executable",std::string())))) + &&serviceOwner&&WaitForSingleObject(serviceOwner.get(),0)==WAIT_TIMEOUT; + const auto window=rawSource.find("windowHandle"); + if(same&&window!=rawSource.end()&&window->is_string()&&!window->get().empty())out["frameSource"]={{"pid",sourcePid},{"startedAt",sourceStarted},{"path",sourcePath},{"windowHandle",*window}}; + } + out["state"]=captured.value("state",captured.value("status",std::string("frame_pending"))); + out["message"]=captured.value("message",std::string("等待厂家标定窗口的新画面。")); + if(same&&captured.value("available",false)&&captured.contains("frame")&&captured["frame"].is_object()){ + auto frame=frame_from_json(captured["frame"]); + const auto age=unix_ms()-frame.capturedMs; + if(age>=0&&age<=2000){out["frame"]=captured["frame"];out["available"]=true;out["state"]="ready";out["message"]="";out["frameSequence"]=frame.sequence;} + else{out["state"]="frame_stale";out["message"]="厂家标定窗口画面已超过2秒未更新。";} + }else if(!same&&rawSource.is_object()){ + out["state"]="window_identity_changed";out["message"]="厂家窗口与本次SDK会话进程身份不一致,停止显示。"; + } + } + if(!includeFrame)out.erase("frame");return out; + } + Json calibration(const std::string &action, const Json &body) { + ready(); + { + std::lock_guard guard(state); + if (scanning) + throw ApiError(409, "scan_active", "Pause acquisition before calibration."); + if (projectReady) + throw ApiError(409, "project_open", + "End the scan project session before entering calibration."); + if (action != "calibrationEnter" && !calibrationActive) + throw ApiError(409, "calibration_required", "Enter calibration first."); + if (action == "calibrationStartSystem" && calibrationSystemStarted) + throw ApiError(409, "calibration_already_started", "System calibration is already started; finish it or recover the session first."); + // Enter may itself time out after the vendor created calibration + // state. Keep this safety latch until the entire SDK is released. + if (action == "calibrationEnter") + calibrationSession = true; + } + if(action=="calibrationEnter"){ + calibrationCapture.stop();std::lock_guard guard(state); + calibrationId.clear();calibrationTelemetry.progress=nullptr; + } + int nextMode, nextTrak; + { + std::lock_guard guard(state); + nextMode = calibrationMode; + nextTrak = trakType; + } + if (action == "calibrationSetMode" || action == "calibrationApplyLast") + nextMode = body.at("mode").get(); + if (action == "calibrationSetTrakType") + nextTrak = body.at("trakType").get(); + Json computeReply = nullptr; + if (!simulated) { + if (action == "calibrationEnter") + service_command("Sn3DEnterCalibrationPage", "enterCalibrationPageFinish"); + else if (action == "calibrationSetMode") + int_command("Sn3DSetCalibrationMode", "setCalibrationModeFinish", nextMode); + else if (action == "calibrationSetTrakType") + int_command("Sn3DSetTrakCalibrationType", "setTrakCalibrationTypeFinish", nextTrak); + else if (action == "calibrationStart") + service_command("Sn3DStartCalibration", "startCalibrationFinish", 300000); + else if (action == "calibrationStartSystem") + service_command("Sn3DStartSystemCalibration", "startSystemCalibrationFinish", 300000); + else if (action == "calibrationSetFree") + bool_command("Sn3DSetFreeCalibrationMode", "setFreeCalibrationModeFinish", + body.at("enabled").get()); + else if (action == "calibrationCapturePose") + service_command("Sn3DFreeCalibrationCapturePose", "freeCalibrationCapturePoseFinish", 300000); + else if (action == "calibrationCompute") + computeReply = service_command("Sn3DFreeCalibrationCompute", "freeCalibrationComputeFinish", 300000); + else if (action == "calibrationSetAdvanced") + bool_command("Sn3DSetAdvancedCalibrationMode", "setAdvancedCalibrationModeFinish", + body.at("enabled").get()); + else if (action == "calibrationApplyLast") + int_command("Sn3DApplyLastCalibration", "applyLastCalibrationFinish", nextMode); + else + throw ApiError(404, "unknown_action", "Unknown calibration action."); + } else if (action == "calibrationStartSystem" && + fs::is_regular_file(root / L"OFFLINE_TEST_CALIBRATION_START_HANG")) { + // Explicit offline simulation only: no vendor DLL/device is used. + std::this_thread::sleep_for(std::chrono::seconds(60)); + } else if (action == "calibrationStartSystem" && + fs::is_regular_file(root / L"OFFLINE_TEST_CALIBRATION_START_TIMEOUT")) { + flag_timeout("OFFLINE_TEST_FIXTURE: system calibration completion timed out."); + throw ApiError(504, "sdk_timeout", "OFFLINE_TEST_FIXTURE: system calibration completion timed out."); + } else if (action == "calibrationCompute" && + fs::is_regular_file(root / L"OFFLINE_TEST_CALIBRATION_COMPUTE_REPLY")) { + // Explicit offline mock only. Feed the fixture through the same + // pending-ACK/message path as actual SDK calculation callbacks. + auto pendingReply = expect("freeCalibrationComputeFinish"); + try { + auto reply = read_json(root / L"OFFLINE_TEST_CALIBRATION_COMPUTE_REPLY").dump(); + on_message(reply.data(), reply.size()); + computeReply = wait(pendingReply, 1000, "Sn3DFreeCalibrationCompute"); + forget(pendingReply); + } catch (...) { + forget(pendingReply); + throw; + } + } + { + std::lock_guard guard(state); + calibrationMode = nextMode; + trakType = nextTrak; + calibrationAction = action.substr(11); + if (!calibrationAction.empty()) + calibrationAction[0] = + static_cast(std::tolower(static_cast(calibrationAction[0]))); + calibrationActive = true; + if (action == "calibrationStartSystem") + calibrationSystemStarted = true; + if (action == "calibrationSetFree") + calibrationFreeEnabled = body.at("enabled").get(); + } + if(action=="calibrationEnter")begin_calibration_view(); + Json result{{"action", action}, {"calibrationActive", true}, {"status", "confirmed"}}; + if(action=="calibrationEnter")result["calibrationView"]=calibration_view(false); + if (action == "calibrationSetMode" || action == "calibrationApplyLast") { + result["mode"] = nextMode; + result["modeName"] = calibration_mode_name(nextMode); + } + if (action == "calibrationCompute" && computeReply.is_object()) + result["sdkResult"] = std::move(computeReply); + return result; + } + void on_scene() { + ++sceneNotifications; + lastSceneNotificationMs = unix_ms(); + std::shared_ptr request; + { + std::lock_guard guard(sceneGate); + request = sceneRequest; + if (!request || request->finished || request->running || retiring || disposed) + return; + ++request->notifications; + request->running = true; + sceneRunning = true; + } + bool succeeded = false; + std::string error, last; + try { + int result = capture(module, request->maximum, request->mask); + if (!result) { + if (request->pauseAcquisition && (request->mask & 4)) { + const auto scene = scene_summary(); + succeeded = + detail::accepts_scene_snapshot(true, request->mask, scene.value("datatype", 0U), + scene.value("meshSource", std::string()) == "whole" && + scene.value("meshPointCount", 0) > 0); + if (!succeeded) + last = "An incremental scene arrived; waiting for the whole mesh produced by Pause."; + } else + succeeded = true; + } else { + const char *detail = bridgeError ? bridgeError() : nullptr; + last = detail ? detail : "Bridge did not return error detail."; + if (result != 1001) + error = last; + } + } catch (const std::exception &e) { + error = e.what(); + } catch (...) { + error = "Native bridge capture failed."; + } + { + std::lock_guard guard(sceneGate); + sceneRunning = false; + request->running = false; + request->lastError = last; + if (!succeeded && error.empty()) { + if (last.find("incremental scene") != std::string::npos) + ++request->incrementalNotifications; + else + ++request->emptyNotifications; + } + if (succeeded || !error.empty()) { + request->finished = true; + request->success = succeeded; + request->error = error; + } + } + sceneDone.notify_all(); + } + Json scene_summary() { + if (!summary) + return {{"available", false}, {"reason", bridgeReason}}; + std::vector buffer(8192); + for (int n = 0; n < 2; n++) { + int code = summary(buffer.data(), static_cast(buffer.size())); + if (!code) + return Json::parse(buffer.data()); + if (code < 0 && code >= -1048576) { + buffer.resize(static_cast(-code)); + continue; + } + throw ApiError(502, "scene_summary_error", "Native summary failed."); + } + throw ApiError(502, "scene_summary_error", "Native summary exceeds permitted size."); + } + Json snapshot(const Json &body) { + auto directory = artifact_directory("scene"); + int maximum = body.value("maxPoints", 100000); + const bool pauseAcquisition = body.value("pauseAcquisition", false); + auto included = body.value("include", Json::array({"points", "markers", "meshes"})); + if (simulated) { + if (pauseAcquisition) + pause(); + write_json(directory / L"manifest.json", + {{"simulated", true}, + {"fixture", "OFFLINE_TEST_FIXTURE"}, + {"available", false}, + {"reason", "Simulation contains no SDK geometry or identifiers."}, + {"pointIdsAvailable", false}, + {"maxPoints", maximum}}); + } else { + if (!raw_available()) + throw ApiError(503, "native_bridge_unavailable", + bridgeReason.empty() ? "Required raw scene SDK exports are unavailable." + : bridgeReason); + auto request = std::make_shared(); + request->maximum = maximum; + request->pauseAcquisition = pauseAcquisition; + for (const auto &item : included) { + auto name = item.get(); + request->mask |= name == "points" ? 1 : name == "markers" ? 2 : 4; + } + { + std::lock_guard guard(sceneGate); + if (sceneRequest || sceneRunning) + throw ApiError(409, "snapshot_busy", "Previous scene copy is still running."); + sceneRequest = request; + } + bool restore; + { + std::lock_guard guard(state); + restore = preview; + } + bool modeRequested = false; + std::exception_ptr error; + try { + detail::capture_scene_snapshot( + pauseAcquisition, + [&] { + auto f = function( + "Sn3DRegisterDataCallback"); + native("Sn3DRegisterDataCallback", [this, f] { return f(scene_callback, this); }); + modeRequested = true; + int_command("Sn3DSetRealtimeScanDataMode", "setRealtimeScanDataModeFinish", 0, 10000); + }, + [&] { + bool active; + { + std::lock_guard guard(state); + active = scanning; + } + if (active) { + log("Snapshot receiver ready; pausing acquisition for whole-scene data."); + pause(); + } else + log("Snapshot requested while acquisition is already paused; a new SDK scene " + "notification is still required."); + }, + [&] { + { + std::unique_lock guard(sceneGate); + if (!sceneDone.wait_for(guard, std::chrono::seconds(10), + [request] { return request->finished; })) { + request->finished = true; + if (request->running) { + guard.unlock(); + flag_timeout("Native scene capture has not returned."); + throw ApiError(504, "sdk_timeout", + "Raw scene native copy did not finish; restart required."); + } + sceneRequest.reset(); + const std::string diagnostic = + "sceneCallbacks=" + std::to_string(request->notifications) + + ", emptyCallbacks=" + std::to_string(request->emptyNotifications) + + ", incrementalCallbacks=" + + std::to_string(request->incrementalNotifications) + + ", totalSceneCallbacks=" + std::to_string(sceneNotifications.load()) + + ", lastSceneCallbackUnixMs=" + + std::to_string(lastSceneNotificationMs.load()) + ". "; + throw ApiError( + 503, "scene_data_unavailable", + "No actual requested SDK scene data arrived within ten seconds. " + + diagnostic + + (pauseAcquisition + ? "Continue acquisition in the current project, then request a " + "new snapshot with pauseAcquisition=true so Pause can publish " + "a whole scene. " + : "For a paused whole-scene snapshot, request " + "pauseAcquisition=true while acquisition is active. ") + + request->lastError); + } + if (!request->success) + throw ApiError(502, "scene_copy_failed", request->error); + } + }, + [&] { + auto self = shared_from_this(); + native( + "FSB_WriteSnapshot", + [self, directory] { + int result = self->writeSnapshot(directory.c_str()); + if (result) { + const char *detail = self->bridgeError(); + throw ApiError(502, "scene_write_failed", + detail ? detail : "Native snapshot write failed."); + } + return 0; + }, + 35000); + }); + } catch (...) { + error = std::current_exception(); + } + { + std::lock_guard guard(sceneGate); + request->finished = true; + if (!request->running && sceneRequest == request) + sceneRequest.reset(); + } + bool safe; + { + std::lock_guard guard(state); + safe = initialized && !restart; + } + if (restore && modeRequested && safe && !sceneRunning) { + try { + int_command("Sn3DSetRealtimeScanDataMode", "setRealtimeScanDataModeFinish", 1, 10000); + } catch (...) { + flag_timeout("Failed to restore preview mode after snapshot."); + error = std::make_exception_ptr( + ApiError(502, "preview_restore_failed", + "Preview mode restoration failed; restart the device service.")); + } + } + if (error) + std::rethrow_exception(error); + } + auto list = register_artifacts(directory); + std::lock_guard guard(state); + return {{"files", list}, + {"maxPoints", maximum}, + {"include", included}, + {"projectId", projectId}, + {"pauseAcquisition", pauseAcquisition}, + {"scanning", scanning}}; + } + Json metrics() { + std::lock_guard guard(frameGate); + return {{"maxFps", fps}, + {"maxWidth", maxWidth}, + {"jpegQuality", jpegQuality}, + {"offeredFrames", offered}, + {"encodedFrames", encoded}, + {"replacedFrames", replaced}, + {"throttledFrames", throttled}, + {"encodingFailures", encodeFailures}, + {"averageEncodeMs", encoded ? std::round(encodeTotal / encoded * 100) / 100 : 0.0}, + {"averageEncodedFps", + std::round(encoded / std::max(.001, (unix_ms() - windowStart) / 1000.0) * 100) / 100}, + {"latestEncodeMs", latest ? Json(latest->encodeMs) : Json(nullptr)}, + {"latestFrameBytes", latest ? latest->jpeg.size() : 0}, + {"latestSequence", latest ? latest->sequence : 0}, + {"frameAgeMs", + latest ? Json(std::max(0, unix_ms() - latest->capturedMs)) : Json(nullptr)}, + {"sourceWidth", latest ? latest->sourceWidth : 0}, + {"sourceHeight", latest ? latest->sourceHeight : 0}, + {"width", latest ? latest->width : 0}, + {"height", latest ? latest->height : 0}, + {"queueDepth", raw ? 1 : 0}, + {"encoderRunning", !encoderStop.load()}, + {"freshnessLimitMs", 2000}, + {"capturedTimeMeaning", "managed_frame_received_not_hardware_exposure"}, + {"captureDiagnostics", captureDiagnostics.snapshot(unix_ms())}, + {"bufferPool", framePool.snapshot()}, + {"simulated", simulated}}; + } + Json status_json() { + std::lock_guard guard(state); + std::lock_guard image(frameGate); + const bool active = initialized && !restart && !disposed && !retiring; + auto now = unix_ms(); + const bool hasAge = lastFrameMs > 0; + const auto age = hasAge ? std::max(0, now - lastFrameMs) : 0; + return { + {"serverTimeUtc", utc_now()}, + {"initialized", active}, + {"sessionId", active && !sessionId.empty() ? Json(sessionId) : Json(nullptr)}, + {"recoverySessionId", calibrationSession && !sessionId.empty() ? Json(sessionId) : Json(nullptr)}, + {"deviceOnline", active && onlineChecked && now - onlineChecked < 10000 ? online : Json(nullptr)}, + {"deviceStatusCheckedUtc", onlineChecked ? Json(utc_from_ms(onlineChecked)) : Json(nullptr)}, + {"battery", battery.snapshot(active && !uncertain, now)}, + {"deviceType", deviceType}, + {"state", restart ? "restart_required" + : uncertain ? "uncertain" + : busy.load() ? "busy" + : !active ? "disconnected" + : scanning ? "scanning" + : projectReady ? "ready" + : "connected"}, + {"busy", busy.load()}, + {"scanning", scanning}, + {"projectReady", projectReady}, + {"projectId", projectReady ? Json(projectId) : Json(nullptr)}, + {"scanMode", scanMode}, + {"scanType", scanType.empty() ? Json(nullptr) : Json(scanType)}, + {"scanDevice", scanDevice.empty() ? Json(nullptr) : Json(scanDevice)}, + {"frameworkImported", frameworkImported}, + {"frameworkFileCount", frameworkFileCount}, + {"frameworkOptimized", frameworkOptimized}, + {"frameworkHasAcquisition", frameworkCaptureStarted}, + {"projectHasAcquisition", acquisitionEverStarted}, + {"scanConfigurationSource", "last_confirmed_sdk_command_not_hardware_readback"}, + {"stateUncertain", uncertain}, + {"restartRequired", restart}, + {"previewEnabled", preview}, + {"frameAgeMs", hasAge ? Json(age) : Json(nullptr)}, + {"frameWidth", latest ? latest->sourceWidth : 0}, + {"frameHeight", latest ? latest->sourceHeight : 0}, + {"previewFresh", active && projectReady && preview && hasAge && age <= 2000 && !uncertain}, + {"stopBehavior", "pause_acquisition_keep_project_and_preview"}, + {"disconnectBehavior", "pause_acquisition_end_sdk_session_keep_disk_files_and_http"}, + {"meshState", meshState}, + {"calibrationActive", calibrationActive}, + {"calibrationSystemStarted", calibrationSystemStarted}, + {"calibrationFreeEnabled", calibrationFreeEnabled}, + {"sdkProcessIsolation", true}, + {"backend", "native_cpp"}, + {"simulated", simulated}}; + } + Json capabilities() { + Json appliedCopy, calibrationState; + // These are SDK enum definitions, not a hardware readback or a claim + // that every connected device supports each calibration workflow. + Json calibrationModes = Json::array(); + for (int mode = 0; mode < 4; ++mode) + calibrationModes.push_back({{"mode", mode}, {"modeName", calibration_mode_name(mode)}}); + bool active; + Json framework; + { + std::lock_guard guard(state); + active = initialized && !restart && !disposed; + appliedCopy = applied; + calibrationState = {{"lastConfirmedAction", calibrationAction}, + {"mode", calibrationMode}, + {"modeName", calibration_mode_name(calibrationMode)}, + {"trakType", trakType}, + {"source", "last_confirmed_command_not_hardware_progress"}}; + framework = {{"scanTypes", {"photogrammetry", "mesh", "markers"}}, + {"devices", {{"tracker", "UE Nova / SDK 0"}, {"scanner", "TE Nova / SDK 1"}}}, + {"photogrammetry", {{"mode", "trak"}, {"device", "tracker"}}}, + {"markers", {{"mode", "laser"}, {"device", "scanner"}}}, + {"import", {{"mode", "trak"}, {"scanType", "mesh"}, {"device", "scanner"}}}, + {"importAvailable", active && projectReady && !scanning && !uncertain && + !calibrationActive && meshState == "none" && + scanMode == "trak" && scanType == "mesh" && + scanDevice == "scanner"}, + {"scanTypeChangeAvailable", active && projectReady && !scanning && !uncertain && + !calibrationActive && meshState == "none"}, + {"deviceChangeAvailable", active && projectReady && !scanning && !uncertain && + !calibrationActive && meshState == "none" && + !acquisitionEverStarted && !frameworkImported}, + {"fileExtensions", {".p3", ".txt", ".asc"}}, + {"maximumFiles", 8}, + {"maximumFileBytes", 16 * 1024 * 1024}, + {"deviceChangeRequiresConfirmation", true}, + {"deviceChangeWithDataAllowed", false}, + {"importRequiresConfirmation", true}, + {"optimizeAvailable", active && projectReady && !scanning && !uncertain && + !calibrationActive && meshState == "none" && + scanMode == "trak" && scanType == "photogrammetry" && + scanDevice == "tracker" && frameworkCaptureStarted}, + {"p3ExportWithoutMeshAvailable", active && projectReady && !scanning && !uncertain && + !calibrationActive && scanMode == "trak" && + scanType == "photogrammetry" && scanDevice == "tracker" && + frameworkCaptureStarted && frameworkOptimized}, + {"startsAcquisitionAutomatically", false}, + {"stationRelocationCommandAvailable", false}}; + } + const bool available = !simulated && raw_available(); + Json sdk = {{"rawBridgeLoaded", capture != nullptr}, + {"rawSceneAvailable", available}, + {"rawSceneReason", bridgeReason.empty() ? Json(nullptr) : Json(bridgeReason)}, + {"snapshot", + {{"formats", {"points.ply", "mesh.ply", "markers.json", "manifest.json"}}, + {"maxPoints", 1000000}, + {"previewMayPause", true}, + {"requiresActualSceneCallback", true}, + {"pauseAcquisitionSupported", true}, + {"pauseAcquisitionDefault", false}, + {"pauseAcquisitionResumesAutomatically", false}, + {"sourceMode", "SDK mode 0: increase mesh"}, + {"dataAvailability", "Only datatypes actually returned by the SDK are exported; points " + "or markers are not guaranteed to exist."}}}, + {"parametersAcceptedWithoutCompletionCallback", {"strongLight", "scanFrameRate"}}, + {"unsupportedTrakParameters", + {"frameworkBrightness", "cloudShowMode", "scanAlignType", "workingDistance", + "workingRange", "meshType", "qualityType", "simplificationByCurvature", + "deleteNeighborhoodAreas", "cornerOptimization"}}, + {"exportFormats", formats_lower}}; + return {{"apiVersion", "1.3"}, + {"deviceFamily", "FreeScan Trak Nova / Trak"}, + {"routes", contracts::routes()}, + {"initialized", active}, + {"rawDataAvailable", available}, + {"rawDataReason", + simulated ? "SIMULATED SDK: no actual scanner geometry is available." + : available ? "Native scene bridge is loaded; actual device scene data is still required." + : bridgeReason.empty() ? "SDK scene exports are not loaded." + : bridgeReason}, + {"controls", + {{"connect", true}, + {"disconnect", true}, + {"reconnect", true}, + {"createProject", true}, + {"setScanType", true}, + {"startScan", true}, + {"stopScan", true}, + {"startPreview", true}, + {"stopPreview", true}}}, + {"features", + {{"parameters", true}, + {"frameworkImport", true}, + {"frameworkOptimize", true}, + {"mesh", true}, + {"meshConfirm", true}, + {"meshUndo", true}, + {"alignment", true}, + {"edit", true}, + {"clipPlane", true}, + {"export", true}, + {"calibration", true}}}, + {"framework", framework}, + {"sdkCapabilities", sdk}, + {"lastParameterCommands", active ? appliedCopy : Json(nullptr)}, + {"parameterStateSource", "SDK completion/acceptance cache in this worker; strongLight and " + "scanFrameRate have no completion callback; not hardware readback"}, + {"calibration", active ? calibrationState : Json(nullptr)}, + {"calibrationModes", calibrationModes}, + {"parameterFields", parameter_fields}, + {"unsupportedTrakParameters", unsupported}, + {"exportFormats", contracts::export_formats()}, + {"preview", metrics()}, + {"restrictions", + {"Pause acquisition before parameters/processing", "Confirm mesh before export", + "Enter calibration before creating a project", + "Editing and clipping require explicit confirmation", + "Unsupported device/mode capabilities fail explicitly", + "Capability declarations do not imply every hardware path was tested"}}, + {"sdkProcessIsolation", true}, + {"backend", "native_cpp"}, + {"simulated", simulated}}; + } + Json execute_action(const std::string &action, const Json &body) { + if (action == "reconnect") + throw ApiError(409, "worker_restart_required", + "Reconnect must replace the SDK worker process through the HTTP supervisor."); + { + std::lock_guard guard(state); + if (restart) + throw ApiError(409, "restart_required", + "Native SDK state requires restarting the device service."); + if (uncertain && action != "stopScan") + throw ApiError(409, "state_uncertain", "Previous operation is unconfirmed."); + } + if (action == "connect") { + bool already; + int type; + { + std::lock_guard guard(state); + already = initialized; + type = body.value("deviceType", deviceType); + } + connect(type); + return {{"alreadyConnected", already}, {"status", status_json()}}; + } + if (action == "disconnect") { + verify_end(body); + std::string previous; + bool had; + { + std::lock_guard guard(state); + previous = projectId; + had = projectReady; + } + bool already = disconnect_inner(); + return {{"disconnected", true}, + {"reconnected", false}, + {"alreadyDisconnected", already}, + {"acquisitionStopped", true}, + {"previousProjectId", had ? Json(previous) : Json(nullptr)}, + {"projectSessionClosed", had}, + {"projectFilesPreserved", true}, + {"downloadsPreserved", true}, + {"httpServiceRunning", true}, + {"projectRestored", false}, + {"sessionId", nullptr}, + {"status", status_json()}}; + } + if (action == "createProject") + return create_project(body); + if (action == "setScanType") + return set_scan_type(body); + if (action == "importFramework") + return import_framework(body); + if (action == "optimizeFramework") + return optimize_framework(); + if (action == "startPreview" || action == "stopPreview") { + require_project(false); + const bool enabled = action == "startPreview"; + bool already; + { + std::lock_guard guard(state); + already = preview == enabled; + } + if (enabled) + start_preview(); + else + stop_preview(); + std::lock_guard guard(state); + return {{"previewEnabled", preview}, + {"alreadyInRequestedState", already}, + {"scanning", scanning}, + {"projectPreserved", true}}; + } + if (action == "startScan") { + require_project(false); + bool already; + { + std::lock_guard guard(state); + if (calibrationActive || meshState != "none") + throw ApiError(409, "processing_active", + "Undo mesh or complete calibration before acquisition."); + if (scanType.empty() || scanDevice.empty()) + throw ApiError(409, "scan_type_required", + "Select and confirm the acquisition type/device before scanning."); + already = scanning; + } + if (!already) { + poll_online(); + { + std::lock_guard guard(state); + if (online.is_boolean() && !online.get()) + throw ApiError(502, "sdk_error", + "Scanner is offline; check power, driver and manufacturer readiness."); + } + if (!simulated) + service_command("Sn3DStartScan", "startScanFinish", 30000, true); + std::lock_guard guard(state); + scanning = true; + acquisitionEverStarted = true; + if (scanType == "photogrammetry") { + frameworkCaptureStarted = true; + frameworkOptimized = false; + } + } + std::lock_guard guard(state); + return {{"scanning", scanning}, {"alreadyScanning", already}, {"projectId", projectId}}; + } + if (action == "stopScan") { + ready(); + { + std::lock_guard guard(state); + if (!projectReady && !uncertain) + throw ApiError(409, "project_required", "Create a project first."); + } + pause(); + std::lock_guard guard(state); + return {{"scanning", false}, + {"acquisitionStopped", true}, + {"projectPreserved", true}, + {"previewEnabled", preview}, + {"sdkOperation", "Sn3DPauseScan"}}; + } + if (action.rfind("calibration", 0) == 0) + return calibration(action, body); + require_project(action != "dataSnapshot"); + if (action == "parameters") + return parameters(body); + if (action == "mesh") { + mesh(body); + return {{"meshState", "preview"}, {"next", "POST /api/v1/mesh/confirm or /mesh/undo"}}; + } + if (action == "meshConfirm") { + { + std::lock_guard guard(state); + if (meshState != "preview") + throw ApiError(409, "mesh_required", "Complete mesh processing before confirmation."); + } + if (!simulated) + service_command("Sn3DConfirmMesh", "confirmMeshFinish"); + { + std::lock_guard guard(state); + meshState = "confirmed"; + } + return {{"meshState", "confirmed"}}; + } + if (action == "meshUndo") { + { + std::lock_guard guard(state); + if (meshState == "none") + throw ApiError(409, "mesh_required", "There is no mesh result to undo."); + } + if (!simulated) + service_command("Sn3DUndoMesh", "undoMeshFinish"); + { + std::lock_guard guard(state); + meshState = "none"; + } + return {{"meshState", "none"}}; + } + if (action == "export") { + bool frameworkExport; + { + std::lock_guard guard(state); + frameworkExport = body.at("formats") == Json({"P3"}) && scanMode == "trak" && + scanType == "photogrammetry" && scanDevice == "tracker" && + frameworkCaptureStarted && frameworkOptimized; + if (!frameworkExport && meshState != "confirmed") + throw ApiError(409, "mesh_confirmation_required", + "Confirm the mesh before model export. A P3-only framework export " + "instead requires captured, paused and optimized photogrammetry data."); + } + return export_data(body, frameworkExport); + } + if (action == "dataSnapshot") + return snapshot(body); + if (action == "align" || action == "edit" || action == "clipPlane") { + { + std::lock_guard guard(state); + if (meshState != "none") + throw ApiError(409, "undo_mesh_first", "Undo the mesh before changing source geometry."); + } + if (action == "align") + return align(body); + if (action == "edit") + return edit(body); + return clip(body); + } + throw ApiError(404, "unknown_action", "Unknown device action."); + } + void stop_threads() { + calibrationCapture.stop(); + pollStop = true; + encoderStop = true; + encodeWake.notify_all(); + if (poller.joinable() && poller.get_id() != std::this_thread::get_id()) + poller.join(); + if (encoder.joinable() && encoder.get_id() != std::this_thread::get_id()) + encoder.join(); + if (gdiplusToken) { + Gdiplus::GdiplusShutdown(gdiplusToken); + gdiplusToken = 0; + } + } + void shutdown_all() { + std::unique_lock op(operation, std::try_to_lock); + if (!op.owns_lock() || nativeRunning || sceneRunning) + throw ApiError(409, "device_busy", "Cannot close while a native operation is running."); + busy = true; + struct Reset { + std::atomic &value; + ~Reset() { + value = false; + } + } reset{busy}; + if (simulated && calibrationSession && + fs::is_regular_file(root / L"OFFLINE_TEST_RECOVERY_CLOSE_FAIL_ONCE")) { + fs::rename(root / L"OFFLINE_TEST_RECOVERY_CLOSE_FAIL_ONCE", + root / L"OFFLINE_TEST_RECOVERY_CLOSE_FAIL_CONSUMED"); + throw ApiError(504, "release_unconfirmed", "OFFLINE_TEST_FIXTURE: calibration release failed once."); + } + if (simulated && restart && fs::is_regular_file(root / L"OFFLINE_TEST_FAILED_INITIALIZE_CONSUMED")) + throw ApiError(504, "release_unconfirmed", "OFFLINE_TEST_FIXTURE: cleanup cannot finish."); + if (disposed && serviceOwner && WaitForSingleObject(serviceOwner.get(), 0) != WAIT_OBJECT_0) + throw ApiError(409, "release_unconfirmed", + "Previous SDK release is unconfirmed and its manufacturer service is still " + "running; no second release or replacement owner was started."); + if (!disposed) + disconnect_inner(true); + retiring = true; + disposed = true; + stop_threads(); + } +}; + +WorkerService::WorkerService(fs::path dataRoot, Json config, bool simulate) + : impl_(std::make_shared(std::move(dataRoot), std::move(config), simulate)) { + impl_->start_threads(); +} +WorkerService::~WorkerService() { + if (!impl_) + return; + try { + impl_->shutdown_all(); + } catch (const std::exception &e) { + impl_->log(std::string("Worker destructor left SDK retired without overlapping release: ") + + e.what()); + impl_->retiring = true; + impl_->disposed = true; + impl_->stop_threads(); + } +} +Json WorkerService::status() { + return impl_->status_json(); +} +Json WorkerService::recovery_info() { + std::lock_guard lock(impl_->state); + return {{"sessionId", impl_->sessionId}, {"calibrationSession", impl_->calibrationSession}, + {"initializationAttempted", impl_->attempted}, + {"initialized", impl_->initialized}, + {"ownerTrustedForForce", impl_->ownerTrustedForForce}, + {"projectReady", impl_->projectReady}, {"scanning", impl_->scanning}, + {"calibrationActive", impl_->calibrationActive}, {"busy", impl_->busy.load() || impl_->nativeRunning.load()}, + {"restartRequired", impl_->restart}, {"deviceType", impl_->deviceType}, + {"simulated", impl_->simulated}, {"owner", impl_->serviceOwnerIdentity}}; +} +Json WorkerService::execute(const std::string &action, const Json &body) { + contracts::validate(action, body); + std::unique_lock lock(impl_->operation, std::try_to_lock); + if (!lock.owns_lock()) + throw ApiError(409, "device_busy", "The SDK worker is processing another operation."); + impl_->busy = true; + struct Reset { + std::atomic &value; + ~Reset() { + value = false; + } + } reset{impl_->busy}; + if (impl_->simulated) + std::this_thread::sleep_for(std::chrono::milliseconds(action == "mesh" ? 200 : 60)); + try { + auto result = impl_->execute_action(action, body); + if (impl_->simulated && result.is_object()) + result["simulated"] = true; + return result; + } catch (const ApiError &error) { + impl_->log(action + ": " + error.what()); + throw; + } catch (const Json::exception &error) { + throw ApiError(400, "invalid_parameter", error.what()); + } catch (const std::exception &error) { + impl_->log(action + ": " + error.what()); + throw ApiError(502, "sdk_error", error.what()); + } +} +Json WorkerService::query(const std::string &action, const Json &arguments) { + if (action == "file") { + std::lock_guard lock(impl_->state); + const auto id = arguments.value("fileId", std::string()); + for (const auto &file : impl_->registered) + if (file.at("fileId") == id) + return file; + throw ApiError(404, "file_not_found", "File is not registered in this worker."); + } + std::unique_lock lock(impl_->operation, std::try_to_lock); + if (!lock.owns_lock()) + throw ApiError(409, "device_busy", "The SDK worker is processing another operation."); + if (action == "capabilities") + return impl_->capabilities(); + if (action == "sceneInfo") { + impl_->require_project(false); + if (impl_->simulated) + return {{"available", false}, + {"simulated", true}, + {"reason", "Simulation has no SDK geometry or identifiers."}, + {"pointIdsAvailable", false}}; + return impl_->scene_summary(); + } + if (action == "previewMetrics") + return impl_->metrics(); + throw ApiError(404, "unknown_query", "Unknown SDK worker query."); +} +Json WorkerService::files() { + std::lock_guard lock(impl_->state); + return impl_->registered; +} +Json WorkerService::calibration_view(bool includeFrame) {return impl_->calibration_view(includeFrame);} +Json WorkerService::frame() { + std::shared_ptr latest; + { + std::lock_guard lock(impl_->frameGate); + latest = impl_->latest; + } + if (!latest) + return Json(nullptr); + Json out = frame_to_json(*latest); + out["encoderMetrics"] = impl_->metrics(); + return out; +} +bool WorkerService::can_close(bool shutdown) { + std::unique_lock op(impl_->operation, std::try_to_lock); + if (!op.owns_lock() || impl_->busy || impl_->nativeRunning || impl_->sceneRunning) + return false; + std::lock_guard lock(impl_->state); + return shutdown || (!impl_->initialized && !impl_->service); +} +void WorkerService::shutdown() { + impl_->shutdown_all(); +} +} // namespace freescan diff --git a/integrations/freescan-service/src/sdk_worker.hpp b/integrations/freescan-service/src/sdk_worker.hpp new file mode 100644 index 0000000..9ea9e49 --- /dev/null +++ b/integrations/freescan-service/src/sdk_worker.hpp @@ -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_; + + 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 diff --git a/integrations/freescan-service/src/supervisor.cpp b/integrations/freescan-service/src/supervisor.cpp new file mode 100644 index 0000000..4989276 --- /dev/null +++ b/integrations/freescan-service/src/supervisor.cpp @@ -0,0 +1,1365 @@ +#include "supervisor.hpp" +#include "sdk_worker.hpp" +#include "contracts.hpp" +#include "device_battery.hpp" +#include "auto_connection.hpp" +#include "sdk_location.hpp" +#include "calibration_files.hpp" +#include "calibration_recovery.hpp" +#include +#include +#include + +namespace freescan { +namespace { +uint64_t process_started(HANDLE handle) { + FILETIME start{}, end{}, kernel{}, user{}; + if (!GetProcessTimes(handle, &start, &end, &kernel, &user)) + throw ApiError(503, "process_identity_error", "无法核验进程启动时间。"); + ULARGE_INTEGER ticks{}; + ticks.LowPart = start.dwLowDateTime; + ticks.HighPart = start.dwHighDateTime; + return ticks.QuadPart; +} +fs::path executable() { + std::vector value(32768); + DWORD size = GetModuleFileNameW(nullptr, value.data(), static_cast(value.size())); + if (!size || size >= value.size()) + throw ApiError(500, "executable_path_error", "无法确定程序路径。"); + return fs::path(std::wstring(value.data(), size)); +} +std::wstring quoted(const std::wstring &value) { + if (value.find(L'"') != std::wstring::npos) + throw ApiError(500, "invalid_path", "启动路径不能含双引号。"); + return L"\"" + value + L"\""; +} +bool exited(HANDLE process) { + return process && WaitForSingleObject(process, 0) == WAIT_OBJECT_0; +} +void verify_process_identity(HANDLE handle, DWORD pid, uint64_t started, const fs::path &expected) { + wchar_t image[32768]{}; + DWORD length = 32768; + if (!handle || !pid || pid == GetCurrentProcessId() || GetProcessId(handle) != pid || + process_started(handle) != started || + !QueryFullProcessImageNameW(handle, 0, image, &length) || + _wcsicmp(fs::absolute(expected).lexically_normal().c_str(), + fs::absolute(fs::path(std::wstring(image, length))).lexically_normal().c_str()) != 0) + throw ApiError(503, "recovery_identity_unverified", "旧进程身份无法核验,未启动第二个SDK后台。"); +} +Handle duplicate_process(HANDLE process) { + HANDLE pinned = nullptr; + if (!DuplicateHandle(GetCurrentProcess(), process, GetCurrentProcess(), &pinned, + 0, FALSE, DUPLICATE_SAME_ACCESS)) + throw ApiError(503, "recovery_identity_unverified", "无法保留已核验的进程句柄。"); + return Handle(pinned); +} +void integer_setting(const Json &value, const char *key, int fallback, int low, int high) { + auto found = value.find(key); + if (found == value.end()) + return; + if (!found->is_number_integer() || found->get() < low || found->get() > high) + throw ApiError(503, "invalid_configuration", + std::string(key) + " 配置超出范围,默认值为 " + std::to_string(fallback) + "。"); +} +} // namespace +Json load_configuration(const fs::path &root) { + fs::path path = root / L"api-settings.json"; + if (!fs::exists(path)) { + Json value{{"enabled", true}, + {"prefix", "http://127.0.0.1:18888/"}, + {"apiKey", new_id() + new_id()}, + {"previewFps", 20}, + {"previewMaxWidth", 1280}, + {"previewJpegQuality", 75}, {"autoConnect", true}, {"autoConnectRetrySeconds", 15}}; + write_json(path, value); + } + Json value = read_json(path); + if (!value.is_object()) + throw ApiError(503, "invalid_configuration", "配置必须是 JSON 对象。"); + std::set fields{"enabled", "prefix", "apiKey", + "previewFps", "previewMaxWidth", "previewJpegQuality", + "sdkPath", "bridgePath", "autoConnect", "autoConnectRetrySeconds"}; + for (auto it = value.begin(); it != value.end(); ++it) + if (!fields.count(it.key())) + throw ApiError(503, "invalid_configuration", "未知配置项:" + it.key()); + if (value.contains("enabled") && !value["enabled"].is_boolean()) + throw ApiError(503, "invalid_configuration", "enabled 必须是布尔值。"); + if (value.contains("autoConnect") && !value["autoConnect"].is_boolean()) + throw ApiError(503, "invalid_configuration", "autoConnect 必须是布尔值。"); + if (!value.contains("apiKey") || !value["apiKey"].is_string()) + throw ApiError(503, "invalid_configuration", "必须配置 API 密钥。"); + auto key = value["apiKey"].get(); + if (key.size() < 32 || + std::any_of(key.begin(), key.end(), [](unsigned char c) { return c < 33 || c > 126; })) + throw ApiError(503, "invalid_configuration", "API 密钥至少32位可见ASCII字符。"); + if (!value.contains("prefix") || !value["prefix"].is_string()) + throw ApiError(503, "invalid_configuration", "必须配置 HTTP 根地址。"); + integer_setting(value, "previewFps", 20, 1, 30); + integer_setting(value, "previewMaxWidth", 1280, 320, 3840); + integer_setting(value, "previewJpegQuality", 75, 30, 95); + integer_setting(value, "autoConnectRetrySeconds", 15, 5, 300); + for (auto name : {"sdkPath", "bridgePath"}) + if (value.contains(name) && !value[name].is_string()) + throw ApiError(503, "invalid_configuration", std::string(name) + " 必须是字符串。"); + value["previewFps"] = value.value("previewFps", 20); + value["previewMaxWidth"] = value.value("previewMaxWidth", 1280); + value["previewJpegQuality"] = value.value("previewJpegQuality", 75); + value["autoConnect"] = value.value("autoConnect", true); + value["autoConnectRetrySeconds"] = value.value("autoConnectRetrySeconds", 15); + return value; +} +struct Supervisor::Impl : std::enable_shared_from_this { + fs::path root, logFile; + Json config; + bool simulated; + detail::AutoConnectionPolicy autoConnection; + std::atomic autoStop{false}; + std::mutex autoWaitGate; + std::condition_variable autoWake; + std::atomic stopping{false}, rotating{false}, busy{false}, fault{false}, suspendFrames{false}; + std::atomic recoveryActive{false}; + std::atomic commandGeneration{0}; + std::string activeAction, recoveringSession; + struct RecoveryContext { + std::shared_ptr owner; + Handle worker, manufacturer; + Json info; + std::string originalSession; + bool connectionAttempted = true; + bool replacement = false; + }; + std::shared_ptr recoveryContext; + std::mutex commandGate, workerGate, frameGate, fileGate; + std::shared_ptr client; + Handle process; + DWORD pid = 0; + uint64_t started = 0, epoch = 0, sequence = 0, lastOffered = 0, encoded = 0; + int deviceType = 3; + int64_t metricStart = unix_ms(); + double encodeTotal = 0; + std::shared_ptr latest; + Json encoderMetrics; + Json calibrationMetadata=nullptr; + std::shared_ptr calibrationLatest; + std::shared_ptr calibrationOwner; + uint64_t calibrationEpoch=0,calibrationSequence=0; + int64_t calibrationReceived=0; + std::string calibrationNativeKey; + std::map downloads; + std::thread frameThread, autoThread; + Impl(fs::path path, Json cfg, bool mock) + : root(std::move(path)), config(std::move(cfg)), simulated(mock), + autoConnection(config.value("autoConnect", true), config.value("autoConnectRetrySeconds", 15)) { + fs::create_directories(root / L"Logs"); + logFile = root / L"Logs" / wide("native_supervisor_" + new_id() + ".log"); + } + void log(const std::string &line) { + log_line(logFile, line); + std::cout << utc_now() << " " << line << std::endl; + } + std::shared_ptr current() { + std::lock_guard hold(workerGate); + return client; + } + uint64_t currentEpoch() { + std::lock_guard hold(workerGate); + return epoch; + } + Json recovery_session() { + std::lock_guard hold(workerGate); + return recoveringSession.empty() ? Json(nullptr) : Json(recoveringSession); + } + void clearFrame() { + std::lock_guard hold(frameGate); + latest.reset(); + encoderMetrics = nullptr; + encoded = 0; + encodeTotal = 0; + metricStart = unix_ms(); + } + void advance() { + std::lock_guard hold(workerGate); + ++epoch; + } + Json empty() { + Json value{{"serverTimeUtc", utc_now()}, + {"initialized", false}, + {"sessionId", nullptr}, + {"deviceOnline", nullptr}, + {"deviceStatusCheckedUtc", nullptr}, + {"battery", detail::DeviceBatteryCache{}.snapshot(false, unix_ms())}, + {"deviceType", deviceType}, + {"state", recoveryActive ? "recovering" + : fault ? "restart_required" + : busy || rotating ? "busy" + : "disconnected"}, + {"busy", busy || rotating || recoveryActive}, + {"scanning", false}, + {"projectReady", false}, + {"stateUncertain", fault.load()}, + {"restartRequired", fault.load()}, + {"projectId", nullptr}, + {"scanMode", "trak"}, + {"previewEnabled", false}, + {"frameAgeMs", nullptr}, + {"frameWidth", 0}, + {"frameHeight", 0}, + {"previewFresh", false}, + {"stopBehavior", "pause_acquisition_keep_project_and_preview"}, + {"disconnectBehavior", "pause_acquisition_end_sdk_session_keep_disk_files_and_http"}, + {"meshState", "none"}, + {"calibrationActive", false}, + {"recoveryActive", recoveryActive.load()}, + {"recoverySessionId", recovery_session()}, + {"sdkProcessIsolation", true}, + {"implementation", "C++17"}, + {"autoConnection", autoConnection.snapshot()}, + {"simulated", simulated}}; + add_calibration_file_times(value); + return value; + } + void add_calibration_file_times(Json &value) { + try { + // Resolve afresh so a previously missing SDK or updated settings + // cannot leave this read-only metadata query stuck on a stale path. + const auto directory = simulated ? fs::path{} : + detail::locate_sdk_installation(root, executable().parent_path(), config) + .serviceDirectory / L"res" / L"FreeScanTrak"; + value.update(detail::snapshot_calibration_files(directory)); + } catch (const std::exception &) { + // Preserve a usable status response even if one filesystem query fails. + value.update(detail::snapshot_calibration_files({})); + } + } + Json status() { + auto currentClient = current(); + if (!currentClient) + return empty(); + Json value; + try { + value = currentClient->call("status", Json::object(), 4400); + } catch (const std::exception &) { + if (currentClient != current() || rotating) + return empty(); + bool dead = false; + { + std::lock_guard hold(workerGate); + dead = process && exited(process.get()); + } + if (dead) { + fault = true; + clearFrame(); + return empty(); + } + throw ApiError(503, "status_unavailable", "设备后台暂未返回状态,请稍后查询。"); + } + if (currentClient != current()) + return empty(); + if (!value.is_object()) + throw ApiError(502, "worker_protocol_error", "后台状态不是对象。"); + value["sdkProcessIsolation"] = true; + value["implementation"] = "C++17"; + value["simulated"] = simulated; + value["autoConnection"] = autoConnection.snapshot(); + value["recoveryActive"] = recoveryActive.load(); + const auto pendingRecovery = recovery_session(); + if (!pendingRecovery.is_null()) + value["recoverySessionId"] = pendingRecovery; + if (busy || rotating) { + value["busy"] = true; + if (!value.value("restartRequired", false)) + value["state"] = "busy"; + } + if (fault) { + value["battery"] = detail::DeviceBatteryCache{}.snapshot(false, unix_ms()); + value["stateUncertain"] = true; + value["restartRequired"] = true; + value["state"] = "restart_required"; + value["previewFresh"] = false; + } + add_calibration_file_times(value); + if (recoveryActive) { + value["busy"] = true; + value["state"] = "recovering"; + value["previewFresh"] = false; + std::lock_guard hold(workerGate); + if (!recoveringSession.empty()) + value["recoverySessionId"] = recoveringSession; + } + return value; + } + void startWorker() { + { + std::lock_guard hold(workerGate); + if (process && !exited(process.get())) + throw ApiError(409, "worker_still_running", "旧后台尚未退出,不能启动第二个 SDK 会话。"); + } + std::wstring name = wide("FreeScanCpp_" + new_id()); + auto path = executable(); + std::wstring args = quoted(path.wstring()) + L" --worker " + name + L" --data-root " + + quoted(root.wstring()) + L" --parent " + std::to_wstring(GetCurrentProcessId()) + + L" --parent-start " + std::to_wstring(process_started(GetCurrentProcess())); + if (simulated) + args += L" --mock"; + STARTUPINFOW startup{}; + startup.cb = sizeof(startup); + PROCESS_INFORMATION info{}; + if (!CreateProcessW(path.c_str(), args.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, + root.c_str(), &startup, &info)) + throw ApiError(503, "worker_start_failed", + "无法启动 C++ 设备后台,Windows=" + std::to_string(GetLastError())); + CloseHandle(info.hThread); + { + std::lock_guard hold(workerGate); + process.reset(info.hProcess); + pid = info.dwProcessId; + started = process_started(process.get()); + } + auto candidate = std::make_shared(name); + { + std::lock_guard hold(workerGate); + if (recoveryActive && recoveryContext) { + // A failed bootstrap is still our freshly created, unconnected + // child. Retain it for a confirmed retry instead of losing the + // only handle and getting stuck with an unpublished process. + client = candidate; + recoveryContext->owner = candidate; + recoveryContext->worker = duplicate_process(process.get()); + recoveryContext->manufacturer.reset(); + recoveryContext->connectionAttempted = false; + recoveryContext->replacement = true; + recoveryContext->info = {{"sessionId", ""}, {"calibrationSession", false}, + {"projectReady", false}, {"scanning", false}, {"busy", false}, + {"initializationAttempted", false}, {"initialized", false}, + {"ownerTrustedForForce", false}, {"simulated", simulated}, + {"owner", nullptr}, {"deviceType", deviceType}}; + ++epoch; + } + } + int64_t deadline = unix_ms() + 15000; + std::string error; + while (unix_ms() < deadline) { + if (exited(info.hProcess)) { + fault = true; + throw ApiError(503, "worker_start_failed", "新后台启动后已退出。"); + } + try { + candidate->call("status", Json::object(), 2000); + { + std::lock_guard hold(workerGate); + client = candidate; + ++epoch; + } + clearFrame(); + log("C++ 设备后台已就绪,PID " + std::to_string(info.dwProcessId) + ",尚未连接设备。"); + return; + } catch (const std::exception &ex) { + error = ex.what(); + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + fault = true; + throw ApiError(503, "worker_start_failed", "C++ 设备后台未就绪;未启动第二个后台。" + error); + } + void captureFiles(const std::shared_ptr &owner) { + Json values = owner->call("files", Json::object(), 5000); + if (!values.is_array()) + throw ApiError(502, "worker_protocol_error", "下载登记不是数组。"); + std::lock_guard hold(fileGate); + for (const auto &item : values) { + if (!item.is_object() || !item.contains("fileId") || !item["fileId"].is_string()) + throw ApiError(502, "worker_protocol_error", "下载登记无效。"); + std::string id = item["fileId"]; + if (id.size() != 32 || id.find_first_not_of("0123456789abcdef") != std::string::npos) + throw ApiError(502, "worker_protocol_error", "下载编号无效。"); + for (auto key : {"root", "path", "name", "contentType"}) + if (!item.contains(key) || !item[key].is_string()) + throw ApiError(502, "worker_protocol_error", "下载路径字段无效。"); + downloads[id] = item; + } + } + void closeWorker(bool shutdown) { + auto owner = current(); + HANDLE handle = nullptr; + DWORD oldPid = 0; + { + std::lock_guard hold(workerGate); + if (!process) + return; + handle = process.get(); + oldPid = pid; + } + if (!exited(handle) && owner) { + int64_t deadline = unix_ms() + 5000; + while (true) { + bool retry = false; + try { + owner->call("close", Json{{"shutdown", shutdown}}, 5000); + } catch (const ApiError &ex) { + retry = ex.code == "device_busy"; + if (!retry) + log("等待后台退出确认:" + std::string(ex.what())); + } catch (const std::exception &ex) { + log("等待后台退出确认:" + std::string(ex.what())); + } + if (!retry || exited(handle) || unix_ms() >= deadline) + break; + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + } + if (WaitForSingleObject(handle, 12000) != WAIT_OBJECT_0) { + fault = true; + throw ApiError(504, "worker_exit_timeout", + "旧设备后台未确认退出,已停止重连,请正常关闭并重启服务。"); + } + { + std::lock_guard hold(workerGate); + client.reset(); + process.reset(); + pid = 0; + started = 0; + ++epoch; + } + clearFrame(); + log("已核验 C++ 后台退出,PID " + std::to_string(oldPid)); + } + void forceIdleWorkerExit() { + // Only the child retained from CreateProcess is eligible. The command + // gate and sticky session latch exclude project/calibration operations. + if (!autoConnection.may_restart() || autoStop || stopping) + throw ApiError(409, "auto_restart_paused", "自动重启已暂停,未强制关闭SDK后台。"); + auto owner = current(); + HANDLE handle; + DWORD oldPid; + { + std::lock_guard hold(workerGate); + handle = process.get(); + oldPid = pid; + wchar_t image[32768]{}; + DWORD length = 32768; + if (!handle || !oldPid || oldPid == GetCurrentProcessId() || + GetProcessId(handle) != oldPid || process_started(handle) != started || + !QueryFullProcessImageNameW(handle, 0, image, &length) || + _wcsicmp(executable().c_str(), std::wstring(image, length).c_str()) != 0) + throw ApiError(503, "worker_identity_unverified", "SDK后台身份无法核验,未终止任何进程。"); + } + if (!exited(handle)) { + // A responsive worker must still confirm an empty session after + // graceful cleanup. An unresponsive live worker is left untouched. + const auto latestStatus = owner->call("status", Json::object(), 5000); + if (latestStatus.value("projectReady", true) || latestStatus.value("scanning", true) || + latestStatus.value("calibrationActive", true) || + !autoConnection.may_restart() || autoStop || stopping) + throw ApiError(409, "session_protected", "当前会话不能自动强制重启,保留原后台。"); + log("SDK正常退出超时;已核验无工程、未采集、非标定,仅结束本服务创建的SDK后台,PID " + + std::to_string(oldPid)); + if (!TerminateProcess(handle, 0xE0000001) && !exited(handle)) + throw ApiError(503, "worker_termination_failed", "无法结束已核验的SDK后台,未启动新后台。"); + } + // closeWorker checks the original process handle, not a reusable PID. + // It must confirm exit before any new SDK worker can be created. + closeWorker(true); + } + Json execute(const std::string &action, const Json &body, uint64_t expectedGeneration) { + contracts::validate(action, body); + if (recoveryActive) + throw ApiError(409, "calibration_recovery_active", "正在结束旧标定并恢复设备,请等待恢复任务完成。"); + std::unique_lock command(commandGate, std::try_to_lock); + if (!command.owns_lock()) + throw ApiError(409, "device_busy", "设备正在执行其他任务。"); + if (recoveryActive) + throw ApiError(409, "calibration_recovery_active", "正在结束旧标定并恢复设备,请等待恢复任务完成。"); + if (expectedGeneration != UINT64_MAX && expectedGeneration != commandGeneration.load()) + throw ApiError(409, "calibration_aborted", "该请求属于已结束的旧SDK会话,请刷新设备状态后重新提交。"); + if (action == "disconnect") + autoConnection.pause(); + if (stopping) + throw ApiError(503, "shutting_down", "设备服务正在关闭。"); + if (action == "connect" || action == "reconnect") { + autoConnection.resume(); + autoWake.notify_all(); + } + if (fault) + throw ApiError(409, "restart_required", "后台状态待确认,请正常重启设备服务。"); + // Even an unconfirmed create/enter command may have established a + // session. Never replace it automatically on the basis of empty/fault status. + if (action == "createProject" || action == "calibrationEnter") + autoConnection.protect(); + busy = true; + const auto generation = commandGeneration.load(); + { + std::lock_guard hold(workerGate); + activeAction = action; + } + bool reset = action == "createProject" || action == "setScanType" || action == "importFramework"; + if (reset) { + suspendFrames = true; + advance(); + clearFrame(); + } + auto finish = [&] { + if (generation != commandGeneration.load()) + return; // A retired command must not reset its replacement's flags. + if (reset) { + advance(); + clearFrame(); + suspendFrames = false; + } + rotating = false; + busy = false; + std::lock_guard hold(workerGate); + activeAction.clear(); + }; + auto stillCurrent = [&] { + if (generation != commandGeneration.load()) + throw ApiError(409, "calibration_aborted", "旧标定任务已被恢复操作中止,未在新会话中继续。"); + }; + try { + auto owner = current(); + if (!owner) + throw ApiError(503, "worker_unavailable", "设备后台尚未就绪。"); + Json result; + if (action == "disconnect" || action == "reconnect") { + Json before = owner->call("status", Json::object(), 5000); + deviceType = before.value("deviceType", 3); + Json releaseBody = body; + releaseBody.erase("deviceType"); + result = + owner->call("execute", Json{{"action", "disconnect"}, {"body", releaseBody}}, 120000); + captureFiles(owner); + rotating = true; + advance(); + clearFrame(); + closeWorker(false); + startWorker(); + autoConnection.protect(false); + if (action == "reconnect") { + deviceType = body.value("deviceType", deviceType); + auto connection = current()->call( + "execute", Json{{"action", "connect"}, {"body", Json{{"deviceType", deviceType}}}}, + 120000); + result["sessionId"] = connection.at("status").value("sessionId", Json()); + } + result["disconnected"] = action == "disconnect"; + result["reconnected"] = action == "reconnect"; + result["projectRestored"] = false; + result["downloadsPreserved"] = true; + result["httpServiceRunning"] = true; + result["status"] = status(); + log(action == "reconnect" ? "重连成功:新 C++ 后台已连接,未恢复工程或采集。" + : "断开成功:HTTP 服务继续运行。"); + } else { + int timeout = action == "parameters" ? 1500000 + : (action == "mesh" || action == "export" || action == "align" || + action.rfind("calibration", 0) == 0) + ? 360000 + : 150000; + result = owner->call("execute", Json{{"action", action}, {"body", body}}, timeout); + stillCurrent(); + if (action == "export" || action == "dataSnapshot") + captureFiles(owner); + if (action == "startPreview" || action == "stopPreview") { + advance(); + clearFrame(); + } + } + stillCurrent(); + if(action=="calibrationEnter")advance(); + finish(); + if(action=="calibrationEnter")seedCalibrationIdentity(owner,result); + return result; + } catch (const ApiError &ex) { + stillCurrent(); + if (rotating || ex.code == "worker_timeout" || ex.code == "worker_unavailable" || + ex.code == "worker_protocol_error") { + fault = true; + clearFrame(); + } + finish(); + throw; + } catch (...) { + stillCurrent(); + if (rotating) { + fault = true; + clearFrame(); + } + finish(); + throw; + } + } + Json recover(const Json &body) { + contracts::validate("calibrationRecover", body); + bool expectedInactive = false; + if (!recoveryActive.compare_exchange_strong(expectedInactive, true)) + throw ApiError(409, "calibration_recovery_active", "已有标定恢复任务,请等待完成。"); + struct ActiveReset { + std::atomic &active; + ~ActiveReset() { active = false; } + } activeReset{recoveryActive}; + if (stopping) + throw ApiError(503, "shutting_down", "HTTP服务正在关闭,不能恢复标定。"); + + auto expectedSession = body.at("expectedSessionId").get(); + for (auto &character : expectedSession) + if (character >= 'A' && character <= 'F') + character = static_cast(character - 'A' + 'a'); + const bool force = body.value("force", false); + auto owner = current(); + std::shared_ptr context; + bool detached = false; + { + std::lock_guard hold(workerGate); + if (fault && recoveryContext && recoveryContext->originalSession == expectedSession && + (recoveryContext->owner == owner || (!owner && !process && exited(recoveryContext->worker.get())))) { + context = recoveryContext; + if (!owner) { + owner = context->owner; + detached = true; + } + } + } + if (!owner) + throw ApiError(503, "worker_unavailable", "旧SDK后台不可用;未启动第二个会话。"); + // This RPC bypasses both worker operation gates and does no SDK work. + Json info; + try { info = owner->call("recoveryInfo", Json::object(), 5000); } + catch (const ApiError &error) { + // A previous release may have exited the worker before its owner. + // Retain the exact original process handles, never rediscover by PID. + if ((error.code != "worker_unavailable" && error.code != "worker_timeout") || + !context || (!exited(context->worker.get()) && context->connectionAttempted)) + throw; + info = context->info; + } + auto validateInfo = [&](Json value) { + if (context) { + value["sessionId"] = expectedSession; + value["calibrationSession"] = true; + } + detail::validate_calibration_recovery(value, expectedSession, force); + }; + validateInfo(info); + + std::unique_lock command(commandGate, std::try_to_lock); + if (!command.owns_lock()) { + std::lock_guard hold(workerGate); + if (activeAction.rfind("calibration", 0) != 0) + throw ApiError(409, "device_busy", "当前任务不是标定,不能通过标定恢复中止。"); + if (!force) + throw ApiError(409, "recovery_requires_force", "标定任务仍在执行;中止需明确 force:true。"); + } + + // Pin both original process objects before any release or termination. + // No enumeration or image-name based termination is permitted here. + Handle oldWorker, oldManufacturer; + DWORD oldPid; + uint64_t oldStarted; + { + std::lock_guard hold(workerGate); + if (detached) { + if (client || process || !context || !exited(context->worker.get())) + throw ApiError(409, "session_changed", "恢复上下文已变化,请刷新后重试。"); + oldWorker = duplicate_process(context->worker.get()); + oldPid = GetProcessId(oldWorker.get()); + oldStarted = process_started(oldWorker.get()); + } else if (owner != client || !process) + throw ApiError(409, "session_changed", "SDK后台已变化,请刷新状态后重试。"); + else { + oldPid = pid; + oldStarted = started; + oldWorker = duplicate_process(process.get()); + } + } + verify_process_identity(oldWorker.get(), oldPid, oldStarted, executable()); + const bool ownUninitializedReplacement = context && context->replacement && + info.value("initializationAttempted", true) && !info.value("ownerTrustedForForce", false); + if (!simulated && !ownUninitializedReplacement && + !(context && !info.value("initializationAttempted", true))) { + const auto manufacturer = info.value("owner", Json()); + if (!manufacturer.is_object() || !manufacturer.contains("processId") || + !manufacturer["processId"].is_number_unsigned() || + !manufacturer.contains("startedFileTime") || !manufacturer["startedFileTime"].is_string() || + !manufacturer.contains("executable") || !manufacturer["executable"].is_string()) + throw ApiError(503, "recovery_identity_unverified", "厂家后台归属不明,保留旧会话。"); + const auto manufacturerPid = manufacturer.at("processId").get(); + const auto manufacturerStarted = std::stoull(manufacturer.at("startedFileTime").get()); + const auto manufacturerPath = detail::locate_sdk_installation(root, executable().parent_path(), config) + .serviceDirectory / L"FreeScan Trak.exe"; + if (manufacturerPid == oldPid || manufacturerStarted < oldStarted || + _wcsicmp(fs::path(wide(manufacturer.at("executable").get())).lexically_normal().c_str(), + manufacturerPath.lexically_normal().c_str()) != 0) + throw ApiError(503, "recovery_identity_unverified", "厂家进程与当前SDK会话身份不一致。"); + if (context && context->manufacturer) + oldManufacturer = duplicate_process(context->manufacturer.get()); + else + oldManufacturer.reset(OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, + FALSE, manufacturerPid)); + verify_process_identity(oldManufacturer.get(), manufacturerPid, manufacturerStarted, manufacturerPath); + } else if (simulated && !info.value("simulated", false)) + throw ApiError(503, "recovery_identity_unverified", "模拟后台身份不一致。"); + + // Recheck the session immediately before the first destructive action. + if (!exited(oldWorker.get())) { + try { validateInfo(owner->call("recoveryInfo", Json::object(), 5000)); } + catch (const ApiError &error) { + if ((error.code != "worker_unavailable" && error.code != "worker_timeout") || + !context || context->connectionAttempted) + throw; + validateInfo(info); // No SDK command has ever been sent to this child. + } + } + if (!context) + context = std::make_shared(); + context->owner = owner; + context->originalSession = expectedSession; + context->info = info; + context->worker = duplicate_process(oldWorker.get()); + if (oldManufacturer) + context->manufacturer = duplicate_process(oldManufacturer.get()); + autoConnection.pause(); + { + std::lock_guard hold(workerGate); + recoveringSession = expectedSession; + recoveryContext = context; + } + rotating = true; + suspendFrames = true; + advance(); + clearFrame(); + bool forced = false, invalidated = false; + auto invalidate = [&] { + if (!invalidated) { + ++commandGeneration; + invalidated = true; + } + }; + try { + log("标定恢复:已确认旧会话 " + expectedSession + ",先尝试SDK正常释放;不继续标定或采集。"); + try { if (!exited(oldWorker.get())) captureFiles(owner); } + catch (const std::exception &error) { log(std::string("保留已有下载登记:") + error.what()); } + bool gracefullyClosed = exited(oldWorker.get()) && + (!oldManufacturer || exited(oldManufacturer.get())); + if (!gracefullyClosed && !exited(oldWorker.get()) && command.owns_lock() && + !ownUninitializedReplacement) { + try { + // close/shutdown deliberately bypasses execute_action's + // restart_required guard and calls normal Sn3DRelease. + owner->call("close", Json{{"shutdown", true}}, 22000); + gracefullyClosed = WaitForSingleObject(oldWorker.get(), 5000) == WAIT_OBJECT_0 && + (!oldManufacturer || WaitForSingleObject(oldManufacturer.get(), 0) == WAIT_OBJECT_0); + } catch (const std::exception &error) { + log(std::string("标定正常释放尚未确认:") + error.what()); + } + // A successful shutdown may close the pipe before its reply is + // acknowledged. The pinned exit handles, not transport success, + // decide whether a replacement can be started safely. + if (!gracefullyClosed) + gracefullyClosed = WaitForSingleObject(oldWorker.get(), 1000) == WAIT_OBJECT_0 && + (!oldManufacturer || WaitForSingleObject(oldManufacturer.get(), 0) == WAIT_OBJECT_0); + } + if (!gracefullyClosed) { + if (!force) + throw ApiError(409, "recovery_requires_force", "SDK正常释放未完成;旧后台保留,确认中止后可使用 force:true。"); + invalidate(); + forced = true; + log("标定恢复:仅结束已核验的旧SDK后台及其厂家进程,PID " + std::to_string(oldPid)); + if (ownUninitializedReplacement) + log("本次新后台初始化未完成且厂家进程归属不明;仅清理本服务创建的SDK后台,不终止任何未知厂家进程。后续连接仍检查服务占用。"); + if (!exited(oldWorker.get()) && !TerminateProcess(oldWorker.get(), 0xE0000002) && !exited(oldWorker.get())) + throw ApiError(503, "recovery_termination_failed", "无法结束旧SDK后台,未创建新会话。"); + if (WaitForSingleObject(oldWorker.get(), 5000) != WAIT_OBJECT_0) + throw ApiError(504, "recovery_exit_timeout", "旧SDK后台退出未确认,未创建新会话。"); + if (oldManufacturer) { + if (!exited(oldManufacturer.get()) && !TerminateProcess(oldManufacturer.get(), 0xE0000002) && + !exited(oldManufacturer.get())) + throw ApiError(503, "recovery_termination_failed", "无法结束旧厂家后台,未创建新会话。"); + if (WaitForSingleObject(oldManufacturer.get(), 5000) != WAIT_OBJECT_0) + throw ApiError(504, "recovery_exit_timeout", "旧厂家后台退出未确认,未创建新会话。"); + } + } + invalidate(); + // Terminating the pinned worker closes the old RPC, releasing an + // execute() that held commandGate. It cannot mutate new flags. + if (!command.owns_lock()) { + const auto deadline = unix_ms() + 6000; + while (!command.try_lock() && unix_ms() < deadline) + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + if (!command.owns_lock()) + throw ApiError(504, "recovery_gate_timeout", "旧任务尚未退出,未启动新SDK后台。"); + } + { + std::lock_guard hold(workerGate); + if ((!detached && client != owner) || (detached && client)) + throw ApiError(409, "session_changed", "旧后台归属发生变化,停止恢复。"); + client.reset(); + process.reset(); + pid = 0; + started = 0; + activeAction.clear(); + ++epoch; + } + busy = true; + deviceType = info.value("deviceType", deviceType); + startWorker(); + auto replacement = current(); + { + std::lock_guard hold(workerGate); + context->owner = replacement; + context->worker = duplicate_process(process.get()); + context->manufacturer.reset(); + } + context->info = replacement->call("recoveryInfo", Json::object(), 5000); + if (simulated && fs::is_regular_file(root / L"OFFLINE_TEST_RECOVERY_CONNECT_FAIL_ONCE")) { + fs::rename(root / L"OFFLINE_TEST_RECOVERY_CONNECT_FAIL_ONCE", + root / L"OFFLINE_TEST_RECOVERY_CONNECT_FAIL_CONSUMED"); + throw ApiError(503, "recovery_connect_failed", "OFFLINE_TEST_FIXTURE: recovery reconnect failed once."); + } + context->connectionAttempted = true; + replacement->call("execute", Json{{"action", "connect"}, + {"body", Json{{"deviceType", deviceType}}}}, 150000); + const auto after = replacement->call("status", Json::object(), 5000); + if (!after.value("initialized", false) || after.value("restartRequired", false) || + after.value("stateUncertain", false) || after.value("projectReady", true) || + after.value("scanning", true) || after.value("calibrationActive", true) || + !(after.contains("deviceOnline") && after["deviceOnline"] == true)) + throw ApiError(503, "recovery_connect_failed", "旧标定已结束,但新SDK连接未就绪;未恢复标定或采集。"); + fault = false; + rotating = false; + suspendFrames = false; + busy = false; + autoConnection.protect(false); + autoConnection.resume(); + autoConnection.connected(); + { + std::lock_guard hold(workerGate); + recoveringSession.clear(); + recoveryContext.reset(); + } + log("标定恢复成功:旧会话已结束,新SDK已连接;HTTP父服务保持运行。"); + auto finalStatus = status(); + finalStatus["recoveryActive"] = false; + finalStatus["busy"] = false; + finalStatus["state"] = after.at("state"); + finalStatus["recoverySessionId"] = nullptr; + return {{"recovered", true}, {"reconnected", true}, {"calibrationAborted", true}, + {"forced", forced}, {"previousSessionId", expectedSession}, + {"newSessionId", after.value("sessionId", Json())}, + {"httpServiceRunning", true}, {"downloadsPreserved", true}, {"status", std::move(finalStatus)}}; + } catch (...) { + // If replacement initialization failed, keep its own identity and + // metadata for an explicit retry of this same recovery chain. + try { + const auto last = current(); + if (context && last && context->owner == last && !exited(context->worker.get())) + context->info = last->call("recoveryInfo", Json::object(), 1500); + } catch (...) { } + fault = true; + rotating = false; + suspendFrames = false; + // An invalidated old task cannot clear busy; the recovery owner does. + busy = false; + clearFrame(); + log("标定恢复失败:自动连接保持暂停,未自动继续标定或采集,请查看错误与日志。"); + throw; + } + } + void automaticStep() { + if (recoveryActive) + return; + const auto monitor = autoConnection.snapshot(); + if (!monitor.value("enabled", false) || monitor.value("paused", false) || + monitor.value("state", std::string()) == "blocked" || autoStop || stopping) + return; + // Routine observation must not occupy the control gate and make a + // manual command fail with device_busy. Mutating recovery below still + // rechecks state while holding that gate. + auto observedOwner = current(); + if (observedOwner) { + try { + const auto observed = observedOwner->call("status", Json::object(), 5000); + if (observedOwner != current()) + return; + const bool safeConnected = observed.value("initialized", false) && !fault && + !observed.value("restartRequired", false) && !observed.value("stateUncertain", false) && + !(observed.contains("deviceOnline") && observed["deviceOnline"] == false); + if (safeConnected || observed.value("projectReady", false) || + observed.value("scanning", false) || observed.value("calibrationActive", false)) { + autoConnection.decide(observed, unix_ms()); + return; + } + if (observed.value("busy", false)) + return; + } catch (const std::exception &) { + // The locked path distinguishes a dead owner from an unknown + // live state and preserves the session protection latch. + } + } + std::unique_lock command(commandGate, std::try_to_lock); + if (!command.owns_lock() || autoStop || stopping || recoveryActive) + return; + auto owner = current(); + if (!owner) + return; + Json before; + try { + before = owner->call("status", Json::object(), 5000); + } catch (const ApiError &error) { + bool dead; + { + std::lock_guard hold(workerGate); + dead = process && exited(process.get()); + } + if (!dead) { + autoConnection.failed(error, unix_ms()); + return; // Unknown state never authorizes replacing a live worker. + } + before = empty(); + before["restartRequired"] = true; + } + if (fault) + before["restartRequired"] = true; + const auto action = autoConnection.decide(before, unix_ms()); + if (action == detail::AutoConnectionAction::none) + return; + bool cleanupUnconfirmed = false; + busy = true; + try { + deviceType = before.value("deviceType", deviceType); + if (action == detail::AutoConnectionAction::recycle) { + cleanupUnconfirmed = true; + log("SDK自动重启:当前无工程或标定会话,先请求正常退出旧SDK后台。"); + try { captureFiles(owner); } + catch (const std::exception &error) { + // Completed export/snapshot registrations are already in + // the HTTP parent; unavailable workers cannot erase them. + log(std::string("保留父服务已有下载登记;旧后台登记暂不可读:") + error.what()); + } + rotating = true; + advance(); + clearFrame(); + bool forced = false; + try { closeWorker(true); } + catch (const ApiError &error) { + if (error.code != "worker_exit_timeout") + throw; + forceIdleWorkerExit(); + forced = true; + } + startWorker(); + autoConnection.restarted(forced, unix_ms()); + log("SDK工作进程已重启,HTTP父服务和历史任务保持运行。"); + fault = false; + cleanupUnconfirmed = false; + } + log("自动连接SDK;不创建工程、不开始采集。"); + current()->call("execute", Json{{"action", "connect"}, + {"body", Json{{"deviceType", deviceType}}}}, 150000); + const auto after = current()->call("status", Json::object(), 5000); + if (!after.value("initialized", false) || after.value("restartRequired", false) || + after.value("stateUncertain", false) || + (after.contains("deviceOnline") && after["deviceOnline"] == false)) + throw ApiError(503, "device_offline", "SDK连接尚未就绪或设备离线,稍后重试。"); + autoConnection.connected(); + log("SDK自动连接成功,等待外部创建工程和开始扫描。"); + } catch (const ApiError &error) { + if (cleanupUnconfirmed || error.code == "worker_timeout" || + error.code == "worker_unavailable" || error.code == "worker_protocol_error") + fault = true; + autoConnection.failed(error, unix_ms(), cleanupUnconfirmed); + log(std::string(cleanupUnconfirmed ? "自动重连已停止:" : "自动连接失败,等待重试:") + error.what()); + } catch (const std::exception &error) { + fault = true; + autoConnection.failed(ApiError(503, "auto_connection_error", error.what()), unix_ms(), true); + log(std::string("自动重连已停止:") + error.what()); + } + rotating = false; + busy = false; + } + void autoLoop() { + std::unique_lock wait(autoWaitGate); + // HTTP is already available. Give callers a chance to observe the + // initial waiting state and avoid performing SDK work on HTTP startup. + while (!autoWake.wait_for(wait, std::chrono::seconds(1), [this] { return autoStop.load(); })) { + wait.unlock(); + try { automaticStep(); } + catch (const std::exception &error) { + autoConnection.failed(ApiError(503, "auto_connection_error", error.what()), unix_ms(), true); + } + wait.lock(); + } + } + void seedCalibrationIdentity(const std::shared_ptr &owner,const Json &result) noexcept { + try { + if(owner!=current()||rotating||recoveryActive||stopping||fault)return; + const auto view=result.value("calibrationView",Json(nullptr)); + if(!view.is_object()||view.value("source",std::string())!="sdk_calibration_window"||!view.value("calibrationActive",false) + ||!view.value("sessionId",Json(nullptr)).is_string()||view["sessionId"].get().empty() + ||!view.value("calibrationId",Json(nullptr)).is_string()||view["calibrationId"].get().empty())return; + const auto round=currentEpoch(); + std::lock_guard hold(frameGate); + // A newer atomic worker snapshot already contains this exact entry; + // never replace its real frame with an identity-only seed. + if(calibrationOwner==owner&&calibrationEpoch==round&&calibrationMetadata.is_object() + &&calibrationMetadata.value("calibrationId",Json(nullptr))==view["calibrationId"])return; + if(calibrationEpoch>round)return; + auto seed=view;seed.erase("frame");seed["available"]=false;seed["frameSource"]=nullptr; + seed["state"]="frame_pending";seed["message"]="已进入厂家标定页面,等待本次窗口的新画面。";seed["frameSequence"]=calibrationSequence; + calibrationLatest.reset();calibrationNativeKey.clear();calibrationMetadata=std::move(seed); + calibrationOwner=owner;calibrationEpoch=round;calibrationReceived=unix_ms(); + }catch(...){/* Optional display metadata cannot reverse a confirmed SDK page entry. */} + } + Json calibrationSnapshot(bool includeFrame) { + std::shared_ptr owner;uint64_t round=0;bool alive=false; + {std::lock_guard hold(workerGate);owner=client;round=epoch;alive=process&&!exited(process.get());} + std::unique_lock hold(frameGate); + Json out{{"source","sdk_calibration_window"},{"sessionId",nullptr},{"calibrationId",nullptr}, + {"calibrationActive",false},{"available",false},{"state","calibration_inactive"}, + {"message","当前没有可核验的厂家标定窗口会话。"},{"frameSequence",calibrationSequence}, + {"frameSource",nullptr},{"progress",nullptr},{"temperatures",{{"scanner",nullptr},{"tracker",nullptr}}}}; + bool same=alive&&owner&&owner==calibrationOwner&&round==calibrationEpoch&&!rotating&&!recoveryActive&&!stopping&&!fault; + if(same&&calibrationMetadata.is_object()&&unix_ms()-calibrationReceived<=2000){ + out=calibrationMetadata;out["frameSequence"]=calibrationSequence; + if(out.value("available",false)){ + if(!calibrationLatest||unix_ms()-calibrationLatest->capturedMs<0||unix_ms()-calibrationLatest->capturedMs>2000){ + out["available"]=false;out["frameSource"]=nullptr;out["state"]="frame_stale";out["message"]="厂家标定窗口画面已过期。"; + }else if(includeFrame)out["frame"]=frame_to_json(*calibrationLatest); + } + } + if(includeFrame&&!out.contains("frame"))out["frame"]=nullptr; + hold.unlock(); + if(owner!=current()||round!=currentEpoch()||rotating||recoveryActive||stopping||fault){ + out["calibrationActive"]=false;out["available"]=false;out["frameSource"]=nullptr;out["state"]="session_changed";out["message"]="原SDK标定会话已经切换或结束。"; + if(includeFrame)out["frame"]=nullptr; + } + return out; + } + void receiveCalibration(const std::shared_ptr &owner,uint64_t round) { + Json data=owner->call("calibrationView",Json::object(),3000); + if(owner!=current()||round!=currentEpoch()||rotating||recoveryActive)return; + if(!data.is_object()||data.value("source",std::string())!="sdk_calibration_window")throw ApiError(502,"worker_protocol_error","标定窗口元数据来源无效。"); + std::shared_ptr frame; + std::string key; + if(data.value("available",false)){ + if(!data.value("calibrationActive",false)||!data.contains("frame")||!data["frame"].is_object()||!data.value("frameSource",Json(nullptr)).is_object())throw ApiError(502,"worker_protocol_error","标定窗口帧缺少会话归属。"); + frame=std::make_shared(frame_from_json(data["frame"])); + key=data.value("sessionId",std::string())+":"+data.value("calibrationId",std::string())+":"+data["frameSource"].dump()+":"+std::to_string(frame->sequence)+":"+std::to_string(frame->capturedMs); + } + data.erase("frame"); + std::lock_guard hold(frameGate); + if(calibrationEpoch>round)return; // A delayed pre-entry RPC must not overwrite its synchronous identity seed. + if(frame){ + if(key!=calibrationNativeKey){calibrationNativeKey=key;frame->sequence=++calibrationSequence;calibrationLatest=std::move(frame);} + data["frameSequence"]=calibrationSequence; + }else{calibrationLatest.reset();calibrationNativeKey.clear();data["frameSource"]=nullptr;data["frameSequence"]=calibrationSequence;} + calibrationMetadata=std::move(data);calibrationOwner=owner;calibrationEpoch=round;calibrationReceived=unix_ms(); + } + Json query(const std::string &action, const Json &args) { + if(action=="calibrationView"||action=="calibrationViewFrame")return calibrationSnapshot(action=="calibrationViewFrame"); + if (action == "file") { + std::lock_guard hold(fileGate); + auto it = downloads.find(args.value("fileId", std::string())); + if (it == downloads.end()) + throw ApiError(404, "file_not_found", "文件编号不存在或已随服务重启失效。"); + return it->second; + } + if (action == "capabilities") { + Json out; + const auto owner = current(); + try { + if (!owner || recoveryActive) + throw ApiError(503, "worker_unavailable", "SDK后台切换中。"); + out = owner->call("query", Json{{"action", action}, {"args", args}}, 4500); + } catch (const std::exception &) { + // Static HTTP declarations remain available when the worker's + // operation gate is busy or its previous process already exited. + // No device state/readback is invented in this fallback. + out = {{"apiVersion", "1.3"}, {"deviceFamily", "FreeScan Trak Nova / Trak"}, + {"initialized", false}, {"calibration", nullptr}, + {"rawDataAvailable", false}, {"rawDataReason", "设备后台忙或恢复中,静态接口能力仍可查询。"}, + {"capabilitySource", "http_parent_static_declarations"}, + {"features", {{"calibration", true}, {"calibrationRecovery", true}}}, + {"controls", {{"connect", true}, {"disconnect", true}, {"reconnect", true}}}, + {"calibrationModes", Json::array({{{"mode", 0}, {"modeName", "跟踪仪标定"}}, + {{"mode", 1}, {"modeName", "系统标定"}}, + {{"mode", 2}, {"modeName", "探针标定"}}, + {{"mode", 3}, {"modeName", "UE Nova 激光标定"}}})}}; + } + out["routes"] = contracts::routes(); + out["features"]["calibrationRecovery"] = true; + out["implementation"] = "C++17"; + out["sdkProcessIsolation"] = true; + out["simulated"] = simulated; + return out; + } + auto owner = current(); + if (!owner) + throw ApiError(503, "worker_unavailable", "设备后台正在切换,请稍后刷新。"); + Json out = owner->call("query", Json{{"action", action}, {"args", args}}, + action == "sceneInfo" ? 14000 : 4500); + if (action == "capabilities" && out.is_object()) { + out["implementation"] = "C++17"; + out["sdkProcessIsolation"] = true; + out["simulated"] = simulated; + } + return out; + } + void frameLoop() { + std::shared_ptr previous; + uint64_t last = 0;int64_t nextCalibration=0; + while (!stopping) { + auto owner = current(); + auto round = currentEpoch(); + if (owner && !rotating && !suspendFrames) { + if (owner != previous) { + previous = owner; + last = 0; + } + if(unix_ms()>=nextCalibration){ + nextCalibration=unix_ms()+100; + try{receiveCalibration(owner,round);} + catch(const std::exception &){std::lock_guard hold(frameGate);if(calibrationEpoch<=round){calibrationLatest.reset();calibrationMetadata=nullptr;calibrationNativeKey.clear();}} + } + try { + Json data = owner->call("frame", Json::object(), 3000); + if (owner == current() && round == currentEpoch() && !rotating && !suspendFrames) { + if (data.is_null()) + clearFrame(); + else { + FrameSnapshot frame = frame_from_json(data); + { + std::lock_guard hold(frameGate); + encoderMetrics = data.value("encoderMetrics", Json(nullptr)); + } + if (frame.sequence != last) { + last = frame.sequence; + std::lock_guard hold(frameGate); + frame.sequence = ++sequence; + latest = std::make_shared(std::move(frame)); + ++encoded; + encodeTotal += latest->encodeMs; + } + } + } + } catch (const std::exception &) { + if (owner == current() && !rotating) + clearFrame(); + } + } + std::this_thread::sleep_for(std::chrono::milliseconds(40)); + } + } +}; +Supervisor::Supervisor(fs::path root, Json config, bool mock) + : impl_(std::make_shared(std::move(root), std::move(config), mock)) {} +Supervisor::~Supervisor() { + if (impl_) { + impl_->autoStop = true; + impl_->autoWake.notify_all(); + if (impl_->autoThread.joinable()) + impl_->autoThread.join(); + impl_->stopping = true; + if (impl_->frameThread.joinable()) + impl_->frameThread.join(); + } +} +void Supervisor::start() { + impl_->rotating = true; + try { + impl_->startWorker(); + impl_->rotating = false; + auto self = impl_; + impl_->frameThread = std::thread([self] { self->frameLoop(); }); + } catch (...) { + impl_->fault = true; + impl_->rotating = false; + throw; + } +} +void Supervisor::start_auto_connection() { + if (impl_->config.value("autoConnect", true)) { + auto self = impl_; + impl_->autoThread = std::thread([self] { self->autoLoop(); }); + } +} +void Supervisor::pause_auto_connection() { + impl_->autoConnection.pause(); +} +bool Supervisor::stop() { + if (impl_->recoveryActive) { + impl_->log("标定恢复尚未完成,请等待后停止HTTP服务。"); + return false; + } + impl_->autoConnection.pause(); + std::unique_lock command(impl_->commandGate, std::try_to_lock); + if (!command.owns_lock()) { + impl_->log("请等待当前设备任务结束后再关闭服务。"); + return false; + } + impl_->autoStop = true; + impl_->autoWake.notify_all(); + if (impl_->autoThread.joinable()) + impl_->autoThread.join(); + impl_->rotating = true; + try { + impl_->closeWorker(true); + impl_->stopping = true; + if (impl_->frameThread.joinable()) + impl_->frameThread.join(); + return true; + } catch (const std::exception &ex) { + impl_->fault = true; + impl_->rotating = false; + impl_->log("服务尚未关闭:" + std::string(ex.what())); + return false; + } +} +Json Supervisor::status() { + return impl_->status(); +} +uint64_t Supervisor::command_generation() const { + return impl_->commandGeneration.load(); +} +Json Supervisor::execute(const std::string &action, const Json &body, uint64_t expectedGeneration) { + return impl_->execute(action, body, expectedGeneration); +} +Json Supervisor::recover(const Json &body) { + return impl_->recover(body); +} +Json Supervisor::query(const std::string &action, const Json &args) { + return impl_->query(action, args); +} +std::shared_ptr Supervisor::frame() { + std::lock_guard hold(impl_->frameGate); + return impl_->latest; +} +Json Supervisor::metrics() { + std::lock_guard hold(impl_->frameGate); + auto latest = impl_->latest; + Json out{ + {"maxFps", impl_->config.value("previewFps", 20)}, + {"maxWidth", impl_->config.value("previewMaxWidth", 1280)}, + {"jpegQuality", impl_->config.value("previewJpegQuality", 75)}, + {"offeredFrames", impl_->encoded}, + {"encodedFrames", impl_->encoded}, + {"replacedFrames", 0}, + {"throttledFrames", 0}, + {"encodingFailures", 0}, + {"averageEncodeMs", impl_->encoded ? impl_->encodeTotal / impl_->encoded : 0}, + {"averageEncodedFps", impl_->encoded * 1000.0 / std::max(1, unix_ms() - impl_->metricStart)}, + {"latestEncodeMs", latest ? Json(latest->encodeMs) : Json()}, + {"latestFrameBytes", latest ? latest->jpeg.size() : 0}, + {"latestSequence", latest ? latest->sequence : 0}, + {"frameAgeMs", latest ? Json(std::max(0, unix_ms() - latest->capturedMs)) : Json()}, + {"sourceWidth", latest ? latest->sourceWidth : 0}, + {"sourceHeight", latest ? latest->sourceHeight : 0}, + {"width", latest ? latest->width : 0}, + {"height", latest ? latest->height : 0}, + {"queueDepth", 0}, + {"encoderRunning", false}, + {"freshnessLimitMs", 2000}, + {"capturedTimeMeaning", "managed_frame_received_not_hardware_exposure"}, + {"implementation", "C++17"}, + {"metricSource", "parent_imported_jpeg_cache"}}; + if (impl_->encoderMetrics.is_object()) { + out.update(impl_->encoderMetrics); + out["metricSource"] = "worker_encoder_cache"; + out["latestSequence"] = latest ? latest->sequence : 0; + out["frameAgeMs"] = latest ? Json(std::max(0, unix_ms() - latest->capturedMs)) : Json(); + } + out["importedFrames"] = impl_->encoded; + return out; +} + +namespace { +struct WorkerContext { + std::shared_ptr service; + std::mutex command; + std::atomic closing{false}; + DWORD threadId; +}; +} // namespace +int run_worker(const fs::path &root, const Json &config, const std::wstring &name, DWORD parentPid, + uint64_t parentStarted, bool simulated) { + CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + MSG first{}; + PeekMessageW(&first, nullptr, WM_USER, WM_USER, PM_NOREMOVE); + auto context = std::make_shared(); + context->service = std::make_shared(root, config, simulated); + context->threadId = GetCurrentThreadId(); + Handle parent(OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, parentPid)); + if (!parent || process_started(parent.get()) != parentStarted) + return 2; + PipeServer server(name, [context](const std::string &method, const Json &args) -> Json { + if (method == "status") + return context->service->status(); + if (method == "recoveryInfo") + return context->service->recovery_info(); + if (method == "frame") + return context->service->frame(); + if(method=="calibrationView")return context->service->calibration_view(true); + if (method == "files") + return context->service->files(); + if (method == "query") { + auto action = args.at("action").get(); + if (action == "capabilities" || action == "file") + return context->service->query(action, args.value("args", Json::object())); + if (action != "sceneInfo") + throw ApiError(404, "unknown_query", "后台查询不存在。"); + std::unique_lock hold(context->command, std::try_to_lock); + if (!hold.owns_lock()) + throw ApiError(409, "device_busy", "后台正在执行其他任务。"); + if (context->closing) + throw ApiError(503, "shutting_down", "后台正在关闭。"); + return context->service->query(action, args.value("args", Json::object())); + } + std::unique_lock hold(context->command, std::try_to_lock); + if (!hold.owns_lock()) + throw ApiError(409, "device_busy", "后台正在执行其他任务。"); + if (context->closing) + throw ApiError(503, "shutting_down", "后台正在关闭。"); + if (method == "execute") { + auto action = args.at("action").get(); + if (action == "reconnect") + throw ApiError(409, "worker_restart_required", "重连必须由 HTTP 父进程更换 SDK 后台。"); + return context->service->execute(action, args.at("body")); + } + if (method == "close") { + bool shutdown = args.value("shutdown", false); + if (!context->service->can_close(shutdown)) + throw ApiError(409, "device_busy", "SDK 当前操作尚未结束,不能关闭后台。"); + context->closing = true; + context->service->shutdown(); + PostThreadMessageW(context->threadId, WM_QUIT, 0, 0); + return Json{{"closing", true}}; + } + throw ApiError(404, "unknown_rpc_method", "后台通信方法不存在。"); + }); + server.start(); + bool done = false; + HANDLE parentHandle = parent.get(); + while (!done) { + DWORD result = MsgWaitForMultipleObjects(1, &parentHandle, FALSE, 1000, QS_ALLINPUT); + if (result == WAIT_OBJECT_0) { + std::unique_lock hold(context->command, std::try_to_lock); + if (hold.owns_lock() && context->service->can_close(true)) { + context->closing = true; + context->service->shutdown(); + done = true; + } else + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + while (PeekMessageW(&first, nullptr, 0, 0, PM_REMOVE)) { + if (first.message == WM_QUIT) { + done = true; + break; + } + TranslateMessage(&first); + DispatchMessageW(&first); + } + } + server.stop(); + context->service->shutdown(); + CoUninitialize(); + return 0; +} +} // namespace freescan diff --git a/integrations/freescan-service/src/supervisor.hpp b/integrations/freescan-service/src/supervisor.hpp new file mode 100644 index 0000000..f96c13d --- /dev/null +++ b/integrations/freescan-service/src/supervisor.hpp @@ -0,0 +1,27 @@ +#pragma once +#include "common.hpp" +#include "pipe_rpc.hpp" +namespace freescan { +class Supervisor { + struct Impl; + std::shared_ptr 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 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 diff --git a/integrations/freescan-service/tests/battery_test.cpp b/integrations/freescan-service/tests/battery_test.cpp new file mode 100644 index 0000000..7455f83 --- /dev/null +++ b/integrations/freescan-service/tests/battery_test.cpp @@ -0,0 +1,204 @@ +#include "../src/device_battery.hpp" +#include +#include + +// 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{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{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()) : value.get(); + 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{-1, "-1", -10, 101, "101", + (std::numeric_limits::min)(), + (std::numeric_limits::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()) : value.get(); + check(result.at("rawValue") == expected, "Out-of-range integer reports preserve their exact raw value."); + } + for (const auto &invalid : std::vector{nullptr, true, false, 17.0, 17.5, "", " ", " 17", "17 ", + "+17", "17.0", "17%", "1e2", "--1", "-", "0x11", + "2147483648", "-2147483649", "9223372036854775808", "-9223372036854775809", + (std::numeric_limits::max)(), + (std::numeric_limits::min)(), + (std::numeric_limits::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{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; + } +} diff --git a/integrations/freescan-service/tests/calibration_files_test.cpp b/integrations/freescan-service/tests/calibration_files_test.cpp new file mode 100644 index 0000000..8d3fc41 --- /dev/null +++ b/integrations/freescan-service/tests/calibration_files_test.cpp @@ -0,0 +1,214 @@ +#include "../src/calibration_files.hpp" +#include + +// 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(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 names; + for (const auto &item : value.at("calibrationFileTimes")) + names.push_back(item.at("fileName").get()); + 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; + } +} diff --git a/integrations/freescan-service/tests/calibration_recovery_test.cpp b/integrations/freescan-service/tests/calibration_recovery_test.cpp new file mode 100644 index 0000000..fd1b00e --- /dev/null +++ b/integrations/freescan-service/tests/calibration_recovery_test.cpp @@ -0,0 +1,66 @@ +#include "../src/calibration_recovery.hpp" +#include + +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; + } +} diff --git a/integrations/freescan-service/tests/contracts_test.cpp b/integrations/freescan-service/tests/contracts_test.cpp new file mode 100644 index 0000000..46aa779 --- /dev/null +++ b/integrations/freescan-service/tests/contracts_test.cpp @@ -0,0 +1,428 @@ +#include "../src/contracts.hpp" +#include +#include +#include + +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(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 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 seen; + for (const auto &route : api::routes()) { + const auto line = route.get(); + 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(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::infinity(), -std::numeric_limits::infinity(), + std::numeric_limits::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 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::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; + } +} diff --git a/integrations/freescan-service/tests/measure-preview.mjs b/integrations/freescan-service/tests/measure-preview.mjs new file mode 100644 index 0000000..e0455af --- /dev/null +++ b/integrations/freescan-service/tests/measure-preview.mjs @@ -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)); diff --git a/integrations/freescan-service/tests/native-api.test.mjs b/integrations/freescan-service/tests/native-api.test.mjs new file mode 100644 index 0000000..a719ccf --- /dev/null +++ b/integrations/freescan-service/tests/native-api.test.mjs @@ -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); + } +}); diff --git a/integrations/freescan-service/tests/preview_capture_test.cpp b/integrations/freescan-service/tests/preview_capture_test.cpp new file mode 100644 index 0000000..7f32a22 --- /dev/null +++ b/integrations/freescan-service/tests/preview_capture_test.cpp @@ -0,0 +1,306 @@ +#include "../src/preview_capture.hpp" +#include +#include +#include +#include +#include +#include + +// 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 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(); } +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); + static_assert(!std::is_copy_assignable_v); + static_assert(std::is_nothrow_move_constructible_v); + static_assert(std::is_nothrow_move_assignable_v); + 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 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 leases; + std::array 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, 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, 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 warm; + std::array 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, PreviewFramePool::capacity> owners{}; + std::atomic ready{0}, finished{0}, acquired{0}, duplicates{0}, corruption{0}; + std::atomic begin{false}; + constexpr unsigned threads = 8, iterations = 1500; + std::array 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() >= 0 && final.at("averageCallbackMs").get() >= 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; + } +} diff --git a/integrations/freescan-service/tests/support/preview-pipeline.js b/integrations/freescan-service/tests/support/preview-pipeline.js new file mode 100644 index 0000000..e468861 --- /dev/null +++ b/integrations/freescan-service/tests/support/preview-pipeline.js @@ -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]; +} diff --git a/integrations/freescan-service/tests/worker_test.cpp b/integrations/freescan-service/tests/worker_test.cpp new file mode 100644 index 0000000..7e6c8ae --- /dev/null +++ b/integrations/freescan-service/tests/worker_test.cpp @@ -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 +#include +#include +#include + +// 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 passed{0}; +void check(bool condition, const std::string &message) { + if (!condition) + throw std::runtime_error(message); + ++passed; +} +template 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 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{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{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{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{"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{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{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(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> 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(); + 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>{{"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()))); + 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().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>{ + {"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())); + const auto content = bytes(path); + const auto id = file.at("fileId").get(); + 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())), + "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()))), + "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> 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 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() > 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(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> 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(); + 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(); + 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() >= 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() >= 0 && + capture.at("maxCallbackMs").get() >= capture.at("averageCallbackMs").get(), + "Completed callback timings remain valid without synchronous callback logging."); + check(pool.at("capacity") == 3 && pool.at("allocatedSlots").get() <= 3 && + pool.at("reuses").get() > 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().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; + } +} diff --git a/integrations/freescan-service/third_party/LICENSE.nlohmann-json b/integrations/freescan-service/third_party/LICENSE.nlohmann-json new file mode 100644 index 0000000..b5a1027 --- /dev/null +++ b/integrations/freescan-service/third_party/LICENSE.nlohmann-json @@ -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. diff --git a/integrations/freescan-service/third_party/README.md b/integrations/freescan-service/third_party/README.md new file mode 100644 index 0000000..85d75f1 --- /dev/null +++ b/integrations/freescan-service/third_party/README.md @@ -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 系统组件不作为第三方源码随包分发。 diff --git a/integrations/freescan-service/third_party/json.hpp b/integrations/freescan-service/third_party/json.hpp new file mode 100644 index 0000000..82d69f7 --- /dev/null +++ b/integrations/freescan-service/third_party/json.hpp @@ -0,0 +1,25526 @@ +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + +/****************************************************************************\ + * Note on documentation: The source files contain links to the online * + * documentation of the public API at https://json.nlohmann.me. This URL * + * contains the most recent documentation and should also be applicable to * + * previous versions; documentation for deprecated functions is not * + * removed, but marked deprecated. See "Generate documentation" section in * + * file docs/README.md. * +\****************************************************************************/ + +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ + +#include // all_of, find, for_each +#include // nullptr_t, ptrdiff_t, size_t +#include // hash, less +#include // initializer_list +#ifndef JSON_NO_IO + #include // istream, ostream +#endif // JSON_NO_IO +#include // random_access_iterator_tag +#include // unique_ptr +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// This file contains all macro definitions affecting or depending on the ABI + +#ifndef JSON_SKIP_LIBRARY_VERSION_CHECK + #if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH) + #if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 12 || NLOHMANN_JSON_VERSION_PATCH != 0 + #warning "Already included a different version of the library!" + #endif + #endif +#endif + +#define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_MINOR 12 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_PATCH 0 // NOLINT(modernize-macro-to-enum) + +#ifndef JSON_DIAGNOSTICS + #define JSON_DIAGNOSTICS 0 +#endif + +#ifndef JSON_DIAGNOSTIC_POSITIONS + #define JSON_DIAGNOSTIC_POSITIONS 0 +#endif + +#ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 +#endif + +#if JSON_DIAGNOSTICS + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag +#else + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS +#endif + +#if JSON_DIAGNOSTIC_POSITIONS + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS _dp +#else + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS +#endif + +#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp +#else + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION + #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 +#endif + +// Construct the namespace ABI tags component +#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c) json_abi ## a ## b ## c +#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b, c) \ + NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c) + +#define NLOHMANN_JSON_ABI_TAGS \ + NLOHMANN_JSON_ABI_TAGS_CONCAT( \ + NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \ + NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON, \ + NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS) + +// Construct the namespace version component +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \ + _v ## major ## _ ## minor ## _ ## patch +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) + +#if NLOHMANN_JSON_NAMESPACE_NO_VERSION +#define NLOHMANN_JSON_NAMESPACE_VERSION +#else +#define NLOHMANN_JSON_NAMESPACE_VERSION \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \ + NLOHMANN_JSON_VERSION_MINOR, \ + NLOHMANN_JSON_VERSION_PATCH) +#endif + +// Combine namespace components +#define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b +#define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \ + NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) + +#ifndef NLOHMANN_JSON_NAMESPACE +#define NLOHMANN_JSON_NAMESPACE \ + nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN +#define NLOHMANN_JSON_NAMESPACE_BEGIN \ + namespace nlohmann \ + { \ + inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) \ + { +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_END +#define NLOHMANN_JSON_NAMESPACE_END \ + } /* namespace (inline namespace) NOLINT(readability/namespace) */ \ + } // namespace nlohmann +#endif + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // transform +#include // array +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#ifdef JSON_HAS_CPP_17 + #include // optional +#endif +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // nullptr_t +#include // exception +#if JSON_DIAGNOSTICS + #include // accumulate +#endif +#include // runtime_error +#include // to_string +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // uint8_t +#include // string + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // declval, pair +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +// https://en.cppreference.com/w/cpp/experimental/is_detected +struct nonesuch +{ + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; +}; + +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; + +template class Op, class... Args> +struct detector>, Op, Args...> +{ + using value_t = std::true_type; + using type = Op; +}; + +template class Op, class... Args> +using is_detected = typename detector::value_t; + +template class Op, class... Args> +struct is_detected_lazy : is_detected { }; + +template class Op, class... Args> +using detected_t = typename detector::type; + +template class Op, class... Args> +using detected_or = detector; + +template class Op, class... Args> +using detected_or_t = typename detected_or::type; + +template class Op, class... Args> +using is_detected_exact = std::is_same>; + +template class Op, class... Args> +using is_detected_convertible = + std::is_convertible, To>; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + + +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-FileCopyrightText: 2016 - 2021 Evan Nemerson +// SPDX-License-Identifier: MIT + +/* Hedley - https://nemequ.github.io/hedley + * Created by Evan Nemerson + */ + +#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) +#if defined(JSON_HEDLEY_VERSION) + #undef JSON_HEDLEY_VERSION +#endif +#define JSON_HEDLEY_VERSION 15 + +#if defined(JSON_HEDLEY_STRINGIFY_EX) + #undef JSON_HEDLEY_STRINGIFY_EX +#endif +#define JSON_HEDLEY_STRINGIFY_EX(x) #x + +#if defined(JSON_HEDLEY_STRINGIFY) + #undef JSON_HEDLEY_STRINGIFY +#endif +#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) + +#if defined(JSON_HEDLEY_CONCAT_EX) + #undef JSON_HEDLEY_CONCAT_EX +#endif +#define JSON_HEDLEY_CONCAT_EX(a,b) a##b + +#if defined(JSON_HEDLEY_CONCAT) + #undef JSON_HEDLEY_CONCAT +#endif +#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) + +#if defined(JSON_HEDLEY_CONCAT3_EX) + #undef JSON_HEDLEY_CONCAT3_EX +#endif +#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c + +#if defined(JSON_HEDLEY_CONCAT3) + #undef JSON_HEDLEY_CONCAT3 +#endif +#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) + +#if defined(JSON_HEDLEY_VERSION_ENCODE) + #undef JSON_HEDLEY_VERSION_ENCODE +#endif +#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) + #undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) + #undef JSON_HEDLEY_VERSION_DECODE_MINOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) + #undef JSON_HEDLEY_VERSION_DECODE_REVISION +#endif +#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) + +#if defined(JSON_HEDLEY_GNUC_VERSION) + #undef JSON_HEDLEY_GNUC_VERSION +#endif +#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#elif defined(__GNUC__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) +#endif + +#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) + #undef JSON_HEDLEY_GNUC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GNUC_VERSION) + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION) + #undef JSON_HEDLEY_MSVC_VERSION +#endif +#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) +#elif defined(_MSC_FULL_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) +#elif defined(_MSC_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) + #undef JSON_HEDLEY_MSVC_VERSION_CHECK +#endif +#if !defined(JSON_HEDLEY_MSVC_VERSION) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) +#elif defined(_MSC_VER) && (_MSC_VER >= 1200) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) +#else + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION) + #undef JSON_HEDLEY_INTEL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) +#elif defined(__INTEL_COMPILER) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_VERSION) + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #undef JSON_HEDLEY_INTEL_CL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) + #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION) + #undef JSON_HEDLEY_PGI_VERSION +#endif +#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) + #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) + #undef JSON_HEDLEY_PGI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PGI_VERSION) + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #undef JSON_HEDLEY_SUNPRO_VERSION +#endif +#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) +#elif defined(__SUNPRO_C) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) +#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) +#elif defined(__SUNPRO_CC) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) + #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#endif +#if defined(__EMSCRIPTEN__) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION) + #undef JSON_HEDLEY_ARM_VERSION +#endif +#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) +#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) + #undef JSON_HEDLEY_ARM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_ARM_VERSION) + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION) + #undef JSON_HEDLEY_IBM_VERSION +#endif +#if defined(__ibmxl__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) +#elif defined(__xlC__) && defined(__xlC_ver__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) +#elif defined(__xlC__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) + #undef JSON_HEDLEY_IBM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IBM_VERSION) + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_VERSION) + #undef JSON_HEDLEY_TI_VERSION +#endif +#if \ + defined(__TI_COMPILER_VERSION__) && \ + ( \ + defined(__TMS470__) || defined(__TI_ARM__) || \ + defined(__MSP430__) || \ + defined(__TMS320C2000__) \ + ) +#if (__TI_COMPILER_VERSION__ >= 16000000) + #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif +#endif + +#if defined(JSON_HEDLEY_TI_VERSION_CHECK) + #undef JSON_HEDLEY_TI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_VERSION) + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #undef JSON_HEDLEY_TI_CL2000_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) + #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #undef JSON_HEDLEY_TI_CL430_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) + #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #undef JSON_HEDLEY_TI_ARMCL_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) + #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) + #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #undef JSON_HEDLEY_TI_CL6X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) + #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #undef JSON_HEDLEY_TI_CL7X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) + #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #undef JSON_HEDLEY_TI_CLPRU_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) + #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION) + #undef JSON_HEDLEY_CRAY_VERSION +#endif +#if defined(_CRAYC) + #if defined(_RELEASE_PATCHLEVEL) + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) + #else + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) + #undef JSON_HEDLEY_CRAY_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_CRAY_VERSION) + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION) + #undef JSON_HEDLEY_IAR_VERSION +#endif +#if defined(__IAR_SYSTEMS_ICC__) + #if __VER__ > 1000 + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) + #else + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) + #undef JSON_HEDLEY_IAR_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IAR_VERSION) + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION) + #undef JSON_HEDLEY_TINYC_VERSION +#endif +#if defined(__TINYC__) + #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) + #undef JSON_HEDLEY_TINYC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION) + #undef JSON_HEDLEY_DMC_VERSION +#endif +#if defined(__DMC__) + #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) + #undef JSON_HEDLEY_DMC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_DMC_VERSION) + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #undef JSON_HEDLEY_COMPCERT_VERSION +#endif +#if defined(__COMPCERT_VERSION__) + #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) + #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION) + #undef JSON_HEDLEY_PELLES_VERSION +#endif +#if defined(__POCC__) + #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) + #undef JSON_HEDLEY_PELLES_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PELLES_VERSION) + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #undef JSON_HEDLEY_MCST_LCC_VERSION +#endif +#if defined(__LCC__) && defined(__LCC_MINOR__) + #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) + #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION) + #undef JSON_HEDLEY_GCC_VERSION +#endif +#if \ + defined(JSON_HEDLEY_GNUC_VERSION) && \ + !defined(__clang__) && \ + !defined(JSON_HEDLEY_INTEL_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_ARM_VERSION) && \ + !defined(JSON_HEDLEY_CRAY_VERSION) && \ + !defined(JSON_HEDLEY_TI_VERSION) && \ + !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ + !defined(__COMPCERT__) && \ + !defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_ATTRIBUTE +#endif +#if \ + defined(__has_attribute) && \ + ( \ + (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ + ) +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) +#else +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#endif +#if \ + defined(__has_cpp_attribute) && \ + defined(__cplusplus) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#endif +#if !defined(__cplusplus) || !defined(__has_cpp_attribute) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#elif \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ + (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_BUILTIN) + #undef JSON_HEDLEY_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) +#else + #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) + #undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) + #undef JSON_HEDLEY_GCC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_FEATURE) + #undef JSON_HEDLEY_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) +#else + #define JSON_HEDLEY_HAS_FEATURE(feature) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) + #undef JSON_HEDLEY_GNUC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_FEATURE) + #undef JSON_HEDLEY_GCC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_EXTENSION) + #undef JSON_HEDLEY_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) +#else + #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) + #undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) + #undef JSON_HEDLEY_GCC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_WARNING) + #undef JSON_HEDLEY_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) +#else + #define JSON_HEDLEY_HAS_WARNING(warning) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_WARNING) + #undef JSON_HEDLEY_GNUC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_WARNING) + #undef JSON_HEDLEY_GCC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + defined(__clang__) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ + (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) + #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_PRAGMA(value) __pragma(value) +#else + #define JSON_HEDLEY_PRAGMA(value) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) + #undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#endif +#if defined(JSON_HEDLEY_DIAGNOSTIC_POP) + #undef JSON_HEDLEY_DIAGNOSTIC_POP +#endif +#if defined(__clang__) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) + #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) +#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_PUSH + #define JSON_HEDLEY_DIAGNOSTIC_POP +#endif + +/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") +# if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") +# if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# endif +#endif +#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x +#endif + +#if defined(JSON_HEDLEY_CONST_CAST) + #undef JSON_HEDLEY_CONST_CAST +#endif +#if defined(__cplusplus) +# define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) +#elif \ + JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_REINTERPRET_CAST) + #undef JSON_HEDLEY_REINTERPRET_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) +#else + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_STATIC_CAST) + #undef JSON_HEDLEY_STATIC_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) +#else + #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_CPP_CAST) + #undef JSON_HEDLEY_CPP_CAST +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ + ((T) (expr)) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("diag_suppress=Pe137") \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) +# endif +#else +# define JSON_HEDLEY_CPP_CAST(T, expr) (expr) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunused-function") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif + +#if defined(JSON_HEDLEY_DEPRECATED) + #undef JSON_HEDLEY_DEPRECATED +#endif +#if defined(JSON_HEDLEY_DEPRECATED_FOR) + #undef JSON_HEDLEY_DEPRECATED_FOR +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) +#elif \ + (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) +#elif defined(__cplusplus) && (__cplusplus >= 201402L) + #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") +#else + #define JSON_HEDLEY_DEPRECATED(since) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) +#endif + +#if defined(JSON_HEDLEY_UNAVAILABLE) + #undef JSON_HEDLEY_UNAVAILABLE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) +#else + #define JSON_HEDLEY_UNAVAILABLE(available_since) +#endif + +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT +#endif +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) +#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) +#elif defined(_Check_return_) /* SAL */ + #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ +#else + #define JSON_HEDLEY_WARN_UNUSED_RESULT + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) +#endif + +#if defined(JSON_HEDLEY_SENTINEL) + #undef JSON_HEDLEY_SENTINEL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) +#else + #define JSON_HEDLEY_SENTINEL(position) +#endif + +#if defined(JSON_HEDLEY_NO_RETURN) + #undef JSON_HEDLEY_NO_RETURN +#endif +#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NO_RETURN __noreturn +#elif \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define JSON_HEDLEY_NO_RETURN _Noreturn +#elif defined(__cplusplus) && (__cplusplus >= 201103L) + #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#else + #define JSON_HEDLEY_NO_RETURN +#endif + +#if defined(JSON_HEDLEY_NO_ESCAPE) + #undef JSON_HEDLEY_NO_ESCAPE +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) + #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) +#else + #define JSON_HEDLEY_NO_ESCAPE +#endif + +#if defined(JSON_HEDLEY_UNREACHABLE) + #undef JSON_HEDLEY_UNREACHABLE +#endif +#if defined(JSON_HEDLEY_UNREACHABLE_RETURN) + #undef JSON_HEDLEY_UNREACHABLE_RETURN +#endif +#if defined(JSON_HEDLEY_ASSUME) + #undef JSON_HEDLEY_ASSUME +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_ASSUME(expr) __assume(expr) +#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) + #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) +#elif \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #if defined(__cplusplus) + #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) + #else + #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) + #endif +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() +#elif defined(JSON_HEDLEY_ASSUME) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif +#if !defined(JSON_HEDLEY_ASSUME) + #if defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) + #else + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) + #endif +#endif +#if defined(JSON_HEDLEY_UNREACHABLE) + #if \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) + #else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() + #endif +#else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) +#endif +#if !defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif + +JSON_HEDLEY_DIAGNOSTIC_PUSH +#if JSON_HEDLEY_HAS_WARNING("-Wpedantic") + #pragma clang diagnostic ignored "-Wpedantic" +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) + #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" +#endif +#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) + #if defined(__clang__) + #pragma clang diagnostic ignored "-Wvariadic-macros" + #elif defined(JSON_HEDLEY_GCC_VERSION) + #pragma GCC diagnostic ignored "-Wvariadic-macros" + #endif +#endif +#if defined(JSON_HEDLEY_NON_NULL) + #undef JSON_HEDLEY_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) +#else + #define JSON_HEDLEY_NON_NULL(...) +#endif +JSON_HEDLEY_DIAGNOSTIC_POP + +#if defined(JSON_HEDLEY_PRINTF_FORMAT) + #undef JSON_HEDLEY_PRINTF_FORMAT +#endif +#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) +#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) +#else + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) +#endif + +#if defined(JSON_HEDLEY_CONSTEXPR) + #undef JSON_HEDLEY_CONSTEXPR +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) + #endif +#endif +#if !defined(JSON_HEDLEY_CONSTEXPR) + #define JSON_HEDLEY_CONSTEXPR +#endif + +#if defined(JSON_HEDLEY_PREDICT) + #undef JSON_HEDLEY_PREDICT +#endif +#if defined(JSON_HEDLEY_LIKELY) + #undef JSON_HEDLEY_LIKELY +#endif +#if defined(JSON_HEDLEY_UNLIKELY) + #undef JSON_HEDLEY_UNLIKELY +#endif +#if defined(JSON_HEDLEY_UNPREDICTABLE) + #undef JSON_HEDLEY_UNPREDICTABLE +#endif +#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) + #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) +#elif \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, expected, probability) \ + (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ + })) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ + })) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) +#else +# define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_LIKELY(expr) (!!(expr)) +# define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) +#endif +#if !defined(JSON_HEDLEY_UNPREDICTABLE) + #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) +#endif + +#if defined(JSON_HEDLEY_MALLOC) + #undef JSON_HEDLEY_MALLOC +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_MALLOC __declspec(restrict) +#else + #define JSON_HEDLEY_MALLOC +#endif + +#if defined(JSON_HEDLEY_PURE) + #undef JSON_HEDLEY_PURE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PURE __attribute__((__pure__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) +# define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ + ) +# define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") +#else +# define JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_CONST) + #undef JSON_HEDLEY_CONST +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_CONST __attribute__((__const__)) +#elif \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_CONST _Pragma("no_side_effect") +#else + #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_RESTRICT) + #undef JSON_HEDLEY_RESTRICT +#endif +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT restrict +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + defined(__clang__) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RESTRICT __restrict +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT _Restrict +#else + #define JSON_HEDLEY_RESTRICT +#endif + +#if defined(JSON_HEDLEY_INLINE) + #undef JSON_HEDLEY_INLINE +#endif +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + (defined(__cplusplus) && (__cplusplus >= 199711L)) + #define JSON_HEDLEY_INLINE inline +#elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) + #define JSON_HEDLEY_INLINE __inline__ +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_INLINE __inline +#else + #define JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_ALWAYS_INLINE) + #undef JSON_HEDLEY_ALWAYS_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) +# define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_ALWAYS_INLINE __forceinline +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ + ) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") +#else +# define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_NEVER_INLINE) + #undef JSON_HEDLEY_NEVER_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#else + #define JSON_HEDLEY_NEVER_INLINE +#endif + +#if defined(JSON_HEDLEY_PRIVATE) + #undef JSON_HEDLEY_PRIVATE +#endif +#if defined(JSON_HEDLEY_PUBLIC) + #undef JSON_HEDLEY_PUBLIC +#endif +#if defined(JSON_HEDLEY_IMPORT) + #undef JSON_HEDLEY_IMPORT +#endif +#if defined(_WIN32) || defined(__CYGWIN__) +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC __declspec(dllexport) +# define JSON_HEDLEY_IMPORT __declspec(dllimport) +#else +# if \ + JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + ( \ + defined(__TI_EABI__) && \ + ( \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ + ) \ + ) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) +# define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) +# else +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC +# endif +# define JSON_HEDLEY_IMPORT extern +#endif + +#if defined(JSON_HEDLEY_NO_THROW) + #undef JSON_HEDLEY_NO_THROW +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NO_THROW __declspec(nothrow) +#else + #define JSON_HEDLEY_NO_THROW +#endif + +#if defined(JSON_HEDLEY_FALL_THROUGH) + #undef JSON_HEDLEY_FALL_THROUGH +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) +#elif defined(__fallthrough) /* SAL */ + #define JSON_HEDLEY_FALL_THROUGH __fallthrough +#else + #define JSON_HEDLEY_FALL_THROUGH +#endif + +#if defined(JSON_HEDLEY_RETURNS_NON_NULL) + #undef JSON_HEDLEY_RETURNS_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) +#elif defined(_Ret_notnull_) /* SAL */ + #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ +#else + #define JSON_HEDLEY_RETURNS_NON_NULL +#endif + +#if defined(JSON_HEDLEY_ARRAY_PARAM) + #undef JSON_HEDLEY_ARRAY_PARAM +#endif +#if \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(__STDC_NO_VLA__) && \ + !defined(__cplusplus) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_ARRAY_PARAM(name) (name) +#else + #define JSON_HEDLEY_ARRAY_PARAM(name) +#endif + +#if defined(JSON_HEDLEY_IS_CONSTANT) + #undef JSON_HEDLEY_IS_CONSTANT +#endif +#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) + #undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#endif +/* JSON_HEDLEY_IS_CONSTEXPR_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #undef JSON_HEDLEY_IS_CONSTEXPR_ +#endif +#if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) +#endif +#if !defined(__cplusplus) +# if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) +#endif +# elif \ + ( \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ + !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION)) || \ + (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) +#endif +# elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + defined(JSON_HEDLEY_INTEL_VERSION) || \ + defined(JSON_HEDLEY_TINYC_VERSION) || \ + defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ + defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ + defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ + defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ + defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ + defined(__clang__) +# define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ + sizeof(void) != \ + sizeof(*( \ + 1 ? \ + ((void*) ((expr) * 0L) ) : \ +((struct { char v[sizeof(void) * 2]; } *) 1) \ + ) \ + ) \ + ) +# endif +#endif +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) +#else + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) (0) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) +#endif + +#if defined(JSON_HEDLEY_BEGIN_C_DECLS) + #undef JSON_HEDLEY_BEGIN_C_DECLS +#endif +#if defined(JSON_HEDLEY_END_C_DECLS) + #undef JSON_HEDLEY_END_C_DECLS +#endif +#if defined(JSON_HEDLEY_C_DECL) + #undef JSON_HEDLEY_C_DECL +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { + #define JSON_HEDLEY_END_C_DECLS } + #define JSON_HEDLEY_C_DECL extern "C" +#else + #define JSON_HEDLEY_BEGIN_C_DECLS + #define JSON_HEDLEY_END_C_DECLS + #define JSON_HEDLEY_C_DECL +#endif + +#if defined(JSON_HEDLEY_STATIC_ASSERT) + #undef JSON_HEDLEY_STATIC_ASSERT +#endif +#if \ + !defined(__cplusplus) && ( \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ + (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + defined(_Static_assert) \ + ) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) +#elif \ + (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) +#else +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) +#endif + +#if defined(JSON_HEDLEY_NULL) + #undef JSON_HEDLEY_NULL +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) + #elif defined(NULL) + #define JSON_HEDLEY_NULL NULL + #else + #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) + #endif +#elif defined(NULL) + #define JSON_HEDLEY_NULL NULL +#else + #define JSON_HEDLEY_NULL ((void*) 0) +#endif + +#if defined(JSON_HEDLEY_MESSAGE) + #undef JSON_HEDLEY_MESSAGE +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_MESSAGE(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(message msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) +#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_WARNING) + #undef JSON_HEDLEY_WARNING +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_WARNING(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(clang warning msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_REQUIRE) + #undef JSON_HEDLEY_REQUIRE +#endif +#if defined(JSON_HEDLEY_REQUIRE_MSG) + #undef JSON_HEDLEY_REQUIRE_MSG +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) +# if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") +# define JSON_HEDLEY_REQUIRE(expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), #expr, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), msg, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) +# endif +#else +# define JSON_HEDLEY_REQUIRE(expr) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) +#endif + +#if defined(JSON_HEDLEY_FLAGS) + #undef JSON_HEDLEY_FLAGS +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) + #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) +#else + #define JSON_HEDLEY_FLAGS +#endif + +#if defined(JSON_HEDLEY_FLAGS_CAST) + #undef JSON_HEDLEY_FLAGS_CAST +#endif +#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) +# define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("warning(disable:188)") \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) +#endif + +#if defined(JSON_HEDLEY_EMPTY_BASES) + #undef JSON_HEDLEY_EMPTY_BASES +#endif +#if \ + (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) +#else + #define JSON_HEDLEY_EMPTY_BASES +#endif + +/* Remaining macros are deprecated. */ + +#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#endif +#if defined(__clang__) + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) +#else + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) + #undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#endif +#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) + +#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) + #undef JSON_HEDLEY_CLANG_HAS_FEATURE +#endif +#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) + +#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) + #undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#endif +#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) + +#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_WARNING) + #undef JSON_HEDLEY_CLANG_HAS_WARNING +#endif +#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) + +#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ + + +// This file contains all internal macro definitions (except those affecting ABI) +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them + +// #include + + +// exclude unsupported compilers +#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif +#endif + +// C++ language standard detection +// if the user manually specified the used c++ version this is skipped +#if !defined(JSON_HAS_CPP_23) && !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) + #if (defined(__cplusplus) && __cplusplus > 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG > 202002L) + #define JSON_HAS_CPP_23 + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus > 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG > 201703L) + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus > 201402L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus > 201103L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 + #endif + // the cpp 11 flag is always specified because it is the minimal required version + #define JSON_HAS_CPP_11 +#endif + +#ifdef __has_include + #if __has_include() + #include + #endif +#endif + +#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) + #ifdef JSON_HAS_CPP_17 + #if defined(__cpp_lib_filesystem) + #define JSON_HAS_FILESYSTEM 1 + #elif defined(__cpp_lib_experimental_filesystem) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif !defined(__has_include) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #endif + + // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ + #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__clang_major__) && __clang_major__ < 7 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support + #if defined(_MSC_VER) && _MSC_VER < 1914 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before iOS 13 + #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before macOS Catalina + #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + #endif +#endif + +#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_FILESYSTEM + #define JSON_HAS_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_THREE_WAY_COMPARISON + #if defined(__cpp_impl_three_way_comparison) && __cpp_impl_three_way_comparison >= 201907L \ + && defined(__cpp_lib_three_way_comparison) && __cpp_lib_three_way_comparison >= 201907L + #define JSON_HAS_THREE_WAY_COMPARISON 1 + #else + #define JSON_HAS_THREE_WAY_COMPARISON 0 + #endif +#endif + +#ifndef JSON_HAS_RANGES + // ranges header shipping in GCC 11.1.0 (released 2021-04-27) has syntax error + #if defined(__GLIBCXX__) && __GLIBCXX__ == 20210427 + #define JSON_HAS_RANGES 0 + #elif defined(__cpp_lib_ranges) + #define JSON_HAS_RANGES 1 + #else + #define JSON_HAS_RANGES 0 + #endif +#endif + +#ifndef JSON_HAS_STATIC_RTTI + #if !defined(_HAS_STATIC_RTTI) || _HAS_STATIC_RTTI != 0 + #define JSON_HAS_STATIC_RTTI 1 + #else + #define JSON_HAS_STATIC_RTTI 0 + #endif +#endif + +#ifdef JSON_HAS_CPP_17 + #define JSON_INLINE_VARIABLE inline +#else + #define JSON_INLINE_VARIABLE +#endif + +#if JSON_HEDLEY_HAS_ATTRIBUTE(no_unique_address) + #define JSON_NO_UNIQUE_ADDRESS [[no_unique_address]] +#else + #define JSON_NO_UNIQUE_ADDRESS +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdocumentation" + #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" +#endif + +// allow disabling exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) +#else + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) +#endif + +// override exception macros +#if defined(JSON_THROW_USER) + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER +#endif +#if defined(JSON_TRY_USER) + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER +#endif +#if defined(JSON_CATCH_USER) + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif + +// allow overriding assert +#if !defined(JSON_ASSERT) + #include // assert + #define JSON_ASSERT(x) assert(x) +#endif + +// allow to access some private functions (needed by the test suite) +#if defined(JSON_TESTS_PRIVATE) + #define JSON_PRIVATE_UNLESS_TESTED public +#else + #define JSON_PRIVATE_UNLESS_TESTED private +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + /* NOLINTNEXTLINE(modernize-avoid-c-arrays) we don't want to depend on */ \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + /* NOLINTNEXTLINE(modernize-avoid-c-arrays) we don't want to depend on */ \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [&j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer, \ + class BinaryType, \ + class CustomBaseClass> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// Macros to simplify conversion from/to types + +#define NLOHMANN_JSON_EXPAND( x ) x +#define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME +#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ + NLOHMANN_JSON_PASTE64, \ + NLOHMANN_JSON_PASTE63, \ + NLOHMANN_JSON_PASTE62, \ + NLOHMANN_JSON_PASTE61, \ + NLOHMANN_JSON_PASTE60, \ + NLOHMANN_JSON_PASTE59, \ + NLOHMANN_JSON_PASTE58, \ + NLOHMANN_JSON_PASTE57, \ + NLOHMANN_JSON_PASTE56, \ + NLOHMANN_JSON_PASTE55, \ + NLOHMANN_JSON_PASTE54, \ + NLOHMANN_JSON_PASTE53, \ + NLOHMANN_JSON_PASTE52, \ + NLOHMANN_JSON_PASTE51, \ + NLOHMANN_JSON_PASTE50, \ + NLOHMANN_JSON_PASTE49, \ + NLOHMANN_JSON_PASTE48, \ + NLOHMANN_JSON_PASTE47, \ + NLOHMANN_JSON_PASTE46, \ + NLOHMANN_JSON_PASTE45, \ + NLOHMANN_JSON_PASTE44, \ + NLOHMANN_JSON_PASTE43, \ + NLOHMANN_JSON_PASTE42, \ + NLOHMANN_JSON_PASTE41, \ + NLOHMANN_JSON_PASTE40, \ + NLOHMANN_JSON_PASTE39, \ + NLOHMANN_JSON_PASTE38, \ + NLOHMANN_JSON_PASTE37, \ + NLOHMANN_JSON_PASTE36, \ + NLOHMANN_JSON_PASTE35, \ + NLOHMANN_JSON_PASTE34, \ + NLOHMANN_JSON_PASTE33, \ + NLOHMANN_JSON_PASTE32, \ + NLOHMANN_JSON_PASTE31, \ + NLOHMANN_JSON_PASTE30, \ + NLOHMANN_JSON_PASTE29, \ + NLOHMANN_JSON_PASTE28, \ + NLOHMANN_JSON_PASTE27, \ + NLOHMANN_JSON_PASTE26, \ + NLOHMANN_JSON_PASTE25, \ + NLOHMANN_JSON_PASTE24, \ + NLOHMANN_JSON_PASTE23, \ + NLOHMANN_JSON_PASTE22, \ + NLOHMANN_JSON_PASTE21, \ + NLOHMANN_JSON_PASTE20, \ + NLOHMANN_JSON_PASTE19, \ + NLOHMANN_JSON_PASTE18, \ + NLOHMANN_JSON_PASTE17, \ + NLOHMANN_JSON_PASTE16, \ + NLOHMANN_JSON_PASTE15, \ + NLOHMANN_JSON_PASTE14, \ + NLOHMANN_JSON_PASTE13, \ + NLOHMANN_JSON_PASTE12, \ + NLOHMANN_JSON_PASTE11, \ + NLOHMANN_JSON_PASTE10, \ + NLOHMANN_JSON_PASTE9, \ + NLOHMANN_JSON_PASTE8, \ + NLOHMANN_JSON_PASTE7, \ + NLOHMANN_JSON_PASTE6, \ + NLOHMANN_JSON_PASTE5, \ + NLOHMANN_JSON_PASTE4, \ + NLOHMANN_JSON_PASTE3, \ + NLOHMANN_JSON_PASTE2, \ + NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) +#define NLOHMANN_JSON_PASTE2(func, v1) func(v1) +#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) +#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) +#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) +#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) +#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) +#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) +#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) +#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) +#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) +#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) +#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) +#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) +#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) +#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) +#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) +#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) +#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) +#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) +#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) +#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) +#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) +#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) +#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) +#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) +#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) +#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) +#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) +#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) +#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) +#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) +#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) +#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) +#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) +#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) +#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) +#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) +#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) +#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) +#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) +#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) +#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) +#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) +#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) +#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) +#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) +#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) +#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) +#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) +#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) +#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) +#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) +#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) +#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) +#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) +#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) +#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) +#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) +#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) +#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) +#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) +#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) +#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) + +#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; +#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); +#define NLOHMANN_JSON_FROM_WITH_DEFAULT(v1) nlohmann_json_t.v1 = !nlohmann_json_j.is_null() ? nlohmann_json_j.value(#v1, nlohmann_json_default_obj.v1) : nlohmann_json_default_obj.v1; + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE +@since version 3.9.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT +@since version 3.11.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE +@since version 3.11.3 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE +@since version 3.9.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT +@since version 3.11.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE +@since version 3.11.3 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE(Type, BaseType, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT(Type, BaseType, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE(Type, BaseType, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE(Type, BaseType, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, BaseType, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(Type, BaseType, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +// inspired from https://stackoverflow.com/a/26745591 +// allows calling any std function as if (e.g., with begin): +// using std::begin; begin(x); +// +// it allows using the detected idiom to retrieve the return type +// of such an expression +#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ + namespace detail { \ + using std::std_name; \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + } \ + \ + namespace detail2 { \ + struct std_name##_tag \ + { \ + }; \ + \ + template \ + std_name##_tag std_name(T&&...); \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + \ + template \ + struct would_call_std_##std_name \ + { \ + static constexpr auto const value = ::nlohmann::detail:: \ + is_detected_exact::value; \ + }; \ + } /* namespace detail2 */ \ + \ + template \ + struct would_call_std_##std_name : detail2::would_call_std_##std_name \ + { \ + } + +#ifndef JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_USE_IMPLICIT_CONVERSIONS 1 +#endif + +#if JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_EXPLICIT +#else + #define JSON_EXPLICIT explicit +#endif + +#ifndef JSON_DISABLE_ENUM_SERIALIZATION + #define JSON_DISABLE_ENUM_SERIALIZATION 0 +#endif + +#ifndef JSON_USE_GLOBAL_UDLS + #define JSON_USE_GLOBAL_UDLS 1 +#endif + +#if JSON_HAS_THREE_WAY_COMPARISON + #include // partial_ordering +#endif + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/////////////////////////// +// JSON type enumeration // +/////////////////////////// + +/*! +@brief the JSON type enumeration + +This enumeration collects the different JSON types. It is internally used to +distinguish the stored values, and the functions @ref basic_json::is_null(), +@ref basic_json::is_object(), @ref basic_json::is_array(), +@ref basic_json::is_string(), @ref basic_json::is_boolean(), +@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), +@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), +@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and +@ref basic_json::is_structured() rely on it. + +@note There are three enumeration entries (number_integer, number_unsigned, and +number_float), because the library distinguishes these three types for numbers: +@ref basic_json::number_unsigned_t is used for unsigned integers, +@ref basic_json::number_integer_t is used for signed integers, and +@ref basic_json::number_float_t is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. + +@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON +value with the default value for a given type + +@since version 1.0.0 +*/ +enum class value_t : std::uint8_t +{ + null, ///< null value + object, ///< object (unordered set of name/value pairs) + array, ///< array (ordered collection of values) + string, ///< string value + boolean, ///< boolean value + number_integer, ///< number value (signed integer) + number_unsigned, ///< number value (unsigned integer) + number_float, ///< number value (floating-point) + binary, ///< binary array (ordered collection of bytes) + discarded ///< discarded by the parser callback function +}; + +/*! +@brief comparison operator for JSON types + +Returns an ordering that is similar to Python: +- order: null < boolean < number < object < array < string < binary +- furthermore, each type is not smaller than itself +- discarded values are not comparable +- binary is represented as a b"" string in python and directly comparable to a + string; however, making a binary array directly comparable with a string would + be surprising behavior in a JSON file. + +@since version 1.0.0 +*/ +#if JSON_HAS_THREE_WAY_COMPARISON + inline std::partial_ordering operator<=>(const value_t lhs, const value_t rhs) noexcept // *NOPAD* +#else + inline bool operator<(const value_t lhs, const value_t rhs) noexcept +#endif +{ + static constexpr std::array order = {{ + 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, + 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, + 6 /* binary */ + } + }; + + const auto l_index = static_cast(lhs); + const auto r_index = static_cast(rhs); +#if JSON_HAS_THREE_WAY_COMPARISON + if (l_index < order.size() && r_index < order.size()) + { + return order[l_index] <=> order[r_index]; // *NOPAD* + } + return std::partial_ordering::unordered; +#else + return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; +#endif +} + +// GCC selects the built-in operator< over an operator rewritten from +// a user-defined spaceship operator +// Clang, MSVC, and ICC select the rewritten candidate +// (see GCC bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105200) +#if JSON_HAS_THREE_WAY_COMPARISON && defined(__GNUC__) +inline bool operator<(const value_t lhs, const value_t rhs) noexcept +{ + return std::is_lt(lhs <=> rhs); // *NOPAD* +} +#endif + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/*! +@brief replace all occurrences of a substring by another string + +@param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t +@param[in] f the substring to replace with @a t +@param[in] t the string to replace @a f + +@pre The search string @a f must not be empty. **This precondition is +enforced with an assertion.** + +@since version 2.0.0 +*/ +template +inline void replace_substring(StringType& s, const StringType& f, + const StringType& t) +{ + JSON_ASSERT(!f.empty()); + for (auto pos = s.find(f); // find first occurrence of f + pos != StringType::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t, and + pos = s.find(f, pos + t.size())) // find next occurrence of f + {} +} + +/*! + * @brief string escaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to escape + * @return escaped string + * + * Note the order of escaping "~" to "~0" and "/" to "~1" is important. + */ +template +inline StringType escape(StringType s) +{ + replace_substring(s, StringType{"~"}, StringType{"~0"}); + replace_substring(s, StringType{"/"}, StringType{"~1"}); + return s; +} + +/*! + * @brief string unescaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to unescape + * @return unescaped string + * + * Note the order of escaping "~1" to "/" and "~0" to "~" is important. + */ +template +static void unescape(StringType& s) +{ + replace_substring(s, StringType{"~1"}, StringType{"/"}); + replace_substring(s, StringType{"~0"}, StringType{"~"}); +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // size_t + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; + + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-FileCopyrightText: 2018 The Abseil Authors +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type +#include // index_sequence, make_index_sequence, index_sequence_for + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +using uncvref_t = typename std::remove_cv::type>::type; + +#ifdef JSON_HAS_CPP_14 + +// the following utilities are natively available in C++14 +using std::enable_if_t; +using std::index_sequence; +using std::make_index_sequence; +using std::index_sequence_for; + +#else + +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h +// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. + +//// START OF CODE FROM GOOGLE ABSEIL + +// integer_sequence +// +// Class template representing a compile-time integer sequence. An instantiation +// of `integer_sequence` has a sequence of integers encoded in its +// type through its template arguments (which is a common need when +// working with C++11 variadic templates). `absl::integer_sequence` is designed +// to be a drop-in replacement for C++14's `std::integer_sequence`. +// +// Example: +// +// template< class T, T... Ints > +// void user_function(integer_sequence); +// +// int main() +// { +// // user_function's `T` will be deduced to `int` and `Ints...` +// // will be deduced to `0, 1, 2, 3, 4`. +// user_function(make_integer_sequence()); +// } +template +struct integer_sequence +{ + using value_type = T; + static constexpr std::size_t size() noexcept + { + return sizeof...(Ints); + } +}; + +// index_sequence +// +// A helper template for an `integer_sequence` of `size_t`, +// `absl::index_sequence` is designed to be a drop-in replacement for C++14's +// `std::index_sequence`. +template +using index_sequence = integer_sequence; + +namespace utility_internal +{ + +template +struct Extend; + +// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. +template +struct Extend, SeqSize, 0> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; +}; + +template +struct Extend, SeqSize, 1> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; +}; + +// Recursion helper for 'make_integer_sequence'. +// 'Gen::type' is an alias for 'integer_sequence'. +template +struct Gen +{ + using type = + typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; +}; + +template +struct Gen +{ + using type = integer_sequence; +}; + +} // namespace utility_internal + +// Compile-time sequences of integers + +// make_integer_sequence +// +// This template alias is equivalent to +// `integer_sequence`, and is designed to be a drop-in +// replacement for C++14's `std::make_integer_sequence`. +template +using make_integer_sequence = typename utility_internal::Gen::type; + +// make_index_sequence +// +// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, +// and is designed to be a drop-in replacement for C++14's +// `std::make_index_sequence`. +template +using make_index_sequence = make_integer_sequence; + +// index_sequence_for +// +// Converts a typename pack into an index sequence of the same length, and +// is designed to be a drop-in replacement for C++14's +// `std::index_sequence_for()` +template +using index_sequence_for = make_index_sequence; + +//// END OF CODE FROM GOOGLE ABSEIL + +#endif + +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; + +// taken from ranges-v3 +template +struct static_const +{ + static JSON_INLINE_VARIABLE constexpr T value{}; +}; + +#ifndef JSON_HAS_CPP_17 + template + constexpr T static_const::value; +#endif + +template +constexpr std::array make_array(Args&& ... args) +{ + return std::array {{static_cast(std::forward(args))...}}; +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // numeric_limits +#include // char_traits +#include // tuple +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // random_access_iterator_tag + +// #include + +// #include + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +struct iterator_types {}; + +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; +}; + +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits +{ +}; + +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types +{ +}; + +template +struct iterator_traits::value>> +{ + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); + +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); + +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ + #define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + #include // int64_t, uint64_t + #include // map + #include // allocator + #include // string + #include // vector + + // #include + + + /*! + @brief namespace for Niels Lohmann + @see https://github.com/nlohmann + @since version 1.0.0 + */ + NLOHMANN_JSON_NAMESPACE_BEGIN + + /*! + @brief default JSONSerializer template argument + + This serializer ignores the template arguments and uses ADL + ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) + for serialization. + */ + template + struct adl_serializer; + + /// a class to store JSON values + /// @sa https://json.nlohmann.me/api/basic_json/ + template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector, // cppcheck-suppress syntaxError + class CustomBaseClass = void> + class basic_json; + + /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document + /// @sa https://json.nlohmann.me/api/json_pointer/ + template + class json_pointer; + + /*! + @brief default specialization + @sa https://json.nlohmann.me/api/json/ + */ + using json = basic_json<>; + + /// @brief a minimal map-like container that preserves insertion order + /// @sa https://json.nlohmann.me/api/ordered_map/ + template + struct ordered_map; + + /// @brief specialization that maintains the insertion order of object keys + /// @sa https://json.nlohmann.me/api/ordered_json/ + using ordered_json = basic_json; + + NLOHMANN_JSON_NAMESPACE_END + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + +NLOHMANN_JSON_NAMESPACE_BEGIN +/*! +@brief detail namespace with internal helper functions + +This namespace collects functions that should not be exposed, +implementations of some @ref basic_json methods, and meta-programming helpers. + +@since version 2.1.0 +*/ +namespace detail +{ + +///////////// +// helpers // +///////////// + +// Note to maintainers: +// +// Every trait in this file expects a non CV-qualified type. +// The only exceptions are in the 'aliases for detected' section +// (i.e. those of the form: decltype(T::member_function(std::declval()))) +// +// In this case, T has to be properly CV-qualified to constraint the function arguments +// (e.g. to_json(BasicJsonType&, const T&)) + +template struct is_basic_json : std::false_type {}; + +NLOHMANN_BASIC_JSON_TPL_DECLARATION +struct is_basic_json : std::true_type {}; + +// used by exceptions create() member functions +// true_type for pointer to possibly cv-qualified basic_json or std::nullptr_t +// false_type otherwise +template +struct is_basic_json_context : + std::integral_constant < bool, + is_basic_json::type>::type>::value + || std::is_same::value > +{}; + +////////////////////// +// json_ref helpers // +////////////////////// + +template +class json_ref; + +template +struct is_json_ref : std::false_type {}; + +template +struct is_json_ref> : std::true_type {}; + +////////////////////////// +// aliases for detected // +////////////////////////// + +template +using mapped_type_t = typename T::mapped_type; + +template +using key_type_t = typename T::key_type; + +template +using value_type_t = typename T::value_type; + +template +using difference_type_t = typename T::difference_type; + +template +using pointer_t = typename T::pointer; + +template +using reference_t = typename T::reference; + +template +using iterator_category_t = typename T::iterator_category; + +template +using to_json_function = decltype(T::to_json(std::declval()...)); + +template +using from_json_function = decltype(T::from_json(std::declval()...)); + +template +using get_template_function = decltype(std::declval().template get()); + +// trait checking if JSONSerializer::from_json(json const&, udt&) exists +template +struct has_from_json : std::false_type {}; + +// trait checking if j.get is valid +// use this trait instead of std::is_constructible or std::is_convertible, +// both rely on, or make use of implicit conversions, and thus fail when T +// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) +template +struct is_getable +{ + static constexpr bool value = is_detected::value; +}; + +template +struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if JSONSerializer::from_json(json const&) exists +// this overload is used for non-default-constructible user-defined-types +template +struct has_non_default_from_json : std::false_type {}; + +template +struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if BasicJsonType::json_serializer::to_json exists +// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. +template +struct has_to_json : std::false_type {}; + +template +struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +template +using detect_key_compare = typename T::key_compare; + +template +struct has_key_compare : std::integral_constant::value> {}; + +// obtains the actual object key comparator +template +struct actual_object_comparator +{ + using object_t = typename BasicJsonType::object_t; + using object_comparator_t = typename BasicJsonType::default_object_comparator_t; + using type = typename std::conditional < has_key_compare::value, + typename object_t::key_compare, object_comparator_t>::type; +}; + +template +using actual_object_comparator_t = typename actual_object_comparator::type; + +///////////////// +// char_traits // +///////////////// + +// Primary template of char_traits calls std char_traits +template +struct char_traits : std::char_traits +{}; + +// Explicitly define char traits for unsigned char since it is not standard +template<> +struct char_traits : std::char_traits +{ + using char_type = unsigned char; + using int_type = uint64_t; + + // Redefine to_int_type function + static int_type to_int_type(char_type c) noexcept + { + return static_cast(c); + } + + static char_type to_char_type(int_type i) noexcept + { + return static_cast(i); + } + + static constexpr int_type eof() noexcept + { + return static_cast(std::char_traits::eof()); + } +}; + +// Explicitly define char traits for signed char since it is not standard +template<> +struct char_traits : std::char_traits +{ + using char_type = signed char; + using int_type = uint64_t; + + // Redefine to_int_type function + static int_type to_int_type(char_type c) noexcept + { + return static_cast(c); + } + + static char_type to_char_type(int_type i) noexcept + { + return static_cast(i); + } + + static constexpr int_type eof() noexcept + { + return static_cast(std::char_traits::eof()); + } +}; + +/////////////////// +// is_ functions // +/////////////////// + +// https://en.cppreference.com/w/cpp/types/conjunction +template struct conjunction : std::true_type { }; +template struct conjunction : B { }; +template +struct conjunction +: std::conditional(B::value), conjunction, B>::type {}; + +// https://en.cppreference.com/w/cpp/types/negation +template struct negation : std::integral_constant < bool, !B::value > { }; + +// Reimplementation of is_constructible and is_default_constructible, due to them being broken for +// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). +// This causes compile errors in e.g. clang 3.5 or gcc 4.9. +template +struct is_default_constructible : std::is_default_constructible {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_constructible : std::is_constructible {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_iterator_traits : std::false_type {}; + +template +struct is_iterator_traits> +{ + private: + using traits = iterator_traits; + + public: + static constexpr auto value = + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value; +}; + +template +struct is_range +{ + private: + using t_ref = typename std::add_lvalue_reference::type; + + using iterator = detected_t; + using sentinel = detected_t; + + // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator + // and https://en.cppreference.com/w/cpp/iterator/sentinel_for + // but reimplementing these would be too much work, as a lot of other concepts are used underneath + static constexpr auto is_iterator_begin = + is_iterator_traits>::value; + + public: + static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; +}; + +template +using iterator_t = enable_if_t::value, result_of_begin())>>; + +template +using range_value_t = value_type_t>>; + +// The following implementation of is_complete_type is taken from +// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ +// and is written by Xiang Fan who agreed to using it in this library. + +template +struct is_complete_type : std::false_type {}; + +template +struct is_complete_type : std::true_type {}; + +template +struct is_compatible_object_type_impl : std::false_type {}; + +template +struct is_compatible_object_type_impl < + BasicJsonType, CompatibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + // macOS's is_constructible does not play well with nonesuch... + static constexpr bool value = + is_constructible::value && + is_constructible::value; +}; + +template +struct is_compatible_object_type + : is_compatible_object_type_impl {}; + +template +struct is_constructible_object_type_impl : std::false_type {}; + +template +struct is_constructible_object_type_impl < + BasicJsonType, ConstructibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + static constexpr bool value = + (is_default_constructible::value && + (std::is_move_assignable::value || + std::is_copy_assignable::value) && + (is_constructible::value && + std::is_same < + typename object_t::mapped_type, + typename ConstructibleObjectType::mapped_type >::value)) || + (has_from_json::value || + has_non_default_from_json < + BasicJsonType, + typename ConstructibleObjectType::mapped_type >::value); +}; + +template +struct is_constructible_object_type + : is_constructible_object_type_impl {}; + +template +struct is_compatible_string_type +{ + static constexpr auto value = + is_constructible::value; +}; + +template +struct is_constructible_string_type +{ + // launder type through decltype() to fix compilation failure on ICPC +#ifdef __INTEL_COMPILER + using laundered_type = decltype(std::declval()); +#else + using laundered_type = ConstructibleStringType; +#endif + + static constexpr auto value = + conjunction < + is_constructible, + is_detected_exact>::value; +}; + +template +struct is_compatible_array_type_impl : std::false_type {}; + +template +struct is_compatible_array_type_impl < + BasicJsonType, CompatibleArrayType, + enable_if_t < + is_detected::value&& + is_iterator_traits>>::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 + !std::is_same>::value >> +{ + static constexpr bool value = + is_constructible>::value; +}; + +template +struct is_compatible_array_type + : is_compatible_array_type_impl {}; + +template +struct is_constructible_array_type_impl : std::false_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t::value >> + : std::true_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t < !std::is_same::value&& + !is_compatible_string_type::value&& + is_default_constructible::value&& +(std::is_move_assignable::value || + std::is_copy_assignable::value)&& +is_detected::value&& +is_iterator_traits>>::value&& +is_detected::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 +!std::is_same>::value&& +is_complete_type < +detected_t>::value >> +{ + using value_type = range_value_t; + + static constexpr bool value = + std::is_same::value || + has_from_json::value || + has_non_default_from_json < + BasicJsonType, + value_type >::value; +}; + +template +struct is_constructible_array_type + : is_constructible_array_type_impl {}; + +template +struct is_compatible_integer_type_impl : std::false_type {}; + +template +struct is_compatible_integer_type_impl < + RealIntegerType, CompatibleNumberIntegerType, + enable_if_t < std::is_integral::value&& + std::is_integral::value&& + !std::is_same::value >> +{ + // is there an assert somewhere on overflows? + using RealLimits = std::numeric_limits; + using CompatibleLimits = std::numeric_limits; + + static constexpr auto value = + is_constructible::value && + CompatibleLimits::is_integer && + RealLimits::is_signed == CompatibleLimits::is_signed; +}; + +template +struct is_compatible_integer_type + : is_compatible_integer_type_impl {}; + +template +struct is_compatible_type_impl: std::false_type {}; + +template +struct is_compatible_type_impl < + BasicJsonType, CompatibleType, + enable_if_t::value >> +{ + static constexpr bool value = + has_to_json::value; +}; + +template +struct is_compatible_type + : is_compatible_type_impl {}; + +template +struct is_constructible_tuple : std::false_type {}; + +template +struct is_constructible_tuple> : conjunction...> {}; + +template +struct is_json_iterator_of : std::false_type {}; + +template +struct is_json_iterator_of : std::true_type {}; + +template +struct is_json_iterator_of : std::true_type +{}; + +// checks if a given type T is a template specialization of Primary +template