You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
203 lines
6.9 KiB
Python
203 lines
6.9 KiB
Python
# 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())
|