Fix other ANSCV classes
This commit is contained in:
@@ -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");
|
||||
|
||||
Reference in New Issue
Block a user