am-freescan/integrations/freescan-service/src/supervisor.cpp
Codex a16f16e19a feat(scanner): show native calibration window and SDK progress
Use the existing successful calibration-enter workflow to display the same SDK manufacturer's window and actual callback progress in the task UI. Bind metadata, JPEG and MJPEG to the execution, SDK session, calibration ID and trusted process/window identity; closing the monitor only stops viewing.

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

Validated platform Java compilation/regressions, frontend type checks and standalone build, native compilation/offline and HTTP regressions, immediate calibration identity checks and ten synthetic window close/reopen cycles. Production installation/restart and real scanner calibration remain pending.
2026-11-21 19:52:07 +08:00

1366 lines
68 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "supervisor.hpp"
#include "sdk_worker.hpp"
#include "contracts.hpp"
#include "device_battery.hpp"
#include "auto_connection.hpp"
#include "sdk_location.hpp"
#include "calibration_files.hpp"
#include "calibration_recovery.hpp"
#include <objbase.h>
#include <sstream>
#include <iostream>
namespace freescan {
namespace {
uint64_t process_started(HANDLE handle) {
FILETIME start{}, end{}, kernel{}, user{};
if (!GetProcessTimes(handle, &start, &end, &kernel, &user))
throw ApiError(503, "process_identity_error", "无法核验进程启动时间。");
ULARGE_INTEGER ticks{};
ticks.LowPart = start.dwLowDateTime;
ticks.HighPart = start.dwHighDateTime;
return ticks.QuadPart;
}
fs::path executable() {
std::vector<wchar_t> value(32768);
DWORD size = GetModuleFileNameW(nullptr, value.data(), static_cast<DWORD>(value.size()));
if (!size || size >= value.size())
throw ApiError(500, "executable_path_error", "无法确定程序路径。");
return fs::path(std::wstring(value.data(), size));
}
std::wstring quoted(const std::wstring &value) {
if (value.find(L'"') != std::wstring::npos)
throw ApiError(500, "invalid_path", "启动路径不能含双引号。");
return L"\"" + value + L"\"";
}
bool exited(HANDLE process) {
return process && WaitForSingleObject(process, 0) == WAIT_OBJECT_0;
}
void verify_process_identity(HANDLE handle, DWORD pid, uint64_t started, const fs::path &expected) {
wchar_t image[32768]{};
DWORD length = 32768;
if (!handle || !pid || pid == GetCurrentProcessId() || GetProcessId(handle) != pid ||
process_started(handle) != started ||
!QueryFullProcessImageNameW(handle, 0, image, &length) ||
_wcsicmp(fs::absolute(expected).lexically_normal().c_str(),
fs::absolute(fs::path(std::wstring(image, length))).lexically_normal().c_str()) != 0)
throw ApiError(503, "recovery_identity_unverified", "旧进程身份无法核验,未启动第二个SDK后台。");
}
Handle duplicate_process(HANDLE process) {
HANDLE pinned = nullptr;
if (!DuplicateHandle(GetCurrentProcess(), process, GetCurrentProcess(), &pinned,
0, FALSE, DUPLICATE_SAME_ACCESS))
throw ApiError(503, "recovery_identity_unverified", "无法保留已核验的进程句柄。");
return Handle(pinned);
}
void integer_setting(const Json &value, const char *key, int fallback, int low, int high) {
auto found = value.find(key);
if (found == value.end())
return;
if (!found->is_number_integer() || found->get<int64_t>() < low || found->get<int64_t>() > high)
throw ApiError(503, "invalid_configuration",
std::string(key) + " 配置超出范围,默认值为 " + std::to_string(fallback) + "。");
}
} // namespace
Json load_configuration(const fs::path &root) {
fs::path path = root / L"api-settings.json";
if (!fs::exists(path)) {
Json value{{"enabled", true},
{"prefix", "http://127.0.0.1:18888/"},
{"apiKey", new_id() + new_id()},
{"previewFps", 20},
{"previewMaxWidth", 1280},
{"previewJpegQuality", 75}, {"autoConnect", true}, {"autoConnectRetrySeconds", 15}};
write_json(path, value);
}
Json value = read_json(path);
if (!value.is_object())
throw ApiError(503, "invalid_configuration", "配置必须是 JSON 对象。");
std::set<std::string> fields{"enabled", "prefix", "apiKey",
"previewFps", "previewMaxWidth", "previewJpegQuality",
"sdkPath", "bridgePath", "autoConnect", "autoConnectRetrySeconds"};
for (auto it = value.begin(); it != value.end(); ++it)
if (!fields.count(it.key()))
throw ApiError(503, "invalid_configuration", "未知配置项:" + it.key());
if (value.contains("enabled") && !value["enabled"].is_boolean())
throw ApiError(503, "invalid_configuration", "enabled 必须是布尔值。");
if (value.contains("autoConnect") && !value["autoConnect"].is_boolean())
throw ApiError(503, "invalid_configuration", "autoConnect 必须是布尔值。");
if (!value.contains("apiKey") || !value["apiKey"].is_string())
throw ApiError(503, "invalid_configuration", "必须配置 API 密钥。");
auto key = value["apiKey"].get<std::string>();
if (key.size() < 32 ||
std::any_of(key.begin(), key.end(), [](unsigned char c) { return c < 33 || c > 126; }))
throw ApiError(503, "invalid_configuration", "API 密钥至少32位可见ASCII字符。");
if (!value.contains("prefix") || !value["prefix"].is_string())
throw ApiError(503, "invalid_configuration", "必须配置 HTTP 根地址。");
integer_setting(value, "previewFps", 20, 1, 30);
integer_setting(value, "previewMaxWidth", 1280, 320, 3840);
integer_setting(value, "previewJpegQuality", 75, 30, 95);
integer_setting(value, "autoConnectRetrySeconds", 15, 5, 300);
for (auto name : {"sdkPath", "bridgePath"})
if (value.contains(name) && !value[name].is_string())
throw ApiError(503, "invalid_configuration", std::string(name) + " 必须是字符串。");
value["previewFps"] = value.value("previewFps", 20);
value["previewMaxWidth"] = value.value("previewMaxWidth", 1280);
value["previewJpegQuality"] = value.value("previewJpegQuality", 75);
value["autoConnect"] = value.value("autoConnect", true);
value["autoConnectRetrySeconds"] = value.value("autoConnectRetrySeconds", 15);
return value;
}
struct Supervisor::Impl : std::enable_shared_from_this<Supervisor::Impl> {
fs::path root, logFile;
Json config;
bool simulated;
detail::AutoConnectionPolicy autoConnection;
std::atomic<bool> autoStop{false};
std::mutex autoWaitGate;
std::condition_variable autoWake;
std::atomic<bool> stopping{false}, rotating{false}, busy{false}, fault{false}, suspendFrames{false};
std::atomic<bool> recoveryActive{false};
std::atomic<uint64_t> commandGeneration{0};
std::string activeAction, recoveringSession;
struct RecoveryContext {
std::shared_ptr<PipeClient> owner;
Handle worker, manufacturer;
Json info;
std::string originalSession;
bool connectionAttempted = true;
bool replacement = false;
};
std::shared_ptr<RecoveryContext> recoveryContext;
std::mutex commandGate, workerGate, frameGate, fileGate;
std::shared_ptr<PipeClient> client;
Handle process;
DWORD pid = 0;
uint64_t started = 0, epoch = 0, sequence = 0, lastOffered = 0, encoded = 0;
int deviceType = 3;
int64_t metricStart = unix_ms();
double encodeTotal = 0;
std::shared_ptr<FrameSnapshot> latest;
Json encoderMetrics;
Json calibrationMetadata=nullptr;
std::shared_ptr<FrameSnapshot> calibrationLatest;
std::shared_ptr<PipeClient> calibrationOwner;
uint64_t calibrationEpoch=0,calibrationSequence=0;
int64_t calibrationReceived=0;
std::string calibrationNativeKey;
std::map<std::string, Json> downloads;
std::thread frameThread, autoThread;
Impl(fs::path path, Json cfg, bool mock)
: root(std::move(path)), config(std::move(cfg)), simulated(mock),
autoConnection(config.value("autoConnect", true), config.value("autoConnectRetrySeconds", 15)) {
fs::create_directories(root / L"Logs");
logFile = root / L"Logs" / wide("native_supervisor_" + new_id() + ".log");
}
void log(const std::string &line) {
log_line(logFile, line);
std::cout << utc_now() << " " << line << std::endl;
}
std::shared_ptr<PipeClient> current() {
std::lock_guard<std::mutex> hold(workerGate);
return client;
}
uint64_t currentEpoch() {
std::lock_guard<std::mutex> hold(workerGate);
return epoch;
}
Json recovery_session() {
std::lock_guard<std::mutex> hold(workerGate);
return recoveringSession.empty() ? Json(nullptr) : Json(recoveringSession);
}
void clearFrame() {
std::lock_guard<std::mutex> hold(frameGate);
latest.reset();
encoderMetrics = nullptr;
encoded = 0;
encodeTotal = 0;
metricStart = unix_ms();
}
void advance() {
std::lock_guard<std::mutex> hold(workerGate);
++epoch;
}
Json empty() {
Json value{{"serverTimeUtc", utc_now()},
{"initialized", false},
{"sessionId", nullptr},
{"deviceOnline", nullptr},
{"deviceStatusCheckedUtc", nullptr},
{"battery", detail::DeviceBatteryCache{}.snapshot(false, unix_ms())},
{"deviceType", deviceType},
{"state", recoveryActive ? "recovering"
: fault ? "restart_required"
: busy || rotating ? "busy"
: "disconnected"},
{"busy", busy || rotating || recoveryActive},
{"scanning", false},
{"projectReady", false},
{"stateUncertain", fault.load()},
{"restartRequired", fault.load()},
{"projectId", nullptr},
{"scanMode", "trak"},
{"previewEnabled", false},
{"frameAgeMs", nullptr},
{"frameWidth", 0},
{"frameHeight", 0},
{"previewFresh", false},
{"stopBehavior", "pause_acquisition_keep_project_and_preview"},
{"disconnectBehavior", "pause_acquisition_end_sdk_session_keep_disk_files_and_http"},
{"meshState", "none"},
{"calibrationActive", false},
{"recoveryActive", recoveryActive.load()},
{"recoverySessionId", recovery_session()},
{"sdkProcessIsolation", true},
{"implementation", "C++17"},
{"autoConnection", autoConnection.snapshot()},
{"simulated", simulated}};
add_calibration_file_times(value);
return value;
}
void add_calibration_file_times(Json &value) {
try {
// Resolve afresh so a previously missing SDK or updated settings
// cannot leave this read-only metadata query stuck on a stale path.
const auto directory = simulated ? fs::path{} :
detail::locate_sdk_installation(root, executable().parent_path(), config)
.serviceDirectory / L"res" / L"FreeScanTrak";
value.update(detail::snapshot_calibration_files(directory));
} catch (const std::exception &) {
// Preserve a usable status response even if one filesystem query fails.
value.update(detail::snapshot_calibration_files({}));
}
}
Json status() {
auto currentClient = current();
if (!currentClient)
return empty();
Json value;
try {
value = currentClient->call("status", Json::object(), 4400);
} catch (const std::exception &) {
if (currentClient != current() || rotating)
return empty();
bool dead = false;
{
std::lock_guard<std::mutex> hold(workerGate);
dead = process && exited(process.get());
}
if (dead) {
fault = true;
clearFrame();
return empty();
}
throw ApiError(503, "status_unavailable", "设备后台暂未返回状态,请稍后查询。");
}
if (currentClient != current())
return empty();
if (!value.is_object())
throw ApiError(502, "worker_protocol_error", "后台状态不是对象。");
value["sdkProcessIsolation"] = true;
value["implementation"] = "C++17";
value["simulated"] = simulated;
value["autoConnection"] = autoConnection.snapshot();
value["recoveryActive"] = recoveryActive.load();
const auto pendingRecovery = recovery_session();
if (!pendingRecovery.is_null())
value["recoverySessionId"] = pendingRecovery;
if (busy || rotating) {
value["busy"] = true;
if (!value.value("restartRequired", false))
value["state"] = "busy";
}
if (fault) {
value["battery"] = detail::DeviceBatteryCache{}.snapshot(false, unix_ms());
value["stateUncertain"] = true;
value["restartRequired"] = true;
value["state"] = "restart_required";
value["previewFresh"] = false;
}
add_calibration_file_times(value);
if (recoveryActive) {
value["busy"] = true;
value["state"] = "recovering";
value["previewFresh"] = false;
std::lock_guard<std::mutex> hold(workerGate);
if (!recoveringSession.empty())
value["recoverySessionId"] = recoveringSession;
}
return value;
}
void startWorker() {
{
std::lock_guard<std::mutex> hold(workerGate);
if (process && !exited(process.get()))
throw ApiError(409, "worker_still_running", "旧后台尚未退出,不能启动第二个 SDK 会话。");
}
std::wstring name = wide("FreeScanCpp_" + new_id());
auto path = executable();
std::wstring args = quoted(path.wstring()) + L" --worker " + name + L" --data-root " +
quoted(root.wstring()) + L" --parent " + std::to_wstring(GetCurrentProcessId()) +
L" --parent-start " + std::to_wstring(process_started(GetCurrentProcess()));
if (simulated)
args += L" --mock";
STARTUPINFOW startup{};
startup.cb = sizeof(startup);
PROCESS_INFORMATION info{};
if (!CreateProcessW(path.c_str(), args.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr,
root.c_str(), &startup, &info))
throw ApiError(503, "worker_start_failed",
"无法启动 C++ 设备后台,Windows=" + std::to_string(GetLastError()));
CloseHandle(info.hThread);
{
std::lock_guard<std::mutex> hold(workerGate);
process.reset(info.hProcess);
pid = info.dwProcessId;
started = process_started(process.get());
}
auto candidate = std::make_shared<PipeClient>(name);
{
std::lock_guard<std::mutex> hold(workerGate);
if (recoveryActive && recoveryContext) {
// A failed bootstrap is still our freshly created, unconnected
// child. Retain it for a confirmed retry instead of losing the
// only handle and getting stuck with an unpublished process.
client = candidate;
recoveryContext->owner = candidate;
recoveryContext->worker = duplicate_process(process.get());
recoveryContext->manufacturer.reset();
recoveryContext->connectionAttempted = false;
recoveryContext->replacement = true;
recoveryContext->info = {{"sessionId", ""}, {"calibrationSession", false},
{"projectReady", false}, {"scanning", false}, {"busy", false},
{"initializationAttempted", false}, {"initialized", false},
{"ownerTrustedForForce", false}, {"simulated", simulated},
{"owner", nullptr}, {"deviceType", deviceType}};
++epoch;
}
}
int64_t deadline = unix_ms() + 15000;
std::string error;
while (unix_ms() < deadline) {
if (exited(info.hProcess)) {
fault = true;
throw ApiError(503, "worker_start_failed", "新后台启动后已退出。");
}
try {
candidate->call("status", Json::object(), 2000);
{
std::lock_guard<std::mutex> hold(workerGate);
client = candidate;
++epoch;
}
clearFrame();
log("C++ 设备后台已就绪,PID " + std::to_string(info.dwProcessId) + ",尚未连接设备。");
return;
} catch (const std::exception &ex) {
error = ex.what();
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
fault = true;
throw ApiError(503, "worker_start_failed", "C++ 设备后台未就绪;未启动第二个后台。" + error);
}
void captureFiles(const std::shared_ptr<PipeClient> &owner) {
Json values = owner->call("files", Json::object(), 5000);
if (!values.is_array())
throw ApiError(502, "worker_protocol_error", "下载登记不是数组。");
std::lock_guard<std::mutex> hold(fileGate);
for (const auto &item : values) {
if (!item.is_object() || !item.contains("fileId") || !item["fileId"].is_string())
throw ApiError(502, "worker_protocol_error", "下载登记无效。");
std::string id = item["fileId"];
if (id.size() != 32 || id.find_first_not_of("0123456789abcdef") != std::string::npos)
throw ApiError(502, "worker_protocol_error", "下载编号无效。");
for (auto key : {"root", "path", "name", "contentType"})
if (!item.contains(key) || !item[key].is_string())
throw ApiError(502, "worker_protocol_error", "下载路径字段无效。");
downloads[id] = item;
}
}
void closeWorker(bool shutdown) {
auto owner = current();
HANDLE handle = nullptr;
DWORD oldPid = 0;
{
std::lock_guard<std::mutex> hold(workerGate);
if (!process)
return;
handle = process.get();
oldPid = pid;
}
if (!exited(handle) && owner) {
int64_t deadline = unix_ms() + 5000;
while (true) {
bool retry = false;
try {
owner->call("close", Json{{"shutdown", shutdown}}, 5000);
} catch (const ApiError &ex) {
retry = ex.code == "device_busy";
if (!retry)
log("等待后台退出确认:" + std::string(ex.what()));
} catch (const std::exception &ex) {
log("等待后台退出确认:" + std::string(ex.what()));
}
if (!retry || exited(handle) || unix_ms() >= deadline)
break;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
if (WaitForSingleObject(handle, 12000) != WAIT_OBJECT_0) {
fault = true;
throw ApiError(504, "worker_exit_timeout",
"旧设备后台未确认退出,已停止重连,请正常关闭并重启服务。");
}
{
std::lock_guard<std::mutex> hold(workerGate);
client.reset();
process.reset();
pid = 0;
started = 0;
++epoch;
}
clearFrame();
log("已核验 C++ 后台退出,PID " + std::to_string(oldPid));
}
void forceIdleWorkerExit() {
// Only the child retained from CreateProcess is eligible. The command
// gate and sticky session latch exclude project/calibration operations.
if (!autoConnection.may_restart() || autoStop || stopping)
throw ApiError(409, "auto_restart_paused", "自动重启已暂停,未强制关闭SDK后台。");
auto owner = current();
HANDLE handle;
DWORD oldPid;
{
std::lock_guard<std::mutex> hold(workerGate);
handle = process.get();
oldPid = pid;
wchar_t image[32768]{};
DWORD length = 32768;
if (!handle || !oldPid || oldPid == GetCurrentProcessId() ||
GetProcessId(handle) != oldPid || process_started(handle) != started ||
!QueryFullProcessImageNameW(handle, 0, image, &length) ||
_wcsicmp(executable().c_str(), std::wstring(image, length).c_str()) != 0)
throw ApiError(503, "worker_identity_unverified", "SDK后台身份无法核验,未终止任何进程。");
}
if (!exited(handle)) {
// A responsive worker must still confirm an empty session after
// graceful cleanup. An unresponsive live worker is left untouched.
const auto latestStatus = owner->call("status", Json::object(), 5000);
if (latestStatus.value("projectReady", true) || latestStatus.value("scanning", true) ||
latestStatus.value("calibrationActive", true) ||
!autoConnection.may_restart() || autoStop || stopping)
throw ApiError(409, "session_protected", "当前会话不能自动强制重启,保留原后台。");
log("SDK正常退出超时;已核验无工程、未采集、非标定,仅结束本服务创建的SDK后台,PID " +
std::to_string(oldPid));
if (!TerminateProcess(handle, 0xE0000001) && !exited(handle))
throw ApiError(503, "worker_termination_failed", "无法结束已核验的SDK后台,未启动新后台。");
}
// closeWorker checks the original process handle, not a reusable PID.
// It must confirm exit before any new SDK worker can be created.
closeWorker(true);
}
Json execute(const std::string &action, const Json &body, uint64_t expectedGeneration) {
contracts::validate(action, body);
if (recoveryActive)
throw ApiError(409, "calibration_recovery_active", "正在结束旧标定并恢复设备,请等待恢复任务完成。");
std::unique_lock<std::mutex> command(commandGate, std::try_to_lock);
if (!command.owns_lock())
throw ApiError(409, "device_busy", "设备正在执行其他任务。");
if (recoveryActive)
throw ApiError(409, "calibration_recovery_active", "正在结束旧标定并恢复设备,请等待恢复任务完成。");
if (expectedGeneration != UINT64_MAX && expectedGeneration != commandGeneration.load())
throw ApiError(409, "calibration_aborted", "该请求属于已结束的旧SDK会话,请刷新设备状态后重新提交。");
if (action == "disconnect")
autoConnection.pause();
if (stopping)
throw ApiError(503, "shutting_down", "设备服务正在关闭。");
if (action == "connect" || action == "reconnect") {
autoConnection.resume();
autoWake.notify_all();
}
if (fault)
throw ApiError(409, "restart_required", "后台状态待确认,请正常重启设备服务。");
// Even an unconfirmed create/enter command may have established a
// session. Never replace it automatically on the basis of empty/fault status.
if (action == "createProject" || action == "calibrationEnter")
autoConnection.protect();
busy = true;
const auto generation = commandGeneration.load();
{
std::lock_guard<std::mutex> hold(workerGate);
activeAction = action;
}
bool reset = action == "createProject" || action == "setScanType" || action == "importFramework";
if (reset) {
suspendFrames = true;
advance();
clearFrame();
}
auto finish = [&] {
if (generation != commandGeneration.load())
return; // A retired command must not reset its replacement's flags.
if (reset) {
advance();
clearFrame();
suspendFrames = false;
}
rotating = false;
busy = false;
std::lock_guard<std::mutex> hold(workerGate);
activeAction.clear();
};
auto stillCurrent = [&] {
if (generation != commandGeneration.load())
throw ApiError(409, "calibration_aborted", "旧标定任务已被恢复操作中止,未在新会话中继续。");
};
try {
auto owner = current();
if (!owner)
throw ApiError(503, "worker_unavailable", "设备后台尚未就绪。");
Json result;
if (action == "disconnect" || action == "reconnect") {
Json before = owner->call("status", Json::object(), 5000);
deviceType = before.value("deviceType", 3);
Json releaseBody = body;
releaseBody.erase("deviceType");
result =
owner->call("execute", Json{{"action", "disconnect"}, {"body", releaseBody}}, 120000);
captureFiles(owner);
rotating = true;
advance();
clearFrame();
closeWorker(false);
startWorker();
autoConnection.protect(false);
if (action == "reconnect") {
deviceType = body.value("deviceType", deviceType);
auto connection = current()->call(
"execute", Json{{"action", "connect"}, {"body", Json{{"deviceType", deviceType}}}},
120000);
result["sessionId"] = connection.at("status").value("sessionId", Json());
}
result["disconnected"] = action == "disconnect";
result["reconnected"] = action == "reconnect";
result["projectRestored"] = false;
result["downloadsPreserved"] = true;
result["httpServiceRunning"] = true;
result["status"] = status();
log(action == "reconnect" ? "重连成功:新 C++ 后台已连接,未恢复工程或采集。"
: "断开成功:HTTP 服务继续运行。");
} else {
int timeout = action == "parameters" ? 1500000
: (action == "mesh" || action == "export" || action == "align" ||
action.rfind("calibration", 0) == 0)
? 360000
: 150000;
result = owner->call("execute", Json{{"action", action}, {"body", body}}, timeout);
stillCurrent();
if (action == "export" || action == "dataSnapshot")
captureFiles(owner);
if (action == "startPreview" || action == "stopPreview") {
advance();
clearFrame();
}
}
stillCurrent();
if(action=="calibrationEnter")advance();
finish();
if(action=="calibrationEnter")seedCalibrationIdentity(owner,result);
return result;
} catch (const ApiError &ex) {
stillCurrent();
if (rotating || ex.code == "worker_timeout" || ex.code == "worker_unavailable" ||
ex.code == "worker_protocol_error") {
fault = true;
clearFrame();
}
finish();
throw;
} catch (...) {
stillCurrent();
if (rotating) {
fault = true;
clearFrame();
}
finish();
throw;
}
}
Json recover(const Json &body) {
contracts::validate("calibrationRecover", body);
bool expectedInactive = false;
if (!recoveryActive.compare_exchange_strong(expectedInactive, true))
throw ApiError(409, "calibration_recovery_active", "已有标定恢复任务,请等待完成。");
struct ActiveReset {
std::atomic<bool> &active;
~ActiveReset() { active = false; }
} activeReset{recoveryActive};
if (stopping)
throw ApiError(503, "shutting_down", "HTTP服务正在关闭,不能恢复标定。");
auto expectedSession = body.at("expectedSessionId").get<std::string>();
for (auto &character : expectedSession)
if (character >= 'A' && character <= 'F')
character = static_cast<char>(character - 'A' + 'a');
const bool force = body.value("force", false);
auto owner = current();
std::shared_ptr<RecoveryContext> context;
bool detached = false;
{
std::lock_guard<std::mutex> hold(workerGate);
if (fault && recoveryContext && recoveryContext->originalSession == expectedSession &&
(recoveryContext->owner == owner || (!owner && !process && exited(recoveryContext->worker.get())))) {
context = recoveryContext;
if (!owner) {
owner = context->owner;
detached = true;
}
}
}
if (!owner)
throw ApiError(503, "worker_unavailable", "旧SDK后台不可用;未启动第二个会话。");
// This RPC bypasses both worker operation gates and does no SDK work.
Json info;
try { info = owner->call("recoveryInfo", Json::object(), 5000); }
catch (const ApiError &error) {
// A previous release may have exited the worker before its owner.
// Retain the exact original process handles, never rediscover by PID.
if ((error.code != "worker_unavailable" && error.code != "worker_timeout") ||
!context || (!exited(context->worker.get()) && context->connectionAttempted))
throw;
info = context->info;
}
auto validateInfo = [&](Json value) {
if (context) {
value["sessionId"] = expectedSession;
value["calibrationSession"] = true;
}
detail::validate_calibration_recovery(value, expectedSession, force);
};
validateInfo(info);
std::unique_lock<std::mutex> command(commandGate, std::try_to_lock);
if (!command.owns_lock()) {
std::lock_guard<std::mutex> hold(workerGate);
if (activeAction.rfind("calibration", 0) != 0)
throw ApiError(409, "device_busy", "当前任务不是标定,不能通过标定恢复中止。");
if (!force)
throw ApiError(409, "recovery_requires_force", "标定任务仍在执行;中止需明确 force:true。");
}
// Pin both original process objects before any release or termination.
// No enumeration or image-name based termination is permitted here.
Handle oldWorker, oldManufacturer;
DWORD oldPid;
uint64_t oldStarted;
{
std::lock_guard<std::mutex> hold(workerGate);
if (detached) {
if (client || process || !context || !exited(context->worker.get()))
throw ApiError(409, "session_changed", "恢复上下文已变化,请刷新后重试。");
oldWorker = duplicate_process(context->worker.get());
oldPid = GetProcessId(oldWorker.get());
oldStarted = process_started(oldWorker.get());
} else if (owner != client || !process)
throw ApiError(409, "session_changed", "SDK后台已变化,请刷新状态后重试。");
else {
oldPid = pid;
oldStarted = started;
oldWorker = duplicate_process(process.get());
}
}
verify_process_identity(oldWorker.get(), oldPid, oldStarted, executable());
const bool ownUninitializedReplacement = context && context->replacement &&
info.value("initializationAttempted", true) && !info.value("ownerTrustedForForce", false);
if (!simulated && !ownUninitializedReplacement &&
!(context && !info.value("initializationAttempted", true))) {
const auto manufacturer = info.value("owner", Json());
if (!manufacturer.is_object() || !manufacturer.contains("processId") ||
!manufacturer["processId"].is_number_unsigned() ||
!manufacturer.contains("startedFileTime") || !manufacturer["startedFileTime"].is_string() ||
!manufacturer.contains("executable") || !manufacturer["executable"].is_string())
throw ApiError(503, "recovery_identity_unverified", "厂家后台归属不明,保留旧会话。");
const auto manufacturerPid = manufacturer.at("processId").get<DWORD>();
const auto manufacturerStarted = std::stoull(manufacturer.at("startedFileTime").get<std::string>());
const auto manufacturerPath = detail::locate_sdk_installation(root, executable().parent_path(), config)
.serviceDirectory / L"FreeScan Trak.exe";
if (manufacturerPid == oldPid || manufacturerStarted < oldStarted ||
_wcsicmp(fs::path(wide(manufacturer.at("executable").get<std::string>())).lexically_normal().c_str(),
manufacturerPath.lexically_normal().c_str()) != 0)
throw ApiError(503, "recovery_identity_unverified", "厂家进程与当前SDK会话身份不一致。");
if (context && context->manufacturer)
oldManufacturer = duplicate_process(context->manufacturer.get());
else
oldManufacturer.reset(OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE,
FALSE, manufacturerPid));
verify_process_identity(oldManufacturer.get(), manufacturerPid, manufacturerStarted, manufacturerPath);
} else if (simulated && !info.value("simulated", false))
throw ApiError(503, "recovery_identity_unverified", "模拟后台身份不一致。");
// Recheck the session immediately before the first destructive action.
if (!exited(oldWorker.get())) {
try { validateInfo(owner->call("recoveryInfo", Json::object(), 5000)); }
catch (const ApiError &error) {
if ((error.code != "worker_unavailable" && error.code != "worker_timeout") ||
!context || context->connectionAttempted)
throw;
validateInfo(info); // No SDK command has ever been sent to this child.
}
}
if (!context)
context = std::make_shared<RecoveryContext>();
context->owner = owner;
context->originalSession = expectedSession;
context->info = info;
context->worker = duplicate_process(oldWorker.get());
if (oldManufacturer)
context->manufacturer = duplicate_process(oldManufacturer.get());
autoConnection.pause();
{
std::lock_guard<std::mutex> hold(workerGate);
recoveringSession = expectedSession;
recoveryContext = context;
}
rotating = true;
suspendFrames = true;
advance();
clearFrame();
bool forced = false, invalidated = false;
auto invalidate = [&] {
if (!invalidated) {
++commandGeneration;
invalidated = true;
}
};
try {
log("标定恢复:已确认旧会话 " + expectedSession + ",先尝试SDK正常释放;不继续标定或采集。");
try { if (!exited(oldWorker.get())) captureFiles(owner); }
catch (const std::exception &error) { log(std::string("保留已有下载登记:") + error.what()); }
bool gracefullyClosed = exited(oldWorker.get()) &&
(!oldManufacturer || exited(oldManufacturer.get()));
if (!gracefullyClosed && !exited(oldWorker.get()) && command.owns_lock() &&
!ownUninitializedReplacement) {
try {
// close/shutdown deliberately bypasses execute_action's
// restart_required guard and calls normal Sn3DRelease.
owner->call("close", Json{{"shutdown", true}}, 22000);
gracefullyClosed = WaitForSingleObject(oldWorker.get(), 5000) == WAIT_OBJECT_0 &&
(!oldManufacturer || WaitForSingleObject(oldManufacturer.get(), 0) == WAIT_OBJECT_0);
} catch (const std::exception &error) {
log(std::string("标定正常释放尚未确认:") + error.what());
}
// A successful shutdown may close the pipe before its reply is
// acknowledged. The pinned exit handles, not transport success,
// decide whether a replacement can be started safely.
if (!gracefullyClosed)
gracefullyClosed = WaitForSingleObject(oldWorker.get(), 1000) == WAIT_OBJECT_0 &&
(!oldManufacturer || WaitForSingleObject(oldManufacturer.get(), 0) == WAIT_OBJECT_0);
}
if (!gracefullyClosed) {
if (!force)
throw ApiError(409, "recovery_requires_force", "SDK正常释放未完成;旧后台保留,确认中止后可使用 force:true。");
invalidate();
forced = true;
log("标定恢复:仅结束已核验的旧SDK后台及其厂家进程,PID " + std::to_string(oldPid));
if (ownUninitializedReplacement)
log("本次新后台初始化未完成且厂家进程归属不明;仅清理本服务创建的SDK后台,不终止任何未知厂家进程。后续连接仍检查服务占用。");
if (!exited(oldWorker.get()) && !TerminateProcess(oldWorker.get(), 0xE0000002) && !exited(oldWorker.get()))
throw ApiError(503, "recovery_termination_failed", "无法结束旧SDK后台,未创建新会话。");
if (WaitForSingleObject(oldWorker.get(), 5000) != WAIT_OBJECT_0)
throw ApiError(504, "recovery_exit_timeout", "旧SDK后台退出未确认,未创建新会话。");
if (oldManufacturer) {
if (!exited(oldManufacturer.get()) && !TerminateProcess(oldManufacturer.get(), 0xE0000002) &&
!exited(oldManufacturer.get()))
throw ApiError(503, "recovery_termination_failed", "无法结束旧厂家后台,未创建新会话。");
if (WaitForSingleObject(oldManufacturer.get(), 5000) != WAIT_OBJECT_0)
throw ApiError(504, "recovery_exit_timeout", "旧厂家后台退出未确认,未创建新会话。");
}
}
invalidate();
// Terminating the pinned worker closes the old RPC, releasing an
// execute() that held commandGate. It cannot mutate new flags.
if (!command.owns_lock()) {
const auto deadline = unix_ms() + 6000;
while (!command.try_lock() && unix_ms() < deadline)
std::this_thread::sleep_for(std::chrono::milliseconds(20));
if (!command.owns_lock())
throw ApiError(504, "recovery_gate_timeout", "旧任务尚未退出,未启动新SDK后台。");
}
{
std::lock_guard<std::mutex> hold(workerGate);
if ((!detached && client != owner) || (detached && client))
throw ApiError(409, "session_changed", "旧后台归属发生变化,停止恢复。");
client.reset();
process.reset();
pid = 0;
started = 0;
activeAction.clear();
++epoch;
}
busy = true;
deviceType = info.value("deviceType", deviceType);
startWorker();
auto replacement = current();
{
std::lock_guard<std::mutex> hold(workerGate);
context->owner = replacement;
context->worker = duplicate_process(process.get());
context->manufacturer.reset();
}
context->info = replacement->call("recoveryInfo", Json::object(), 5000);
if (simulated && fs::is_regular_file(root / L"OFFLINE_TEST_RECOVERY_CONNECT_FAIL_ONCE")) {
fs::rename(root / L"OFFLINE_TEST_RECOVERY_CONNECT_FAIL_ONCE",
root / L"OFFLINE_TEST_RECOVERY_CONNECT_FAIL_CONSUMED");
throw ApiError(503, "recovery_connect_failed", "OFFLINE_TEST_FIXTURE: recovery reconnect failed once.");
}
context->connectionAttempted = true;
replacement->call("execute", Json{{"action", "connect"},
{"body", Json{{"deviceType", deviceType}}}}, 150000);
const auto after = replacement->call("status", Json::object(), 5000);
if (!after.value("initialized", false) || after.value("restartRequired", false) ||
after.value("stateUncertain", false) || after.value("projectReady", true) ||
after.value("scanning", true) || after.value("calibrationActive", true) ||
!(after.contains("deviceOnline") && after["deviceOnline"] == true))
throw ApiError(503, "recovery_connect_failed", "旧标定已结束,但新SDK连接未就绪;未恢复标定或采集。");
fault = false;
rotating = false;
suspendFrames = false;
busy = false;
autoConnection.protect(false);
autoConnection.resume();
autoConnection.connected();
{
std::lock_guard<std::mutex> hold(workerGate);
recoveringSession.clear();
recoveryContext.reset();
}
log("标定恢复成功:旧会话已结束,新SDK已连接;HTTP父服务保持运行。");
auto finalStatus = status();
finalStatus["recoveryActive"] = false;
finalStatus["busy"] = false;
finalStatus["state"] = after.at("state");
finalStatus["recoverySessionId"] = nullptr;
return {{"recovered", true}, {"reconnected", true}, {"calibrationAborted", true},
{"forced", forced}, {"previousSessionId", expectedSession},
{"newSessionId", after.value("sessionId", Json())},
{"httpServiceRunning", true}, {"downloadsPreserved", true}, {"status", std::move(finalStatus)}};
} catch (...) {
// If replacement initialization failed, keep its own identity and
// metadata for an explicit retry of this same recovery chain.
try {
const auto last = current();
if (context && last && context->owner == last && !exited(context->worker.get()))
context->info = last->call("recoveryInfo", Json::object(), 1500);
} catch (...) { }
fault = true;
rotating = false;
suspendFrames = false;
// An invalidated old task cannot clear busy; the recovery owner does.
busy = false;
clearFrame();
log("标定恢复失败:自动连接保持暂停,未自动继续标定或采集,请查看错误与日志。");
throw;
}
}
void automaticStep() {
if (recoveryActive)
return;
const auto monitor = autoConnection.snapshot();
if (!monitor.value("enabled", false) || monitor.value("paused", false) ||
monitor.value("state", std::string()) == "blocked" || autoStop || stopping)
return;
// Routine observation must not occupy the control gate and make a
// manual command fail with device_busy. Mutating recovery below still
// rechecks state while holding that gate.
auto observedOwner = current();
if (observedOwner) {
try {
const auto observed = observedOwner->call("status", Json::object(), 5000);
if (observedOwner != current())
return;
const bool safeConnected = observed.value("initialized", false) && !fault &&
!observed.value("restartRequired", false) && !observed.value("stateUncertain", false) &&
!(observed.contains("deviceOnline") && observed["deviceOnline"] == false);
if (safeConnected || observed.value("projectReady", false) ||
observed.value("scanning", false) || observed.value("calibrationActive", false)) {
autoConnection.decide(observed, unix_ms());
return;
}
if (observed.value("busy", false))
return;
} catch (const std::exception &) {
// The locked path distinguishes a dead owner from an unknown
// live state and preserves the session protection latch.
}
}
std::unique_lock<std::mutex> command(commandGate, std::try_to_lock);
if (!command.owns_lock() || autoStop || stopping || recoveryActive)
return;
auto owner = current();
if (!owner)
return;
Json before;
try {
before = owner->call("status", Json::object(), 5000);
} catch (const ApiError &error) {
bool dead;
{
std::lock_guard<std::mutex> hold(workerGate);
dead = process && exited(process.get());
}
if (!dead) {
autoConnection.failed(error, unix_ms());
return; // Unknown state never authorizes replacing a live worker.
}
before = empty();
before["restartRequired"] = true;
}
if (fault)
before["restartRequired"] = true;
const auto action = autoConnection.decide(before, unix_ms());
if (action == detail::AutoConnectionAction::none)
return;
bool cleanupUnconfirmed = false;
busy = true;
try {
deviceType = before.value("deviceType", deviceType);
if (action == detail::AutoConnectionAction::recycle) {
cleanupUnconfirmed = true;
log("SDK自动重启:当前无工程或标定会话,先请求正常退出旧SDK后台。");
try { captureFiles(owner); }
catch (const std::exception &error) {
// Completed export/snapshot registrations are already in
// the HTTP parent; unavailable workers cannot erase them.
log(std::string("保留父服务已有下载登记;旧后台登记暂不可读:") + error.what());
}
rotating = true;
advance();
clearFrame();
bool forced = false;
try { closeWorker(true); }
catch (const ApiError &error) {
if (error.code != "worker_exit_timeout")
throw;
forceIdleWorkerExit();
forced = true;
}
startWorker();
autoConnection.restarted(forced, unix_ms());
log("SDK工作进程已重启,HTTP父服务和历史任务保持运行。");
fault = false;
cleanupUnconfirmed = false;
}
log("自动连接SDK;不创建工程、不开始采集。");
current()->call("execute", Json{{"action", "connect"},
{"body", Json{{"deviceType", deviceType}}}}, 150000);
const auto after = current()->call("status", Json::object(), 5000);
if (!after.value("initialized", false) || after.value("restartRequired", false) ||
after.value("stateUncertain", false) ||
(after.contains("deviceOnline") && after["deviceOnline"] == false))
throw ApiError(503, "device_offline", "SDK连接尚未就绪或设备离线,稍后重试。");
autoConnection.connected();
log("SDK自动连接成功,等待外部创建工程和开始扫描。");
} catch (const ApiError &error) {
if (cleanupUnconfirmed || error.code == "worker_timeout" ||
error.code == "worker_unavailable" || error.code == "worker_protocol_error")
fault = true;
autoConnection.failed(error, unix_ms(), cleanupUnconfirmed);
log(std::string(cleanupUnconfirmed ? "自动重连已停止:" : "自动连接失败,等待重试:") + error.what());
} catch (const std::exception &error) {
fault = true;
autoConnection.failed(ApiError(503, "auto_connection_error", error.what()), unix_ms(), true);
log(std::string("自动重连已停止:") + error.what());
}
rotating = false;
busy = false;
}
void autoLoop() {
std::unique_lock<std::mutex> wait(autoWaitGate);
// HTTP is already available. Give callers a chance to observe the
// initial waiting state and avoid performing SDK work on HTTP startup.
while (!autoWake.wait_for(wait, std::chrono::seconds(1), [this] { return autoStop.load(); })) {
wait.unlock();
try { automaticStep(); }
catch (const std::exception &error) {
autoConnection.failed(ApiError(503, "auto_connection_error", error.what()), unix_ms(), true);
}
wait.lock();
}
}
void seedCalibrationIdentity(const std::shared_ptr<PipeClient> &owner,const Json &result) noexcept {
try {
if(owner!=current()||rotating||recoveryActive||stopping||fault)return;
const auto view=result.value("calibrationView",Json(nullptr));
if(!view.is_object()||view.value("source",std::string())!="sdk_calibration_window"||!view.value("calibrationActive",false)
||!view.value("sessionId",Json(nullptr)).is_string()||view["sessionId"].get<std::string>().empty()
||!view.value("calibrationId",Json(nullptr)).is_string()||view["calibrationId"].get<std::string>().empty())return;
const auto round=currentEpoch();
std::lock_guard<std::mutex> hold(frameGate);
// A newer atomic worker snapshot already contains this exact entry;
// never replace its real frame with an identity-only seed.
if(calibrationOwner==owner&&calibrationEpoch==round&&calibrationMetadata.is_object()
&&calibrationMetadata.value("calibrationId",Json(nullptr))==view["calibrationId"])return;
if(calibrationEpoch>round)return;
auto seed=view;seed.erase("frame");seed["available"]=false;seed["frameSource"]=nullptr;
seed["state"]="frame_pending";seed["message"]="已进入厂家标定页面,等待本次窗口的新画面。";seed["frameSequence"]=calibrationSequence;
calibrationLatest.reset();calibrationNativeKey.clear();calibrationMetadata=std::move(seed);
calibrationOwner=owner;calibrationEpoch=round;calibrationReceived=unix_ms();
}catch(...){/* Optional display metadata cannot reverse a confirmed SDK page entry. */}
}
Json calibrationSnapshot(bool includeFrame) {
std::shared_ptr<PipeClient> owner;uint64_t round=0;bool alive=false;
{std::lock_guard<std::mutex> hold(workerGate);owner=client;round=epoch;alive=process&&!exited(process.get());}
std::unique_lock<std::mutex> hold(frameGate);
Json out{{"source","sdk_calibration_window"},{"sessionId",nullptr},{"calibrationId",nullptr},
{"calibrationActive",false},{"available",false},{"state","calibration_inactive"},
{"message","当前没有可核验的厂家标定窗口会话。"},{"frameSequence",calibrationSequence},
{"frameSource",nullptr},{"progress",nullptr},{"temperatures",{{"scanner",nullptr},{"tracker",nullptr}}}};
bool same=alive&&owner&&owner==calibrationOwner&&round==calibrationEpoch&&!rotating&&!recoveryActive&&!stopping&&!fault;
if(same&&calibrationMetadata.is_object()&&unix_ms()-calibrationReceived<=2000){
out=calibrationMetadata;out["frameSequence"]=calibrationSequence;
if(out.value("available",false)){
if(!calibrationLatest||unix_ms()-calibrationLatest->capturedMs<0||unix_ms()-calibrationLatest->capturedMs>2000){
out["available"]=false;out["frameSource"]=nullptr;out["state"]="frame_stale";out["message"]="厂家标定窗口画面已过期。";
}else if(includeFrame)out["frame"]=frame_to_json(*calibrationLatest);
}
}
if(includeFrame&&!out.contains("frame"))out["frame"]=nullptr;
hold.unlock();
if(owner!=current()||round!=currentEpoch()||rotating||recoveryActive||stopping||fault){
out["calibrationActive"]=false;out["available"]=false;out["frameSource"]=nullptr;out["state"]="session_changed";out["message"]="原SDK标定会话已经切换或结束。";
if(includeFrame)out["frame"]=nullptr;
}
return out;
}
void receiveCalibration(const std::shared_ptr<PipeClient> &owner,uint64_t round) {
Json data=owner->call("calibrationView",Json::object(),3000);
if(owner!=current()||round!=currentEpoch()||rotating||recoveryActive)return;
if(!data.is_object()||data.value("source",std::string())!="sdk_calibration_window")throw ApiError(502,"worker_protocol_error","标定窗口元数据来源无效。");
std::shared_ptr<FrameSnapshot> frame;
std::string key;
if(data.value("available",false)){
if(!data.value("calibrationActive",false)||!data.contains("frame")||!data["frame"].is_object()||!data.value("frameSource",Json(nullptr)).is_object())throw ApiError(502,"worker_protocol_error","标定窗口帧缺少会话归属。");
frame=std::make_shared<FrameSnapshot>(frame_from_json(data["frame"]));
key=data.value("sessionId",std::string())+":"+data.value("calibrationId",std::string())+":"+data["frameSource"].dump()+":"+std::to_string(frame->sequence)+":"+std::to_string(frame->capturedMs);
}
data.erase("frame");
std::lock_guard<std::mutex> hold(frameGate);
if(calibrationEpoch>round)return; // A delayed pre-entry RPC must not overwrite its synchronous identity seed.
if(frame){
if(key!=calibrationNativeKey){calibrationNativeKey=key;frame->sequence=++calibrationSequence;calibrationLatest=std::move(frame);}
data["frameSequence"]=calibrationSequence;
}else{calibrationLatest.reset();calibrationNativeKey.clear();data["frameSource"]=nullptr;data["frameSequence"]=calibrationSequence;}
calibrationMetadata=std::move(data);calibrationOwner=owner;calibrationEpoch=round;calibrationReceived=unix_ms();
}
Json query(const std::string &action, const Json &args) {
if(action=="calibrationView"||action=="calibrationViewFrame")return calibrationSnapshot(action=="calibrationViewFrame");
if (action == "file") {
std::lock_guard<std::mutex> hold(fileGate);
auto it = downloads.find(args.value("fileId", std::string()));
if (it == downloads.end())
throw ApiError(404, "file_not_found", "文件编号不存在或已随服务重启失效。");
return it->second;
}
if (action == "capabilities") {
Json out;
const auto owner = current();
try {
if (!owner || recoveryActive)
throw ApiError(503, "worker_unavailable", "SDK后台切换中。");
out = owner->call("query", Json{{"action", action}, {"args", args}}, 4500);
} catch (const std::exception &) {
// Static HTTP declarations remain available when the worker's
// operation gate is busy or its previous process already exited.
// No device state/readback is invented in this fallback.
out = {{"apiVersion", "1.3"}, {"deviceFamily", "FreeScan Trak Nova / Trak"},
{"initialized", false}, {"calibration", nullptr},
{"rawDataAvailable", false}, {"rawDataReason", "设备后台忙或恢复中,静态接口能力仍可查询。"},
{"capabilitySource", "http_parent_static_declarations"},
{"features", {{"calibration", true}, {"calibrationRecovery", true}}},
{"controls", {{"connect", true}, {"disconnect", true}, {"reconnect", true}}},
{"calibrationModes", Json::array({{{"mode", 0}, {"modeName", "跟踪仪标定"}},
{{"mode", 1}, {"modeName", "系统标定"}},
{{"mode", 2}, {"modeName", "探针标定"}},
{{"mode", 3}, {"modeName", "UE Nova 激光标定"}}})}};
}
out["routes"] = contracts::routes();
out["features"]["calibrationRecovery"] = true;
out["implementation"] = "C++17";
out["sdkProcessIsolation"] = true;
out["simulated"] = simulated;
return out;
}
auto owner = current();
if (!owner)
throw ApiError(503, "worker_unavailable", "设备后台正在切换,请稍后刷新。");
Json out = owner->call("query", Json{{"action", action}, {"args", args}},
action == "sceneInfo" ? 14000 : 4500);
if (action == "capabilities" && out.is_object()) {
out["implementation"] = "C++17";
out["sdkProcessIsolation"] = true;
out["simulated"] = simulated;
}
return out;
}
void frameLoop() {
std::shared_ptr<PipeClient> previous;
uint64_t last = 0;int64_t nextCalibration=0;
while (!stopping) {
auto owner = current();
auto round = currentEpoch();
if (owner && !rotating && !suspendFrames) {
if (owner != previous) {
previous = owner;
last = 0;
}
if(unix_ms()>=nextCalibration){
nextCalibration=unix_ms()+100;
try{receiveCalibration(owner,round);}
catch(const std::exception &){std::lock_guard<std::mutex> hold(frameGate);if(calibrationEpoch<=round){calibrationLatest.reset();calibrationMetadata=nullptr;calibrationNativeKey.clear();}}
}
try {
Json data = owner->call("frame", Json::object(), 3000);
if (owner == current() && round == currentEpoch() && !rotating && !suspendFrames) {
if (data.is_null())
clearFrame();
else {
FrameSnapshot frame = frame_from_json(data);
{
std::lock_guard<std::mutex> hold(frameGate);
encoderMetrics = data.value("encoderMetrics", Json(nullptr));
}
if (frame.sequence != last) {
last = frame.sequence;
std::lock_guard<std::mutex> hold(frameGate);
frame.sequence = ++sequence;
latest = std::make_shared<FrameSnapshot>(std::move(frame));
++encoded;
encodeTotal += latest->encodeMs;
}
}
}
} catch (const std::exception &) {
if (owner == current() && !rotating)
clearFrame();
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(40));
}
}
};
Supervisor::Supervisor(fs::path root, Json config, bool mock)
: impl_(std::make_shared<Impl>(std::move(root), std::move(config), mock)) {}
Supervisor::~Supervisor() {
if (impl_) {
impl_->autoStop = true;
impl_->autoWake.notify_all();
if (impl_->autoThread.joinable())
impl_->autoThread.join();
impl_->stopping = true;
if (impl_->frameThread.joinable())
impl_->frameThread.join();
}
}
void Supervisor::start() {
impl_->rotating = true;
try {
impl_->startWorker();
impl_->rotating = false;
auto self = impl_;
impl_->frameThread = std::thread([self] { self->frameLoop(); });
} catch (...) {
impl_->fault = true;
impl_->rotating = false;
throw;
}
}
void Supervisor::start_auto_connection() {
if (impl_->config.value("autoConnect", true)) {
auto self = impl_;
impl_->autoThread = std::thread([self] { self->autoLoop(); });
}
}
void Supervisor::pause_auto_connection() {
impl_->autoConnection.pause();
}
bool Supervisor::stop() {
if (impl_->recoveryActive) {
impl_->log("标定恢复尚未完成,请等待后停止HTTP服务。");
return false;
}
impl_->autoConnection.pause();
std::unique_lock<std::mutex> command(impl_->commandGate, std::try_to_lock);
if (!command.owns_lock()) {
impl_->log("请等待当前设备任务结束后再关闭服务。");
return false;
}
impl_->autoStop = true;
impl_->autoWake.notify_all();
if (impl_->autoThread.joinable())
impl_->autoThread.join();
impl_->rotating = true;
try {
impl_->closeWorker(true);
impl_->stopping = true;
if (impl_->frameThread.joinable())
impl_->frameThread.join();
return true;
} catch (const std::exception &ex) {
impl_->fault = true;
impl_->rotating = false;
impl_->log("服务尚未关闭:" + std::string(ex.what()));
return false;
}
}
Json Supervisor::status() {
return impl_->status();
}
uint64_t Supervisor::command_generation() const {
return impl_->commandGeneration.load();
}
Json Supervisor::execute(const std::string &action, const Json &body, uint64_t expectedGeneration) {
return impl_->execute(action, body, expectedGeneration);
}
Json Supervisor::recover(const Json &body) {
return impl_->recover(body);
}
Json Supervisor::query(const std::string &action, const Json &args) {
return impl_->query(action, args);
}
std::shared_ptr<const FrameSnapshot> Supervisor::frame() {
std::lock_guard<std::mutex> hold(impl_->frameGate);
return impl_->latest;
}
Json Supervisor::metrics() {
std::lock_guard<std::mutex> hold(impl_->frameGate);
auto latest = impl_->latest;
Json out{
{"maxFps", impl_->config.value("previewFps", 20)},
{"maxWidth", impl_->config.value("previewMaxWidth", 1280)},
{"jpegQuality", impl_->config.value("previewJpegQuality", 75)},
{"offeredFrames", impl_->encoded},
{"encodedFrames", impl_->encoded},
{"replacedFrames", 0},
{"throttledFrames", 0},
{"encodingFailures", 0},
{"averageEncodeMs", impl_->encoded ? impl_->encodeTotal / impl_->encoded : 0},
{"averageEncodedFps", impl_->encoded * 1000.0 / std::max<int64_t>(1, unix_ms() - impl_->metricStart)},
{"latestEncodeMs", latest ? Json(latest->encodeMs) : Json()},
{"latestFrameBytes", latest ? latest->jpeg.size() : 0},
{"latestSequence", latest ? latest->sequence : 0},
{"frameAgeMs", latest ? Json(std::max<int64_t>(0, unix_ms() - latest->capturedMs)) : Json()},
{"sourceWidth", latest ? latest->sourceWidth : 0},
{"sourceHeight", latest ? latest->sourceHeight : 0},
{"width", latest ? latest->width : 0},
{"height", latest ? latest->height : 0},
{"queueDepth", 0},
{"encoderRunning", false},
{"freshnessLimitMs", 2000},
{"capturedTimeMeaning", "managed_frame_received_not_hardware_exposure"},
{"implementation", "C++17"},
{"metricSource", "parent_imported_jpeg_cache"}};
if (impl_->encoderMetrics.is_object()) {
out.update(impl_->encoderMetrics);
out["metricSource"] = "worker_encoder_cache";
out["latestSequence"] = latest ? latest->sequence : 0;
out["frameAgeMs"] = latest ? Json(std::max<int64_t>(0, unix_ms() - latest->capturedMs)) : Json();
}
out["importedFrames"] = impl_->encoded;
return out;
}
namespace {
struct WorkerContext {
std::shared_ptr<WorkerService> service;
std::mutex command;
std::atomic<bool> closing{false};
DWORD threadId;
};
} // namespace
int run_worker(const fs::path &root, const Json &config, const std::wstring &name, DWORD parentPid,
uint64_t parentStarted, bool simulated) {
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
MSG first{};
PeekMessageW(&first, nullptr, WM_USER, WM_USER, PM_NOREMOVE);
auto context = std::make_shared<WorkerContext>();
context->service = std::make_shared<WorkerService>(root, config, simulated);
context->threadId = GetCurrentThreadId();
Handle parent(OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, parentPid));
if (!parent || process_started(parent.get()) != parentStarted)
return 2;
PipeServer server(name, [context](const std::string &method, const Json &args) -> Json {
if (method == "status")
return context->service->status();
if (method == "recoveryInfo")
return context->service->recovery_info();
if (method == "frame")
return context->service->frame();
if(method=="calibrationView")return context->service->calibration_view(true);
if (method == "files")
return context->service->files();
if (method == "query") {
auto action = args.at("action").get<std::string>();
if (action == "capabilities" || action == "file")
return context->service->query(action, args.value("args", Json::object()));
if (action != "sceneInfo")
throw ApiError(404, "unknown_query", "后台查询不存在。");
std::unique_lock<std::mutex> hold(context->command, std::try_to_lock);
if (!hold.owns_lock())
throw ApiError(409, "device_busy", "后台正在执行其他任务。");
if (context->closing)
throw ApiError(503, "shutting_down", "后台正在关闭。");
return context->service->query(action, args.value("args", Json::object()));
}
std::unique_lock<std::mutex> hold(context->command, std::try_to_lock);
if (!hold.owns_lock())
throw ApiError(409, "device_busy", "后台正在执行其他任务。");
if (context->closing)
throw ApiError(503, "shutting_down", "后台正在关闭。");
if (method == "execute") {
auto action = args.at("action").get<std::string>();
if (action == "reconnect")
throw ApiError(409, "worker_restart_required", "重连必须由 HTTP 父进程更换 SDK 后台。");
return context->service->execute(action, args.at("body"));
}
if (method == "close") {
bool shutdown = args.value("shutdown", false);
if (!context->service->can_close(shutdown))
throw ApiError(409, "device_busy", "SDK 当前操作尚未结束,不能关闭后台。");
context->closing = true;
context->service->shutdown();
PostThreadMessageW(context->threadId, WM_QUIT, 0, 0);
return Json{{"closing", true}};
}
throw ApiError(404, "unknown_rpc_method", "后台通信方法不存在。");
});
server.start();
bool done = false;
HANDLE parentHandle = parent.get();
while (!done) {
DWORD result = MsgWaitForMultipleObjects(1, &parentHandle, FALSE, 1000, QS_ALLINPUT);
if (result == WAIT_OBJECT_0) {
std::unique_lock<std::mutex> hold(context->command, std::try_to_lock);
if (hold.owns_lock() && context->service->can_close(true)) {
context->closing = true;
context->service->shutdown();
done = true;
} else
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
while (PeekMessageW(&first, nullptr, 0, 0, PM_REMOVE)) {
if (first.message == WM_QUIT) {
done = true;
break;
}
TranslateMessage(&first);
DispatchMessageW(&first);
}
}
server.stop();
context->service->shutdown();
CoUninitialize();
return 0;
}
} // namespace freescan