Merge the bridge and a home-screen interface into one app
The HEOS app is unpleasant to use for the four things that actually get
done in this house, so this is those four things on one screen: volume
for the Home 400 and the Living Room pair, joining either to the AVR,
splitting them off again, and picking the AVR's input.
The bridge's logic moves in mostly intact, split into a HEOS client, an
AVR client and a controller, with two grouping bugs fixed on the way:
* Merging a room into the AVR sent only the pair's leader pid, which
left the second Home 200 behind. Group targets now expand to every
member pid, and unmerging re-forms the pair rather than leaving two
lone speakers. The members are learned while the pair is visible and
remembered in members.json so a restart can still rebuild it.
* Volume for the pair used its gid, which stops existing the moment it
joins the AVR's group. It now falls back to the member players.
Both sockets are kept open rather than reconnecting per command, which
is what made every button press feel slow; the AVR connection doubles as
a listener, so input changes made with the physical remote show up too.
The original query-string endpoints still answer, so anything already
pointed at the bridge keeps working.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,126 @@
|
||||
"""HEOS CLI client (TCP port 1255).
|
||||
|
||||
HEOS is not JSON-RPC or anything else standard: you send one
|
||||
`heos://group/command?a=1&b=2` line and read back one JSON line. This
|
||||
keeps the socket open between commands -- the panel fires a command on
|
||||
every button press, and a fresh TCP handshake per press is what made
|
||||
the original bridge feel sluggish.
|
||||
"""
|
||||
|
||||
import json
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import unquote_plus
|
||||
|
||||
|
||||
class HeosError(RuntimeError):
|
||||
"""The device answered, but said no (or never answered at all)."""
|
||||
|
||||
|
||||
def parse_message(message: str) -> dict:
|
||||
"""Turn a HEOS `heos.message` string into a dict.
|
||||
|
||||
e.g. "pid=12345&level=23" -> {"pid": "12345", "level": "23"}
|
||||
"""
|
||||
result = {}
|
||||
for part in message.split("&"):
|
||||
if "=" in part:
|
||||
key, value = part.split("=", 1)
|
||||
result[key] = unquote_plus(value)
|
||||
elif part:
|
||||
result[part] = ""
|
||||
return result
|
||||
|
||||
|
||||
class HeosClient:
|
||||
"""One persistent, lock-guarded, self-healing HEOS connection."""
|
||||
|
||||
def __init__(self, host: str, port: int = 1255, timeout: float = 5.0):
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.timeout = timeout
|
||||
self._sock = None
|
||||
self._buffer = b""
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# -- connection management -----------------------------------------
|
||||
def _connect(self):
|
||||
self._close()
|
||||
sock = socket.create_connection((self.host, self.port), timeout=self.timeout)
|
||||
sock.settimeout(self.timeout)
|
||||
self._sock = sock
|
||||
self._buffer = b""
|
||||
|
||||
def _close(self):
|
||||
if self._sock is not None:
|
||||
try:
|
||||
self._sock.close()
|
||||
except OSError:
|
||||
pass
|
||||
self._sock = None
|
||||
self._buffer = b""
|
||||
|
||||
def _read_line(self, deadline: float) -> bytes:
|
||||
while b"\r\n" not in self._buffer:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("no reply from HEOS in time")
|
||||
self._sock.settimeout(remaining)
|
||||
chunk = self._sock.recv(4096)
|
||||
if not chunk:
|
||||
raise ConnectionError("HEOS closed the connection")
|
||||
self._buffer += chunk
|
||||
line, self._buffer = self._buffer.split(b"\r\n", 1)
|
||||
return line
|
||||
|
||||
# -- the one method everything else goes through -------------------
|
||||
def command(self, path: str, **params) -> dict:
|
||||
"""Send `heos://<path>?<params>` and return the parsed reply.
|
||||
|
||||
Retries once on a socket-level problem, because HEOS quietly
|
||||
drops connections that have been idle for a few minutes.
|
||||
"""
|
||||
with self._lock:
|
||||
for attempt in (1, 2):
|
||||
try:
|
||||
if self._sock is None:
|
||||
self._connect()
|
||||
return self._exchange(path, params)
|
||||
except (OSError, ValueError) as exc:
|
||||
# ValueError covers a desynced stream (bad JSON): in
|
||||
# both cases the fix is the same, start a fresh socket.
|
||||
self._close()
|
||||
if attempt == 2:
|
||||
raise HeosError(f"cannot reach HEOS at {self.host}: {exc}") from exc
|
||||
|
||||
def _exchange(self, path: str, params: dict) -> dict:
|
||||
query = "&".join(f"{k}={v}" for k, v in params.items() if v is not None)
|
||||
command = f"heos://{path}" + (f"?{query}" if query else "")
|
||||
self._sock.sendall(command.encode("utf-8") + b"\r\n")
|
||||
|
||||
# Browse calls can take a while, hence the generous overall budget.
|
||||
deadline = time.monotonic() + self.timeout * 3
|
||||
while True:
|
||||
reply = json.loads(self._read_line(deadline).decode("utf-8"))
|
||||
heos = reply.get("heos", {})
|
||||
|
||||
if heos.get("command") != path:
|
||||
continue # an event or a late reply to something else
|
||||
if "under process" in heos.get("message", ""):
|
||||
continue # placeholder ack; the real payload follows
|
||||
if heos.get("result") == "fail":
|
||||
raise HeosError(_failure_text(heos))
|
||||
return reply
|
||||
|
||||
def heart_beat(self):
|
||||
"""Keep the socket warm so the first press after an idle spell is
|
||||
as fast as the rest."""
|
||||
self.command("system/heart_beat")
|
||||
|
||||
|
||||
def _failure_text(heos: dict) -> str:
|
||||
message = parse_message(heos.get("message", ""))
|
||||
text = message.get("text") or "unknown error"
|
||||
eid = message.get("eid")
|
||||
return f"HEOS refused '{heos.get('command')}': {text}" + (f" (eid {eid})" if eid else "")
|
||||
Reference in New Issue
Block a user