am-freescan/integrations/freescan-service/src/sdk_worker.cpp

2798 lines
136 KiB
C++
Raw Normal View History

#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 <objidl.h>
#include <gdiplus.h>
#include <tlhelp32.h>
#include <future>
#include <sstream>
#include <iomanip>
#include <regex>
#include <deque>
#include <cmath>
#include <cstring>
#include <cwctype>
#include <limits>
#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<char>(std::tolower(static_cast<unsigned char>(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<wchar_t> b(32768);
DWORD n = GetModuleFileNameW(nullptr, b.data(), static_cast<DWORD>(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<char>(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<std::streamsize>(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<Sn3dPointData> points(const Json &body, const char *key) {
std::vector<Sn3dPointData> out;
if (!body.contains(key))
return out;
for (const auto &p : body.at(key))
out.push_back({p.at(0).get<float>(), p.at(1).get<float>(), p.at(2).get<float>()});
return out;
}
std::vector<int64_t> ids(const Json &body, const char *key) {
if (!body.contains(key))
return {};
return body.at(key).get<std::vector<int64_t>>();
}
std::string failure(const Json &j) {
if (!j.is_object())
return {};
if (j.contains("success") && j["success"].is_boolean() && !j["success"].get<bool>())
return "success=false";
if (j.contains("result")) {
const auto &r = j["result"];
if (r.is_string()) {
auto s = lower(r.get<std::string>());
if (!s.empty() && s != "success" && s != "ok" && s != "0")
return "result=" + r.get<std::string>();
} else if (r.is_boolean() && !r.get<bool>())
return "result=false";
else if (r.is_number_integer() && r.get<int64_t>() != 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<std::string>()) : j[k].get<int64_t>();
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<std::string> parameter_fields = {"pointDistance", "brightness", "lightSourceMode",
"scanFrameRate", "highSpeedMode", "addMarkerMode",
"viewLock", "localEnlargedView", "qualityColor",
"strongLight", "preScanMode", "markerDiameters"};
const std::vector<std::string> unsupported = {"frameworkBrightness", "cloudShowMode", "scanAlignType",
"workingDistance", "workingRange"};
const std::vector<std::string> 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<Impl> {
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<bool> 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<std::shared_ptr<void>> retained;
struct Pending {
std::mutex mutex;
std::condition_variable cv;
std::set<std::string> names;
bool done = false;
std::string error;
Json reply = nullptr;
};
std::vector<std::shared_ptr<Pending>> 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<uint64_t> sceneNotifications{0};
std::atomic<int64_t> lastSceneNotificationMs{0};
std::shared_ptr<SceneRequest> 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<FrameSnapshot> 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<uint8_t> storage(bytes);
auto *codecs = reinterpret_cast<Gdiplus::ImageCodecInfo *>(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<std::shared_ptr<Impl>>;
static auto *mutex = new std::mutex;
std::lock_guard<std::mutex> guard(*mutex);
roots->push_back(shared_from_this());
}
template <class T> std::shared_ptr<T> keep(T value) {
auto p = std::make_shared<T>(std::move(value));
std::lock_guard<std::mutex> guard(retainedGate);
retained.push_back(p);
return p;
}
const char *text(const std::string &value) {
return keep(value)->c_str();
}
template <class T> T *array_ptr(const std::shared_ptr<std::vector<T>> &p) {
return p->empty() ? nullptr : p->data();
}
void flag_timeout(const std::string &message) {
std::lock_guard<std::mutex> 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<std::string, std::string> 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 <class T> 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<T>(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<unsigned int>(code);
throw ApiError(502, "sdk_error", s.str());
}
}
int native(const std::string &name, std::function<int()> 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<std::promise<int>>();
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<Pending> expect(const std::string &names) {
auto p = std::make_shared<Pending>();
std::istringstream stream(names);
std::string name;
while (std::getline(stream, name, '|'))
p->names.insert(name);
std::lock_guard<std::mutex> guard(ackGate);
pending.push_back(p);
return p;
}
void forget(const std::shared_ptr<Pending> &p) {
if (!p)
return;
std::lock_guard<std::mutex> guard(ackGate);
pending.erase(std::remove(pending.begin(), pending.end(), p), pending.end());
}
Json wait(const std::shared_ptr<Pending> &p, int timeout, const std::string &name) {
std::unique_lock<std::mutex> 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<int()> 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<Sync>(api + "Sync");
native(api + "Sync", [this, fn] { return fn(service, 30000); });
return nullptr;
} else {
auto fn = function<Async>(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<Sync>(api + "Sync");
native(api + "Sync", [this, fn, value] { return fn(service, value, 30000); });
} else {
auto fn = function<Fn>(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<int(WINAPI *)(void *, bool)>(api);
command(api, completion, [this, fn, value] { return fn(service, value); });
}
template <class T>
void pointer_command(const std::string &api, const std::string &completion, const std::shared_ptr<T> &p,
int timeout = 120000) {
auto fn = function<int(WINAPI *)(void *, T *)>(api);
command(api, completion, [this, fn, p] { return fn(service, p.get()); }, timeout);
}
bool enter_callback() {
std::lock_guard<std::mutex> guard(callbackGate);
if (disposed || retiring)
return false;
callbacks++;
return true;
}
void leave_callback() {
std::lock_guard<std::mutex> guard(callbackGate);
callbacks--;
callbackDone.notify_all();
}
static void CALLBACK message_callback(int, int, void *data, size_t size, void *owner) {
auto *self = static_cast<Impl *>(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<Impl *>(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<Impl *>(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<char *>(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<std::string>();
auto error = failure(j);
{
std::lock_guard<std::mutex> guard(state);
if(attempted&&!retiring&&!disposed&&!restart&&!sessionId.empty())calibrationTelemetry.observe(j,unix_ms());
}
if (name == "sdkDeviceStatus" && error.empty()) {
std::lock_guard<std::mutex> 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<std::string>())
: d["scanMode"].get<int>();
std::lock_guard<std::mutex> 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<std::shared_ptr<Pending>> list;
{
std::lock_guard<std::mutex> guard(ackGate);
list = pending;
}
for (auto &item : list) {
const auto completion = detail::sdk_completion(item->names, j, error);
if (completion.done) {
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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, &params) != 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<FrameSnapshot>();
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<ULONG>(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<double, std::milli>(Clock::now() - started).count();
std::lock_guard<std::mutex> guard(frameGate);
if (image->epoch == frameEpoch && !disposed) {
value->sequence = ++sequence;
encoded++;
encodeTotal += value->encodeMs;
latest = std::move(value);
}
} catch (...) {
std::lock_guard<std::mutex> guard(frameGate);
encodeFailures++;
}
}
CoUninitialize();
}
void simulated_frame() {
bool enabled;
{
std::lock_guard<std::mutex> guard(state);
enabled = initialized && preview && projectReady;
}
if (!enabled)
return;
const int w = 640, h = 360;
std::vector<uint8_t> 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<DWORD> service_processes(bool requireExpectedPath) {
std::vector<DWORD> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<fs::path> candidates;
if (config.contains("bridgePath") && config["bridgePath"].is_string())
candidates.emplace_back(wide(config["bridgePath"].get<std::string>()));
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<BridgeInt>(get("FSB_GetAbiVersion")),
size = reinterpret_cast<BridgeInt>(get("FSB_GetSceneStructSize"));
if (!abi || !size || abi() != 1 || size() != 608) {
bridgeReason = "Native bridge ABI is incompatible.";
return;
}
capture = reinterpret_cast<BridgeCapture>(get("FSB_Capture"));
summary = reinterpret_cast<BridgeSummary>(get("FSB_GetSummary"));
writeSnapshot = reinterpret_cast<BridgeWrite>(get("FSB_WriteSnapshot"));
clearScene = reinterpret_cast<BridgeClear>(get("FSB_Clear"));
bridgeError = reinterpret_cast<BridgeError>(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<wchar_t> 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<std::mutex> 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<std::mutex> guard(state);
attempted = true;
battery.clear();
deviceType = type;
sessionId = new_id();
calibrationTelemetry.clear();calibrationId.clear();calibrationViewError.clear();calibrationViewMessage.clear();
}
if (simulated) {
std::lock_guard<std::mutex> guard(state);
service = reinterpret_cast<void *>(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<LogSettingLevel>(2);
startup->windowVis = false;
startup->clearService = false;
startup->sdk_performanceLevel = static_cast<ConfigLevel>(1);
fs::create_directories(root / L"Logs" / L"SDK");
auto set = function<int(WINAPI *)(const Sn3DStartupConfig &)>("Sn3DSetStartupParam");
native("Sn3DSetStartupParam", [set, startup] { return set(*startup); });
auto p = expect("initializeFinish|sdkInitializeFinish|InitializeFinish");
try {
auto init = function<int(WINAPI *)(void **, int)>("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<int(WINAPI *)(void *, SDKCORE_CALLBACK, void *)>("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<std::mutex> guard(state);
initialized = true;
}
poll_online();
{
std::lock_guard<std::mutex> 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<std::mutex> guard(state);
initialized = false;
uncertain = restart = true;
battery.clear();
throw;
}
}
void poll_online() {
if (simulated) {
std::lock_guard<std::mutex> guard(state);
online = true;
onlineChecked = unix_ms();
return;
}
ready();
auto data = keep(DeviceStatus{});
auto fn = function<int(WINAPI *)(void *, DeviceStatus *)>("Sn3DGetDeviceStatus");
native("Sn3DGetDeviceStatus", [this, fn, data] { return fn(service, data.get()); }, 5000);
std::lock_guard<std::mutex> 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<std::mutex> op(operation, std::try_to_lock);
if (op.owns_lock()) {
bool active;
{
std::lock_guard<std::mutex> 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<std::mutex> guard(state, std::try_to_lock);
if (guard.owns_lock()) {
std::unique_lock<std::mutex> 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<int64_t>(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<std::mutex> guard(state);
if (preview)
return;
}
if (!simulated) {
if (address("Sn3DRegisterDataCallback")) {
auto f = function<int(WINAPI *)(Sn3DSceneDataCallBack, void *)>("Sn3DRegisterDataCallback");
native("Sn3DRegisterDataCallback", [this, f] { return f(scene_callback, this); }, 15000);
}
if (address("Sn3DSetRealtimeScanDataMode"))
int_command("Sn3DSetRealtimeScanDataMode", "", 1);
auto f = function<int(WINAPI *)(void *, Sn3DOffscreenRenderCallback, void *)>(
"Sn3DRegisterOffscreenRenderCallback");
native(
"Sn3DRegisterOffscreenRenderCallback",
[this, f] { return f(service, render_callback, this); }, 15000);
}
{
std::lock_guard<std::mutex> guard(state);
preview = true;
}
try {
if (!simulated) {
auto f = function<int(WINAPI *)()>("Sn3DStartOffscreenRender");
native("Sn3DStartOffscreenRender", [f] { return f(); }, 15000);
}
} catch (...) {
{
std::lock_guard<std::mutex> guard(state);
preview = false;
}
clear_frames();
throw;
}
}
void stop_preview(int timeout = 15000) {
bool enabled;
{
std::lock_guard<std::mutex> guard(state);
enabled = preview;
}
if (enabled && !simulated) {
auto f = function<int(WINAPI *)()>("Sn3DStopOffscreenRender");
native("Sn3DStopOffscreenRender", [f] { return f(); }, timeout);
}
{
std::lock_guard<std::mutex> guard(state);
preview = false;
}
clear_frames();
}
void pause() {
ready();
if (!simulated)
service_command("Sn3DPauseScan", "pauseScanFinish|pauseScanFinish1", 30000, true);
std::lock_guard<std::mutex> 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<std::mutex> guard(state);
if (body.contains("expectedSessionId")) {
std::string expected =
body["expectedSessionId"].is_null() ? "" : body["expectedSessionId"].get<std::string>();
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<std::string>();
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<std::mutex> 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<std::mutex> guard(ackGate);
if (!pending.empty())
throw ApiError(409, "device_busy", "An SDK completion is still pending.");
}
retiring = true;
calibrationCapture.stop();
{
std::lock_guard<std::mutex> 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<std::chrono::milliseconds>(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<std::mutex> 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<int(WINAPI *)(void **)>("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<std::mutex> 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<fs::path> 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<std::mutex> 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<std::mutex> 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<IrScanSubMode>(0);
value->irParams.irAlignType = static_cast<AlignType>(100);
value->irParams.irPointDis = 1.0f;
if (address("Sn3DCreateProjectSync")) {
auto f = function<int(WINAPI *)(void *, ProjectInfo *, int)>("Sn3DCreateProjectSync");
native("Sn3DCreateProjectSync", [this, f, value] { return f(service, value.get(), 30000); });
} else
pointer_command("Sn3DCreateProject", "createProjectFinish", value, 30000);
}
{
std::lock_guard<std::mutex> 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<std::mutex> guard(state);
scanDevice = "scanner";
}
if (!simulated)
int_command("Sn3DSetScanType", "setScanTypeFinish", SNSDK_SCANTYPE_POINTCLOUD, 30000);
{
std::lock_guard<std::mutex> 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<std::mutex> guard(state);
if (restart)
throw;
}
std::lock_guard<std::mutex> 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>();
std::string requestedDevice;
bool deviceChanged, already;
{
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::string>());
auto pinnedFiles = keep(std::vector<Handle>());
for (const auto &item : body.at("fileIds")) {
const auto id = item.get<std::string>();
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<const char *>());
for (const auto &name : *fileNames)
pointers->push_back(name.c_str());
if (!simulated) {
auto fn = function<int(WINAPI *)(void *, const char **, int)>("Sn3DImportGlobalMarkers");
command("Sn3DImportGlobalMarkers", "importGlobalMarkersFinish",
[this, fn, pointers, fileNames, pinnedFiles] {
return fn(service, pointers->data(), static_cast<int>(pointers->size()));
});
}
pinnedFiles->clear(); // SDK completion confirmed; no write/delete lock is needed afterwards.
{
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> 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<int(WINAPI *)(void *, float)>("Sn3DSetPointDistance");
float value = v.get<float>();
command(
"Sn3DSetPointDistance", "setPointDistanceFinish",
[this, f, value] { return f(service, value); }, 120000);
} else if (key == "markerDiameters") {
auto data = keep(v.get<std::vector<int>>());
auto f = function<int(WINAPI *)(void *, const int *, int)>("Sn3DSetMarkerDiameterType");
command("Sn3DSetMarkerDiameterType", "setMarkerDiameterTypeFinish", [this, f, data] {
return f(service, data->data(), static_cast<int>(data->size()));
});
} else if (key == "brightness")
int_command("Sn3DSetScanMeshBrightnessLevel", "setScanMeshBrightnessLevelFinish",
v.get<int>());
else if (key == "lightSourceMode")
int_command("Sn3DSetLightSourceMode", "setLightSourceModeFinish", v.get<int>());
else if (key == "scanFrameRate")
int_command("Sn3DSetScanFrameRate", "", v.get<int>());
else {
static const std::map<std::string, std::pair<std::string, std::string>> 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<bool>());
}
}
std::lock_guard<std::mutex> 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<FilterLevel>(b.value("filterLevel", 0));
p->smooth_level = static_cast<SmoothLevel>(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<int>();
}
if (b.contains("fillSmallHole") && !b["fillSmallHole"].is_null()) {
p->fill_small_hole_ischeck = 1;
p->fill_small_hole_value = b["fillSmallHole"].get<int>();
}
pointer_command("Sn3DMesh", "meshFinish", p, 300000);
}
std::lock_guard<std::mutex> 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<std::vector<std::string>>();
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<std::string> 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<std::mutex> 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<std::string>();
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<std::string> modes = {"featureAuto", "markerAuto", "featureManual",
"markerManual"};
auto mode = body.at("mode").get<std::string>();
p->alignType = static_cast<AlignType>(
std::distance(modes.begin(), std::find(modes.begin(), modes.end(), mode)));
p->fixKey = text(guid_d(body.at("fixedProjectUuid").get<std::string>()));
p->floatKey = text(guid_d(body.at("movingProjectUuid").get<std::string>()));
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<int>(fixed->size());
p->v_fixPos = array_ptr(fixed);
p->v_floatPosCount = static_cast<int>(moving->size());
p->v_floatPos = array_ptr(moving);
p->fixMarkerCount = static_cast<int>(fixedIds->size());
p->fixMarkerId = array_ptr(fixedIds);
p->fixMarkerPos = array_ptr(fixedMarkers);
p->floatMarkerCount = static_cast<int>(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<std::string>()));
if (body.contains("cloudUuid"))
p->cloudUuid = text(guid_d(body.at("cloudUuid").get<std::string>()));
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<std::mutex> 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<int(WINAPI *)(void *,bool,int)>("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<std::mutex> guard(state);
calibrationViewError=error.code;calibrationViewMessage=error.what();
}catch(const std::exception &error){
std::lock_guard<std::mutex> guard(state);
calibrationViewError="calibration_window_unavailable";calibrationViewMessage=error.what();
}
}
Json calibration_view(bool includeFrame) {
std::lock_guard<std::mutex> 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<std::string>().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<std::mutex> 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<std::mutex> guard(state);
calibrationId.clear();calibrationTelemetry.progress=nullptr;
}
int nextMode, nextTrak;
{
std::lock_guard<std::mutex> guard(state);
nextMode = calibrationMode;
nextTrak = trakType;
}
if (action == "calibrationSetMode" || action == "calibrationApplyLast")
nextMode = body.at("mode").get<int>();
if (action == "calibrationSetTrakType")
nextTrak = body.at("trakType").get<int>();
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<bool>());
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<bool>());
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<std::mutex> guard(state);
calibrationMode = nextMode;
trakType = nextTrak;
calibrationAction = action.substr(11);
if (!calibrationAction.empty())
calibrationAction[0] =
static_cast<char>(std::tolower(static_cast<unsigned char>(calibrationAction[0])));
calibrationActive = true;
if (action == "calibrationStartSystem")
calibrationSystemStarted = true;
if (action == "calibrationSetFree")
calibrationFreeEnabled = body.at("enabled").get<bool>();
}
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<SceneRequest> request;
{
std::lock_guard<std::mutex> 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<std::mutex> 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<char> buffer(8192);
for (int n = 0; n < 2; n++) {
int code = summary(buffer.data(), static_cast<int>(buffer.size()));
if (!code)
return Json::parse(buffer.data());
if (code < 0 && code >= -1048576) {
buffer.resize(static_cast<size_t>(-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<SceneRequest>();
request->maximum = maximum;
request->pauseAcquisition = pauseAcquisition;
for (const auto &item : included) {
auto name = item.get<std::string>();
request->mask |= name == "points" ? 1 : name == "markers" ? 2 : 4;
}
{
std::lock_guard<std::mutex> guard(sceneGate);
if (sceneRequest || sceneRunning)
throw ApiError(409, "snapshot_busy", "Previous scene copy is still running.");
sceneRequest = request;
}
bool restore;
{
std::lock_guard<std::mutex> guard(state);
restore = preview;
}
bool modeRequested = false;
std::exception_ptr error;
try {
detail::capture_scene_snapshot(
pauseAcquisition,
[&] {
auto f = function<int(WINAPI *)(Sn3DSceneDataCallBack, void *)>(
"Sn3DRegisterDataCallback");
native("Sn3DRegisterDataCallback", [this, f] { return f(scene_callback, this); });
modeRequested = true;
int_command("Sn3DSetRealtimeScanDataMode", "setRealtimeScanDataModeFinish", 0, 10000);
},
[&] {
bool active;
{
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> guard(sceneGate);
request->finished = true;
if (!request->running && sceneRequest == request)
sceneRequest.reset();
}
bool safe;
{
std::lock_guard<std::mutex> 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<std::mutex> guard(state);
return {{"files", list},
{"maxPoints", maximum},
{"include", included},
{"projectId", projectId},
{"pauseAcquisition", pauseAcquisition},
{"scanning", scanning}};
}
Json metrics() {
std::lock_guard<std::mutex> 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<int64_t>(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<std::mutex> guard(state);
std::lock_guard<std::mutex> image(frameGate);
const bool active = initialized && !restart && !disposed && !retiring;
auto now = unix_ms();
const bool hasAge = lastFrameMs > 0;
const auto age = hasAge ? std::max<int64_t>(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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> guard(state);
already = preview == enabled;
}
if (enabled)
start_preview();
else
stop_preview();
std::lock_guard<std::mutex> guard(state);
return {{"previewEnabled", preview},
{"alreadyInRequestedState", already},
{"scanning", scanning},
{"projectPreserved", true}};
}
if (action == "startScan") {
require_project(false);
bool already;
{
std::lock_guard<std::mutex> 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<std::mutex> guard(state);
if (online.is_boolean() && !online.get<bool>())
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<std::mutex> guard(state);
scanning = true;
acquisitionEverStarted = true;
if (scanType == "photogrammetry") {
frameworkCaptureStarted = true;
frameworkOptimized = false;
}
}
std::lock_guard<std::mutex> guard(state);
return {{"scanning", scanning}, {"alreadyScanning", already}, {"projectId", projectId}};
}
if (action == "stopScan") {
ready();
{
std::lock_guard<std::mutex> guard(state);
if (!projectReady && !uncertain)
throw ApiError(409, "project_required", "Create a project first.");
}
pause();
std::lock_guard<std::mutex> 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<std::mutex> guard(state);
if (meshState != "preview")
throw ApiError(409, "mesh_required", "Complete mesh processing before confirmation.");
}
if (!simulated)
service_command("Sn3DConfirmMesh", "confirmMeshFinish");
{
std::lock_guard<std::mutex> guard(state);
meshState = "confirmed";
}
return {{"meshState", "confirmed"}};
}
if (action == "meshUndo") {
{
std::lock_guard<std::mutex> 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<std::mutex> guard(state);
meshState = "none";
}
return {{"meshState", "none"}};
}
if (action == "export") {
bool frameworkExport;
{
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> 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<bool> &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<Impl>(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<std::mutex> 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<std::mutex> 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<bool> &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<std::mutex> 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<std::mutex> 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<std::mutex> lock(impl_->state);
return impl_->registered;
}
Json WorkerService::calibration_view(bool includeFrame) {return impl_->calibration_view(includeFrame);}
Json WorkerService::frame() {
std::shared_ptr<FrameSnapshot> latest;
{
std::lock_guard<std::mutex> 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<std::mutex> op(impl_->operation, std::try_to_lock);
if (!op.owns_lock() || impl_->busy || impl_->nativeRunning || impl_->sceneRunning)
return false;
std::lock_guard<std::mutex> lock(impl_->state);
return shutdown || (!impl_->initialized && !impl_->service);
}
void WorkerService::shutdown() {
impl_->shutdown_all();
}
} // namespace freescan