-
Notifications
You must be signed in to change notification settings - Fork 1
/
battstatus.cpp
1673 lines (1438 loc) · 53.8 KB
/
battstatus.cpp
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* battstatus - Monitor the Windows battery status for changes in state
Sample output:
[Wed Aug 02 12:15:55 PM]: 5 hr 30 min (99%) remaining
[Wed Aug 02 12:17:38 PM]: WM_POWERBROADCAST: PBT_APMPOWERSTATUSCHANGE
[Wed Aug 02 12:17:38 PM]: 99% available (plugged in, not charging)
[Wed Aug 02 12:17:44 PM]: Fully charged (100%)
[Wed Aug 02 12:41:50 PM]: WM_POWERBROADCAST: PBT_APMPOWERSTATUSCHANGE
[Wed Aug 02 12:41:50 PM]: 99% remaining
[Wed Aug 02 12:45:14 PM]: 8 hr 13 min (98%) remaining
[Wed Aug 02 12:49:39 PM]: 7 hr 37 min (97%) remaining
It can optionally show verbose information and prevent sleep. Use option --help
to see the usage information.
To build using Visual Studio 2008 (with TR1 support) or later:
cl /W4 /wd4127 /wd4530 battstatus.cpp user32.lib powrprof.lib setupapi.lib
To build using MinGW or MinGW-w64:
g++ -Wall -std=gnu++11 -o battstatus battstatus.cpp -lpowrprof -lsetupapi -luuid
https://github.com/jay/battstatus
*//*
Copyright (C) 2017 Jay Satiro <[email protected]>
All rights reserved.
This file is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This file is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
<https://www.gnu.org/licenses/#GPL>
*/
#define _WIN32_WINNT 0x0501
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#define WIN32_NO_STATUS
#include <windows.h>
#undef WIN32_NO_STATUS
#ifdef __MINGW32__
#include <_mingw.h>
#ifdef __MINGW64_VERSION_MAJOR
#include <batclass.h>
#include <ntstatus.h>
#else
#include <ddk/batclass.h>
#include <ddk/ntddk.h>
#endif
#else
#include <batclass.h>
#include <ntstatus.h>
#endif
#include <devguid.h>
#include <powrprof.h>
#include <setupapi.h>
#include <assert.h>
#include <limits.h>
#include <stdio.h>
#include <time.h>
#include <deque>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <type_traits>
#include <vector>
#ifndef ES_AWAYMODE_REQUIRED
#define ES_AWAYMODE_REQUIRED ((DWORD)0x00000040)
#endif
#ifndef PBTF_APMRESUMEFROMFAILURE
#define PBTF_APMRESUMEFROMFAILURE 0x00000001
#endif
#ifndef PBT_POWERSETTINGCHANGE
#define PBT_POWERSETTINGCHANGE 0x8013
#endif
#ifndef SPSF_BATTERYCHARGING
#define SPSF_BATTERYCHARGING 8
#endif
#ifndef SPSF_BATTERYNOBATTERY
#define SPSF_BATTERYNOBATTERY 128
#endif
/* The battery saver status is available since Windows 10. It's stored in
member SystemStatusFlag but older headers use the name Reserved1. */
#if defined(__MINGW64_VERSION_MAJOR) || \
!defined(SYSTEM_STATUS_FLAG_POWER_SAVING_ON)
#define SystemStatusFlag Reserved1
#endif
#ifndef SYSTEM_STATUS_FLAG_POWER_SAVING_ON
#define SYSTEM_STATUS_FLAG_POWER_SAVING_ON 1
#endif
// Bool macros for SYSTEM_POWER_STATUS
#define BATTSAVER(status) \
((status).SystemStatusFlag == SYSTEM_STATUS_FLAG_POWER_SAVING_ON)
#define CHARGING(status) (!!((status).BatteryFlag & SPSF_BATTERYCHARGING))
#define NO_BATTERY(status) (!!((status).BatteryFlag & SPSF_BATTERYNOBATTERY))
#define PLUGGED_IN(status) ((status).ACLineStatus == 1)
/* Sample output at field width 22:
ACLineStatus: Offline
BatteryFlag: Low
BatteryLifePercent: 17%
BatteryLifeTime: 42 min
BatteryFullLifeTime: Unknown
Battery discharge: -11433mW
*/
#define BATT_FIELD_WIDTH 22
using namespace std;
/* In Visual Studio 2008 we need the TR1 functions in std::tr1, which is only
available if its optional feature pack or SP1 is installed. */
#if _MSC_VER == 1500
using namespace std::tr1;
#endif
// Command line options, refer to ShowUsage
unsigned lifetime_span_minutes;
bool monitor = true;
bool prevent_sleep;
bool console_title;
unsigned verbose;
RTL_OSVERSIONINFOW os;
/* There are certain times when the battery charge state should be suppressed,
such as when it continually changes in a short period of time and verbose
mode is disabled. */
bool suppress_charge_state;
/* There are certain times when the battery lifetime should be suppressed, such
as when the computer just woke up. */
bool suppress_lifetime;
/* There are certain times when SYSTEM_POWER_STATUS error messages should be
suppressed, such as when GetSystemPowerStatus fails continuously. */
bool suppress_sps_errmsgs;
/* time as local time string in format: Tue May 16 03:24:31 PM */
string TimeToLocalTimeStr(time_t t)
{
char buf[100];
/* localtime is thread-safe in Windows but the per-thread structure that's
returned is shared by gmtime, mktime, mkgmtime. */
struct tm *lt = localtime(&t);
// old format: "%Y-%m-%d %H:%M:%S" 2017-05-16 15:10:08
if(!lt || !strftime(buf, sizeof buf, "%a %b %d %I:%M:%S %p", lt))
return "Unknown time";
return buf;
}
/* The timestamp style in verbose mode:
--- Sun May 28 07:00:55 PM ---
text
*/
#define TIMESTAMPED_HEADER \
"\n--- " << TimeToLocalTimeStr(time(NULL)).c_str() << " ---\n"
/* The timestamp style in default mode: [Sun May 28 07:00:27 PM]: text */
#define TIMESTAMPED_PREFIX \
"[" << TimeToLocalTimeStr(time(NULL)).c_str() << "]: "
template <typename T>
string UndocumentedValueStr(T undocumented_value)
{
stringstream ss;
ss << "Undocumented value: " << undocumented_value;
if(is_arithmetic<T>::value)
ss << " (hex: " << hex << undocumented_value << ")";
return ss.str();
}
string UndocumentedValueStr(char undocumented_value)
{
// can't use conditional class here since VS2008 doesn't have it
if(is_signed<char>::value)
return UndocumentedValueStr<signed>(undocumented_value);
else
return UndocumentedValueStr<unsigned>(undocumented_value);
}
string UndocumentedValueStr(unsigned char undocumented_value)
{
return UndocumentedValueStr<unsigned>(undocumented_value);
}
string UndocumentedValueStr(signed char undocumented_value)
{
return UndocumentedValueStr<signed>(undocumented_value);
}
/* Relative capacity and rate:
According to BATTERY_INFORMATION documentation the capacity and rate
information reported by a battery may be relative, with all rate information
reported in units per hour.
"If [flag BATTERY_CAPACITY_RELATIVE] is set, all references to units in
the other battery documentation can be ignored."
That flag is set per battery, however most of this program looks at overall
battery use in structures where that information is not available, so in
those cases we treat it as unknown.
https://msdn.microsoft.com/en-us/library/windows/desktop/aa372661.aspx */
enum CapacityType
{
CAPACITY_TYPE_UNKNOWN,
CAPACITY_TYPE_RELATIVE,
CAPACITY_TYPE_MILLIWATT_HOUR
};
enum RateType
{
RATE_TYPE_UNKNOWN,
RATE_TYPE_RELATIVE,
RATE_TYPE_MILLIWATT
};
string CapacityStr(DWORD unit, enum CapacityType ct = CAPACITY_TYPE_UNKNOWN)
{
stringstream ss;
ss << unit;
if(ct == CAPACITY_TYPE_RELATIVE)
ss << " (relative)";
else if(ct == CAPACITY_TYPE_MILLIWATT_HOUR)
ss << "mWh";
else
ss << "mWh (or relative)";
return ss.str();
}
string RateStr(DWORD unit, enum RateType rt = RATE_TYPE_UNKNOWN)
{
stringstream ss;
if(rt == RATE_TYPE_RELATIVE)
ss << unit << " (relative)";
else {
/* Rate as described by SYSTEM_BATTERY_STATE (other rates may differ):
"The current rate of discharge of the battery, in mW. A nonzero,
positive rate indicates charging; a negative rate indicates discharging.
Some batteries report only discharging rates. This value should be
treated as a LONG as it can contain negative values (with the high bit
set)."
However when some of my batteries charge the Rate is:
0x80000000 == -2147483648 (LONG) == 2147483648 (DWORD)
When my batteries are removed the Rate is 0. */
if(unit == 0 || unit == 0x80000000)
return "Unknown";
ss << showpos << (LONG)unit;
if(rt == RATE_TYPE_MILLIWATT)
ss << "mW";
else
ss << "mW (or relative)";
}
return ss.str();
}
string RateStr(LONG Rate, enum RateType rt = RATE_TYPE_UNKNOWN)
{
return RateStr((DWORD)Rate, rt);
}
string CapabilitiesStr(ULONG Capabilities)
{
if(Capabilities == 0)
return "<none>";
stringstream ss;
#define EXTRACT_CAPABILITIES(flag) \
if((Capabilities & flag)) { \
if(ss.tellp() > 0) \
ss << " | "; \
ss << #flag; \
Capabilities &= ~flag; \
}
EXTRACT_CAPABILITIES(BATTERY_CAPACITY_RELATIVE);
EXTRACT_CAPABILITIES(BATTERY_IS_SHORT_TERM);
EXTRACT_CAPABILITIES(BATTERY_SET_CHARGE_SUPPORTED);
EXTRACT_CAPABILITIES(BATTERY_SET_DISCHARGE_SUPPORTED);
EXTRACT_CAPABILITIES(BATTERY_SYSTEM_BATTERY);
if(Capabilities) {
if(ss.tellp() > 0)
ss << " | ";
ss << UndocumentedValueStr(Capabilities);
}
return ss.str();
}
string TechnologyStr(UCHAR Technology)
{
switch(Technology)
{
case 0: return "Nonrechargeable";
case 1: return "Rechargeable";
}
return UndocumentedValueStr(Technology);
}
string ChemistryStr(const UCHAR Chemistry[4])
{
/* Chemistry is "not necessarily zero-terminated" */
int i;
for(i = 0; i < 4; ++i) {
if(Chemistry[i] == '\0')
break;
}
return string((const char *)Chemistry, i);
}
string DesignedCapacityStr(ULONG DesignedCapacity,
enum CapacityType ct = CAPACITY_TYPE_UNKNOWN)
{
return CapacityStr(DesignedCapacity, ct);
}
string FullChargedCapacityStr(ULONG FullChargedCapacity,
enum CapacityType ct = CAPACITY_TYPE_UNKNOWN)
{
return CapacityStr(FullChargedCapacity, ct);
}
/* DefaultAlert1:
"The manufacturer's suggestion of a capacity, in mWh, at which a low battery
alert should occur."
*/
string DefaultAlert1Str(DWORD DefaultAlert1,
enum CapacityType ct = CAPACITY_TYPE_UNKNOWN)
{
return CapacityStr(DefaultAlert1, ct);
}
/* DefaultAlert2:
"The manufacturer's suggestion of a capacity, in mWh, at which a warning
battery alert should occur."
*/
string DefaultAlert2Str(DWORD DefaultAlert2,
enum CapacityType ct = CAPACITY_TYPE_UNKNOWN)
{
return CapacityStr(DefaultAlert2, ct);
}
string CriticalBiasStr(ULONG CriticalBias,
enum CapacityType ct = CAPACITY_TYPE_UNKNOWN)
{
return CapacityStr(CriticalBias, ct);
}
string CycleCountStr(ULONG CycleCount)
{
stringstream ss;
ss << CycleCount;
return ss.str();
}
string BatteryInformationStr(const BATTERY_INFORMATION *bi)
{
stringstream ss;
enum CapacityType ct = ((bi->Capabilities & BATTERY_CAPACITY_RELATIVE) ?
CAPACITY_TYPE_RELATIVE :
CAPACITY_TYPE_MILLIWATT_HOUR);
#define BATTINFO_PRELUDE(item) \
ss << left << setw(BATT_FIELD_WIDTH) << #item ": " << right;
#define SHOW_BATTINFO(item) \
BATTINFO_PRELUDE(item); \
ss << item##Str(bi->item) << "\n";
#define SHOW_BATTINFO_CAPACITY_MEMBER(item) \
BATTINFO_PRELUDE(item); \
ss << item##Str(bi->item, ct) << "\n";
SHOW_BATTINFO(Capabilities);
SHOW_BATTINFO(Technology);
SHOW_BATTINFO(Chemistry);
SHOW_BATTINFO_CAPACITY_MEMBER(DesignedCapacity);
SHOW_BATTINFO_CAPACITY_MEMBER(FullChargedCapacity);
SHOW_BATTINFO_CAPACITY_MEMBER(DefaultAlert1);
SHOW_BATTINFO_CAPACITY_MEMBER(DefaultAlert2);
SHOW_BATTINFO_CAPACITY_MEMBER(CriticalBias);
SHOW_BATTINFO(CycleCount);
return ss.str();
}
void ShowBatteryInformation(const BATTERY_INFORMATION *bi)
{
cout << BatteryInformationStr(bi) << flush;
}
string ManufactureDateStr(BATTERY_MANUFACTURE_DATE *mnfctr_date)
{
stringstream ss;
if(!mnfctr_date->Year)
return "Unknown";
ss.fill('0');
ss << setw(4) << (unsigned)mnfctr_date->Year << "-"
<< setw(2) << (unsigned)mnfctr_date->Month << "-"
<< setw(2) << (unsigned)mnfctr_date->Day;
return ss.str();
}
// this is the input for EnumBattInterfacesProc
struct device {
/* slot always has a valid number. Any other member may be valid. */
unsigned slot; // battery interface number (starts at 0, sequential)
HANDLE handle; // battery interface handle (invalid: INVALID_HANDLE_VALUE)
wchar_t *path; // battery interface path
};
/* this is the output for EnumBattInterfacesProc
MSDN says battery tags are not unique between battery device interfaces
(slots), therefore more than one slot may have a battery with the same tag.
Furthermore the tag may change even if the battery hasn't, and when that
happens "all cached data should be re-read".
To see if the same physical battery is present compare unique_id, not tag.
https://msdn.microsoft.com/en-us/library/windows/desktop/aa372659.aspx
*/
struct battery {
/* 'success' signifies that all requested information was obtained from the
battery. Unless otherwise noted any member may be valid even if success is
false. To determine if a battery is present in the slot check if
tag != BATTERY_TAG_INVALID. */
bool success;
ULONG tag; // battery tag (invalid: BATTERY_TAG_INVALID)
wchar_t *unique_id; // string that uniquely identifies the battery
wchar_t *path; // battery interface path
// battery manufacture date (unknown: 0000-00-00)
BATTERY_MANUFACTURE_DATE mnfctr_date;
BATTERY_INFORMATION info; // battery info (invalid: success is false)
double health; // percentage of full capacity vs design capacity
};
typedef BOOL (CALLBACK* BATTINTENUMPROC)(const struct device *device,
void *cbdata);
/* Get battery info for each battery.
Pass a pointer to an _empty_ vector<battery> as cbdata.
This is called by EnumBattInterfaces once for each battery interface without
skipping any inaccessible devices, starting at 0 until the last interface.
After this function returns the device resources are freed. If you'll need to
reopen the battery interface later, make a copy of the path.
TRUE: Continue on to the next interface.
FALSE: Stop enumerating interfaces; do not call this function again.
*/
BOOL CALLBACK EnumBattInterfacesProc(const struct device *device,
void *cbdata)
{
DWORD bytes_written;
vector<battery> *batteries = (vector<battery> *)cbdata;
batteries->push_back(battery());
struct battery *battery = &batteries->back();
battery->tag = BATTERY_TAG_INVALID;
if(!device->path || device->handle == INVALID_HANDLE_VALUE)
return TRUE; // interface inaccessible, continue on
battery->path = _wcsdup(device->path);
if(!battery->path) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
// How long to wait for the interface to return a battery tag
ULONG wait = 0;
if(!DeviceIoControl(device->handle, IOCTL_BATTERY_QUERY_TAG,
&wait, sizeof(wait),
&battery->tag, sizeof(battery->tag),
&bytes_written, NULL)) {
return TRUE; // battery not found, continue on
}
BATTERY_QUERY_INFORMATION bqi = { battery->tag };
bqi.InformationLevel = BatteryUniqueID;
wchar_t buffer[1024];
if(!DeviceIoControl(device->handle, IOCTL_BATTERY_QUERY_INFORMATION,
&bqi, sizeof(bqi),
buffer, sizeof(buffer),
&bytes_written, NULL)) {
return TRUE; // unique id string not found or too long, continue on
}
battery->unique_id = _wcsdup(buffer);
if(!battery->unique_id) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
bqi.InformationLevel = BatteryManufactureDate;
if(!DeviceIoControl(device->handle, IOCTL_BATTERY_QUERY_INFORMATION,
&bqi, sizeof(bqi),
&battery->mnfctr_date, sizeof(battery->mnfctr_date),
&bytes_written, NULL)) {
// assume manufacture date unknown (0000-00-00)
memset(&battery->mnfctr_date, 0, sizeof battery->mnfctr_date);
}
bqi.InformationLevel = BatteryInformation;
if(!DeviceIoControl(device->handle, IOCTL_BATTERY_QUERY_INFORMATION,
&bqi, sizeof(bqi),
&battery->info, sizeof(battery->info),
&bytes_written, NULL)) {
memset(&battery->info, 0, sizeof battery->info);
return TRUE; // battery info isn't accessible, continue on
}
if(!battery->info.FullChargedCapacity ||
battery->info.FullChargedCapacity == (ULONG)-1)
battery->health = 0;
else if(!battery->info.DesignedCapacity ||
battery->info.DesignedCapacity == (ULONG)-1 ||
battery->info.FullChargedCapacity >= battery->info.DesignedCapacity)
battery->health = 100;
else {
battery->health = 100 * ((double)battery->info.FullChargedCapacity /
battery->info.DesignedCapacity);
}
battery->success = true;
return TRUE;
}
/* Enumerate the battery device interfaces.
EnumProc should be called by this function once for each battery interface
without skipping any inaccessible devices, starting at 0 until the last
interface.
TRUE: EnumProc was called and returned TRUE for all interfaces.
FALSE: No interfaces found, out of memory or EnumProc returned FALSE.
*/
BOOL WINAPI EnumBattInterfaces(BATTINTENUMPROC EnumProc, void *cbdata)
{
HDEVINFO hdev = SetupDiGetClassDevs(&GUID_DEVCLASS_BATTERY, 0, 0,
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if(hdev == INVALID_HANDLE_VALUE)
return FALSE;
DWORD idev = 0;
for(; idev < 100; ++idev) {
struct device device;
device.slot = idev;
device.handle = INVALID_HANDLE_VALUE;
device.path = NULL;
SP_DEVICE_INTERFACE_DATA did = { sizeof did, };
if(SetupDiEnumDeviceInterfaces(hdev, NULL, &GUID_DEVCLASS_BATTERY, idev,
&did)) {
DWORD cbRequired = 0;
if(!SetupDiGetDeviceInterfaceDetailW(hdev, &did, NULL, 0,
&cbRequired, 0) &&
GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
PSP_DEVICE_INTERFACE_DETAIL_DATA_W pdidd =
(PSP_DEVICE_INTERFACE_DETAIL_DATA_W)calloc(1, cbRequired);
if(!pdidd) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
pdidd->cbSize = sizeof(*pdidd);
if(SetupDiGetDeviceInterfaceDetailW(hdev, &did, pdidd, cbRequired,
&cbRequired, 0)) {
device.path = _wcsdup(pdidd->DevicePath);
if(!device.path) {
free(pdidd);
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
device.handle = CreateFileW(device.path,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
}
free(pdidd);
}
}
else if(GetLastError() == ERROR_NO_MORE_ITEMS)
break;
BOOL rc = EnumProc(&device, cbdata);
DWORD gle = GetLastError();
free(device.path);
if(device.handle != INVALID_HANDLE_VALUE)
CloseHandle(device.handle);
if(!rc) {
SetLastError(gle);
return FALSE;
}
}
return TRUE;
}
void ShowIndividualBatteryHealth()
{
const char *borderline = "========================================="
"======================================\n";
const char *sepline = "-----------------------------------------"
"--------------------------------------\n";
wstringstream wss;
wss << borderline <<
"Individual Battery Health:\n"
"\n"
"This program is designed to monitor the overall combined battery capacity,\n"
"however what follows is the percentage of how much capacity each individual\n"
"battery is currently able to store (full capacity) versus how much capacity\n"
"it was initially able to store (design capacity), also known as health. A\n"
"battery will lose health the more charge cycles it is put through. Other\n"
"factors affect health such as the method of charging. For example, in my\n"
"experience working on a number of Dell Latitudes, the ExpressCharge feature\n"
"can reduce health faster than normal.\n";
vector<battery> batteries;
EnumBattInterfaces(EnumBattInterfacesProc, &batteries);
unsigned batteries_present = 0;
for(DWORD i = 0; i < batteries.size(); ++i, wss << sepline) {
wss << "\n" << sepline;
wss << "Slot #" << i << ": "
<< (batteries[i].path ? batteries[i].path : L"(inaccessible)") << "\n";
if(batteries[i].tag == BATTERY_TAG_INVALID) {
wss << "(empty)\n";
continue;
}
++batteries_present;
if(!batteries[i].success) {
wss << "(inaccessible)\n";
continue;
}
wss << "\n\"" << batteries[i].unique_id << "\" is at "
<< std::fixed << setprecision(2)
<< batteries[i].health << "% health\n";
wss << "\n" << BatteryInformationStr(&batteries[i].info).c_str();
wss << left << setw(BATT_FIELD_WIDTH) << "Manufacture Date: "
<< right << ManufactureDateStr(&batteries[i].mnfctr_date).c_str()
<< "\n";
}
wss << "\nCounted " << batteries_present << " "
<< (batteries_present == 1 ? "battery" : "batteries") << " "
<< "and " << batteries.size() << " battery interfaces. "
<< "(" << TimeToLocalTimeStr(time(NULL)).c_str() << ")\n";
wss << "\n" << borderline;
wcout << endl << wss.str() << endl;
}
string ACLineStatusStr(unsigned ACLineStatus)
{
switch(ACLineStatus)
{
case 0: return "Offline";
case 1: return "Online";
case 255: return "Unknown status";
}
return UndocumentedValueStr(ACLineStatus);
}
string BatteryFlagStr(unsigned BatteryFlag)
{
/* BatteryFlag "value is zero if the battery is not being charged and the
battery capacity is between low and high." ie if 33 <= percentage <= 66.
Earlier revisions of this function showed 'Normal' instead of '<none>',
but that was less correct since technically 'Normal' is not a flag, and
things like 'Normal | Charging' would need to be handled. */
if(BatteryFlag == 0)
return "<none>";
stringstream ss;
#define EXTRACT_BATTERYFLAG(flag, name) \
if((BatteryFlag & flag)) { \
if(ss.tellp() > 0) \
ss << " | "; \
ss << name; \
BatteryFlag &= ~flag; \
}
EXTRACT_BATTERYFLAG(1, "High");
EXTRACT_BATTERYFLAG(2, "Low");
EXTRACT_BATTERYFLAG(4, "Critical");
EXTRACT_BATTERYFLAG(SPSF_BATTERYCHARGING, "Charging");
EXTRACT_BATTERYFLAG(SPSF_BATTERYNOBATTERY, "No system battery");
EXTRACT_BATTERYFLAG(255, "Unknown status");
if(BatteryFlag) {
if(ss.tellp() > 0)
ss << " | ";
ss << UndocumentedValueStr(BatteryFlag);
}
return ss.str();
}
/* BatteryLifePercent is "255 if status is unknown." */
#define PERCENT_UNKNOWN ((BYTE)255)
string BatteryLifePercentStr(unsigned BatteryLifePercent)
{
stringstream ss;
if(BatteryLifePercent <= 100)
ss << (DWORD)BatteryLifePercent << "%";
else if(BatteryLifePercent == PERCENT_UNKNOWN)
ss << "Unknown status";
else
ss << UndocumentedValueStr(BatteryLifePercent);
return ss.str();
}
/* SystemStatusFlag:
"This flag and the GUID_POWER_SAVING_STATUS GUID were introduced in Windows 10.
This flag was previously reserved, named Reserved1, and had a value of 0."
*/
string SystemStatusFlagStr(unsigned SystemStatusFlag)
{
switch(SystemStatusFlag)
{
case 0: return "Battery saver is off";
case 1: return "Battery saver is on";
}
return UndocumentedValueStr(SystemStatusFlag);
}
/* BatteryLifeTime is "-1 if remaining seconds are unknown or if the device
is connected to AC power." */
#define LIFETIME_UNKNOWN ((DWORD)-1)
/* Format the number of battery life seconds in the same format as the systray:
1 hr 01 min; 1 hr 00 min; 1 min or "Unknown" if LIFETIME_UNKNOWN.
*/
string BatteryLifeTimeStr(DWORD BatteryLifeTime)
{
if(BatteryLifeTime == LIFETIME_UNKNOWN)
return "Unknown";
DWORD hours = BatteryLifeTime / 3600;
DWORD minutes = (BatteryLifeTime % 3600) / 60;
stringstream ss;
if(hours) {
ss << hours << " hr " << setw(2);
ss.fill('0');
}
ss << minutes << " min";
return ss.str();
}
/* BatteryFullLifeTime:
"The system is only capable of estimating BatteryFullLifeTime based on
calculations on BatteryLifeTime and BatteryLifePercent. Without smart battery
subsystems, this value may not be accurate enough to be useful."
*/
string BatteryFullLifeTimeStr(DWORD BatteryFullLifeTime)
{
return BatteryLifeTimeStr(BatteryFullLifeTime);
}
void ShowPowerStatus(const SYSTEM_POWER_STATUS *status)
{
#define SHOW_STATUS(item) \
cout << left << setw(BATT_FIELD_WIDTH) << #item ": " \
<< right << item##Str(status->item) << "\n";
SHOW_STATUS(ACLineStatus);
SHOW_STATUS(BatteryFlag);
SHOW_STATUS(BatteryLifePercent);
if(os.dwMajorVersion >= 10) { /* SystemStatusFlag was added in Windows 10 */
cout << left << setw(BATT_FIELD_WIDTH) << "SystemStatusFlag: "
<< right << SystemStatusFlagStr(status->SystemStatusFlag) << "\n";
}
SHOW_STATUS(BatteryLifeTime);
SHOW_STATUS(BatteryFullLifeTime);
cout << flush;
}
enum cpstype { CPS_EQUAL, CPS_NOTEQUAL };
enum cpstype ComparePowerStatus(const SYSTEM_POWER_STATUS *a,
const SYSTEM_POWER_STATUS *b)
{
#define COMPARE_STATUS(item) \
if(a->item != b->item) \
return CPS_NOTEQUAL;
COMPARE_STATUS(ACLineStatus);
COMPARE_STATUS(BatteryFlag);
COMPARE_STATUS(BatteryLifePercent);
COMPARE_STATUS(SystemStatusFlag);
COMPARE_STATUS(BatteryLifeTime);
COMPARE_STATUS(BatteryFullLifeTime);
return CPS_EQUAL;
}
#define FUNC_SHOW_BOOL(item) \
string item##Str(BOOL item) \
{ \
stringstream ss; \
ss << (item == TRUE ? "TRUE" : \
(item == FALSE ? "FALSE" : \
UndocumentedValueStr(item))); \
return ss.str(); \
}
FUNC_SHOW_BOOL(AcOnLine);
FUNC_SHOW_BOOL(BatteryPresent);
FUNC_SHOW_BOOL(Charging);
FUNC_SHOW_BOOL(Discharging);
string MaxCapacityStr(DWORD MaxCapacity)
{
return CapacityStr(MaxCapacity);
}
string RemainingCapacityStr(DWORD RemainingCapacity)
{
return CapacityStr(RemainingCapacity);
}
string EstimatedTimeStr(DWORD EstimatedTime)
{
return BatteryLifeTimeStr(EstimatedTime);
}
void ShowBatteryState(const SYSTEM_BATTERY_STATE *state)
{
#define SHOW_STATE(item) \
cout << left << setw(BATT_FIELD_WIDTH) << #item ": " \
<< right << item##Str(state->item) << "\n";
SHOW_STATE(AcOnLine);
SHOW_STATE(BatteryPresent);
SHOW_STATE(Charging);
SHOW_STATE(Discharging);
SHOW_STATE(MaxCapacity);
SHOW_STATE(RemainingCapacity);
SHOW_STATE(Rate);
SHOW_STATE(EstimatedTime);
SHOW_STATE(DefaultAlert1);
SHOW_STATE(DefaultAlert2);
cout << flush;
}
/* Return the battery power rate in mW.
A negative rate means discharging and a positive rate means charging.
0 means neither charging nor discharging.
Ignore errors: Don't show them and return 0.
*/
LONG GetBatteryPowerRate()
{
/* Note SYSTEM_BATTERY_STATE seems to be updated by the OS at the same
frequency as SYSTEM_POWER_STATUS, which is not necessarily that often. */
SYSTEM_BATTERY_STATE sbs;
if(CallNtPowerInformation(SystemBatteryState, NULL, 0, &sbs, sizeof sbs))
return 0;
/* As described in RateStr(), 0x80000000 is an invalid value and any other
value should be converted to LONG. */
return ((DWORD)sbs.Rate != 0x80000000) ? (LONG)sbs.Rate : 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if(verbose >= 3)
{
/* show all window messages */
cout << TIMESTAMPED_PREFIX
<< hex << "WindowProc: msg 0x" << msg << ", wparam 0x" << wParam
<< ", lparam 0x" << lParam << dec << endl;
}
switch(msg) {
/* WM_POWERBROADCAST:
"Notifies applications of a change in the power status of the computer,
such as a switch from battery power to A/C. The system also broadcasts
this event when remaining battery power slips below the threshold
specified by the user or if the battery power changes by a specified
percentage."
PBT_APMPOWERSTATUSCHANGE:
"This event can occur when battery life drops to less than 5 minutes, or
when the percentage of battery life drops below 10 percent, or if the
battery life changes by 3 percent."
Note this is a broadcast message and therefore not received by
message-only windows. */
case WM_POWERBROADCAST:
if(wParam == PBT_APMPOWERSTATUSCHANGE) {
static SYSTEM_POWER_STATUS status, prev_status;
prev_status = status;
if(GetSystemPowerStatus(&status)) {
#if 0
cout << "PBT_APMPOWERSTATUSCHANGE DEBUG: \n---\n(prev_status)\n";
ShowPowerStatus(&prev_status);
cout << "---\n(status)\n";
ShowPowerStatus(&status);
cout << "---" << endl;
#endif
/* If the charge state is being suppressed but only it or members
affected by it have changed then don't show anything. */
if(suppress_charge_state &&
status.BatteryLifePercent == prev_status.BatteryLifePercent &&
((status.BatteryFlag & ~SPSF_BATTERYCHARGING) ==
(prev_status.BatteryFlag & ~SPSF_BATTERYCHARGING)))
return TRUE;
}
else
status = prev_status;
}
#define CASE_PBT(item) \
case item: cout << #item; break;
cout << TIMESTAMPED_PREFIX << "WM_POWERBROADCAST: ";
switch(wParam) {
CASE_PBT(PBT_APMQUERYSUSPEND); /* 0x0000 */ /* Win2k & XP only */
CASE_PBT(PBT_APMQUERYSTANDBY); /* 0x0001 */ /* Win2k & XP only */
CASE_PBT(PBT_APMQUERYSUSPENDFAILED); /* 0x0002 */ /* Win2k & XP only */
CASE_PBT(PBT_APMQUERYSTANDBYFAILED); /* 0x0003 */ /* Win2k & XP only */
CASE_PBT(PBT_APMSUSPEND); /* 0x0004 */
CASE_PBT(PBT_APMSTANDBY); /* 0x0005 */
CASE_PBT(PBT_APMRESUMECRITICAL); /* 0x0006 */ /* Win2k & XP only */
CASE_PBT(PBT_APMRESUMESUSPEND); /* 0x0007 */
CASE_PBT(PBT_APMRESUMESTANDBY); /* 0x0008 */
CASE_PBT(PBT_APMBATTERYLOW); /* 0x0009 */ /* Win2k & XP only */
CASE_PBT(PBT_APMPOWERSTATUSCHANGE); /* 0x000A */
CASE_PBT(PBT_APMOEMEVENT); /* 0x000B */ /* Win2k & XP only */
CASE_PBT(PBT_APMRESUMEAUTOMATIC); /* 0x0012 */
CASE_PBT(PBT_POWERSETTINGCHANGE); /* 0x8013 */
default: cout << UndocumentedValueStr(wParam);
}
if(lParam == 0 &&
wParam != PBT_APMQUERYSUSPEND &&
wParam != PBT_APMQUERYSTANDBY) {
/* lParam in this case has no significance so skip showing it */
cout << endl;
return TRUE;
}
cout << " (lParam: ";
if(wParam == PBT_APMQUERYSUSPEND ||
wParam == PBT_APMQUERYSTANDBY) {
LPARAM unknown = (LPARAM)(lParam & ~1);