diff --git a/env.example b/env.example index 1549c89..324e8f6 100644 --- a/env.example +++ b/env.example @@ -1 +1,2 @@ -export SUSPEND_SECRET=some-password \ No newline at end of file +export SUSPEND_SECRET=some-password +export HASS_TOKEN=12312312312 \ No newline at end of file diff --git a/kodi-with-passthrough.sh b/kodi-with-passthrough.sh new file mode 100755 index 0000000..8bb313e --- /dev/null +++ b/kodi-with-passthrough.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +set -euo pipefail + +CARD="alsa_card.pci-0000_03_00.1" +CARD_SUFFIX="${CARD#alsa_card.}" +STEREO_PROFILE="output:hdmi-stereo-extra3" +SURROUND_PROFILE="output:hdmi-surround71-extra3" + +echo "Switching ONKYO to 7.1..." +pactl set-card-profile "$CARD" "$SURROUND_PROFILE" + +sleep 2 + +echo "Switching ONKYO to stereo..." +pactl set-card-profile "$CARD" "$STEREO_PROFILE" + +echo "Clearing default sink configuration..." +wpctl clear-default + +sleep 3 + +echo "Launching Kodi..." +flatpak run tv.kodi.Kodi & +KODI_PID=$! + +trap 'kill "$KODI_PID" 2>/dev/null || true; wait "$KODI_PID" 2>/dev/null || true' INT TERM + +wait "$KODI_PID" || true + +echo "Kodi exited. Restoring 7.1 profile and default sink..." +pactl set-card-profile "$CARD" "$SURROUND_PROFILE" + +# Give PipeWire a moment to expose the sink for the new profile +sleep 1 + +SINK="alsa_output.${CARD_SUFFIX}.hdmi-surround71-extra3" +if pactl list short sinks | awk '{print $2}' | grep -qx "$SINK"; then + pactl set-default-sink "$SINK" + echo "Default sink set to: $SINK" +else + echo "Warning: sink '$SINK' not found; listing available sinks:" >&2 + pactl list short sinks >&2 +fi + +echo "Done." diff --git a/xing-wei-remap/__pycache__/ha_volume.cpython-314.pyc b/xing-wei-remap/__pycache__/ha_volume.cpython-314.pyc new file mode 100644 index 0000000..92d26a6 Binary files /dev/null and b/xing-wei-remap/__pycache__/ha_volume.cpython-314.pyc differ diff --git a/xing-wei-remap/ha_volume.py b/xing-wei-remap/ha_volume.py new file mode 100644 index 0000000..5e5396a --- /dev/null +++ b/xing-wei-remap/ha_volume.py @@ -0,0 +1,202 @@ +# ha_volume.py +"""Adjust a Home Assistant media_player volume by a signed delta. + +Usable both as a CLI tool and as an importable module. + + from ha_volume import adjust_volume + adjust_volume(5) # +5 percentage points on default entity + adjust_volume(-5, entity="media_player.kitchen") + old, new = adjust_volume(5) # get the before/after levels back + +Reads HASS_TOKEN from ../env (auto-discovered relative to this file), then +falls back to $HASS_TOKEN / $HASS_URL / $HASS_ENTITY. + +Stdlib only: urllib, json, argparse, pathlib, os, sys. +""" +from __future__ import annotations + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request +from pathlib import Path + +DEFAULT_ENTITY = "media_player.tx_nr7100" +DEFAULT_URL = "http://192.168.1.90:8123" + + +class HAError(RuntimeError): + """Raised for any Home Assistant API / config failure.""" + + +# --------------------------------------------------------------------------- # +# Config discovery +# --------------------------------------------------------------------------- # + +def load_env(path: Path) -> dict[str, str]: + """Parse a simple shell-style env file (supports `export ` and quotes).""" + env: dict[str, str] = {} + if not path.is_file(): + return env + for raw in path.read_text().splitlines(): + line = raw.strip() + if not line or line.startswith("#"): + continue + if line.startswith("export "): + line = line[len("export "):].lstrip() + if "=" not in line: + continue + key, _, val = line.partition("=") + key, val = key.strip(), val.strip() + if len(val) >= 2 and val[0] == val[-1] and val[0] in ("'", '"'): + val = val[1:-1] + env[key] = val + return env + + +def find_env_file(start: Path | None = None) -> Path | None: + """Search for `../env` relative to *start* (defaults to this file's dir).""" + here = (start or Path(__file__)).resolve().parent + for cand in (here / ".." / "env", Path.cwd() / ".." / "env", Path.cwd() / "env"): + if cand.is_file(): + return cand.resolve() + return None + + +def _resolve( + *, + entity: str | None, + url: str | None, + token: str | None, + env_file: Path | str | None, +) -> tuple[str, str, str]: + """Fill in entity / url / token from args, env file, then process env.""" + env_path = Path(env_file).expanduser() if env_file else find_env_file() + env = load_env(env_path) if env_path else {} + + tok = token or env.get("HASS_TOKEN") or os.environ.get("HASS_TOKEN") + if not tok: + where = env_path or "" + raise HAError(f"HASS_TOKEN not in {where} or $HASS_TOKEN") + + ent = entity or env.get("HASS_ENTITY") or os.environ.get("HASS_ENTITY") or DEFAULT_ENTITY + base = (url or env.get("HASS_URL") or os.environ.get("HASS_URL") or DEFAULT_URL).rstrip("/") + return ent, base, tok + + +# --------------------------------------------------------------------------- # +# HTTP +# --------------------------------------------------------------------------- # + +def _request(url: str, token: str, *, method: str = "GET", payload=None): + data = json.dumps(payload).encode() if payload is not None else None + headers = {"Authorization": f"Bearer {token}"} + if data is not None: + headers["Content-Type"] = "application/json" + req = urllib.request.Request(url, data=data, headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=10) as resp: + raw = resp.read() + except urllib.error.HTTPError as e: + raise HAError(f"{method} {url} -> {e.code} {e.reason}") from e + except urllib.error.URLError as e: + raise HAError(f"cannot reach {url}: {e.reason}") from e + return json.loads(raw) if raw else None + + +# --------------------------------------------------------------------------- # +# Public API +# --------------------------------------------------------------------------- # + +def get_volume( + entity: str | None = None, + *, + url: str | None = None, + token: str | None = None, + env_file: Path | str | None = None, +) -> float: + """Return the current volume_level (0.0-1.0) for *entity*.""" + ent, base, tok = _resolve(entity=entity, url=url, token=token, env_file=env_file) + state = _request(f"{base}/api/states/{ent}", tok) + try: + return float(state["attributes"]["volume_level"]) + except (KeyError, TypeError, ValueError) as e: + raise HAError( + f"{ent} has no volume_level (state={state.get('state')!r})" + ) from e + + +def set_volume( + level: float, + entity: str | None = None, + *, + url: str | None = None, + token: str | None = None, + env_file: Path | str | None = None, +) -> None: + """Set volume_level (0.0-1.0), clamped to range.""" + ent, base, tok = _resolve(entity=entity, url=url, token=token, env_file=env_file) + level = max(0.0, min(1.0, float(level))) + _request(f"{base}/api/services/media_player/volume_set", tok, method="POST", payload={ + "entity_id": ent, + "volume_level": round(level, 3), + }) + + +def adjust_volume( + delta: int, + entity: str | None = None, + *, + url: str | None = None, + token: str | None = None, + env_file: Path | str | None = None, +) -> tuple[float, float]: + """Add *delta* percentage points to *entity*'s volume; returns (old, new).""" + ent, base, tok = _resolve(entity=entity, url=url, token=token, env_file=env_file) + current = float(_request(f"{base}/api/states/{ent}", tok)["attributes"]["volume_level"]) + new = max(0.0, min(1.0, current + delta / 100.0)) + if abs(new - current) < 1e-9: + return current, current + _request(f"{base}/api/services/media_player/volume_set", tok, method="POST", payload={ + "entity_id": ent, + "volume_level": round(new, 3), + }) + return current, new + + +# --------------------------------------------------------------------------- # +# CLI +# --------------------------------------------------------------------------- # + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser( + description="Add a signed delta (percentage points) to a HA media_player volume." + ) + ap.add_argument("delta", type=int, help="integer delta, e.g. 5 or -5") + ap.add_argument("--entity", default=None, help=f"default: {DEFAULT_ENTITY}") + ap.add_argument("--url", default=None, help=f"default: {DEFAULT_URL}") + ap.add_argument("--env-file", default=None, help="path to env file (default: auto)") + args = ap.parse_args(argv) + + try: + old, new = adjust_volume( + args.delta, + entity=args.entity, + url=args.url, + env_file=args.env_file, + ) + except HAError as e: + print(f"error: {e}", file=sys.stderr) + return 1 + + if abs(new - old) < 1e-9: + print(f"volume already at {old:.2f} ({args.delta:+d} requested)") + else: + print(f"volume: {old:.2f} -> {new:.2f} ({args.delta:+d})") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/xing-wei-remap/remap.py b/xing-wei-remap/remap.py index c30b307..16e28b7 100755 --- a/xing-wei-remap/remap.py +++ b/xing-wei-remap/remap.py @@ -5,21 +5,36 @@ import os import evdev from evdev import ecodes, UInput +from ha_volume import adjust_volume, HAError + DEVICE_NAME = "XING WEI 2.4G USB USB Composite Device Consumer Control" +# HID consumer scancodes carried in MSC_SCAN.value for the volume keys. +VOLUP_SCAN = 0xC00E9 # -> KEY_VOLUMEUP +VOLDOWN_SCAN = 0xC00EA # -> KEY_VOLUMEDOWN + +# How much to change HA volume_level per keypress, in percentage points. +VOLUME_STEP = 2 + +# Bidirectional maps between EV_KEY codes and MSC_SCAN values +SCAN_TO_KEY = { + VOLUP_SCAN: ecodes.KEY_VOLUMEUP, + VOLDOWN_SCAN: ecodes.KEY_VOLUMEDOWN, +} +KEY_TO_SCAN = {v: k for k, v in SCAN_TO_KEY.items()} +SCAN_TO_DIR = {VOLUP_SCAN: "up", VOLDOWN_SCAN: "down"} + def kodi_running(): for pid in os.listdir("/proc"): if not pid.isdigit(): continue - try: with open(f"/proc/{pid}/comm") as f: if f.read().strip() in ("kodi", "kodi.bin"): return True except (OSError, PermissionError): pass - return False @@ -28,87 +43,186 @@ def find_device(): for path in evdev.list_devices(): try: dev = evdev.InputDevice(path) - if dev.name == DEVICE_NAME: if ecodes.KEY_BACK in dev.capabilities().get(ecodes.EV_KEY, []): print(f"Found device: {path}", flush=True) return dev - dev.close() - except (OSError, PermissionError): pass - - print("Waiting for device...", flush=True) + print("Waiting for XING WEI device...", flush=True) time.sleep(2) def run(): while True: dev = find_device() - ui = None + + passthrough = None + remapper = None + + # Remember which key was used for the current BACK press. + back_key = None + + # Per-scancode state for volume keys while the device is grabbed. + # "intercepting" -> we swallowed the press; swallow the release too. + # "passthrough" -> we forwarded the press; forward the release too. + # Entry present -> key currently held (press is in progress). + # Entry absent -> key is released. + vol_state = {} try: - # Create a clean virtual keyboard - ui = UInput( + passthrough = UInput.from_device( + dev, + name="XING WEI Passthrough", + vendor=0x1915, + product=0x1025, + version=0x0201 + ) + + remapper = UInput( events={ ecodes.EV_KEY: [ ecodes.KEY_ESC, ecodes.KEY_BACKSPACE, ecodes.KEY_LEFTSHIFT, ecodes.KEY_TAB, - ] + [ - key for key in dev.capabilities().get(ecodes.EV_KEY, []) - if key not in ( - ecodes.KEY_BACK, - ecodes.KEY_HOMEPAGE, - ) ] }, - name="XING WEI Remapped Keyboard", + name="XING WEI Remapped Keys", bustype=0x03, vendor=0x1915, - product=0x1025, + product=0x1026, version=0x0201 ) dev.grab() print("Device grabbed successfully!", flush=True) + print("Created: XING WEI Passthrough", flush=True) + print("Created: XING WEI Remapped Keys", flush=True) print("BACK: ESC / BACKSPACE (Kodi)", flush=True) print("HOME: SHIFT + TAB", flush=True) + print(f"VOL UP/DOWN: HA volume {VOLUME_STEP:+d}/{-VOLUME_STEP:+d} (Kodi)", + flush=True) for event in dev.read_loop(): - if event.type == ecodes.EV_KEY: - + # ------------------------------------------------------------------ + # MSC_SCAN: runs *before* the matching EV_KEY in each batch. We use + # it to decide (and remember) whether to intercept this press. + # ------------------------------------------------------------------ + if event.type == ecodes.EV_MSC and event.code == ecodes.MSC_SCAN: + + scan = event.value + if scan in SCAN_TO_KEY: + state = vol_state.get(scan) + + if state == "intercepting": + # Release scan of an intercepted key: keep suppressed. + continue + + if state == "passthrough": + # Release scan of a passed-through key: forward it. + passthrough.write_event(event) + continue + + # New press. Decide now based on Kodi; remember the + # decision so the release cannot flip mid-press. + if kodi_running(): + vol_state[scan] = "intercepting" + continue + else: + vol_state[scan] = "passthrough" + passthrough.write_event(event) + continue + + # Non-volume scan: forward as before. + passthrough.write_event(event) + + # ------------------------------------------------------------------ + # EV_KEY + # ------------------------------------------------------------------ + elif event.type == ecodes.EV_KEY: + + scan = KEY_TO_SCAN.get(event.code) + state = vol_state.get(scan) if scan is not None else None + + # ---- Volume key that we're intercepting (Kodi is running) ---- + if state == "intercepting": + if event.value == 1: + delta = VOLUME_STEP if SCAN_TO_DIR[scan] == "up" else -VOLUME_STEP + try: + adjust_volume(delta) + except HAError as e: + print(f"volume adjust failed: {e}", flush=True) + except Exception as e: + print(f"volume adjust error: {e!r}", flush=True) + elif event.value == 0: + # Release completes the pair; clear state. + del vol_state[scan] + # Suppress either way. + continue + + # ---- Volume key we're passing through ---- + if state == "passthrough": + passthrough.write_event(event) + if event.value == 0: + del vol_state[scan] + continue + + # ---- BACK -> ESC / BACKSPACE ---- if event.code == ecodes.KEY_BACK: - key = ( - ecodes.KEY_BACKSPACE - if kodi_running() - else ecodes.KEY_ESC + + if event.value == 1: + back_key = ( + ecodes.KEY_BACKSPACE + if kodi_running() + else ecodes.KEY_ESC + ) + elif back_key is None: + back_key = ( + ecodes.KEY_BACKSPACE + if kodi_running() + else ecodes.KEY_ESC + ) + + remapper.write( + ecodes.EV_KEY, + back_key, + event.value ) - ui.write(ecodes.EV_KEY, key, event.value) - ui.syn() + if event.value == 0: + back_key = None + # ---- HOME -> SHIFT + TAB ---- elif event.code == ecodes.KEY_HOMEPAGE: if event.value == 1: - ui.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 1) - ui.write(ecodes.EV_KEY, ecodes.KEY_TAB, 1) - ui.syn() - - ui.write(ecodes.EV_KEY, ecodes.KEY_TAB, 0) - ui.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 0) - ui.syn() + remapper.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 1) + remapper.write(ecodes.EV_KEY, ecodes.KEY_TAB, 1) + remapper.write(ecodes.EV_KEY, ecodes.KEY_TAB, 0) + remapper.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 0) + remapper.syn() + # ---- Everything else goes to passthrough ---- else: - ui.write_event(event) - + passthrough.write_event(event) + + # ------------------------------------------------------------------ + # SYN + # ------------------------------------------------------------------ + elif event.type == ecodes.EV_SYN: + passthrough.write_event(event) + if event.code == ecodes.SYN_REPORT: + remapper.syn() + + # ------------------------------------------------------------------ + # Anything else (REL, ABS, etc.) + # ------------------------------------------------------------------ else: - # Ignore non-key events from the consumer-control device - pass + passthrough.write_event(event) except (OSError, IOError) as e: print(f"Device error: {e}", flush=True) @@ -121,8 +235,11 @@ def run(): pass dev.close() - if ui: - ui.close() + if passthrough: + passthrough.close() + + if remapper: + remapper.close() print("Reconnecting in 2 seconds...", flush=True) time.sleep(2)