-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBatteryManagement.cs
216 lines (193 loc) · 10.5 KB
/
BatteryManagement.cs
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
using Microsoft.Win32.SafeHandles;
using System.IO;
using System.Runtime.InteropServices;
using Windows.Devices.Power;
using System.Collections.Specialized;
namespace PowerTray
{
internal class BatteryManagement
{
public static OrderedDictionary GetBatteryInfo(uint batteryTag, SafeFileHandle batteryHandle) // MOVE TO BATTERY MANAGEMENTTNTIT
{
var dataDict = new OrderedDictionary {};
var batteryReport = Battery.AggregateBattery.GetReport(); // get battery info (slow)
if (batteryHandle == null)
{
dataDict = new OrderedDictionary {
{ "Status", 0 },
{ "Percent Remaining", 0.0 },
{ "Remaining Charge mWh", 0 },
{ "Reported Time Left", "0" },
{ "Reported Charge Rate mW", 0 },
{ "Battery Health", 0 },
{ "Battery Capacity mWh", 0 },
{ "Design Capacity mWh", 0 },
{ "Voltage", 0 } };
return dataDict;
}
//var batteries = new ManagementObjectSearcher("SELECT * FROM CIM_Battery").Get(); //get advanced battery info
//ManagementObject main_battery = new ManagementObject();
////gets the first battery using the dumbest way possible :) USE INDEX INSTEAD
//foreach (ManagementObject battery in batteries)
//{
// Debug.Print(battery.ToString());
// main_battery = battery;
// break;
//};
Kernel32.BATTERY_WAIT_STATUS bws = default;
bws.BatteryTag = batteryTag;
Kernel32.BATTERY_STATUS batteryStatus = default;
int remainChargeCapMwh = 0;
int chargeRate = 0;
float voltage = 0;
if (Kernel32.DeviceIoControl(batteryHandle,
Kernel32.IOCTL.IOCTL_BATTERY_QUERY_STATUS,
ref bws,
Marshal.SizeOf(bws),
ref batteryStatus,
Marshal.SizeOf(batteryStatus),
out _,
IntPtr.Zero))
{
remainChargeCapMwh = (int)batteryStatus.Capacity;
chargeRate = (int)batteryStatus.Rate;
voltage = (float)batteryStatus.Voltage / 1000f;
}
dataDict.Add("Status", batteryReport.Status);
dataDict.Add("Percent Remaining", ((double)remainChargeCapMwh / (double)batteryReport.FullChargeCapacityInMilliwattHours) * 100);
dataDict.Add("Remaining Charge mWh", remainChargeCapMwh);
double rtimeLeft = 0;
if (chargeRate < 0)
{
rtimeLeft = (remainChargeCapMwh / -(double)chargeRate) * 60;
}
if (chargeRate > 0)
{
rtimeLeft = (((int)batteryReport.FullChargeCapacityInMilliwattHours - remainChargeCapMwh) / (double)chargeRate) * 60;
}
dataDict.Add("Reported Time Left", App.EasySecondsToTime((int)rtimeLeft));
dataDict.Add("Reported Charge Rate mW", chargeRate);
dataDict.Add("Battery Health", ((double)batteryReport.FullChargeCapacityInMilliwattHours / (double)batteryReport.DesignCapacityInMilliwattHours) * 100);
dataDict.Add("Battery Capacity mWh", batteryReport.FullChargeCapacityInMilliwattHours);
dataDict.Add("Design Capacity mWh", batteryReport.DesignCapacityInMilliwattHours);
dataDict.Add("Voltage", voltage);
//dataDict.Add("----", "----");
//foreach (PropertyData property in main_battery.Properties)
//{
// if (property.Value != null)
// {
// dataDict.Add(property.Name, property.Value);
// }
//}
return dataDict;
}
public static unsafe dynamic[] GetBatteryTag()
{
uint batteryTag = 0;
SafeFileHandle batteryHandle = null;
IntPtr hdev = SetupApi.SetupDiGetClassDevs(ref SetupApi.GUID_DEVICE_BATTERY, IntPtr.Zero, IntPtr.Zero, SetupApi.DIGCF_PRESENT | SetupApi.DIGCF_DEVICEINTERFACE);
if (hdev != SetupApi.INVALID_HANDLE_VALUE)
{
for (uint i = 0; ; i++)
{
SetupApi.SP_DEVICE_INTERFACE_DATA did = default;
did.cbSize = (uint)Marshal.SizeOf(typeof(SetupApi.SP_DEVICE_INTERFACE_DATA));
if (!SetupApi.SetupDiEnumDeviceInterfaces(hdev,
IntPtr.Zero,
ref SetupApi.GUID_DEVICE_BATTERY,
i,
ref did))
{
if (Marshal.GetLastWin32Error() == SetupApi.ERROR_NO_MORE_ITEMS)
break;
}
else
{
SetupApi.SetupDiGetDeviceInterfaceDetail(hdev,
did,
IntPtr.Zero,
0,
out uint cbRequired,
IntPtr.Zero);
if (Marshal.GetLastWin32Error() == SetupApi.ERROR_INSUFFICIENT_BUFFER)
{
IntPtr pdidd = Kernel32.LocalAlloc(Kernel32.LPTR, cbRequired);
Marshal.WriteInt32(pdidd, Environment.Is64BitProcess ? 8 : 4 + Marshal.SystemDefaultCharSize); // cbSize.
if (SetupApi.SetupDiGetDeviceInterfaceDetail(hdev,
did,
pdidd,
cbRequired,
out _,
IntPtr.Zero))
{
string devicePath = new((char*)(pdidd + 4));
SafeFileHandle battery = Kernel32.CreateFile(devicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero);
batteryHandle = battery;
if (!battery.IsInvalid)
{
Kernel32.BATTERY_QUERY_INFORMATION bqi = default;
uint dwWait = 0;
if (Kernel32.DeviceIoControl(battery,
Kernel32.IOCTL.IOCTL_BATTERY_QUERY_TAG,
ref dwWait,
Marshal.SizeOf(dwWait),
ref bqi.BatteryTag,
Marshal.SizeOf(bqi.BatteryTag),
out _,
IntPtr.Zero))
{
batteryTag = bqi.BatteryTag;
}
}
}
Kernel32.LocalFree(pdidd);
}
}
}
SetupApi.SetupDiDestroyDeviceInfoList(hdev);
}
return [batteryHandle, batteryTag];
}
}
internal class SetupApi
{
internal const int DIGCF_DEVICEINTERFACE = 0x00000010;
internal const int DIGCF_PRESENT = 0x00000002;
internal const int ERROR_INSUFFICIENT_BUFFER = 122;
internal const int ERROR_NO_MORE_ITEMS = 259;
private const string DllName = "SetupAPI.dll";
internal static Guid GUID_DEVICE_BATTERY = new(0x72631e54, 0x78A4, 0x11d0, 0xbc, 0xf7, 0x00, 0xaa, 0x00, 0xb7, 0xb3, 0x2a);
internal static readonly IntPtr INVALID_HANDLE_VALUE = new(-1);
[DllImport(DllName, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
internal static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid, IntPtr Enumerator, IntPtr hwndParent, uint Flags);
[DllImport(DllName, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetupDiEnumDeviceInterfaces
(IntPtr DeviceInfoSet, IntPtr DeviceInfoData, ref Guid InterfaceClassGuid, uint MemberIndex, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData);
[DllImport(DllName, SetLastError = true, EntryPoint = "SetupDiGetDeviceInterfaceDetailW", CharSet = CharSet.Unicode)]
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetupDiGetDeviceInterfaceDetail
(
IntPtr DeviceInfoSet,
in SP_DEVICE_INTERFACE_DATA DeviceInterfaceData,
[Out, Optional] IntPtr DeviceInterfaceDetailData,
uint DeviceInterfaceDetailDataSize,
out uint RequiredSize,
IntPtr DeviceInfoData = default);
[DllImport(DllName, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);
[StructLayout(LayoutKind.Sequential)]
internal struct SP_DEVICE_INTERFACE_DATA
{
public uint cbSize;
public Guid InterfaceClassGuid;
public uint Flags;
public IntPtr Reserved;
}
}
}