Repository navigation
fix: Bluetooth pads show the battery Windows shows #225
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,240 @@ | ||
| using System.Runtime.InteropServices; | ||
| using Microsoft.Win32.SafeHandles; | ||
|
|
||
| namespace ConsoleMode.Native; | ||
|
|
||
| /// <summary>What a HID collection says about itself, read without opening it for input.</summary> | ||
| internal sealed record HidInfo(string Path, ushort VendorId, ushort ProductId, ushort UsagePage, ushort Usage, int InputReportLength) | ||
| { | ||
| /// <summary>Usage page 1 (Generic Desktop), joystick or gamepad: a game controller, not a keyboard, a headset or a mouse.</summary> | ||
| public bool IsGameController => UsagePage == 0x01 && Usage is 0x04 or 0x05; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Lists the HID collections Windows knows, and walks the device tree above one of them. Opening a collection | ||
| /// "for query" (no read access) works even while XInput, Steam or a game has it open. | ||
| /// </summary> | ||
| internal static class HidDevices | ||
| { | ||
| /// <summary>Every present HID collection, as a device interface path.</summary> | ||
| public static IEnumerable<string> EnumeratePaths() | ||
| { | ||
| HidD_GetHidGuid(out var guid); | ||
| var set = SetupDiGetClassDevs(ref guid, 0, 0, DigcfPresent | DigcfDeviceInterface); | ||
| if (set == -1) yield break; | ||
| try | ||
| { | ||
| var data = new SpDeviceInterfaceData { Size = Marshal.SizeOf<SpDeviceInterfaceData>() }; | ||
| for (uint i = 0; SetupDiEnumDeviceInterfaces(set, 0, ref guid, i, ref data); i++) | ||
| { | ||
| SetupDiGetDeviceInterfaceDetail(set, ref data, 0, 0, out var needed, 0); | ||
| if (needed == 0) continue; | ||
| var detail = Marshal.AllocHGlobal((int)needed); | ||
| try | ||
| { | ||
| // cbSize of SP_DEVICE_INTERFACE_DETAIL_DATA_W: 8 on x64, 6 on x86. | ||
| Marshal.WriteInt32(detail, IntPtr.Size == 8 ? 8 : 6); | ||
| if (!SetupDiGetDeviceInterfaceDetail(set, ref data, detail, needed, out _, 0)) continue; | ||
| var path = Marshal.PtrToStringUni(detail + 4); | ||
| if (!string.IsNullOrEmpty(path)) yield return path; | ||
| } | ||
| finally | ||
| { | ||
| Marshal.FreeHGlobal(detail); | ||
| } | ||
| } | ||
| } | ||
| finally | ||
| { | ||
| SetupDiDestroyDeviceInfoList(set); | ||
| } | ||
| } | ||
|
|
||
| /// <summary>Vendor, product and top-level usage of a collection; null when it can't be queried.</summary> | ||
| public static HidInfo? Query(string path) | ||
| { | ||
| using var handle = CreateFile(path, 0, FileShareRead | FileShareWrite, 0, OpenExisting, 0, 0); | ||
| if (handle.IsInvalid) return null; | ||
| var attributes = new HiddAttributes { Size = Marshal.SizeOf<HiddAttributes>() }; | ||
| if (!HidD_GetAttributes(handle, ref attributes)) return null; | ||
| if (!HidD_GetPreparsedData(handle, out var preparsed)) return null; | ||
| try | ||
| { | ||
| if (HidP_GetCaps(preparsed, out var caps) != HidpStatusSuccess) return null; | ||
| return new HidInfo(path, attributes.VendorId, attributes.ProductId, caps.UsagePage, caps.Usage, caps.InputReportByteLength); | ||
| } | ||
| finally | ||
| { | ||
| HidD_FreePreparsedData(preparsed); | ||
| } | ||
| } | ||
|
|
||
| /// <summary>The device node behind a collection's interface path (0 when Windows doesn't know it).</summary> | ||
| public static uint DevNodeOf(string interfacePath) | ||
| { | ||
| var key = DevPKeyInstanceId; | ||
| var id = GetInterfaceString(interfacePath, ref key); | ||
| if (string.IsNullOrEmpty(id)) return 0; | ||
| return CM_Locate_DevNodeW(out var node, id, 0) == CrSuccess ? node : 0; | ||
| } | ||
|
|
||
| /// <summary>The parent of a device node, or 0 at the top.</summary> | ||
| public static uint ParentOf(uint node) => CM_Get_Parent(out var parent, node, 0) == CrSuccess ? parent : 0; | ||
|
|
||
| /// <summary>A one-byte property of a device node, or null when the node doesn't have it.</summary> | ||
| public static byte? GetByte(uint node, Guid fmtid, uint pid) | ||
| { | ||
| var key = new DevPropKey { FmtId = fmtid, Pid = pid }; | ||
| var buffer = new byte[1]; | ||
| uint size = 1; | ||
| if (CM_Get_DevNode_PropertyW(node, ref key, out var type, buffer, ref size, 0) != CrSuccess) return null; | ||
| return type == DevPropTypeByte && size == 1 ? buffer[0] : null; | ||
| } | ||
|
|
||
| /// <summary>The name Windows shows for a device node (Device Manager, Settings → Bluetooth).</summary> | ||
| public static string? GetName(uint node) | ||
| { | ||
| var friendly = DevPKeyFriendlyName; | ||
| var name = GetString(node, ref friendly); | ||
| if (!string.IsNullOrWhiteSpace(name)) return name; | ||
| var description = DevPKeyDeviceDesc; | ||
| name = GetString(node, ref description); | ||
| return string.IsNullOrWhiteSpace(name) ? null : name; | ||
| } | ||
|
|
||
| /// <summary>The device instance id of a node ("BTHLE\DEV_..."), for logs and stable keys.</summary> | ||
| public static string? GetInstanceId(uint node) | ||
| { | ||
| var key = DevPKeyInstanceId; | ||
| return GetString(node, ref key); | ||
| } | ||
|
|
||
| private static string? GetString(uint node, ref DevPropKey key) | ||
| { | ||
| uint size = 0; | ||
| var status = CM_Get_DevNode_PropertyW(node, ref key, out _, null, ref size, 0); | ||
| if (status != CrBufferSmall || size == 0) return null; | ||
| var buffer = new byte[size]; | ||
| if (CM_Get_DevNode_PropertyW(node, ref key, out var type, buffer, ref size, 0) != CrSuccess || type != DevPropTypeString) return null; | ||
| return System.Text.Encoding.Unicode.GetString(buffer, 0, (int)size).TrimEnd('\0'); | ||
| } | ||
|
|
||
| private static string? GetInterfaceString(string interfacePath, ref DevPropKey key) | ||
| { | ||
| uint size = 0; | ||
| var status = CM_Get_Device_Interface_PropertyW(interfacePath, ref key, out _, null, ref size, 0); | ||
| if (status != CrBufferSmall || size == 0) return null; | ||
| var buffer = new byte[size]; | ||
| if (CM_Get_Device_Interface_PropertyW(interfacePath, ref key, out var type, buffer, ref size, 0) != CrSuccess || type != DevPropTypeString) return null; | ||
| return System.Text.Encoding.Unicode.GetString(buffer, 0, (int)size).TrimEnd('\0'); | ||
| } | ||
|
|
||
| private static readonly DevPropKey DevPKeyInstanceId = new() { FmtId = new Guid("78c34fc8-104a-4aca-9ea4-524d52996e57"), Pid = 256 }; | ||
| private static readonly DevPropKey DevPKeyFriendlyName = new() { FmtId = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), Pid = 14 }; | ||
| private static readonly DevPropKey DevPKeyDeviceDesc = new() { FmtId = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), Pid = 2 }; | ||
|
|
||
| private const uint FileShareRead = 0x1; | ||
| private const uint FileShareWrite = 0x2; | ||
| private const uint OpenExisting = 3; | ||
| private const uint DigcfPresent = 0x2; | ||
| private const uint DigcfDeviceInterface = 0x10; | ||
| private const int HidpStatusSuccess = 0x00110000; | ||
| private const int CrSuccess = 0x00; | ||
| private const int CrBufferSmall = 0x1A; | ||
| private const uint DevPropTypeByte = 0x03; | ||
| private const uint DevPropTypeString = 0x12; | ||
|
|
||
| [StructLayout(LayoutKind.Sequential)] | ||
| private struct DevPropKey | ||
| { | ||
| public Guid FmtId; | ||
| public uint Pid; | ||
| } | ||
|
|
||
| [StructLayout(LayoutKind.Sequential)] | ||
| private struct HiddAttributes | ||
| { | ||
| public int Size; | ||
| public ushort VendorId; | ||
| public ushort ProductId; | ||
| public ushort VersionNumber; | ||
| } | ||
|
|
||
| [StructLayout(LayoutKind.Sequential)] | ||
| private struct HidpCaps | ||
| { | ||
| public ushort Usage; | ||
| public ushort UsagePage; | ||
| public ushort InputReportByteLength; | ||
| public ushort OutputReportByteLength; | ||
| public ushort FeatureReportByteLength; | ||
| [MarshalAs(UnmanagedType.ByValArray, SizeConst = 17)] public ushort[] Reserved; | ||
| public ushort NumberLinkCollectionNodes; | ||
| public ushort NumberInputButtonCaps; | ||
| public ushort NumberInputValueCaps; | ||
| public ushort NumberInputDataIndices; | ||
| public ushort NumberOutputButtonCaps; | ||
| public ushort NumberOutputValueCaps; | ||
| public ushort NumberOutputDataIndices; | ||
| public ushort NumberFeatureButtonCaps; | ||
| public ushort NumberFeatureValueCaps; | ||
| public ushort NumberFeatureDataIndices; | ||
| } | ||
|
|
||
| [StructLayout(LayoutKind.Sequential)] | ||
| private struct SpDeviceInterfaceData | ||
| { | ||
| public int Size; | ||
| public Guid InterfaceClassGuid; | ||
| public uint Flags; | ||
| public nint Reserved; | ||
| } | ||
|
|
||
| [DllImport("hid.dll")] | ||
| private static extern void HidD_GetHidGuid(out Guid guid); | ||
|
|
||
| [DllImport("hid.dll")] | ||
| [return: MarshalAs(UnmanagedType.U1)] | ||
| private static extern bool HidD_GetAttributes(SafeFileHandle device, ref HiddAttributes attributes); | ||
|
|
||
| [DllImport("hid.dll")] | ||
| [return: MarshalAs(UnmanagedType.U1)] | ||
| private static extern bool HidD_GetPreparsedData(SafeFileHandle device, out nint preparsed); | ||
|
|
||
| [DllImport("hid.dll")] | ||
| [return: MarshalAs(UnmanagedType.U1)] | ||
| private static extern bool HidD_FreePreparsedData(nint preparsed); | ||
|
|
||
| [DllImport("hid.dll")] | ||
| private static extern int HidP_GetCaps(nint preparsed, out HidpCaps caps); | ||
|
|
||
| [DllImport("setupapi.dll", CharSet = CharSet.Unicode)] | ||
| private static extern nint SetupDiGetClassDevs(ref Guid classGuid, nint enumerator, nint parent, uint flags); | ||
|
|
||
| [DllImport("setupapi.dll", SetLastError = true)] | ||
| [return: MarshalAs(UnmanagedType.Bool)] | ||
| private static extern bool SetupDiEnumDeviceInterfaces(nint set, nint deviceInfo, ref Guid classGuid, uint index, ref SpDeviceInterfaceData data); | ||
|
|
||
| [DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)] | ||
| [return: MarshalAs(UnmanagedType.Bool)] | ||
| private static extern bool SetupDiGetDeviceInterfaceDetail(nint set, ref SpDeviceInterfaceData data, nint detail, uint detailSize, out uint requiredSize, nint deviceInfo); | ||
|
|
||
| [DllImport("setupapi.dll")] | ||
| [return: MarshalAs(UnmanagedType.Bool)] | ||
| private static extern bool SetupDiDestroyDeviceInfoList(nint set); | ||
|
|
||
| [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] | ||
| private static extern SafeFileHandle CreateFile(string name, uint access, uint share, nint security, uint creation, uint flags, nint template); | ||
|
|
||
| [DllImport("cfgmgr32.dll", CharSet = CharSet.Unicode)] | ||
| private static extern int CM_Get_Device_Interface_PropertyW(string deviceInterface, ref DevPropKey key, out uint type, byte[]? buffer, ref uint size, uint flags); | ||
|
|
||
| [DllImport("cfgmgr32.dll", CharSet = CharSet.Unicode)] | ||
| private static extern int CM_Locate_DevNodeW(out uint devInst, string deviceId, uint flags); | ||
|
|
||
| [DllImport("cfgmgr32.dll")] | ||
| private static extern int CM_Get_Parent(out uint parent, uint devInst, uint flags); | ||
|
|
||
| [DllImport("cfgmgr32.dll")] | ||
| private static extern int CM_Get_DevNode_PropertyW(uint devInst, ref DevPropKey key, out uint type, byte[]? buffer, ref uint size, uint flags); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| using ConsoleMode.Native; | ||
|
|
||
| namespace ConsoleMode.Services; | ||
|
|
||
| /// <summary> | ||
| /// The battery Windows keeps for each Bluetooth game controller: the number Settings → Bluetooth shows (issue #224). | ||
| /// Windows stores it on the pad's Bluetooth device node, above the HID collection the game input comes from; | ||
| /// this walks up from every gamepad collection to find it. Pads on a cable or a dongle have no such node and are | ||
| /// left to the other sources. | ||
| /// </summary> | ||
| public static class BluetoothBatteryReader | ||
| { | ||
| /// <summary>DEVPKEY {104EA319-6EE2-4701-BD47-8DDBF425BBE5} 2: Bluetooth battery level, one byte, 0..100.</summary> | ||
| private static readonly Guid BatteryLevelKey = new("104EA319-6EE2-4701-BD47-8DDBF425BBE5"); | ||
| private const uint BatteryLevelPid = 2; | ||
|
|
||
| /// <summary>How far up the tree to look (HID collection → Bluetooth service → Bluetooth device, with room to spare).</summary> | ||
| private const int MaxDepth = 6; | ||
|
|
||
| /// <summary>Reads every Bluetooth pad now. Blocks briefly (device queries): call it off the UI thread.</summary> | ||
| public static IReadOnlyList<BatteryReading> Read() | ||
| { | ||
| var list = new List<BatteryReading>(); | ||
| // A pad can expose several HID collections; each Bluetooth device is listed once. | ||
| var seen = new HashSet<uint>(); | ||
| foreach (var path in HidDevices.EnumeratePaths()) | ||
| { | ||
| if (HidDevices.Query(path) is not { IsGameController: true } info) continue; | ||
| var node = HidDevices.DevNodeOf(path); | ||
| for (var depth = 0; node != 0 && depth < MaxDepth; depth++, node = HidDevices.ParentOf(node)) | ||
| { | ||
| if (HidDevices.GetByte(node, BatteryLevelKey, BatteryLevelPid) is not { } level) continue; | ||
| if (!seen.Add(node)) break; | ||
| if (ControllerBattery.FromBluetooth(level) is not { } percent) break; | ||
| var id = HidDevices.GetInstanceId(node) ?? path; | ||
| list.Add(new BatteryReading($"bt:{id}", HidDevices.GetName(node) ?? "Bluetooth", percent, false, false, | ||
| ControllerBattery.SourceBluetooth, info.VendorId, info.ProductId)); | ||
| break; | ||
| } | ||
| } | ||
| return list; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,12 @@ | ||
| namespace ConsoleMode.Services; | ||
|
|
||
| /// <summary>One pad's battery. <paramref name="Approximate"/>: XInput only gives four steps (shown with "~").</summary> | ||
| public sealed record BatteryReading(string Id, string Name, int Percent, bool Charging, bool Approximate, string Source); | ||
| /// <summary> | ||
| /// One pad's battery. <paramref name="Approximate"/>: XInput only gives four steps (shown with "~"). | ||
| /// <paramref name="VendorId"/>/<paramref name="ProductId"/>: the pad's USB/Bluetooth ids when the source knows them (0 otherwise), | ||
| /// so the Bluetooth reading can stand in for another source's reading of the same pad. | ||
| /// </summary> | ||
| public sealed record BatteryReading(string Id, string Name, int Percent, bool Charging, bool Approximate, string Source, | ||
| ushort VendorId = 0, ushort ProductId = 0); | ||
|
|
||
| /// <summary> | ||
| /// Pure battery logic (issue #70): turns what Windows.Gaming.Input, XInput and the Sony HID | ||
|
|
@@ -13,6 +18,12 @@ public static class ControllerBattery | |
| public const string SourceSony = "hid"; | ||
| public const string SourceWgi = "wgi"; | ||
| public const string SourceXInput = "xinput"; | ||
| public const string SourceBluetooth = "bluetooth"; | ||
|
|
||
| /// <summary> | ||
| /// The level Windows keeps for a Bluetooth device (what Settings → Bluetooth shows), 0..100; null when it is out of range. | ||
| /// </summary> | ||
| public static int? FromBluetooth(byte level) => level <= 100 ? level : null; | ||
|
|
||
| // XInput BATTERY_TYPE_* and BATTERY_LEVEL_*. | ||
| public const byte XInputTypeDisconnected = 0x00; | ||
|
|
@@ -103,19 +114,34 @@ public static (int Percent, bool Charging)? FromDs4Status(byte status) | |
| /// when Windows.Gaming.Input reported no non-Sony pad (they would be the same Xbox pads twice). | ||
| /// </summary> | ||
| /// <param name="wgi">Readings with whether each comes from a Sony pad.</param> | ||
| /// <param name="bluetooth"> | ||
| /// What Windows' Bluetooth stack says (issue #224): the same number as Settings → Bluetooth. It replaces | ||
| /// Windows.Gaming.Input's reading of the same pad (same vendor and product id), which some pads fill with a fixed | ||
| /// value (an Amazon Luna pad read 10 % for days). The Sony HID value still wins for PlayStation pads. | ||
| /// </param> | ||
| public static IReadOnlyList<BatteryReading> Combine( | ||
| IEnumerable<BatteryReading> sonyHid, | ||
| IEnumerable<(BatteryReading Reading, bool Sony)> wgi, | ||
| IEnumerable<BatteryReading> xinput) | ||
| IEnumerable<BatteryReading> xinput, | ||
| IEnumerable<BatteryReading>? bluetooth = null) | ||
| { | ||
| var result = sonyHid.ToList(); | ||
| var hasSony = result.Count > 0; | ||
| var fromWgi = wgi.Where(w => !(w.Sony && hasSony)).ToList(); | ||
| var fromBluetooth = (bluetooth ?? []).Where(b => !(hasSony && b.VendorId == ControllerMapping.SonyVendorId)).ToList(); | ||
| var fromWgi = wgi | ||
| .Where(w => !(w.Sony && hasSony)) | ||
| .Where(w => !fromBluetooth.Any(b => SamePad(b, w.Reading))) | ||
| .ToList(); | ||
| result.AddRange(fromBluetooth); | ||
| result.AddRange(fromWgi.Select(w => w.Reading)); | ||
| if (!fromWgi.Any(w => !w.Sony)) result.AddRange(xinput); | ||
| if (fromBluetooth.Count == 0 && !fromWgi.Any(w => !w.Sony)) result.AddRange(xinput); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This gates the entire XInput fallback on whether any Bluetooth pad was found. With one Bluetooth reading, an unrelated XInput-only controller whose battery is not reported by WGI is omitted from the combined list. Keep the fallback available for other pads while avoiding a duplicate reading for the Bluetooth pad. Technical details# Preserve unrelated XInput fallback readings
## Affected sites
- `src/ConsoleMode/Services/ControllerBattery.cs:137` — suppresses all XInput readings when `fromBluetooth` is non-empty.
## Required outcome
- A Bluetooth battery reading should replace or suppress only a reading for that same pad; it should not hide an unrelated XInput-only pad.
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Intended, and the same trade-off the existing rule makes for Windows.Gaming.Input: XInput slots can't be tied to a device (no vendor/product id), so with a Bluetooth pad present its own XInput reading would show as a second, rough battery for the same pad. The case left out is a wireless XInput-only pad whose battery Windows.Gaming.Input doesn't report, next to a Bluetooth pad; rare, and it only hides the XInput estimate. Leaving it as is. |
||
| return result; | ||
| } | ||
|
|
||
| /// <summary>Two readings of the same model of pad (ids known on both sides).</summary> | ||
| private static bool SamePad(BatteryReading a, BatteryReading b) => | ||
| a.VendorId != 0 && a.VendorId == b.VendorId && a.ProductId == b.ProductId; | ||
|
|
||
| /// <summary>What the header shows when several pads report: the emptiest one.</summary> | ||
| public static BatteryReading? Lowest(IEnumerable<BatteryReading> readings) => | ||
| readings.OrderBy(r => r.Percent).ThenBy(r => r.Charging).FirstOrDefault(); | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This asks the device-interface property API for
DEVPKEY_Device_InstanceId, which is a device property rather than a device-interface property. If Windows does not expose that key on the interface, this returns no ID,DevNodeOfreturns0, and the battery reader never walks the device tree, so no Bluetooth readings are produced.Technical details
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Windows does expose DEVPKEY_Device_InstanceId on device interfaces (it is in the documented set of device interface properties). Checked on the owner's PC with a harness compiling this file:
DevNodeOfresolved every HID interface there (Logitech receiver, Apple keyboard, other HID devices) and the walk went HID → USB interface → receiver → hubs → root hub with the right instance ids. Leaving it as is.