Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ English (US) release notes, mirroring CHANGELOG.md (Brazilian Portuguese). Befor
## [Unreleased]
### Changes
- **Receive test versions** now brings betas only. Alpha versions, like those of the upcoming 2.0, are closed tests and no longer arrive through the app's updates, even with the option on. (#223)
### Fixes
- Controller battery: on Bluetooth pads, the corner of the screen shows the same value as Windows Settings → Bluetooth. Some pads sent Windows a fixed value through the other path (an Amazon Luna pad always showed 10 % while at 90 %; reported by PLEXX-DE, issue #224). PlayStation pads still read the battery from the pad itself. (#225)

## [1.7.1-beta.3]
### Fixes
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ Notas em português do Brasil; a versão em inglês (Estados Unidos) fica em `CH
## [Unreleased]
### Mudanças
- **Receber versões de teste** agora traz só as betas. As versões alpha, como as da futura 2.0, são testes fechados e não chegam mais pela atualização do app, nem com a opção ligada. (#223)
### Correções
- Bateria do controle: nos controles Bluetooth, o canto da tela mostra o mesmo valor das Configurações do Windows → Bluetooth. Alguns controles mandavam ao Windows um valor fixo pelo outro caminho (um Amazon Luna aparecia sempre com 10 % estando em 90 %; relatado pelo PLEXX-DE, issue #224). Os controles PlayStation continuam lendo a bateria pelo próprio controle. (#225)

## [1.7.1-beta.3]
### Correções
Expand Down
7 changes: 7 additions & 0 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,13 @@ Pré-requisito: RivaTuner Statistics Server instalado, com "Show On-Screen Displ
- [ ] Com a sessão ativa e a opção ligada, minimizar e reabrir pela bandeja continua funcionando; o atalho do controle para abrir o app também traz a janela de volta.
- [ ] Fechar no X (sem sessão ativa) continua fechando o app, com a opção ligada ou desligada.

## Bateria dos controles Bluetooth (#225, issue #224)

- [ ] Controle Bluetooth que não é PlayStation (Amazon Luna, Xbox por Bluetooth, 8BitDo…): a bateria no canto da tela é a mesma de Configurações → Bluetooth (pode levar até 30 s para atualizar). O log tem "Controle: bateria pelo Bluetooth do Windows: <nome> (<vid:pid>) <n>%" uma vez. Resultado: ______
- [ ] Diagnóstico (Copiar diagnóstico / relatório de feedback): o controle Bluetooth mostra a mesma bateria. Resultado: ______
- [ ] DualSense ou DualShock 4 por Bluetooth: a bateria continua a do próprio controle (sem "~"), como antes. Resultado: ______
- [ ] Controle com fio ou com receptor USB: a bateria continua como antes (ou não aparece, sem bateria). Resultado: ______

## Nomes das categorias do Sistema (#221, issue #219)

- [ ] Idioma alemão, janela pequena (~1100 px) e tela cheia na TV: em Sistema, "Beim Starten des Konsolenmodus" e "Tastenkombination, Hilfe und Daten" aparecem inteiros, sem "…". O mesmo em francês ("Autres applications du développeur"). Resultado: ______
Expand Down
240 changes: 240 additions & 0 deletions src/ConsoleMode/Native/HidDevices.cs
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);

Copy link
Copy Markdown
Contributor

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, DevNodeOf returns 0, and the battery reader never walks the device tree, so no Bluetooth readings are produced.

Technical details
# Resolve the HID interface to its device node

## Affected sites
- `src/ConsoleMode/Native/HidDevices.cs:76` — requests `DEVPKEY_Device_InstanceId` via `CM_Get_Device_Interface_PropertyW`.
- `src/ConsoleMode/Native/HidDevices.cs:138` — returns `0` when this lookup fails.
- `src/ConsoleMode/Services/BluetoothBatteryReader.cs:29-30` — skips the property walk for node `0`.

## Required outcome
- Reliably resolve each HID interface to its associated device node so the Bluetooth battery property can be read.

## Suggested approach
- Use a device-interface property to obtain the associated device instance ID, or retrieve the device node through the SetupAPI interface detail call.

## Evidence
- [DEVPKEY_Device_InstanceId](https://learn.microsoft.com/en-us/windows-hardware/drivers/install/devpkey-device-instanceid)
- [CM_Get_Device_Interface_PropertyW](https://learn.microsoft.com/en-us/windows/win32/api/cfgmgr32/nf-cfgmgr32-cm_get_device_interface_propertyw)
- [SetupDiGetDeviceInterfaceDetailW](https://learn.microsoft.com/en-us/windows/win32/api/setupapi/nf-setupapi-setupdigetdeviceinterfacedetailw)

Copy link
Copy Markdown
Owner Author

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: DevNodeOf resolved 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.

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);
}
43 changes: 43 additions & 0 deletions src/ConsoleMode/Services/BluetoothBatteryReader.cs
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;
}
}
36 changes: 31 additions & 5 deletions src/ConsoleMode/Services/ControllerBattery.cs
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
Expand All @@ -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;
Expand Down Expand Up @@ -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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The 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();
Expand Down
Loading
Loading