#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; } }