diff --git a/README.md b/README.md index 901e0ea6e8..c9e959d735 100644 --- a/README.md +++ b/README.md @@ -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`) | diff --git a/bin/gamesir-battery.py b/bin/gamesir-battery.py new file mode 100644 index 0000000000..6cae887f60 --- /dev/null +++ b/bin/gamesir-battery.py @@ -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()) diff --git a/docs/gamesir-battery.md b/docs/gamesir-battery.md new file mode 100644 index 0000000000..b977dc313b --- /dev/null +++ b/docs/gamesir-battery.md @@ -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 +``` diff --git a/meson.build b/meson.build index 1cbb8caaae..82751087a4 100644 --- a/meson.build +++ b/meson.build @@ -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', diff --git a/tests/test_gamesir_battery.py b/tests/test_gamesir_battery.py new file mode 100644 index 0000000000..d38b93bdbe --- /dev/null +++ b/tests/test_gamesir_battery.py @@ -0,0 +1,140 @@ +import contextlib +import importlib.util +import io +import os +from pathlib import Path +import tempfile +import threading +import unittest +from unittest.mock import Mock, patch + + +SCRIPT = Path(__file__).resolve().parents[1] / "bin" / "gamesir-battery.py" +spec = importlib.util.spec_from_file_location("gamesir_battery", SCRIPT) +battery = importlib.util.module_from_spec(spec) +spec.loader.exec_module(battery) + + +def report(percent=100, charging=False): + data = [0] * 64 + data[0] = 0x12 + data[1:5] = [128] * 4 + data[35] = int(charging) + data[36] = percent + return data + + +class BatteryTests(unittest.TestCase): + def test_percentage_and_charging(self): + for percent in (0, 1, 5, 50, 99, 100): + self.assertEqual(battery.parse_report(report(percent)), f"{percent}%") + self.assertEqual(battery.parse_report(report(76, True)), "76% charging") + + def test_unrelated_short_empty_and_invalid_reports(self): + for data in ([], [0x12], report()[:36], report() + [0], + [0x12] + [0] * 63, report(101), report(255), + [0x10] + report()[1:]): + self.assertIsNone(battery.parse_report(data)) + + def test_atomic_cache_and_stale_status(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "nested" / "battery.txt" + self.assertEqual(battery.status(output), "Disconnected") + battery.publish(output, "75%") + self.assertEqual(battery.status(output), "75%") + battery.publish(output, "74% charging") + self.assertEqual(battery.status(output), "74% charging") + self.assertEqual(list(output.parent.iterdir()), [output]) + os.utime(output, (1, 1)) + self.assertEqual(battery.status(output), "Disconnected") + + def test_default_output_respects_xdg(self): + with patch.dict(os.environ, {"XDG_CACHE_HOME": "/custom/cache"}): + self.assertEqual(battery.default_output(), + Path("/custom/cache/MangoHud/gamesir-battery.txt")) + + def test_once_reads_without_writing_cache(self): + device = Mock() + device.write.return_value = 64 + device.read.side_effect = [[0x10] + [0] * 63, report(82)] + with patch.object(battery, "publish") as publish, io.StringIO() as output: + with contextlib.redirect_stdout(output): + self.assertTrue(battery.read_device(device, Path("unused"), + threading.Event(), once=True)) + self.assertEqual(output.getvalue(), "82%\n") + publish.assert_not_called() + device.write.assert_called_once_with(battery.HEARTBEAT) + device.set_nonblocking.assert_called_once_with(True) + + def test_heartbeat_is_rate_limited_and_unchanged_cache_is_refreshed(self): + device = Mock() + device.write.return_value = 64 + device.read.return_value = report(67) + stop = threading.Event() + ticks = iter([0, 0, .25, .5, .75, 1.0]) + + def clock(): + try: + return next(ticks) + except StopIteration: + stop.set() + return 1.1 + + with patch.object(battery.time, "monotonic", side_effect=clock), \ + patch.object(battery, "publish") as publish: + battery.read_device(device, Path("unused"), stop) + self.assertEqual(device.write.call_count, 3) + self.assertEqual(publish.call_count, 2) + + def test_invalid_stream_times_out_instead_of_staying_connected(self): + device = Mock() + device.write.return_value = 64 + device.read.return_value = [0x12] + [0] * 63 + with patch.object(battery.time, "monotonic", side_effect=[0, 0, 5]), \ + patch.object(battery, "publish") as publish: + with self.assertRaisesRegex(OSError, "No valid GameSir"): + battery.read_device(device, Path("unused"), threading.Event()) + publish.assert_not_called() + + def test_failed_heartbeat_is_reported(self): + device = Mock() + device.write.return_value = -1 + with self.assertRaisesRegex(OSError, "heartbeat"): + battery.read_device(device, Path("unused"), threading.Event()) + + def test_enumeration_deduplicates_hid_usages_and_closes_handle(self): + hid = Mock() + hid.enumerate.return_value = [{"path": b"/dev/hidraw0"}] * 3 + with patch.object(battery, "read_device", return_value=True): + self.assertEqual(battery.run(hid, Path("unused"), + threading.Event(), once=True), 0) + hid.enumerate.assert_called_once_with(0x3537, 0x10C6) + hid.device.assert_called_once() + hid.device.return_value.close.assert_called_once() + + def test_permission_failure_closes_handle_and_returns_failure(self): + hid = Mock() + hid.enumerate.return_value = [{"path": b"/dev/hidraw0"}] + hid.device.return_value.open_path.side_effect = OSError("Permission denied") + with self.assertLogs(level="WARNING"): + self.assertEqual(battery.run(hid, Path("unused"), + threading.Event(), once=True), 1) + hid.device.return_value.close.assert_called_once() + + def test_disconnect_publishes_status_and_retries_after_hotplug(self): + hid = Mock() + hid.enumerate.side_effect = [[], [{"path": b"/dev/hidraw0"}]] + stop = Mock() + stop.is_set.side_effect = [False, False, True] + with patch.object(battery, "read_device", side_effect=OSError("unplugged")), \ + patch.object(battery, "publish") as publish, \ + self.assertLogs(level="WARNING"): + self.assertEqual(battery.run(hid, Path("unused"), stop), 0) + self.assertEqual(hid.enumerate.call_count, 2) + hid.device.return_value.close.assert_called_once() + self.assertEqual(publish.call_args.args[1], "Disconnected") + self.assertEqual(stop.wait.call_count, 2) + + +if __name__ == "__main__": + unittest.main()