From fdef27d57455da6c576115997ee29b4a5b8f2207 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sun, 15 Nov 2026 06:42:40 -0500 Subject: [PATCH] docs(poc): verify SSAP subscriptions, msg id interleaving, and cold-boot WoL timing - Add wake (--mac, --broadcast), subscribe-test, and turn-off subcommands to docs/poc/tv_test.py - Document verified 'type': 'subscribe' behavior on audio/getStatus (including nested volumeStatus.soundOutput) and getForegroundAppInfo in docs/poc/capabilities.md - Record empirical observation that mutating commands push subscription update frames before their own request response frame on the same WebSocket - Record deep cold-standby WoL boot timing (~30-35s to TLS + register, requiring open_timeout >= 3-4s and ~45s wake budget) --- docs/poc/capabilities.md | 9 ++- docs/poc/tv_test.py | 139 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+), 5 deletions(-) diff --git a/docs/poc/capabilities.md b/docs/poc/capabilities.md index ab46a61..3aa0e83 100644 --- a/docs/poc/capabilities.md +++ b/docs/poc/capabilities.md @@ -39,12 +39,11 @@ Empirical notes from probing `192.168.1.11` (`Ethernet`, MAC `7c:64:6c:94:d1:24` - **Power lifecycle (`turnOff` + Wake-on-LAN)**: - `ssap://system/turnOff` cleanly powers the TV into standby (`returnValue: true`). - Sending a standard WoL magic packet (`0xff * 6 + mac * 16`) over UDP broadcast (`255.255.255.255:9`) to Ethernet MAC `7c:64:6c:94:d1:24` successfully wakes and powers on the TV from standby. - - While the TV is in standby/booting, `wss://192.168.1.11:3001` accepts the WebSocket upgrade and immediately closes with `1008 (policy violation) Try Again Later (EWS)`—providing an instant fail-fast / boot-polling signal without waiting for a TCP timeout. + - While the TV is in warm standby/booting right after `turnOff`, `wss://192.168.1.11:3001` accepts the WebSocket upgrade and immediately closes with `1008 (policy violation) Try Again Later (EWS)`. In deep cold standby (after extended power-off), the TCP/TLS opening handshake times out (`TimeoutError`), and cold-booting via WoL until `wss://:3001` completes TLS + `register` takes `~30–35s` (requiring `open_timeout >= 3–4s` and a `~45s` wake timeout budget). +- **Subscriptions & `msg["id"]` interleaving (`"type": "subscribe"`)**: + - Verified `"type": "subscribe"` on both `ssap://com.webos.applicationManager/getForegroundAppInfo` (`{"subscribed": true, "returnValue": true, "appId": "com.webos.app.livetv", ...}`) and `ssap://audio/getStatus` (`{"returnValue": true, "mute": false, "volume": 27, "volumeStatus": {"soundOutput": "tv_speaker", "maxVolume": 100, "muteStatus": false, ...}}`). + - When sending a mutating request (`ssap://audio/setMute`) on the same WebSocket, the TV pushes the updated `sub_audio` subscription frame **before** the `req_mute_on` / `req_mute_off` response frame—confirming that persistent clients must demultiplex incoming frames by `msg["id"]`. ### Blocked on Retail Firmware - **`ssap://settings/getSystemSettings`**: Returned `401 insufficient permissions` (low-level picture/network/system settings are restricted to signed LG system apps). - -### Not Yet Tested on This Device - -- **Subscriptions**: `"type": "subscribe"` on `audio/getStatus` and `getForegroundAppInfo` for a persistent client. diff --git a/docs/poc/tv_test.py b/docs/poc/tv_test.py index 0c7d501..3b60288 100644 --- a/docs/poc/tv_test.py +++ b/docs/poc/tv_test.py @@ -5,7 +5,9 @@ from __future__ import annotations import argparse import asyncio import json +import socket import ssl +import time from pathlib import Path from typing import Any @@ -42,9 +44,21 @@ COMMANDS: dict[str, tuple[str, dict[str, Any]]] = { "vol-down": ("ssap://audio/volumeDown", {}), "mute": ("ssap://audio/setMute", {"mute": True}), "unmute": ("ssap://audio/setMute", {"mute": False}), + "turn-off": ("ssap://system/turnOff", {}), } +def send_wol(mac: str, broadcast: str = "255.255.255.255", port: int = 9) -> None: + """Broadcast a Wake-on-LAN magic packet for the given MAC address.""" + clean_hex = mac.replace(":", "").replace("-", "") + if len(clean_hex) != 12: + raise ValueError(f"Invalid MAC address: {mac}") + magic = b"\xff" * 6 + bytes.fromhex(clean_hex) * 16 + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) + sock.sendto(magic, (broadcast, port)) + + def build_ssl_context() -> ssl.SSLContext: """Create an SSL context that accepts the TV's self-signed certificate.""" ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) @@ -122,6 +136,114 @@ async def pair_and_send( return json.loads(await ws.recv()) +async def wake_and_wait( + ip: str, + port: int, + mac: str, + key_file: Path, + broadcast: str = "255.255.255.255", + timeout_s: float = 45.0, +) -> dict[str, Any]: + """Send WoL magic packet and poll SSAP until registration succeeds.""" + send_wol(mac, broadcast=broadcast) + start = time.monotonic() + last_error = "" + attempts = 0 + keys = load_client_keys(key_file) + saved_key = keys.get(ip) + scheme = "wss" if port == 3001 else "ws" + ssl_ctx = build_ssl_context() if scheme == "wss" else None + + while (time.monotonic() - start) < timeout_s: + attempts += 1 + try: + async with websockets.connect( + f"{scheme}://{ip}:{port}", ssl=ssl_ctx, open_timeout=4.0 + ) as ws: + await ws.send(json.dumps(build_register_payload(saved_key))) + msg = json.loads(await asyncio.wait_for(ws.recv(), timeout=3.0)) + if msg.get("type") == "registered": + return { + "status": "connected", + "attempts": attempts, + "elapsed_ms": round((time.monotonic() - start) * 1000), + "last_error": last_error, + } + last_error = f"unexpected frame: {msg.get('type')}" + except Exception as exc: + last_error = f"{type(exc).__name__}: {exc}" + await asyncio.sleep(1.0) + + raise TimeoutError(f"Wake timed out after {attempts} attempts ({last_error})") + + +async def verify_subscriptions(ip: str, port: int, key_file: Path) -> dict[str, Any]: + """Verify SSAP subscribe frames, push updates on state change, and id multiplexing.""" + keys = load_client_keys(key_file) + saved_key = keys.get(ip) + scheme = "wss" if port == 3001 else "ws" + ssl_ctx = build_ssl_context() if scheme == "wss" else None + + async with websockets.connect( + f"{scheme}://{ip}:{port}", ssl=ssl_ctx, ping_interval=10, ping_timeout=5 + ) as ws: + await ws.send(json.dumps(build_register_payload(saved_key))) + reg = json.loads(await asyncio.wait_for(ws.recv(), timeout=3.0)) + if reg.get("type") != "registered": + raise RuntimeError(f"Expected registered, got: {reg.get('type')}") + + await ws.send( + json.dumps({"id": "sub_audio", "type": "subscribe", "uri": "ssap://audio/getStatus"}) + ) + await ws.send( + json.dumps( + { + "id": "sub_fg", + "type": "subscribe", + "uri": "ssap://com.webos.applicationManager/getForegroundAppInfo", + } + ) + ) + await ws.send( + json.dumps( + {"id": "req_info", "type": "request", "uri": "ssap://system/getSystemInfo"} + ) + ) + + frames: list[dict[str, Any]] = [] + for _ in range(3): + frames.append(json.loads(await asyncio.wait_for(ws.recv(), timeout=3.0))) + + # Trigger a mute toggle to verify sub_audio pushes a second frame automatically + await ws.send( + json.dumps( + { + "id": "req_mute_on", + "type": "request", + "uri": "ssap://audio/setMute", + "payload": {"mute": True}, + } + ) + ) + for _ in range(2): + frames.append(json.loads(await asyncio.wait_for(ws.recv(), timeout=3.0))) + + await ws.send( + json.dumps( + { + "id": "req_mute_off", + "type": "request", + "uri": "ssap://audio/setMute", + "payload": {"mute": False}, + } + ) + ) + for _ in range(2): + frames.append(json.loads(await asyncio.wait_for(ws.recv(), timeout=3.0))) + + return {"frames": frames} + + def parse_args() -> argparse.Namespace: """Parse CLI arguments.""" parser = argparse.ArgumentParser( @@ -155,12 +277,29 @@ def parse_args() -> argparse.Namespace: raw_p = sub.add_parser("raw", help="Send an arbitrary SSAP URI + JSON payload.") raw_p.add_argument("uri", help="SSAP URI (e.g. ssap://system/getSystemInfo)") raw_p.add_argument("--payload", default="{}", help="JSON payload string") + + wake_p = sub.add_parser("wake", help="Wake TV via WoL and poll until SSAP registers.") + wake_p.add_argument("--mac", required=True, help="TV MAC address (XX:XX:XX:XX:XX:XX)") + wake_p.add_argument("--broadcast", default="255.255.255.255", help="WoL broadcast IP") + + sub.add_parser("subscribe-test", help="Verify SSAP subscriptions and id multiplexing.") return parser.parse_args() def main() -> None: """CLI entry point.""" args = parse_args() + if args.command == "wake": + response = asyncio.run( + wake_and_wait(args.ip, args.port, args.mac, args.key_file, broadcast=args.broadcast) + ) + print(json.dumps(response, indent=2)) + return + if args.command == "subscribe-test": + response = asyncio.run(verify_subscriptions(args.ip, args.port, args.key_file)) + print(json.dumps(response, indent=2)) + return + if args.command == "toast": uri = "ssap://system.notifications/createToast" payload: dict[str, Any] = {"message": args.message}