Fix other ANSCV classes

This commit is contained in:
2026-05-09 16:47:46 +10:00
parent aa323a07a3
commit a94bf88a5b
16 changed files with 1197 additions and 197 deletions
+567
View File
@@ -1,3 +1,13 @@
// Windows / COM / PDH / DXGI headers must precede any include that drops
// `using namespace std;` into the global scope (base64.h does), otherwise
// the SDK's `byte` typedef in <rpcndr.h> collides with `std::byte`.
#include <pdh.h>
#include <pdhmsg.h>
#include <psapi.h>
#include <comdef.h>
#include <Wbemidl.h>
#include <dxgi.h>
#include "Utility.h"
#include <hwinfo/PCIMapper.h>
#include <hwinfo/hwinfo.h>
@@ -21,6 +31,10 @@
#include <filesystem>
#include <system_error>
#include <cstdlib>
#include <thread>
#include <sstream>
#include <iomanip>
#include <locale>
// Forward-declare OutputDebugStringA without pulling in <windows.h> (which
// drags winsock conflicts as noted in ANSLicense.h). Used by ANSCENTER_DebugLog.
@@ -529,9 +543,562 @@ extern "C" {
}
}
// ============================================================================
// SystemHealth sampler — process-wide singleton.
//
// Wraps a long-lived PDH query so subsequent ::Sample() calls only pay for one
// PdhCollectQueryData and a few format calls. PDH delta-rate counters
// (Bytes/sec, % time, etc.) need two samples to produce a value, so the
// first call after process start blocks ~150 ms; later calls return cached
// values within 500 ms, otherwise re-collect on demand.
//
// Counters use English names (`PdhAddEnglishCounterW`) so the same paths work
// regardless of the OS display language.
// ============================================================================
namespace {
double Pdh_GetSingle(PDH_HCOUNTER c) {
if (!c) return -1.0;
PDH_FMT_COUNTERVALUE val{};
PDH_STATUS s = PdhGetFormattedCounterValue(c, PDH_FMT_DOUBLE | PDH_FMT_NOCAP100, nullptr, &val);
if (s != ERROR_SUCCESS) return -1.0;
if (val.CStatus != PDH_CSTATUS_VALID_DATA && val.CStatus != PDH_CSTATUS_NEW_DATA)
return -1.0;
return val.doubleValue;
}
double Pdh_SumWildcard(PDH_HCOUNTER c) {
if (!c) return -1.0;
DWORD bufSize = 0, count = 0;
PDH_STATUS s = PdhGetFormattedCounterArrayW(c, PDH_FMT_DOUBLE, &bufSize, &count, nullptr);
if (s != PDH_MORE_DATA) return -1.0;
std::vector<BYTE> buf(bufSize);
auto* items = reinterpret_cast<PDH_FMT_COUNTERVALUE_ITEM_W*>(buf.data());
s = PdhGetFormattedCounterArrayW(c, PDH_FMT_DOUBLE, &bufSize, &count, items);
if (s != ERROR_SUCCESS) return -1.0;
double sum = 0.0;
for (DWORD i = 0; i < count; ++i) {
const auto& v = items[i].FmtValue;
if (v.CStatus == PDH_CSTATUS_VALID_DATA || v.CStatus == PDH_CSTATUS_NEW_DATA)
sum += v.doubleValue;
}
return sum;
}
// CPU temperature via WMI's MSAcpi_ThermalZoneTemperature (root\WMI namespace).
// Returns the highest reported zone, in °C, or -1.0 if unavailable. Caveats:
// - Most consumer desktops either expose nothing here or report a fixed
// placeholder (often 27.85 °C / 30.10 dK) regardless of real die temp.
// - Laptops and workstation/server boards generally report something
// plausible; a vendor SDK is still preferable for absolute accuracy.
//
// Each call self-contains COM init: we try MULTITHREADED, accept
// RPC_E_CHANGED_MODE if the calling thread is already STA-initialised, and
// only CoUninitialize when we own the init. Security init is one-shot per
// process. Total cost ~3–10 ms.
double ReadCpuTempCelsiusViaWmi() {
HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
const bool weInited = (hr == S_OK || hr == S_FALSE);
if (FAILED(hr) && hr != RPC_E_CHANGED_MODE) return -1.0;
static std::once_flag s_secOnce;
std::call_once(s_secOnce, [] {
// Best-effort; RPC_E_TOO_LATE is fine — someone else initialised first.
CoInitializeSecurity(nullptr, -1, nullptr, nullptr,
RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE,
nullptr, EOAC_NONE, nullptr);
});
double maxTempC = -1.0;
IWbemLocator* pLoc = nullptr;
if (SUCCEEDED(CoCreateInstance(CLSID_WbemLocator, nullptr, CLSCTX_INPROC_SERVER,
IID_IWbemLocator, reinterpret_cast<LPVOID*>(&pLoc)))) {
IWbemServices* pSvc = nullptr;
if (SUCCEEDED(pLoc->ConnectServer(_bstr_t(L"ROOT\\WMI"),
nullptr, nullptr, nullptr, 0, nullptr, nullptr, &pSvc))) {
CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, nullptr,
RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE,
nullptr, EOAC_NONE);
IEnumWbemClassObject* pEnum = nullptr;
if (SUCCEEDED(pSvc->ExecQuery(_bstr_t(L"WQL"),
_bstr_t(L"SELECT CurrentTemperature FROM MSAcpi_ThermalZoneTemperature"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
nullptr, &pEnum))) {
IWbemClassObject* pObj = nullptr;
ULONG ret = 0;
while (pEnum->Next(WBEM_INFINITE, 1, &pObj, &ret) == S_OK && ret > 0) {
VARIANT v;
VariantInit(&v);
if (SUCCEEDED(pObj->Get(L"CurrentTemperature", 0, &v, nullptr, nullptr))) {
long raw = 0;
bool gotIt = true;
switch (v.vt) {
case VT_I4: raw = v.lVal; break;
case VT_UI4: raw = static_cast<long>(v.ulVal); break;
case VT_I2: raw = v.iVal; break;
case VT_UI2: raw = v.uiVal; break;
default: gotIt = false; break;
}
if (gotIt && raw > 0) {
// ACPI reports tenths of Kelvin. Windows returns
// a constant 3010 (== 27.85 °C) when the firmware
// does not actually expose a thermal zone — drop
// that sentinel so callers see -1 instead of
// believable-looking junk.
if (raw == 3010) continue;
const double t = (raw / 10.0) - 273.15;
if (t > maxTempC) maxTempC = t;
}
}
VariantClear(&v);
pObj->Release();
}
pEnum->Release();
}
pSvc->Release();
}
pLoc->Release();
}
if (weInited) CoUninitialize();
return maxTempC;
}
// ============================================================================
// Per-adapter GPU breakdown.
//
// PDH counters under "\GPU Engine(*)" and "\GPU Process Memory(*)" report one
// row per (process, adapter, engine, ...) tuple. Naively summing them across
// every adapter is wrong on hybrid systems — an iGPU at 60% plus a dGPU at
// 60% reads as 120% (capped to 100%), and per-process VRAM mixes physically
// disjoint memories.
//
// PDH instance names embed the owning adapter's LUID:
// pid_<PID>_luid_0x<HIGH>_0x<LOW>_phys_<N>[_eng_<N>_engtype_<TYPE>]
// So we enumerate adapters via DXGI to learn LUID -> {vendor, name, VRAM},
// parse each PDH instance name's LUID, and accumulate per-adapter.
// ============================================================================
struct GpuAdapter {
LUID luid{};
DWORD vendorId{0};
std::string name; // UTF-8
int64_t dedicatedVramMB{0};
bool isDiscrete{false}; // heuristic: dedicated VRAM ≥ 1 GiB
// running totals — reset every Sample()
double loadPercent{0.0};
int64_t processMemMB{0};
};
const char* VendorString(DWORD vendorId) {
switch (vendorId) {
case 0x10DE: return "NVIDIA";
case 0x1002: return "AMD";
case 0x8086: return "Intel";
case 0x1414: return "Microsoft"; // Basic Render Driver
case 0x5143: return "Qualcomm";
case 0x106B: return "Apple";
default: return "Other";
}
}
std::string WideToUtf8(const wchar_t* w) {
if (!w) return {};
const int len = WideCharToMultiByte(CP_UTF8, 0, w, -1, nullptr, 0, nullptr, nullptr);
if (len <= 1) return {};
std::string s(static_cast<size_t>(len - 1), '\0');
WideCharToMultiByte(CP_UTF8, 0, w, -1, s.data(), len, nullptr, nullptr);
return s;
}
std::vector<GpuAdapter> EnumerateGpuAdapters() {
std::vector<GpuAdapter> out;
IDXGIFactory1* factory = nullptr;
if (FAILED(CreateDXGIFactory1(__uuidof(IDXGIFactory1),
reinterpret_cast<void**>(&factory))) || !factory) {
ANS_DBG("HealthSampler", "CreateDXGIFactory1 failed; GPU detail unavailable");
return out;
}
UINT i = 0;
IDXGIAdapter1* adapter = nullptr;
while (factory->EnumAdapters1(i++, &adapter) != DXGI_ERROR_NOT_FOUND) {
DXGI_ADAPTER_DESC1 desc{};
if (SUCCEEDED(adapter->GetDesc1(&desc)) &&
!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) {
GpuAdapter a;
a.luid = desc.AdapterLuid;
a.vendorId = desc.VendorId;
a.name = WideToUtf8(desc.Description);
a.dedicatedVramMB = static_cast<int64_t>(desc.DedicatedVideoMemory / (1024ULL * 1024ULL));
a.isDiscrete = a.dedicatedVramMB >= 1024; // ≥ 1 GiB ⇒ probably dGPU
out.push_back(std::move(a));
}
adapter->Release();
adapter = nullptr;
}
factory->Release();
return out;
}
bool ParseLuidFromInstance(const wchar_t* inst, LUID& out) {
if (!inst) return false;
const wchar_t* p = wcsstr(inst, L"luid_0x");
if (!p) return false;
p += 7; // skip "luid_0x"
unsigned long high = 0, low = 0;
if (swscanf_s(p, L"%lx_0x%lx", &high, &low) != 2) return false;
out.HighPart = static_cast<LONG>(high);
out.LowPart = low;
return true;
}
GpuAdapter* FindByLuid(std::vector<GpuAdapter>& adapters, const LUID& luid) {
for (auto& a : adapters) {
if (a.luid.LowPart == luid.LowPart && a.luid.HighPart == luid.HighPart)
return &a;
}
return nullptr;
}
// Aggregate a GPU PDH wildcard counter into per-adapter buckets.
// pidFilter != 0 means "only count instances owned by this PID" (used for the
// per-process GPU memory counter); 0 means "count all" (used for utilisation).
void AggregateGpuCounter(PDH_HCOUNTER counter,
std::vector<GpuAdapter>& adapters,
DWORD pidFilter,
bool isMemoryCounter) {
if (!counter) return;
DWORD bufSize = 0, count = 0;
const DWORD fmt = isMemoryCounter ? PDH_FMT_LARGE : PDH_FMT_DOUBLE;
PDH_STATUS s = PdhGetFormattedCounterArrayW(counter, fmt, &bufSize, &count, nullptr);
if (s != PDH_MORE_DATA) return;
std::vector<BYTE> buf(bufSize);
auto* items = reinterpret_cast<PDH_FMT_COUNTERVALUE_ITEM_W*>(buf.data());
s = PdhGetFormattedCounterArrayW(counter, fmt, &bufSize, &count, items);
if (s != ERROR_SUCCESS) return;
wchar_t pidPrefix[64] = {};
size_t pidPrefixLen = 0;
if (pidFilter) {
swprintf_s(pidPrefix, L"pid_%lu_", pidFilter);
pidPrefixLen = wcslen(pidPrefix);
}
for (DWORD i = 0; i < count; ++i) {
const auto& v = items[i].FmtValue;
if (v.CStatus != PDH_CSTATUS_VALID_DATA && v.CStatus != PDH_CSTATUS_NEW_DATA)
continue;
if (pidFilter &&
_wcsnicmp(items[i].szName, pidPrefix, pidPrefixLen) != 0)
continue;
LUID luid{};
if (!ParseLuidFromInstance(items[i].szName, luid)) continue;
GpuAdapter* a = FindByLuid(adapters, luid);
if (!a) continue;
if (isMemoryCounter)
a->processMemMB += v.largeValue / (1024 * 1024);
else
a->loadPercent += v.doubleValue;
}
}
// Choose which adapter the flat `gpuLoadPercent` / `valIGPU_MB` fields refer to.
// Hardware preference, deterministic per process: NVIDIA dGPU > AMD dGPU >
// largest VRAM. Returns nullptr only when no adapters exist at all.
GpuAdapter* PickPrimaryAdapter(std::vector<GpuAdapter>& adapters) {
if (adapters.empty()) return nullptr;
for (auto& a : adapters) if (a.vendorId == 0x10DE && a.isDiscrete) return &a;
for (auto& a : adapters) if (a.vendorId == 0x1002 && a.isDiscrete) return &a;
GpuAdapter* best = &adapters.front();
for (auto& a : adapters)
if (a.dedicatedVramMB > best->dedicatedVramMB) best = &a;
return best;
}
// Sum a LARGE-int wildcard counter, restricted to instances whose name begins
// with "pid_<pid>_". Used for per-process GPU memory counters where the
// instance name encodes the owning PID.
int64_t Pdh_SumWildcardLargeByPid(PDH_HCOUNTER c, DWORD pid) {
if (!c) return -1;
DWORD bufSize = 0, count = 0;
PDH_STATUS s = PdhGetFormattedCounterArrayW(c, PDH_FMT_LARGE, &bufSize, &count, nullptr);
if (s != PDH_MORE_DATA) return -1;
std::vector<BYTE> buf(bufSize);
auto* items = reinterpret_cast<PDH_FMT_COUNTERVALUE_ITEM_W*>(buf.data());
s = PdhGetFormattedCounterArrayW(c, PDH_FMT_LARGE, &bufSize, &count, items);
if (s != ERROR_SUCCESS) return -1;
wchar_t prefix[64];
swprintf_s(prefix, L"pid_%lu_", pid);
const size_t prefixLen = wcslen(prefix);
int64_t sum = 0;
for (DWORD i = 0; i < count; ++i) {
const auto& v = items[i].FmtValue;
if (v.CStatus != PDH_CSTATUS_VALID_DATA && v.CStatus != PDH_CSTATUS_NEW_DATA)
continue;
if (_wcsnicmp(items[i].szName, prefix, prefixLen) == 0)
sum += v.largeValue;
}
return sum;
}
class HealthSampler {
public:
static HealthSampler& Get() {
static HealthSampler inst;
return inst;
}
void Sample(ANSCENTER::SystemHealthInfo& out) {
std::lock_guard<std::mutex> lock(_mtx);
const auto now = std::chrono::steady_clock::now();
const bool fresh =
_hasCache &&
std::chrono::duration_cast<std::chrono::milliseconds>(now - _lastSample).count() < 500;
if (fresh) {
out = _cache;
return;
}
if (!_initialized) Init();
if (_query) {
PdhCollectQueryData(_query);
if (!_firstCollectDone) {
// Delta counters need two samples; sleep just enough to make the
// first reading meaningful instead of returning zeros.
std::this_thread::sleep_for(std::chrono::milliseconds(150));
PdhCollectQueryData(_query);
_firstCollectDone = true;
}
ReadFromPdh(out);
}
FillNonPdh(out);
_cache = out;
_lastSample = now;
_hasCache = true;
}
private:
HealthSampler() = default;
~HealthSampler() {
if (_query) {
PdhCloseQuery(_query);
_query = nullptr;
}
}
HealthSampler(const HealthSampler&) = delete;
HealthSampler& operator=(const HealthSampler&) = delete;
void Init() {
if (PdhOpenQueryW(nullptr, 0, &_query) != ERROR_SUCCESS) {
_query = nullptr;
ANS_DBG("HealthSampler", "PdhOpenQueryW failed");
}
if (_query) {
// Best-effort: missing counters just stay null; reads return -1.
PdhAddEnglishCounterW(_query, L"\\Processor(_Total)\\% Processor Time", 0, &_cpuLoad);
PdhAddEnglishCounterW(_query, L"\\Processor Information(_Total)\\% Processor Performance", 0, &_cpuPerf);
PdhAddEnglishCounterW(_query, L"\\PhysicalDisk(_Total)\\% Disk Time", 0, &_diskTime);
PdhAddEnglishCounterW(_query, L"\\PhysicalDisk(_Total)\\Disk Read Bytes/sec", 0, &_diskRead);
PdhAddEnglishCounterW(_query, L"\\PhysicalDisk(_Total)\\Disk Write Bytes/sec", 0, &_diskWrite);
PdhAddEnglishCounterW(_query, L"\\Network Interface(*)\\Bytes Received/sec", 0, &_netRx);
PdhAddEnglishCounterW(_query, L"\\Network Interface(*)\\Bytes Sent/sec", 0, &_netTx);
PdhAddEnglishCounterW(_query, L"\\Network Interface(*)\\Current Bandwidth", 0, &_netBw);
PdhAddEnglishCounterW(_query, L"\\GPU Engine(*)\\Utilization Percentage", 0, &_gpuUtil);
PdhAddEnglishCounterW(_query, L"\\GPU Process Memory(*)\\Dedicated Usage", 0, &_gpuMem);
}
// Cache static CPU info; nominal frequency is needed to convert the
// PDH "% Processor Performance" reading into a real GHz value.
try {
auto sockets = hwinfo::getAllSockets();
if (!sockets.empty()) {
const auto& cpu = sockets.front().CPU();
_cpuModel = cpu.modelName();
_baseClockMHz = cpu.regularClockSpeed_MHz();
if (_baseClockMHz <= 0) _baseClockMHz = cpu.maxClockSpeed_MHz();
}
} catch (...) {}
// Cache the GPU adapter list once. Adapter set is stable on desktops;
// hot-plug eGPU swaps would need a re-enumeration but that is rare.
try {
_gpuAdaptersTemplate = EnumerateGpuAdapters();
ANS_DBG("HealthSampler", "DXGI: %zu GPU adapter(s) discovered",
_gpuAdaptersTemplate.size());
} catch (...) {}
_initialized = true;
}
void ReadFromPdh(ANSCENTER::SystemHealthInfo& out) {
out.cpuLoadPercent = Pdh_GetSingle(_cpuLoad);
const double perfPct = Pdh_GetSingle(_cpuPerf);
if (perfPct >= 0 && _baseClockMHz > 0)
out.cpuFreqGHz = (_baseClockMHz / 1000.0) * (perfPct / 100.0);
double diskTime = Pdh_GetSingle(_diskTime);
if (diskTime >= 0) {
// PDH "% Disk Time" can exceed 100 on multi-disk arrays; cap so the
// value matches what users see in Task Manager.
if (diskTime > 100.0) diskTime = 100.0;
out.diskLoadPercent = diskTime;
}
const double rd = Pdh_GetSingle(_diskRead);
const double wr = Pdh_GetSingle(_diskWrite);
if (rd >= 0) out.diskReadSpeedMBs = rd / (1024.0 * 1024.0);
if (wr >= 0) out.diskWriteSpeedMBs = wr / (1024.0 * 1024.0);
const double netRxBps = Pdh_SumWildcard(_netRx);
const double netTxBps = Pdh_SumWildcard(_netTx);
const double netBwBps = Pdh_SumWildcard(_netBw);
if (netRxBps >= 0) out.netReceiveSpeedMBs = netRxBps / (1024.0 * 1024.0);
if (netTxBps >= 0) out.netSendSpeedMBs = netTxBps / (1024.0 * 1024.0);
if (netBwBps > 0 && netRxBps >= 0 && netTxBps >= 0) {
// Current Bandwidth is bits/s; rx+tx are bytes/s — convert before dividing.
double pct = ((netRxBps + netTxBps) * 8.0 / netBwBps) * 100.0;
if (pct > 100.0) pct = 100.0;
out.netLoadPercent = pct;
}
// Per-adapter GPU breakdown. Falls back to the old summation only if
// DXGI gave us nothing (very rare — would mean no Direct3D-capable
// adapter at all, or the call was blocked by group policy).
if (!_gpuAdaptersTemplate.empty()) {
std::vector<GpuAdapter> adapters = _gpuAdaptersTemplate; // fresh accumulators
AggregateGpuCounter(_gpuUtil, adapters, /*pidFilter*/ 0, false);
AggregateGpuCounter(_gpuMem, adapters, GetCurrentProcessId(), true);
for (auto& a : adapters) if (a.loadPercent > 100.0) a.loadPercent = 100.0;
if (GpuAdapter* primary = PickPrimaryAdapter(adapters)) {
out.gpuLoadPercent = primary->loadPercent;
out.valIGPU_MB = primary->processMemMB;
out.gpuName = primary->name;
}
// Build per-adapter detail string. Using '|' between fields and
// ',' between adapters keeps ';' free for the outer separator.
std::ostringstream os;
os.imbue(std::locale::classic());
os << std::fixed << std::setprecision(2);
for (size_t i = 0; i < adapters.size(); ++i) {
if (i > 0) os << ',';
std::string n = adapters[i].name;
std::replace(n.begin(), n.end(), ';', ',');
std::replace(n.begin(), n.end(), '|', '/');
os << n << '|'
<< VendorString(adapters[i].vendorId) << '|'
<< adapters[i].loadPercent << '|'
<< adapters[i].processMemMB << '|'
<< adapters[i].dedicatedVramMB;
}
out.gpuAdaptersDetail = os.str();
} else {
// Fallback: lose per-adapter info but still surface something.
double gpu = Pdh_SumWildcard(_gpuUtil);
if (gpu >= 0) {
if (gpu > 100.0) gpu = 100.0;
out.gpuLoadPercent = gpu;
}
const int64_t bytes = Pdh_SumWildcardLargeByPid(_gpuMem, GetCurrentProcessId());
if (bytes >= 0) out.valIGPU_MB = bytes / (1024 * 1024);
}
}
void FillNonPdh(ANSCENTER::SystemHealthInfo& out) {
out.cpuModel = _cpuModel;
MEMORYSTATUSEX ms{};
ms.dwLength = sizeof(ms);
const BOOL memOk = GlobalMemoryStatusEx(&ms);
if (memOk) {
out.memTotalGB = ms.ullTotalPhys / (1024.0 * 1024.0 * 1024.0);
out.memoryFreeGB = ms.ullAvailPhys / (1024.0 * 1024.0 * 1024.0);
out.memoryUsedGB = (ms.ullTotalPhys - ms.ullAvailPhys) / (1024.0 * 1024.0 * 1024.0);
if (ms.ullTotalPageFile > 0) {
out.swapPercent =
((ms.ullTotalPageFile - ms.ullAvailPageFile) * 100.0) / ms.ullTotalPageFile;
}
}
PROCESS_MEMORY_COUNTERS_EX pmc{};
if (GetProcessMemoryInfo(GetCurrentProcess(),
reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmc), sizeof(pmc))) {
out.valIRSS_MB = static_cast<int64_t>(pmc.WorkingSetSize / (1024ULL * 1024ULL));
out.valSwap_MB = static_cast<int64_t>(pmc.PrivateUsage / (1024ULL * 1024ULL));
if (memOk && ms.ullTotalPhys > 0)
out.rssPercent = (pmc.WorkingSetSize * 100.0) / static_cast<double>(ms.ullTotalPhys);
}
wchar_t sysDir[MAX_PATH] = {};
const UINT n = GetSystemDirectoryW(sysDir, MAX_PATH);
if (n >= 3) {
sysDir[3] = L'\0'; // strip down to the volume root, e.g. L"C:\\"
ULARGE_INTEGER freeAvail{}, total{}, totalFree{};
if (GetDiskFreeSpaceExW(sysDir, &freeAvail, &total, &totalFree)) {
out.diskTotalGB = total.QuadPart / (1024.0 * 1024.0 * 1024.0);
out.diskUsedGB = (total.QuadPart - totalFree.QuadPart) / (1024.0 * 1024.0 * 1024.0);
}
}
// CPU temperature: best-effort via ACPI thermal zone. Stays -1 on
// hardware that does not expose MSAcpi_ThermalZoneTemperature.
out.cpuTempDegC = ReadCpuTempCelsiusViaWmi();
}
std::mutex _mtx;
bool _initialized{false};
bool _firstCollectDone{false};
bool _hasCache{false};
std::chrono::steady_clock::time_point _lastSample{};
ANSCENTER::SystemHealthInfo _cache{};
PDH_HQUERY _query {nullptr};
PDH_HCOUNTER _cpuLoad {nullptr};
PDH_HCOUNTER _cpuPerf {nullptr};
PDH_HCOUNTER _diskTime {nullptr};
PDH_HCOUNTER _diskRead {nullptr};
PDH_HCOUNTER _diskWrite{nullptr};
PDH_HCOUNTER _netRx {nullptr};
PDH_HCOUNTER _netTx {nullptr};
PDH_HCOUNTER _netBw {nullptr};
PDH_HCOUNTER _gpuUtil {nullptr};
PDH_HCOUNTER _gpuMem {nullptr};
int64_t _baseClockMHz{-1};
std::string _cpuModel;
std::vector<GpuAdapter> _gpuAdaptersTemplate; // immutable after Init()
};
} // namespace
namespace ANSCENTER
{
SystemHealthInfo ANSLicenseHelper::GetSystemHealthInformation()
{
ANS_DBG("HealthSampler", "GetSystemHealthInformation: enter");
SystemHealthInfo info{};
try {
HealthSampler::Get().Sample(info);
} catch (const std::exception& e) {
ANS_DBG("HealthSampler", "Sample threw: %s", e.what());
} catch (...) {
ANS_DBG("HealthSampler", "Sample threw unknown exception");
}
return info;
}
EngineType ANSCENTER::ANSLicenseHelper::CheckHardwareInformation()
{
ANS_DBG("HWInfo", "CheckHardwareInformation: starting hardware detection");
+126
View File
@@ -317,6 +317,72 @@ namespace ANSCENTER
int enableFeature;
};
// ------------------------------------------------------------------------
// Real-time system telemetry. Snapshot of CPU / GPU / RAM / disk / network
// usage at the time of the call.
//
// Cheap to call frequently — values are cached for ~500 ms via a process-
// wide PDH sampler held in ANSLicense.cpp. The first call after process
// start blocks for ~150 ms because PDH counters require two samples to
// produce a delta-rate reading; subsequent calls are sub-millisecond.
//
// Fields the platform could not provide are set to -1 (or -1.0). Common
// reasons:
// - cpuTempDegC: ACPI thermal zone is unavailable / blocked on most
// consumer hardware. Use a vendor SDK (NVML / ADL / IPMI) for real
// thermals if you need them.
// - netLoadPercent: no network adapter advertises a non-zero
// "Current Bandwidth" (e.g. all interfaces are loopback / virtual).
// - valIGPU_MB: Windows < 10 19H1 does not expose GPU Process Memory
// PDH counters.
//
// Memory / disk units use 1024 base (1 GB == 2^30 bytes); throughput uses
// MB == 2^20 bytes for parity with Task Manager.
// ------------------------------------------------------------------------
struct SystemHealthInfo {
// CPU
double cpuLoadPercent = -1.0; // 0..100, total across all logical cores
double cpuTempDegC = -1.0; // -1 if unavailable
double cpuFreqGHz = -1.0; // current clock (turbo-aware)
std::string cpuModel; // e.g. "Intel(R) Core(TM) i9-..."
// System memory
double memTotalGB = -1.0;
double memoryUsedGB = -1.0;
double memoryFreeGB = -1.0;
double rssPercent = -1.0; // current process WS / total physical
double swapPercent = -1.0; // page file used / page file limit
// Current process
int64_t valIRSS_MB = -1; // working-set size (MB)
int64_t valSwap_MB = -1; // private commit / page-file usage (MB)
int64_t valIGPU_MB = -1; // dedicated GPU memory used by us (MB)
// GPU — values report the *primary* adapter only. On hybrid systems
// (e.g. Iris Xe + RTX 4090) the primary is picked deterministically:
// NVIDIA discrete > AMD discrete > whichever has the most VRAM. Per-
// adapter numbers are available in gpuAdaptersDetail below.
double gpuLoadPercent = -1.0; // 0..100 on the primary adapter only
std::string gpuName; // primary adapter model name
// Per-adapter rollup; one row per physical GPU, comma-separated.
// Row format: <name>|<vendor>|<load%>|<processMemMB>|<vramMB>
// Vendors: NVIDIA / AMD / Intel / Microsoft / Other
// Numbers use the C locale ('.' decimal, 2dp for load%).
std::string gpuAdaptersDetail;
// Disk (system drive — the volume holding %SystemRoot%)
double diskLoadPercent = -1.0;
double diskReadSpeedMBs = -1.0;
double diskWriteSpeedMBs = -1.0;
double diskUsedGB = -1.0;
double diskTotalGB = -1.0;
// Network (sum across all non-loopback interfaces)
double netLoadPercent = -1.0;
double netReceiveSpeedMBs = -1.0;
double netSendSpeedMBs = -1.0;
};
class ANSLICENSE_API SPDLogger
@@ -418,6 +484,7 @@ namespace ANSCENTER
public:
[[nodiscard]] static bool LicenseVerification(std::string licenseKey, int productId, std::string registrationName);
[[nodiscard]] static EngineType CheckHardwareInformation();
[[nodiscard]] static SystemHealthInfo GetSystemHealthInformation();
[[nodiscard]] static std::string ListLicenses();
[[nodiscard]] static int ActivateTrialLicense(std::string productName);
[[nodiscard]] static int DeactivateLicense(std::string productName);
@@ -455,6 +522,65 @@ extern "C" __declspec(dllexport) int ExtractModelZipFile(const char* modelZipFil
extern "C" __declspec(dllexport) int ZipFolderToZipFile(const char* modelFolderSource,const char* modelZipFileDes, const char* password);
extern "C" __declspec(dllexport) int PrepareEdgeModel(const char* modelZipFile, const char* zipFilePassword, const char* edgePassword, const char* modelName, const char* edgeSerialNumber, LStrHandle pathArray);
extern "C" __declspec(dllexport) int GetSystemHardwareInformation(LStrHandle systemHardwareInformation);
// SystemHealthParameters cluster, one scalar at a time. Pass nullptr for any
// field you do not care about. Returns 1 on success, 0 on failure. Cached
// internally so calling at LabVIEW UI rate (e.g. 1 Hz) is essentially free.
extern "C" __declspec(dllexport) int GetSystemHealthParameters(
double* cpuLoadPercent,
double* cpuTempDegC,
double* cpuFreqGHz,
LStrHandle cpuModel,
double* memTotalGB,
double* rssPercent,
double* swapPercent,
double* gpuLoadPercent,
int64_t* valIRSS_MB,
int64_t* valSwap_MB,
int64_t* valIGPU_MB,
double* memoryUsedGB,
double* memoryFreeGB,
double* diskLoadPercent,
double* diskReadSpeedMBs,
double* diskWriteSpeedMBs,
double* diskUsedGB,
double* diskTotalGB,
double* netLoadPercent,
double* netReceiveSpeedMBs,
double* netSendSpeedMBs,
LStrHandle gpuName, // primary adapter name (e.g. "NVIDIA RTX 4090"); pass nullptr to skip
LStrHandle gpuAdaptersDetail); // per-adapter rollup; pass nullptr to skip — see SystemHealthInfo for format
// Same payload as GetSystemHealthParameters, packed into a single string with
// ';' separators in this exact order:
// 1 cpuLoadPercent (%)
// 2 cpuTempDegC (°C, -1 if unavailable)
// 3 cpuFreqGHz (GHz)
// 4 cpuModel (string; any literal ';' in the model is rewritten to ',')
// 5 memTotalGB
// 6 rssPercent (%)
// 7 swapPercent (%)
// 8 gpuLoadPercent (%)
// 9 valIRSS_MB (current process working set, MB)
// 10 valSwap_MB (current process page-file usage, MB)
// 11 valIGPU_MB (current process GPU dedicated memory, MB)
// 12 memoryUsedGB
// 13 memoryFreeGB
// 14 diskLoadPercent (%)
// 15 diskReadSpeedMBs
// 16 diskWriteSpeedMBs
// 17 diskUsedGB
// 18 diskTotalGB
// 19 netLoadPercent (%)
// 20 netReceiveSpeedMBs
// 21 netSendSpeedMBs
// 22 gpuName (primary adapter model, e.g. "NVIDIA RTX 4090")
// 23 gpuAdaptersDetail (per-adapter rollup — see SystemHealthInfo struct)
// Numbers use the C locale ('.' decimal point) and 2-decimal fixed format.
// Any literal ';' in gpuName / gpuAdaptersDetail is rewritten to ',' so the
// outer separator is never ambiguous.
// Returns 1 on success, 0 on failure.
extern "C" __declspec(dllexport) int GetSystemHealthParametersString(LStrHandle outString);
extern "C" __declspec(dllexport) int ReleaseLoggers();
extern "C" __declspec(dllexport) int ListANSLicenses(std::string &listLicense);
extern "C" __declspec(dllexport) int ListANSLicenses_LV(LStrHandle ansProductLicenses);
+3
View File
@@ -52,6 +52,9 @@ target_link_libraries(ANSLicensingSystem PRIVATE
bz2.lib zip.lib
libboost_log-vc143-mt-x64-1_82.lib
shlwapi.lib winhttp.lib
pdh.lib psapi.lib
wbemuuid.lib oleaut32.lib ole32.lib
dxgi.lib
${WIN_COMMON_LIBS}
)
+135
View File
@@ -2,6 +2,10 @@
#include "pch.h"
#include "ANSLicense.h"
#include "Utility.h"
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <locale>
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
@@ -369,6 +373,137 @@ extern "C" __declspec(dllexport) int GetSystemHardwareInformation(LStrHandle sys
}
}
// SystemHealthParameters cluster, decomposed into individual scalar outputs so
// LabVIEW can wire each indicator straight to a Call Library Function Node.
// Any pointer may be nullptr (LabVIEW will pass nullptr for cluster fields the
// caller hasn't bound). cpuModel is optional but recommended; pass an LStrHandle
// or nullptr to skip. Returns 1 on success, 0 on hard failure.
extern "C" __declspec(dllexport) int GetSystemHealthParameters(
double* cpuLoadPercent,
double* cpuTempDegC,
double* cpuFreqGHz,
LStrHandle cpuModel,
double* memTotalGB,
double* rssPercent,
double* swapPercent,
double* gpuLoadPercent,
int64_t* valIRSS_MB,
int64_t* valSwap_MB,
int64_t* valIGPU_MB,
double* memoryUsedGB,
double* memoryFreeGB,
double* diskLoadPercent,
double* diskReadSpeedMBs,
double* diskWriteSpeedMBs,
double* diskUsedGB,
double* diskTotalGB,
double* netLoadPercent,
double* netReceiveSpeedMBs,
double* netSendSpeedMBs,
LStrHandle gpuName,
LStrHandle gpuAdaptersDetail)
{
try {
const ANSCENTER::SystemHealthInfo info =
ANSCENTER::ANSLicenseHelper::GetSystemHealthInformation();
auto writeLStr = [](LStrHandle handle, const std::string& s) {
if (!handle) return;
const int size = static_cast<int>(s.length());
const MgErr err = DSSetHandleSize(handle, sizeof(int32) + size * sizeof(uChar));
if (err == noErr) {
(*handle)->cnt = size;
if (size > 0) memcpy((*handle)->str, s.c_str(), size);
}
};
if (cpuLoadPercent) *cpuLoadPercent = info.cpuLoadPercent;
if (cpuTempDegC) *cpuTempDegC = info.cpuTempDegC;
if (cpuFreqGHz) *cpuFreqGHz = info.cpuFreqGHz;
if (memTotalGB) *memTotalGB = info.memTotalGB;
if (rssPercent) *rssPercent = info.rssPercent;
if (swapPercent) *swapPercent = info.swapPercent;
if (gpuLoadPercent) *gpuLoadPercent = info.gpuLoadPercent;
if (valIRSS_MB) *valIRSS_MB = info.valIRSS_MB;
if (valSwap_MB) *valSwap_MB = info.valSwap_MB;
if (valIGPU_MB) *valIGPU_MB = info.valIGPU_MB;
if (memoryUsedGB) *memoryUsedGB = info.memoryUsedGB;
if (memoryFreeGB) *memoryFreeGB = info.memoryFreeGB;
if (diskLoadPercent) *diskLoadPercent = info.diskLoadPercent;
if (diskReadSpeedMBs) *diskReadSpeedMBs = info.diskReadSpeedMBs;
if (diskWriteSpeedMBs) *diskWriteSpeedMBs = info.diskWriteSpeedMBs;
if (diskUsedGB) *diskUsedGB = info.diskUsedGB;
if (diskTotalGB) *diskTotalGB = info.diskTotalGB;
if (netLoadPercent) *netLoadPercent = info.netLoadPercent;
if (netReceiveSpeedMBs) *netReceiveSpeedMBs = info.netReceiveSpeedMBs;
if (netSendSpeedMBs) *netSendSpeedMBs = info.netSendSpeedMBs;
writeLStr(cpuModel, info.cpuModel);
writeLStr(gpuName, info.gpuName);
writeLStr(gpuAdaptersDetail, info.gpuAdaptersDetail);
return 1;
} catch (...) {
return 0;
}
}
extern "C" __declspec(dllexport) int GetSystemHealthParametersString(LStrHandle outString) {
try {
if (!outString) return 0;
const ANSCENTER::SystemHealthInfo info =
ANSCENTER::ANSLicenseHelper::GetSystemHealthInformation();
// Keep ';' as a clean separator: rewrite any literal ';' inside any
// free-form string field (rare, but vendor strings aren't safe by
// contract).
auto sanitize = [](std::string s) {
std::replace(s.begin(), s.end(), ';', ',');
return s;
};
const std::string model = sanitize(info.cpuModel);
const std::string gpuName_ = sanitize(info.gpuName);
const std::string gpuDetail = sanitize(info.gpuAdaptersDetail);
std::ostringstream os;
os.imbue(std::locale::classic()); // force '.' decimal regardless of system locale
os << std::fixed << std::setprecision(2);
os << info.cpuLoadPercent << ';'
<< info.cpuTempDegC << ';'
<< info.cpuFreqGHz << ';'
<< model << ';'
<< info.memTotalGB << ';'
<< info.rssPercent << ';'
<< info.swapPercent << ';'
<< info.gpuLoadPercent << ';'
<< info.valIRSS_MB << ';'
<< info.valSwap_MB << ';'
<< info.valIGPU_MB << ';'
<< info.memoryUsedGB << ';'
<< info.memoryFreeGB << ';'
<< info.diskLoadPercent << ';'
<< info.diskReadSpeedMBs << ';'
<< info.diskWriteSpeedMBs << ';'
<< info.diskUsedGB << ';'
<< info.diskTotalGB << ';'
<< info.netLoadPercent << ';'
<< info.netReceiveSpeedMBs << ';'
<< info.netSendSpeedMBs << ';'
<< gpuName_ << ';'
<< gpuDetail;
const std::string s = os.str();
const int size = static_cast<int>(s.length());
const MgErr err = DSSetHandleSize(outString, sizeof(int32) + size * sizeof(uChar));
if (err != noErr) return 0;
(*outString)->cnt = size;
if (size > 0) memcpy((*outString)->str, s.c_str(), size);
return 1;
} catch (...) {
return 0;
}
}
extern "C" __declspec(dllexport) int ReleaseLoggers() {
try {
bool result = ANSCENTER::ANSLSHelper::ReleaseLogger();