Add kodi with passthrough. Reconfigure xing-wei remap so it handles volume changes when kodi is open via home assistant instead of over pulseaudio
parent
1d5f74d2c0
commit
419350822f
@ -1 +1,2 @@
|
||||
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."
|
||||
Binary file not shown.
@ -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())
|
||||
Loading…
Reference in New Issue