From d2ff234c1e44f3f1001c1d639d7e34213bd95d8f Mon Sep 17 00:00:00 2001 From: Filipe Moreira Date: Wed, 18 Nov 2026 13:55:27 -0300 Subject: [PATCH 1/2] fix: Bluetooth pads show the battery Windows shows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An Amazon Luna pad read 10 % through Windows.Gaming.Input for days while Settings → Bluetooth said 90 %. Windows keeps the Bluetooth battery level on the pad's Bluetooth device node; BluetoothBatteryReader walks up from every gamepad HID collection to find it, and Combine lets that reading replace Windows.Gaming.Input's (and the rough XInput one) for the same pad, matched by vendor and product id. Sony HID still wins for PlayStation pads. Native/HidDevices holds the HID listing and device-tree queries, to be shared with the generic Home-button reader. Refs #224. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.en-US.md | 2 + CHANGELOG.md | 2 + docs/TESTING.md | 7 + src/ConsoleMode/Native/HidDevices.cs | 240 ++++++++++++++++++ .../Services/BluetoothBatteryReader.cs | 43 ++++ src/ConsoleMode/Services/ControllerBattery.cs | 36 ++- .../Services/ControllerBatteryMonitor.cs | 32 ++- .../ViewModels/MainViewModel.Diagnostics.cs | 2 + .../ControllerBatteryTests.cs | 51 ++++ 9 files changed, 406 insertions(+), 9 deletions(-) create mode 100644 src/ConsoleMode/Native/HidDevices.cs create mode 100644 src/ConsoleMode/Services/BluetoothBatteryReader.cs diff --git a/CHANGELOG.en-US.md b/CHANGELOG.en-US.md index 5132904..abf86f1 100644 --- a/CHANGELOG.en-US.md +++ b/CHANGELOG.en-US.md @@ -3,6 +3,8 @@ English (US) release notes, mirroring CHANGELOG.md (Brazilian Portuguese). Before publishing a version, add a `## [VERSION]` section to **both** files: the workflow publishes the section matching the tag from each one and fails if either is missing. ## [Unreleased] +### 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. (#NNN) ## [1.7.1-beta.3] ### Fixes diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b9d45b..8a8c36f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ Notas em português do Brasil; a versão em inglês (Estados Unidos) fica em `CHANGELOG.en-US.md`. Antes de publicar uma versão, adicione uma seção `## [VERSÃO]` com o changelog daquela versão **nos dois arquivos**. O workflow publica as duas seções correspondentes à tag na mesma release e falha se faltar alguma. ## [Unreleased] +### 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. (#NNN) ## [1.7.1-beta.3] ### Correções diff --git a/docs/TESTING.md b/docs/TESTING.md index 44339f8..314348b 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -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 (#NNN, 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: () %" 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: ______ diff --git a/src/ConsoleMode/Native/HidDevices.cs b/src/ConsoleMode/Native/HidDevices.cs new file mode 100644 index 0000000..47d6e99 --- /dev/null +++ b/src/ConsoleMode/Native/HidDevices.cs @@ -0,0 +1,240 @@ +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +namespace ConsoleMode.Native; + +/// What a HID collection says about itself, read without opening it for input. +internal sealed record HidInfo(string Path, ushort VendorId, ushort ProductId, ushort UsagePage, ushort Usage, int InputReportLength) +{ + /// Usage page 1 (Generic Desktop), joystick or gamepad: a game controller, not a keyboard, a headset or a mouse. + public bool IsGameController => UsagePage == 0x01 && Usage is 0x04 or 0x05; +} + +/// +/// 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. +/// +internal static class HidDevices +{ + /// Every present HID collection, as a device interface path. + public static IEnumerable 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() }; + 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); + } + } + + /// Vendor, product and top-level usage of a collection; null when it can't be queried. + 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() }; + 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); + } + } + + /// The device node behind a collection's interface path (0 when Windows doesn't know it). + 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; + } + + /// The parent of a device node, or 0 at the top. + public static uint ParentOf(uint node) => CM_Get_Parent(out var parent, node, 0) == CrSuccess ? parent : 0; + + /// A one-byte property of a device node, or null when the node doesn't have it. + 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; + } + + /// The name Windows shows for a device node (Device Manager, Settings → Bluetooth). + 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; + } + + /// The device instance id of a node ("BTHLE\DEV_..."), for logs and stable keys. + 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); +} diff --git a/src/ConsoleMode/Services/BluetoothBatteryReader.cs b/src/ConsoleMode/Services/BluetoothBatteryReader.cs new file mode 100644 index 0000000..04939ab --- /dev/null +++ b/src/ConsoleMode/Services/BluetoothBatteryReader.cs @@ -0,0 +1,43 @@ +using ConsoleMode.Native; + +namespace ConsoleMode.Services; + +/// +/// 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. +/// +public static class BluetoothBatteryReader +{ + /// DEVPKEY {104EA319-6EE2-4701-BD47-8DDBF425BBE5} 2: Bluetooth battery level, one byte, 0..100. + private static readonly Guid BatteryLevelKey = new("104EA319-6EE2-4701-BD47-8DDBF425BBE5"); + private const uint BatteryLevelPid = 2; + + /// How far up the tree to look (HID collection → Bluetooth service → Bluetooth device, with room to spare). + private const int MaxDepth = 6; + + /// Reads every Bluetooth pad now. Blocks briefly (device queries): call it off the UI thread. + public static IReadOnlyList Read() + { + var list = new List(); + // A pad can expose several HID collections; each Bluetooth device is listed once. + var seen = new HashSet(); + 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; + } +} diff --git a/src/ConsoleMode/Services/ControllerBattery.cs b/src/ConsoleMode/Services/ControllerBattery.cs index 97db5ca..fcef594 100644 --- a/src/ConsoleMode/Services/ControllerBattery.cs +++ b/src/ConsoleMode/Services/ControllerBattery.cs @@ -1,7 +1,12 @@ namespace ConsoleMode.Services; -/// One pad's battery. : XInput only gives four steps (shown with "~"). -public sealed record BatteryReading(string Id, string Name, int Percent, bool Charging, bool Approximate, string Source); +/// +/// One pad's battery. : XInput only gives four steps (shown with "~"). +/// /: 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. +/// +public sealed record BatteryReading(string Id, string Name, int Percent, bool Charging, bool Approximate, string Source, + ushort VendorId = 0, ushort ProductId = 0); /// /// 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"; + + /// + /// The level Windows keeps for a Bluetooth device (what Settings → Bluetooth shows), 0..100; null when it is out of range. + /// + 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). /// /// Readings with whether each comes from a Sony pad. + /// + /// 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. + /// public static IReadOnlyList Combine( IEnumerable sonyHid, IEnumerable<(BatteryReading Reading, bool Sony)> wgi, - IEnumerable xinput) + IEnumerable xinput, + IEnumerable? 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); return result; } + /// Two readings of the same model of pad (ids known on both sides). + private static bool SamePad(BatteryReading a, BatteryReading b) => + a.VendorId != 0 && a.VendorId == b.VendorId && a.ProductId == b.ProductId; + /// What the header shows when several pads report: the emptiest one. public static BatteryReading? Lowest(IEnumerable readings) => readings.OrderBy(r => r.Percent).ThenBy(r => r.Charging).FirstOrDefault(); diff --git a/src/ConsoleMode/Services/ControllerBatteryMonitor.cs b/src/ConsoleMode/Services/ControllerBatteryMonitor.cs index 9c1ab38..46d7e24 100644 --- a/src/ConsoleMode/Services/ControllerBatteryMonitor.cs +++ b/src/ConsoleMode/Services/ControllerBatteryMonitor.cs @@ -4,8 +4,8 @@ namespace ConsoleMode.Services; /// -/// Reads the battery of the connected pads (issue #70) from Windows.Gaming.Input, XInput and -/// SonyHidReader. Polled every half a minute by the view model, never on the input path. +/// Reads the battery of the connected pads (issue #70) from Windows.Gaming.Input, XInput, +/// SonyHidReader and Windows' Bluetooth stack (BluetoothBatteryReader, issue #224). Polled every half a minute by the view model, never on the input path. /// is the last result, for any screen that wants to list it. /// public static class ControllerBatteryMonitor @@ -31,7 +31,8 @@ public static IReadOnlyList Refresh() var report = raw.TryGetBatteryReport(); if (report is null) continue; if (ControllerBattery.FromWgi(report.RemainingCapacityInMilliwattHours, report.FullChargeCapacityInMilliwattHours, (int)report.Status) is not { } b) continue; - wgi.Add((new BatteryReading(raw.NonRoamableId, raw.DisplayName, b.Percent, b.Charging, false, ControllerBattery.SourceWgi), + wgi.Add((new BatteryReading(raw.NonRoamableId, raw.DisplayName, b.Percent, b.Charging, false, ControllerBattery.SourceWgi, + raw.HardwareVendorId, raw.HardwareProductId), raw.HardwareVendorId == ControllerMapping.SonyVendorId)); } } @@ -56,11 +57,34 @@ public static IReadOnlyList Refresh() } } - var all = ControllerBattery.Combine(SonyHidReader.ReadBatteries(), wgi, xinput); + IReadOnlyList bluetooth = []; + try + { + bluetooth = BluetoothBatteryReader.Read(); + foreach (var reading in bluetooth) + if (Remember(reading.Id)) + AppLog.Write($"Controle: bateria pelo Bluetooth do Windows: {reading.Name} ({reading.VendorId:X4}:{reading.ProductId:X4}) {reading.Percent}%"); + } + catch (Exception ex) + { + if (!_loggedBluetoothError) AppLog.Write($"Controle: bateria pelo Bluetooth do Windows indisponível: {ex.Message}"); + _loggedBluetoothError = true; + } + + var all = ControllerBattery.Combine(SonyHidReader.ReadBatteries(), wgi, xinput, bluetooth); lock (Gate) _snapshot = all; return all; } + private static readonly HashSet LoggedBluetooth = []; + private static bool _loggedBluetoothError; + + /// True the first time a Bluetooth pad is seen, so the log names it once. + private static bool Remember(string id) + { + lock (LoggedBluetooth) return LoggedBluetooth.Add(id); + } + private const byte BatteryDevTypeGamepad = 0x00; [StructLayout(LayoutKind.Sequential)] diff --git a/src/ConsoleMode/ViewModels/MainViewModel.Diagnostics.cs b/src/ConsoleMode/ViewModels/MainViewModel.Diagnostics.cs index 037ff06..71de7d5 100644 --- a/src/ConsoleMode/ViewModels/MainViewModel.Diagnostics.cs +++ b/src/ConsoleMode/ViewModels/MainViewModel.Diagnostics.cs @@ -118,6 +118,8 @@ private static List CollectControllers() }; if (Gamepad.FromGameController(raw) is not null) type += " (gamepad)"; var battery = batteries.FirstOrDefault(b => b.Id == raw.NonRoamableId) + ?? batteries.FirstOrDefault(b => b.Source == ControllerBattery.SourceBluetooth + && b.VendorId == raw.HardwareVendorId && b.ProductId == raw.HardwareProductId) ?? batteries.FirstOrDefault(b => b.Source == (raw.HardwareVendorId == ControllerMapping.SonyVendorId ? ControllerBattery.SourceSony : ControllerBattery.SourceXInput)); diff --git a/tests/ConsoleMode.Tests/ControllerBatteryTests.cs b/tests/ConsoleMode.Tests/ControllerBatteryTests.cs index 42432d0..755e109 100644 --- a/tests/ConsoleMode.Tests/ControllerBatteryTests.cs +++ b/tests/ConsoleMode.Tests/ControllerBatteryTests.cs @@ -195,6 +195,57 @@ private static byte[] Report(byte id, int length, int offset, byte value) return report; } + [Theory] + [InlineData(0, 0)] + [InlineData(90, 90)] + [InlineData(100, 100)] + public void Bluetooth_level_is_the_percentage_windows_shows(byte level, int expected) => + Assert.Equal(expected, ControllerBattery.FromBluetooth(level)); + + [Fact] + public void Bluetooth_level_out_of_range_shows_nothing() => + Assert.Null(ControllerBattery.FromBluetooth(0xFF)); + + [Fact] + public void Bluetooth_replaces_windows_gaming_input_for_the_same_pad() + { + // Issue #224: an Amazon Luna pad read 10 % through Windows.Gaming.Input while Settings → Bluetooth said 90 %. + var wgiLuna = (Reading("luna-wgi", 10, ControllerBattery.SourceWgi) with { VendorId = 0x0171, ProductId = 0x0419 }, false); + var btLuna = Reading("luna-bt", 90, ControllerBattery.SourceBluetooth) with { VendorId = 0x0171, ProductId = 0x0419 }; + var wgiOther = (Reading("other", 70, ControllerBattery.SourceWgi) with { VendorId = 0x045E, ProductId = 0x0B13 }, false); + var xinput = Reading("xinput0", 65, ControllerBattery.SourceXInput, approximate: true); + + var all = ControllerBattery.Combine([], [wgiLuna, wgiOther], [xinput], [btLuna]); + Assert.Equal(["luna-bt", "other"], all.Select(r => r.Id)); + Assert.Equal(90, all[0].Percent); + } + + [Fact] + public void Bluetooth_alone_hides_the_rough_xinput_reading_of_the_same_pad() + { + var btLuna = Reading("luna-bt", 90, ControllerBattery.SourceBluetooth) with { VendorId = 0x0171, ProductId = 0x0419 }; + var xinput = Reading("xinput0", 30, ControllerBattery.SourceXInput, approximate: true); + Assert.Equal(["luna-bt"], ControllerBattery.Combine([], [], [xinput], [btLuna]).Select(r => r.Id)); + } + + [Fact] + public void Sony_hid_still_wins_over_bluetooth_for_playstation_pads() + { + var hid = Reading("ds", 40, ControllerBattery.SourceSony); + var btSony = Reading("ds-bt", 90, ControllerBattery.SourceBluetooth) with { VendorId = ControllerMapping.SonyVendorId, ProductId = 0x0CE6 }; + Assert.Equal(["ds"], ControllerBattery.Combine([hid], [], [], [btSony]).Select(r => r.Id)); + // Without the HID reading (not read yet), the Bluetooth one shows. + Assert.Equal(["ds-bt"], ControllerBattery.Combine([], [], [], [btSony]).Select(r => r.Id)); + } + + [Fact] + public void A_wgi_reading_without_ids_is_never_replaced() + { + var wgi = (Reading("pad", 50, ControllerBattery.SourceWgi), false); + var bt = Reading("bt", 90, ControllerBattery.SourceBluetooth) with { VendorId = 0x0171, ProductId = 0x0419 }; + Assert.Equal(["bt", "pad"], ControllerBattery.Combine([], [wgi], [], [bt]).Select(r => r.Id)); + } + private static BatteryReading Reading(string id, int percent, string source, bool approximate = false) => new(id, id, percent, false, approximate, source); } From 1326d7295fe1d92dcf9e3d3002ecef9f8ac3d661 Mon Sep 17 00:00:00 2001 From: Filipe Moreira Date: Wed, 18 Nov 2026 13:55:42 -0300 Subject: [PATCH 2/2] docs: PR number for the Bluetooth battery Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.en-US.md | 2 +- CHANGELOG.md | 2 +- docs/TESTING.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.en-US.md b/CHANGELOG.en-US.md index abf86f1..899f322 100644 --- a/CHANGELOG.en-US.md +++ b/CHANGELOG.en-US.md @@ -4,7 +4,7 @@ English (US) release notes, mirroring CHANGELOG.md (Brazilian Portuguese). Befor ## [Unreleased] ### 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. (#NNN) +- 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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a8c36f..190afed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ Notas em português do Brasil; a versão em inglês (Estados Unidos) fica em `CH ## [Unreleased] ### 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. (#NNN) +- 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 diff --git a/docs/TESTING.md b/docs/TESTING.md index 314348b..08361ed 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -547,7 +547,7 @@ 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 (#NNN, issue #224) +## 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: () %" uma vez. Resultado: ______ - [ ] Diagnóstico (Copiar diagnóstico / relatório de feedback): o controle Bluetooth mostra a mesma bateria. Resultado: ______