-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCPUGPU.cpp
More file actions
515 lines (435 loc) · 18 KB
/
CPUGPU.cpp
File metadata and controls
515 lines (435 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
// This program is a custom plugin for LCDSmartie https://github.com/LCD-Smartie/LCDSmartie designed to monitor
// and retrieve hardware metrics for CPU and GPU.
// It uses LibreHardwareMonitor and NVIDIA Management Library (NVML) to access sensor data.
// Make sure to add a LibreHardwareMonitor.dll in root LCDSmartie directory and compile with the /clr option.
#define WIN32_LEAN_AND_MEAN // Reduce the inclusion of rarely used Windows headers to speed up compilation.
#include <windows.h>
#include <string>
#include <nvml.h>
#using "LibreHardwareMonitorLib.dll"
using namespace LibreHardwareMonitor::Hardware;
#define DLLEXPORT __declspec(dllexport)
// NVML clock throttle reasons constants.
#define NVML_CLK_THROTTLE_REASON_THERMAL_LIMIT 0x0000000000000002LL
#define NVML_CLK_THROTTLE_REASON_RELIABILITY 0x0000000000000004LL
#define NVML_CLK_THROTTLE_REASON_SW_POWER_CAP 0x0000000000000008LL
static bool nvmlInitialized = false;
static const int CPU_FAN = 2; // Index of the CPU fan, based on motherboard specifications. For me it is a #2 on Nuvoton NCT6796D-R chip
static const int CPU_SPEED = 1800; // Maximum CPU fan speed in RPM, based on CPU cooler specs
static const int MIN_INTERVAL = 300; // Minimum refresh interval in milliseconds
// Class for monitoring CPU
public ref class HardwareMonitor abstract sealed {
public:
static Computer^ computer = nullptr;
// Initialize the hardware monitor
static void Initialize() {
if (computer == nullptr) {
computer = gcnew Computer();
computer->IsCpuEnabled = true;
computer->IsMotherboardEnabled = true,
computer->Open();
}
}
// Close the hardware monitor
static void Close() {
if (computer != nullptr) {
computer->Close();
computer = nullptr;
}
}
};
// Check if the program is running with administrative privileges
bool IsRunningAsAdmin() {
BOOL isAdmin = FALSE;
PSID adminGroup = NULL;
SID_IDENTIFIER_AUTHORITY ntAuthority = SECURITY_NT_AUTHORITY;
if (AllocateAndInitializeSid(
&ntAuthority, 2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&adminGroup))
{
CheckTokenMembership(NULL, adminGroup, &isAdmin);
FreeSid(adminGroup);
}
return isAdmin;
}
// Check if NVML (NVIDIA Management Library) is initialized
bool checkNvmlInitialized(char* errorMsg, size_t bufSize) {
if (!nvmlInitialized) {
snprintf(errorMsg, bufSize, "NVML not initialized");
return false;
}
return true;
}
// Get the current CPU load in percentage
int GetCpuLoad() {
HardwareMonitor::Initialize();
for each (IHardware ^ hardware in HardwareMonitor::computer->Hardware) {
if (hardware->HardwareType == HardwareType::Cpu) {
hardware->Update();
for each (ISensor ^ sensor in hardware->Sensors) {
if (sensor->SensorType == SensorType::Load && sensor->Name == "CPU Total") {
return static_cast<int>(sensor->Value.GetValueOrDefault(0.0f));
}
}
}
}
return -1; // Return -1 if the sensor is not found or the value is unavailable
}
// Get the current CPU power consumption in watts
int GetCpuPower() {
HardwareMonitor::Initialize();
for each (IHardware ^ hardware in HardwareMonitor::computer->Hardware) {
if (hardware->HardwareType == HardwareType::Cpu) {
hardware->Update();
for each (ISensor ^ sensor in hardware->Sensors) {
if (sensor->SensorType == SensorType::Power && sensor->Name->Contains("Package")) {
return static_cast<int>(sensor->Value.GetValueOrDefault(0.0f));
}
}
}
}
return -1; // Return -1 if the sensor is not found or the value is unavailable
}
// Get the current CPU temperature in degrees Celsius
int GetCpuTemperature() {
HardwareMonitor::Initialize();
for each (IHardware ^ hardware in HardwareMonitor::computer->Hardware) {
if (hardware->HardwareType == HardwareType::Cpu) {
hardware->Update();
for each (ISensor ^ sensor in hardware->Sensors) {
if (sensor->SensorType == SensorType::Temperature && sensor->Name == "CPU Package") {
// Ïîëó÷àåì çíà÷åíèå òåìïåðàòóðû è îêðóãëÿåì
return static_cast<int>(sensor->Value.GetValueOrDefault(0.0f));
}
}
}
}
return -1; // Return -1 if the sensor is not found or the value is unavailable
}
// Get the current CPU fan speed as a percentage of the maximum speed
int GetCpuFanSpeed(int fanIndex, int maxFanSpeed) {
HardwareMonitor::Initialize();
int currentFanIndex = 0;
for each (IHardware ^ hardware in HardwareMonitor::computer->Hardware) {
hardware->Update();
// Check subcomponents (e.g., additional sensors on the motherboard)
for each (IHardware ^ subHardware in hardware->SubHardware) {
subHardware->Update();
for each (ISensor ^ subSensor in subHardware->Sensors) {
if (subSensor->SensorType == SensorType::Fan) {
if (currentFanIndex == fanIndex) {
float currentSpeed = subSensor->Value.GetValueOrDefault(0.0f);
if (currentSpeed == 0.0f) return 0; // Return 0 if the fan is not spinning.
// Convert speed to percentage
return static_cast<int>((currentSpeed / maxFanSpeed) * 100.0f);
}
currentFanIndex++;
}
}
}
}
return -1; // Return -1 if the sensor is not found or the value is unavailable
}
// Get the current CPU fan speed in RPM
int GetCpuFanSpeedRPM(int fanIndex, int maxFanSpeed) {
HardwareMonitor::Initialize();
int currentFanIndex = 0;
for each (IHardware ^ hardware in HardwareMonitor::computer->Hardware) {
hardware->Update();
// Check subcomponents (e.g., additional sensors on the motherboard)
for each (IHardware ^ subHardware in hardware->SubHardware) {
subHardware->Update();
for each (ISensor ^ subSensor in subHardware->Sensors) {
if (subSensor->SensorType == SensorType::Fan) {
if (currentFanIndex == fanIndex) {
return static_cast<int>(subSensor->Value.GetValueOrDefault(0.0f));
}
currentFanIndex++;
}
}
}
}
return -1; // Return -1 if the sensor is not found or the value is unavailable
}
// Get the current CPU clock frequency in MHz
float GetCpuFrequency() {
HardwareMonitor::Initialize();
for each (IHardware ^ hardware in HardwareMonitor::computer->Hardware) {
if (hardware->HardwareType == HardwareType::Cpu) {
hardware->Update();
for each (ISensor ^ sensor in hardware->Sensors) {
if (sensor->SensorType == SensorType::Clock && sensor->Name == "CPU Core #1") {
return sensor->Value.GetValueOrDefault(0.0f);
}
}
}
}
return -1; // Return -1 if the sensor is not found or the value is unavailable
}
/*********************************************************
* SmartieInit *
*********************************************************/
// Initializes the Smartie plugin. Checks for administrative privileges,
// initializes the NVML library for GPU monitoring, and sets up the hardware monitor
extern "C" DLLEXPORT void __stdcall SmartieInit() {
if (!IsRunningAsAdmin()) {
MessageBoxA(0, "Administrative privileges required for this plugin", "Error", MB_OK);
}
if (!nvmlInitialized) {
// Attempt to initialize NVML (NVIDIA Management Library) for GPU monitoring
nvmlReturn_t result = nvmlInit();
if (result == NVML_SUCCESS) {
nvmlInitialized = true;
}
else {
MessageBoxA(0, nvmlErrorString(result), "NVML Init Failed", MB_OK);
}
}
try {
// Initialize the CPU hardware monitor
HardwareMonitor::Initialize();
}
catch (System::Exception^ ex) {
MessageBoxA(0, (const char*)(System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(ex->Message)).ToPointer(),
"Initialization Error", MB_OK);
}
}
/*********************************************************
* SmartieFini *
*********************************************************/
// Cleans up and shuts down the Smartie plugin. Releases resources and closes NVML and hardware monitor
extern "C" DLLEXPORT void __stdcall SmartieFini() {
if (nvmlInitialized) {
// Shut down NVML
nvmlShutdown();
nvmlInitialized = false;
// Close the hardware monitor
HardwareMonitor::Close();
}
}
/*********************************************************
* GetMinRefreshInterval *
*********************************************************/
// Returns the minimum refresh interval in milliseconds for sensor data updates
extern "C" DLLEXPORT int __stdcall GetMinRefreshInterval() {
return MIN_INTERVAL;
}
/*********************************************************
* Function 1 *
* Returns CPU sensors data *
*********************************************************/
// Function to retrieve various CPU sensor data (load, power, temperature, fan speed, etc.)
// based on the parameter provided by the user
extern "C" __declspec(dllexport) char* __stdcall function1(char* param1, char* param2) {
static char tempStr[256];
memset(tempStr, 0, sizeof(tempStr));
bool showUnits = (strcmp(param2, "1") == 0);
if (strcmp(param1, "Load") == 0) {
// Retrieve CPU load percentage
int load = GetCpuLoad();
if (load < 0) {
snprintf(tempStr, sizeof(tempStr), "Error reading CPU Load");
}
else {
snprintf(tempStr, sizeof(tempStr), showUnits ? "%u%%" : "%u", load);
}
return tempStr;
}
else if (strcmp(param1, "Power") == 0) {
// Retrieve CPU power consumption
int tdp = GetCpuPower();
if (tdp < 0) {
snprintf(tempStr, sizeof(tempStr), "Error reading CPU Power");
}
else {
snprintf(tempStr, sizeof(tempStr), showUnits ? "%uW" : "%u", tdp);
}
return tempStr;
}
else if (strcmp(param1, "Temp") == 0) {
// Retrieve CPU temperature
int temp = GetCpuTemperature();
if (temp < 0) {
snprintf(tempStr, sizeof(tempStr), "Error reading CPU Temp");
}
else {
snprintf(tempStr, sizeof(tempStr), showUnits ? "%u°C" : "%u", temp);
}
return tempStr;
}
else if (strcmp(param1, "Fan_RPM") == 0) {
// Retrieve CPU Fan speed in RPM
int fanSpeedRPM = GetCpuFanSpeedRPM(CPU_FAN, CPU_SPEED);
if (fanSpeedRPM < 0) {
snprintf(tempStr, sizeof(tempStr), "Error reading Fan Speed");
}
else {
snprintf(tempStr, sizeof(tempStr), showUnits ? "%uRPM" : "%u", fanSpeedRPM);
}
return tempStr;
}
else if (strcmp(param1, "Fan") == 0) {
// Retrieve CPU Fan speed in %
int fanSpeed = GetCpuFanSpeed(CPU_FAN, CPU_SPEED);
if (fanSpeed < 0) {
snprintf(tempStr, sizeof(tempStr), "Error reading Fan Speed");
}
else {
snprintf(tempStr, sizeof(tempStr), showUnits ? "%u%%" : "%u", fanSpeed);
}
return tempStr;
}
else if (strcmp(param1, "Clock") == 0) {
// Retrieve CPU Clock for first core
float clock = GetCpuFrequency();
if (clock < 0) {
snprintf(tempStr, sizeof(tempStr), "Error reading CPU clock");
}
else {
float clockGHz = static_cast<float>(clock) / 1000.0f;
snprintf(tempStr, sizeof(tempStr), showUnits ? "%.2fGHz" : "%.2f", clockGHz);
}
return tempStr;
}
snprintf(tempStr, sizeof(tempStr), "Invalid parameter");
return tempStr;
}
/*********************************************************
* Function 2 *
* Returns GPU sensors data *
*********************************************************/
// Function to retrieve various GPU sensor data (temperature, fan speed, power usage, memory usage, etc.)
// using the NVML library
extern "C" DLLEXPORT char* __stdcall function2(char* param1, char* param2) {
static char tempStr[256];
memset(tempStr, 0, sizeof(tempStr));
if (!checkNvmlInitialized(tempStr, sizeof(tempStr))) {
// Return an error message if NVML is not initialized
return tempStr;
}
nvmlDevice_t device;
nvmlReturn_t result = nvmlDeviceGetHandleByIndex(0, &device);
if (result != NVML_SUCCESS) {
// Return an error message if the GPU handle cannot be obtained
snprintf(tempStr, sizeof(tempStr), "GPU handle error: %s", nvmlErrorString(result));
return tempStr;
}
bool showUnits = (strcmp(param2, "1") == 0);
if (strcmp(param1, "Temp") == 0) {
// Retrieve GPU temperature
unsigned int temp;
result = nvmlDeviceGetTemperature(device, NVML_TEMPERATURE_GPU, &temp);
if (result != NVML_SUCCESS) {
snprintf(tempStr, sizeof(tempStr), "Error getting temp: %s", nvmlErrorString(result));
}
else {
snprintf(tempStr, sizeof(tempStr), showUnits ? "%u°C" : "%u", temp);
}
return tempStr;
}
else if (strcmp(param1, "Limit") == 0) {
// Retrieve symbol '!' if GPU power limit is reached
unsigned long long throttleReasons;
result = nvmlDeviceGetCurrentClocksThrottleReasons(device, &throttleReasons);
if (result != NVML_SUCCESS) {
snprintf(tempStr, sizeof(tempStr), "Error getting throttle reasons: %s", nvmlErrorString(result));
}
else {
snprintf(tempStr, sizeof(tempStr), throttleReasons & NVML_CLK_THROTTLE_REASON_RELIABILITY ? "!" : " ");
}
return tempStr;
}
else if (strcmp(param1, "Fan") == 0) {
// Retrieve GPU Fan speed in %
unsigned int fanSpeed;
result = nvmlDeviceGetFanSpeed(device, &fanSpeed);
if (result != NVML_SUCCESS) {
snprintf(tempStr, sizeof(tempStr), "Error getting fan speed: %s", nvmlErrorString(result));
}
else {
snprintf(tempStr, sizeof(tempStr), showUnits ? "%u%%" : "%u", fanSpeed);
}
return tempStr;
}
else if (strcmp(param1, "Power") == 0) {
// Retrieve GPU power consumption
unsigned int power;
result = nvmlDeviceGetPowerUsage(device, &power);
if (result != NVML_SUCCESS) {
snprintf(tempStr, sizeof(tempStr), "Error getting power usage: %s", nvmlErrorString(result));
}
else {
snprintf(tempStr, sizeof(tempStr), showUnits ? "%uW" : "%u", (unsigned int)(power / 1000.0 + 0.5));
}
return tempStr;
}
else if (strcmp(param1, "Clock") == 0) {
// Retrieve GPU core clock
unsigned int clock;
result = nvmlDeviceGetClock(device, NVML_CLOCK_GRAPHICS, NVML_CLOCK_ID_CURRENT, &clock);
if (result != NVML_SUCCESS) {
snprintf(tempStr, sizeof(tempStr), "Error getting GPU clock: %s", nvmlErrorString(result));
}
else {
float clockGHz = static_cast<float>(clock) / 1000.0f;
snprintf(tempStr, sizeof(tempStr), showUnits ? "%.2fGHz" : "%.2f", clockGHz);
}
return tempStr;
}
else if (strcmp(param1, "Mem_Clock") == 0) {
// Retrieve GPU memory clock
unsigned int memClock;
result = nvmlDeviceGetClock(device, NVML_CLOCK_MEM, NVML_CLOCK_ID_CURRENT, &memClock);
if (result != NVML_SUCCESS) {
snprintf(tempStr, sizeof(tempStr), "Error getting Memory clock: %s", nvmlErrorString(result));
}
else {
float memClockGHz = static_cast<float>(memClock) / 1000.0f;
snprintf(tempStr, sizeof(tempStr), showUnits ? "%.2fGHz" : "%.2f", memClockGHz);
}
return tempStr;
}
else if (strcmp(param1, "Mem_Alloc") == 0) {
// Retrieve GPU memory allocation
nvmlMemory_t memInfo;
result = nvmlDeviceGetMemoryInfo(device, &memInfo);
if (result != NVML_SUCCESS) {
snprintf(tempStr, sizeof(tempStr), "Error getting memory usage: %s", nvmlErrorString(result));
}
else {
float memUsage = (float)memInfo.used / (1024 * 1024 * 1024);
snprintf(tempStr, sizeof(tempStr), showUnits ? "%.1fGb" : "%.1f", memUsage);
}
return tempStr;
}
else if (strcmp(param1, "Mem_Usage") == 0) {
// Retrieve GPU memory usage in %
nvmlMemory_t memInfo;
result = nvmlDeviceGetMemoryInfo(device, &memInfo);
if (result != NVML_SUCCESS) {
snprintf(tempStr, sizeof(tempStr), "Error getting memory usage: %s", nvmlErrorString(result));
}
else {
unsigned int memUsage = (unsigned int)((memInfo.used * 100) / memInfo.total);
snprintf(tempStr, sizeof(tempStr), showUnits ? "%u%%" : "%u", memUsage);
}
return tempStr;
}
else if (strcmp(param1, "Load") == 0) {
// Retrieve GPU load percentage
nvmlUtilization_t utilization;
result = nvmlDeviceGetUtilizationRates(device, &utilization);
if (result != NVML_SUCCESS) {
snprintf(tempStr, sizeof(tempStr), "Error getting GPU load: %s", nvmlErrorString(result));
}
else {
snprintf(tempStr, sizeof(tempStr), showUnits ? "%u%%" : "%u", utilization.gpu);
}
return tempStr;
}
snprintf(tempStr, sizeof(tempStr), "Invalid parameter");
return tempStr;
}