Add kodi with passthrough. Reconfigure xing-wei remap so it handles volume changes when kodi is open via home assistant instead of over pulseaudio

master
Kuba Orlik 2 weeks ago
parent 1d5f74d2c0
commit 419350822f

@ -1 +1,2 @@
export SUSPEND_SECRET=some-password export SUSPEND_SECRET=some-password
export HASS_TOKEN=12312312312

@ -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."

@ -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 "<no ../env found>"
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())

@ -5,21 +5,36 @@ import os
import evdev import evdev
from evdev import ecodes, UInput from evdev import ecodes, UInput
from ha_volume import adjust_volume, HAError
DEVICE_NAME = "XING WEI 2.4G USB USB Composite Device Consumer Control" 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(): def kodi_running():
for pid in os.listdir("/proc"): for pid in os.listdir("/proc"):
if not pid.isdigit(): if not pid.isdigit():
continue continue
try: try:
with open(f"/proc/{pid}/comm") as f: with open(f"/proc/{pid}/comm") as f:
if f.read().strip() in ("kodi", "kodi.bin"): if f.read().strip() in ("kodi", "kodi.bin"):
return True return True
except (OSError, PermissionError): except (OSError, PermissionError):
pass pass
return False return False
@ -28,87 +43,186 @@ def find_device():
for path in evdev.list_devices(): for path in evdev.list_devices():
try: try:
dev = evdev.InputDevice(path) dev = evdev.InputDevice(path)
if dev.name == DEVICE_NAME: if dev.name == DEVICE_NAME:
if ecodes.KEY_BACK in dev.capabilities().get(ecodes.EV_KEY, []): if ecodes.KEY_BACK in dev.capabilities().get(ecodes.EV_KEY, []):
print(f"Found device: {path}", flush=True) print(f"Found device: {path}", flush=True)
return dev return dev
dev.close() dev.close()
except (OSError, PermissionError): except (OSError, PermissionError):
pass pass
print("Waiting for XING WEI device...", flush=True)
print("Waiting for device...", flush=True)
time.sleep(2) time.sleep(2)
def run(): def run():
while True: while True:
dev = find_device() 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: try:
# Create a clean virtual keyboard passthrough = UInput.from_device(
ui = UInput( dev,
name="XING WEI Passthrough",
vendor=0x1915,
product=0x1025,
version=0x0201
)
remapper = UInput(
events={ events={
ecodes.EV_KEY: [ ecodes.EV_KEY: [
ecodes.KEY_ESC, ecodes.KEY_ESC,
ecodes.KEY_BACKSPACE, ecodes.KEY_BACKSPACE,
ecodes.KEY_LEFTSHIFT, ecodes.KEY_LEFTSHIFT,
ecodes.KEY_TAB, 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, bustype=0x03,
vendor=0x1915, vendor=0x1915,
product=0x1025, product=0x1026,
version=0x0201 version=0x0201
) )
dev.grab() dev.grab()
print("Device grabbed successfully!", flush=True) 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("BACK: ESC / BACKSPACE (Kodi)", flush=True)
print("HOME: SHIFT + TAB", 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(): 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: if event.code == ecodes.KEY_BACK:
key = (
ecodes.KEY_BACKSPACE if event.value == 1:
if kodi_running() back_key = (
else ecodes.KEY_ESC 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) if event.value == 0:
ui.syn() back_key = None
# ---- HOME -> SHIFT + TAB ----
elif event.code == ecodes.KEY_HOMEPAGE: elif event.code == ecodes.KEY_HOMEPAGE:
if event.value == 1: if event.value == 1:
ui.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 1) remapper.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 1)
ui.write(ecodes.EV_KEY, ecodes.KEY_TAB, 1) remapper.write(ecodes.EV_KEY, ecodes.KEY_TAB, 1)
ui.syn() remapper.write(ecodes.EV_KEY, ecodes.KEY_TAB, 0)
remapper.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 0)
ui.write(ecodes.EV_KEY, ecodes.KEY_TAB, 0) remapper.syn()
ui.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 0)
ui.syn()
# ---- Everything else goes to passthrough ----
else: 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: else:
# Ignore non-key events from the consumer-control device passthrough.write_event(event)
pass
except (OSError, IOError) as e: except (OSError, IOError) as e:
print(f"Device error: {e}", flush=True) print(f"Device error: {e}", flush=True)
@ -121,8 +235,11 @@ def run():
pass pass
dev.close() dev.close()
if ui: if passthrough:
ui.close() passthrough.close()
if remapper:
remapper.close()
print("Reconnecting in 2 seconds...", flush=True) print("Reconnecting in 2 seconds...", flush=True)
time.sleep(2) time.sleep(2)

Loading…
Cancel
Save