Skip to content
Open
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: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ Parameters that are enabled by default have to be explicitly disabled. These (cu
| `custom_text` | Display a custom text e.g `custom_text=Fsync enabled` |
| `debug` | Shows the graph of gamescope app frametimes and latency (only on gamescope obviously) |
| `device_battery_icon` | Display wirless device battery icon. |
| `device_battery` | Display wireless device battery percent. Currently supported arguments `gamepad` and `mouse` e.g `device_battery=gamepad,mouse` |
| `device_battery` | Display wireless device battery percent. Currently supported arguments `gamepad` and `mouse` e.g `device_battery=gamepad,mouse`. For GameSir G7 Pro 8K receivers without a kernel battery reading, see the [optional external helper](docs/gamesir-battery.md). |
| `display_server` | Display the current display session (e.g. X11 or wayland) |
| `dynamic_frame_timing` | This changes frame_timing y-axis to correspond with the current maximum and minimum frametime instead of being a static 0-50 |
| `engine_short_names` | Display a short version of the used engine (e.g. `OGL` instead of `OpenGL`) |
Expand Down
158 changes: 158 additions & 0 deletions bin/gamesir-battery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
#!/usr/bin/env python3
"""Optional GameSir G7 Pro 8K battery reader for MangoHud's exec option.

Only the 3537:10c6 receiver in XInput mode has been tested. This program sends
the volatile enhanced-report heartbeat; it does not change saved settings or
detach a kernel driver. Run outside the game sandbox, as the desktop user.
"""

import argparse
import logging
import os
from pathlib import Path
import signal
import threading
import time


VENDOR_ID = 0x3537
PRODUCT_ID = 0x10C6
HEARTBEAT = [0x0F, 0xF2] + [0] * 62
REPORT_TIMEOUT = 5.0
MAX_AGE = 10.0


def default_output():
cache = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache"))
return cache / "MangoHud" / "gamesir-battery.txt"


def parse_report(report):
"""Return display text, or None for a short, unrelated or empty report."""
if len(report) != 64 or report[0] != 0x12:
return None
# An idle receiver can send all-zero payloads. A real controller has
# populated stick bytes even when its battery is completely empty.
if not any(report[1:]) or report[36] > 100:
return None
return f"{report[36]}%" + (" charging" if report[35] & 1 else "")


def publish(output, value):
output.parent.mkdir(parents=True, exist_ok=True)
temporary = output.with_name(output.name + f".{os.getpid()}.tmp")
try:
temporary.write_text(value + "\n", encoding="utf-8")
temporary.replace(output)
finally:
temporary.unlink(missing_ok=True)


def status(output):
try:
with output.open(encoding="utf-8") as stream:
# Read contents and timestamp from the same atomic file version.
age = time.time() - os.fstat(stream.fileno()).st_mtime
value = stream.read(64).strip()
if 0 <= age <= MAX_AGE and value:
return value
except OSError:
pass
return "Disconnected"


def read_device(device, output, stop, once=False):
device.set_nonblocking(True)
heartbeat = float("-inf")
last_report = time.monotonic()
last_publish = float("-inf")
previous = None
while not stop.is_set():
now = time.monotonic()
if now - last_report >= REPORT_TIMEOUT:
raise OSError("No valid GameSir battery report for five seconds")
if now - heartbeat >= 0.5:
if device.write(HEARTBEAT) != len(HEARTBEAT):
raise OSError("Could not send GameSir reporting heartbeat")
heartbeat = now
report = device.read(64)
value = parse_report(report)
if value is not None:
if once:
print(value, flush=True)
return True
last_report = now
# Refresh even unchanged values so --status can reject stale files.
if value != previous or now - last_publish >= 1:
publish(output, value)
previous = value
last_publish = now
if not report:
stop.wait(0.02)
return False


def run(hid, output, stop, once=False):
last_error = None
while not stop.is_set():
if not once:
publish(output, "Disconnected")
try:
# HIDAPI can enumerate multiple usages for one hidraw node.
nodes = sorted({d["path"] for d in hid.enumerate(VENDOR_ID, PRODUCT_ID)})
if once and not nodes:
logging.error("No 3537:10c6 receiver found; connect in XInput mode")
return 1
for node in nodes:
device = hid.device()
try:
device.open_path(node)
if read_device(device, output, stop, once):
return 0
except (OSError, ValueError) as error:
if str(error) != last_error:
logging.warning("%s: %s", os.fsdecode(node), error)
last_error = str(error)
finally:
device.close()
if not once:
publish(output, "Disconnected")
except (OSError, ValueError) as error:
logging.warning("Cannot enumerate GameSir receivers: %s", error)
if once:
return 1
stop.wait(3)
return 0


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, default=default_output(),
help="battery text file (default: %(default)s)")
mode = parser.add_mutually_exclusive_group()
mode.add_argument("--once", action="store_true",
help="print one hardware reading and exit without writing a file")
mode.add_argument("--status", action="store_true",
help="print the cached reading, or Disconnected if stale/missing")
args = parser.parse_args()
if args.status:
print(status(args.output))
return 0
try:
import hid
except ImportError:
parser.error("Install the hidapi Python bindings (python-hidapi on Arch Linux)")
if not hasattr(hid, "device"):
parser.error("The hid module must provide hid.device() (the hidapi bindings)")
stop = threading.Event()
for signum in (signal.SIGINT, signal.SIGTERM):
signal.signal(signum, lambda *_: stop.set())
try:
return run(hid, args.output, stop, args.once)
finally:
if not args.once:
publish(args.output, "Disconnected")


if __name__ == "__main__":
raise SystemExit(main())
112 changes: 112 additions & 0 deletions docs/gamesir-battery.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# GameSir G7 Pro 8K battery workaround

Some GameSir receivers expose an Xbox-compatible gamepad without exposing a
battery in `/sys/class/power_supply`. `device_battery=gamepad` consequently has
no reading to display. PS4 emulation can expose a battery but report a constant,
incorrect 5%. See [issue #2199](https://github.com/flightlessmango/MangoHud/issues/2199).

`bin/gamesir-battery.py` is an optional external helper for the **G7 Pro 8K PC
receiver `3537:10c6` in 2.4 GHz XInput mode**. Other GameSir models, receiver IDs,
Bluetooth, wired mode and PS4 mode are not supported by this helper. It is not
automatically installed or started by MangoHud.

The helper sends a 64-byte `0x0f, 0xf2` heartbeat every half second to request
GameSir's enhanced reports. It reads the percentage from byte 36 (zero based)
of the 64-byte `0x12` report, and charging from byte 35 bit 0. It does **write**
to the vendor HID interface, but does not save configuration, switch modes,
detach `xpad`, or claim exclusive access. MangoHud itself only runs a command
to read the helper's cached result; the overlay never opens the USB device.

This protocol was identified using the
[GameSir Linux tools project](https://github.com/broroeror/gamesir-linux-tools).
Deadband does not need to be installed or running. The workaround reported
100% on the fully charged controller in #2199; this is not a calibration or
validation of every battery level or the charging flag.

## Setup

Install Python 3 and the `hidapi` Python bindings, which expose `hid.device()`.
On Arch Linux/CachyOS the bindings are packaged as `python-hidapi`. Run the
helper as your desktop user, with read/write permission for the receiver's
vendor `/dev/hidraw*` node. Do not run the game or MangoHud as root. A system
udev rule, if needed, can grant the logged-in user access to this specific
receiver:

```udev
SUBSYSTEM=="hidraw", ATTRS{idVendor}=="3537", ATTRS{idProduct}=="10c6", TAG+="uaccess"
```

An administrator can place that rule in
`/etc/udev/rules.d/70-gamesir-g7-pro-8k.rules`, reload the udev rules and
reconnect the receiver. This grants access to the receiver's HID interfaces,
not just its battery data. No rule is needed if your existing device rules
already grant the required access.

From a MangoHud source checkout, first check the hardware reading:

```sh
python3 bin/gamesir-battery.py --once
```

Then leave one copy running outside the game's sandbox:

```sh
python3 bin/gamesir-battery.py
```

It writes atomically to `$XDG_CACHE_HOME/MangoHud/gamesir-battery.txt`, defaulting
to `~/.cache/MangoHud/gamesir-battery.txt`. Reconnecting the receiver is handled
automatically. `--status` returns `Disconnected` for a missing file or a reading
older than ten seconds, even if the helper was killed unexpectedly.

Add this to your MangoHud config, replacing `/absolute/path/to/MangoHud` with
your checkout's location:

```ini
legacy_layout=0
custom_text=G7 Pro
exec=python3 /absolute/path/to/MangoHud/bin/gamesir-battery.py --status
```

`--status` needs only Python, not the HID bindings or device access. Keep the
script and cache accessible inside the game runtime. If the game sees a
different home directory or `XDG_CACHE_HOME`, pass the same explicit
`--output /absolute/shared/path/battery.txt` to the reader and `--status`.
Quote paths containing spaces. This uses a custom text element rather than
the built-in `device_battery` element; keep `device_battery=gamepad` only if you
also want readings for other controllers.

To start the helper at login, install this as
`~/.config/systemd/user/gamesir-battery.service`, replacing the script path:

```ini
[Unit]
Description=GameSir G7 Pro 8K battery reader for MangoHud

[Service]
ExecStart=/usr/bin/python3 /absolute/path/to/MangoHud/bin/gamesir-battery.py
Restart=on-failure
RestartSec=5

[Install]
WantedBy=default.target
```

Stop the foreground reader, then run:

```sh
systemctl --user daemon-reload
systemctl --user enable --now gamesir-battery.service
```

To stop automatic reading, use
`systemctl --user disable --now gamesir-battery.service` and remove the custom
MangoHud config lines. Do not run multiple battery readers for the same receiver.

## Tests

No controller or HID bindings are required for the mocked protocol tests:

```sh
python3 -m unittest discover -s tests -p 'test_gamesir_battery.py' -v
```
4 changes: 4 additions & 0 deletions meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,10 @@ if get_option('include_doc')
endif

if get_option('tests').enabled()
test('gamesir battery helper', prog_python,
args: ['-m', 'unittest', 'discover', '-s',
meson.project_source_root() / 'tests', '-p', 'test_gamesir_battery.py'])

# cmocka_dep = dependency('cmocka', fallback: ['cmocka', 'cmocka_dep'])

# e = executable('amdgpu', 'tests/test_amdgpu.cpp',
Expand Down
Loading