Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f579ac37bf | ||
|
|
e146ab12a8 | ||
|
|
3f02236f60 | ||
|
|
3b8938c5fb | ||
|
|
5c493362b2 | ||
|
|
c4abbfcc3c | ||
|
|
41d197ee59 | ||
|
|
372235e9d5 | ||
|
|
7250944cc3 | ||
|
|
72745b85d4 |
No files matched your search
@@ -1 +1,46 @@
|
|||||||
"""Core LG webOS TV transport, protocol, and state machine package."""
|
"""Core LG webOS TV transport, protocol, and state machine package."""
|
||||||
|
|
||||||
|
from lg_smtv_mcp.tv_core.manager import ConnectionState, TvManager, TvState, send_wol
|
||||||
|
from lg_smtv_mcp.tv_core.pointer import BUTTON_ALLOWLIST, PointerClient, normalize_button_keys
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import (
|
||||||
|
CaptureResult,
|
||||||
|
CaptureTransport,
|
||||||
|
FrameCapturer,
|
||||||
|
KeysResult,
|
||||||
|
TextResult,
|
||||||
|
TvStateSnapshot,
|
||||||
|
TvStatus,
|
||||||
|
WebSocketClosedError,
|
||||||
|
WebSocketConnectFn,
|
||||||
|
WebSocketTransport,
|
||||||
|
)
|
||||||
|
from lg_smtv_mcp.tv_core.ssap import (
|
||||||
|
PERMISSIONS,
|
||||||
|
SsapClient,
|
||||||
|
build_register_payload,
|
||||||
|
websockets_connect,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"BUTTON_ALLOWLIST",
|
||||||
|
"CaptureResult",
|
||||||
|
"CaptureTransport",
|
||||||
|
"ConnectionState",
|
||||||
|
"FrameCapturer",
|
||||||
|
"KeysResult",
|
||||||
|
"PERMISSIONS",
|
||||||
|
"PointerClient",
|
||||||
|
"SsapClient",
|
||||||
|
"TextResult",
|
||||||
|
"TvManager",
|
||||||
|
"TvState",
|
||||||
|
"TvStateSnapshot",
|
||||||
|
"TvStatus",
|
||||||
|
"WebSocketClosedError",
|
||||||
|
"WebSocketConnectFn",
|
||||||
|
"WebSocketTransport",
|
||||||
|
"build_register_payload",
|
||||||
|
"normalize_button_keys",
|
||||||
|
"send_wol",
|
||||||
|
"websockets_connect",
|
||||||
|
]
|
||||||
@@ -0,0 +1,597 @@
|
|||||||
|
"""Single-owner TV connection state machine, subscribe cache, and control surface."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import socket
|
||||||
|
import time
|
||||||
|
from collections.abc import AsyncGenerator, Callable
|
||||||
|
from contextlib import asynccontextmanager, suppress
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from enum import StrEnum
|
||||||
|
from typing import Any, cast
|
||||||
|
|
||||||
|
from lg_smtv_mcp.config import TvConfig, require_mac
|
||||||
|
from lg_smtv_mcp.errors import ConfigError, ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.tv_core.pointer import PointerClient, normalize_button_keys
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import (
|
||||||
|
CaptureResult,
|
||||||
|
FrameCapturer,
|
||||||
|
KeysResult,
|
||||||
|
TextResult,
|
||||||
|
TvStateSnapshot,
|
||||||
|
TvStatus,
|
||||||
|
WebSocketConnectFn,
|
||||||
|
)
|
||||||
|
from lg_smtv_mcp.tv_core.ssap import SsapClient, websockets_connect
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class ConnectionState(StrEnum):
|
||||||
|
"""Lifecycle states of the single-owner TvManager connection loop."""
|
||||||
|
|
||||||
|
CONNECTING = "CONNECTING"
|
||||||
|
CONNECTED = "CONNECTED"
|
||||||
|
STANDBY_OFFLINE = "STANDBY_OFFLINE"
|
||||||
|
WAKING = "WAKING"
|
||||||
|
PAIRING_REQUIRED = "PAIRING_REQUIRED"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(slots=True)
|
||||||
|
class TvState:
|
||||||
|
"""Mutable internal cache of TV state populated by SSAP subscribe streams."""
|
||||||
|
|
||||||
|
volume: int | None = None
|
||||||
|
muted: bool | None = None
|
||||||
|
sound_output: str | None = None
|
||||||
|
foreground_app: str | None = None
|
||||||
|
last_updated: float | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def send_wol(mac: str, broadcast_addr: 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("-", "").strip()
|
||||||
|
if len(clean_hex) != 12:
|
||||||
|
raise ConfigError(f"Invalid MAC address for Wake-on-LAN: {mac!r}")
|
||||||
|
try:
|
||||||
|
mac_bytes = bytes.fromhex(clean_hex)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ConfigError(f"Invalid MAC address for Wake-on-LAN: {mac!r}") from exc
|
||||||
|
|
||||||
|
magic = b"\xff" * 6 + mac_bytes * 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_addr, port))
|
||||||
|
|
||||||
|
|
||||||
|
class TvManager:
|
||||||
|
"""Single-owner connection state machine and serialized control surface."""
|
||||||
|
|
||||||
|
state: ConnectionState
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
config: TvConfig,
|
||||||
|
*,
|
||||||
|
connect_fn: WebSocketConnectFn = websockets_connect,
|
||||||
|
capture_client: FrameCapturer | None = None,
|
||||||
|
wol_fn: Callable[[str, str, int], None] = send_wol,
|
||||||
|
backoff_steps: tuple[float, ...] = (2.0, 5.0, 15.0, 30.0),
|
||||||
|
wake_poll_interval: float = 1.0,
|
||||||
|
wake_timeout: float = 45.0,
|
||||||
|
ui_lock_timeout: float = 25.0,
|
||||||
|
) -> None:
|
||||||
|
self._config = config
|
||||||
|
self._connect_fn = connect_fn
|
||||||
|
self._capture_client = capture_client
|
||||||
|
self._wol_fn = wol_fn
|
||||||
|
self._backoff_steps = backoff_steps
|
||||||
|
self._wake_poll_interval = wake_poll_interval
|
||||||
|
self._wake_timeout = wake_timeout
|
||||||
|
self._ui_lock_timeout = ui_lock_timeout
|
||||||
|
|
||||||
|
self.state = ConnectionState.CONNECTING
|
||||||
|
self._tv_state = TvState()
|
||||||
|
self._ui_lock = asyncio.Lock()
|
||||||
|
self._client_key: str | None = None
|
||||||
|
|
||||||
|
self._ssap: SsapClient | None = None
|
||||||
|
self._pointer: PointerClient | None = None
|
||||||
|
self._loop_task: asyncio.Task[None] | None = None
|
||||||
|
self._wake_task: asyncio.Task[TvStatus] | None = None
|
||||||
|
self._stopping = False
|
||||||
|
|
||||||
|
self._wake_or_reload_event = asyncio.Event()
|
||||||
|
self._disconnected_event = asyncio.Event()
|
||||||
|
self._connected_event = asyncio.Event()
|
||||||
|
self._wake_done_event = asyncio.Event()
|
||||||
|
self._disconnect_code = ErrorCode.TV_OFFLINE_STANDBY
|
||||||
|
self._wake_requested = False
|
||||||
|
self._reload_requested = False
|
||||||
|
self._wake_failure: TvError | None = None
|
||||||
|
|
||||||
|
async def start(self) -> None:
|
||||||
|
"""Start the background connection state machine loop."""
|
||||||
|
if self._loop_task is None or self._loop_task.done():
|
||||||
|
self._stopping = False
|
||||||
|
self._loop_task = asyncio.create_task(self._connection_loop())
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
"""Stop the connection loop and close all underlying transports."""
|
||||||
|
self._stopping = True
|
||||||
|
self._wake_or_reload_event.set()
|
||||||
|
self._disconnected_event.set()
|
||||||
|
|
||||||
|
if self._wake_task is not None and not self._wake_task.done():
|
||||||
|
self._wake_task.cancel()
|
||||||
|
with suppress(asyncio.CancelledError):
|
||||||
|
await self._wake_task
|
||||||
|
|
||||||
|
if self._loop_task is not None and not self._loop_task.done():
|
||||||
|
self._loop_task.cancel()
|
||||||
|
with suppress(asyncio.CancelledError):
|
||||||
|
await self._loop_task
|
||||||
|
self._loop_task = None
|
||||||
|
|
||||||
|
await self._teardown_transports(close_capture=True)
|
||||||
|
|
||||||
|
def reload_client_key(self) -> None:
|
||||||
|
"""Reload the saved client key from disk (e.g. on SIGHUP)."""
|
||||||
|
loaded = self._try_load_client_key()
|
||||||
|
if loaded is not None:
|
||||||
|
self._client_key = loaded
|
||||||
|
self._reload_requested = True
|
||||||
|
if self.state is ConnectionState.PAIRING_REQUIRED:
|
||||||
|
self._wake_or_reload_event.set()
|
||||||
|
|
||||||
|
async def wake(self) -> TvStatus:
|
||||||
|
"""Send a Wake-on-LAN packet and wait for the TV to register."""
|
||||||
|
if self.state is ConnectionState.CONNECTED:
|
||||||
|
return TvStatus(status="already_connected", elapsed_ms=0)
|
||||||
|
if self.state is ConnectionState.PAIRING_REQUIRED:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.PAIRING_REQUIRED,
|
||||||
|
"TV requires pairing before wake; run pair CLI first",
|
||||||
|
)
|
||||||
|
|
||||||
|
if self._wake_task is None or self._wake_task.done():
|
||||||
|
self._wake_task = asyncio.create_task(self._run_wake())
|
||||||
|
return await asyncio.shield(self._wake_task)
|
||||||
|
|
||||||
|
def get_state(self) -> TvStateSnapshot:
|
||||||
|
"""Return a lock-free snapshot of the cached TV state."""
|
||||||
|
connected = self.state is ConnectionState.CONNECTED
|
||||||
|
return TvStateSnapshot(
|
||||||
|
connected=connected,
|
||||||
|
stale=not connected,
|
||||||
|
volume=self._tv_state.volume,
|
||||||
|
muted=self._tv_state.muted,
|
||||||
|
sound_output=self._tv_state.sound_output,
|
||||||
|
foreground_app=self._tv_state.foreground_app,
|
||||||
|
last_updated=self._tv_state.last_updated,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def _run_wake(self) -> TvStatus:
|
||||||
|
mac = require_mac(self._config)
|
||||||
|
start = time.monotonic()
|
||||||
|
self._wol_fn(mac, self._config.wol_broadcast, 9)
|
||||||
|
|
||||||
|
self._wake_failure = None
|
||||||
|
self._connected_event.clear()
|
||||||
|
self._wake_done_event.clear()
|
||||||
|
self._wake_requested = True
|
||||||
|
self._wake_or_reload_event.set()
|
||||||
|
|
||||||
|
if self.state is ConnectionState.CONNECTED:
|
||||||
|
self._wake_requested = False
|
||||||
|
return TvStatus(status="already_connected", elapsed_ms=0)
|
||||||
|
|
||||||
|
wait_connected = asyncio.create_task(self._connected_event.wait())
|
||||||
|
wait_failed = asyncio.create_task(self._wake_done_event.wait())
|
||||||
|
try:
|
||||||
|
async with asyncio.timeout(self._wake_timeout):
|
||||||
|
done, _ = await asyncio.wait(
|
||||||
|
{wait_connected, wait_failed},
|
||||||
|
return_when=asyncio.FIRST_COMPLETED,
|
||||||
|
)
|
||||||
|
if wait_failed in done and self._wake_failure is not None:
|
||||||
|
raise self._wake_failure
|
||||||
|
except TimeoutError as exc:
|
||||||
|
if self.state is ConnectionState.WAKING:
|
||||||
|
self.state = ConnectionState.STANDBY_OFFLINE
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.WAKE_TIMEOUT,
|
||||||
|
f"TV did not become ready within {self._wake_timeout:.0f}s",
|
||||||
|
) from exc
|
||||||
|
finally:
|
||||||
|
self._wake_requested = False
|
||||||
|
for task in (wait_connected, wait_failed):
|
||||||
|
if not task.done():
|
||||||
|
task.cancel()
|
||||||
|
with suppress(asyncio.CancelledError):
|
||||||
|
await task
|
||||||
|
|
||||||
|
elapsed_ms = int((time.monotonic() - start) * 1000)
|
||||||
|
return TvStatus(status="connected", elapsed_ms=elapsed_ms)
|
||||||
|
|
||||||
|
async def _connection_loop(self) -> None:
|
||||||
|
backoff_idx = 0
|
||||||
|
while not self._stopping:
|
||||||
|
if self._wake_requested:
|
||||||
|
self.state = ConnectionState.WAKING
|
||||||
|
elif self.state not in (ConnectionState.CONNECTING, ConnectionState.WAKING):
|
||||||
|
self.state = ConnectionState.CONNECTING
|
||||||
|
|
||||||
|
try:
|
||||||
|
await self._connect_and_subscribe()
|
||||||
|
except TvError as exc:
|
||||||
|
await self._teardown_transports(
|
||||||
|
close_capture=exc.code is not ErrorCode.PAIRING_REQUIRED
|
||||||
|
)
|
||||||
|
if exc.code is ErrorCode.PAIRING_REQUIRED:
|
||||||
|
self.state = ConnectionState.PAIRING_REQUIRED
|
||||||
|
self._wake_requested = False
|
||||||
|
self._wake_failure = exc
|
||||||
|
self._wake_done_event.set()
|
||||||
|
backoff_idx = await self._wait_backoff(backoff_idx)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if self._wake_requested:
|
||||||
|
self.state = ConnectionState.WAKING
|
||||||
|
await asyncio.sleep(self._wake_poll_interval)
|
||||||
|
continue
|
||||||
|
|
||||||
|
self.state = ConnectionState.STANDBY_OFFLINE
|
||||||
|
backoff_idx = await self._wait_backoff(backoff_idx)
|
||||||
|
continue
|
||||||
|
|
||||||
|
backoff_idx = 0
|
||||||
|
self.state = ConnectionState.CONNECTED
|
||||||
|
self._disconnected_event.clear()
|
||||||
|
self._connected_event.set()
|
||||||
|
|
||||||
|
await self._disconnected_event.wait()
|
||||||
|
if self._stopping:
|
||||||
|
break
|
||||||
|
|
||||||
|
is_pairing = self._disconnect_code is ErrorCode.PAIRING_REQUIRED
|
||||||
|
await self._teardown_transports(close_capture=not is_pairing)
|
||||||
|
if is_pairing:
|
||||||
|
self._wake_requested = False
|
||||||
|
self.state = (
|
||||||
|
ConnectionState.PAIRING_REQUIRED if is_pairing else ConnectionState.STANDBY_OFFLINE
|
||||||
|
)
|
||||||
|
backoff_idx = await self._wait_backoff(backoff_idx)
|
||||||
|
|
||||||
|
async def _wait_backoff(self, backoff_idx: int) -> int:
|
||||||
|
current_idx = backoff_idx
|
||||||
|
while not self._stopping:
|
||||||
|
if self._wake_requested:
|
||||||
|
return 0
|
||||||
|
if self.state is ConnectionState.PAIRING_REQUIRED and self._reload_requested:
|
||||||
|
self._reload_requested = False
|
||||||
|
return current_idx
|
||||||
|
|
||||||
|
delay = self._backoff_steps[min(current_idx, len(self._backoff_steps) - 1)]
|
||||||
|
next_idx = min(current_idx + 1, len(self._backoff_steps) - 1)
|
||||||
|
self._wake_or_reload_event.clear()
|
||||||
|
|
||||||
|
# Re-check after clearing the event so concurrent wake/reload signals are not lost.
|
||||||
|
if self._wake_requested:
|
||||||
|
return 0
|
||||||
|
if self.state is ConnectionState.PAIRING_REQUIRED and self._reload_requested:
|
||||||
|
self._reload_requested = False
|
||||||
|
return current_idx
|
||||||
|
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(self._wake_or_reload_event.wait(), timeout=delay)
|
||||||
|
except TimeoutError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if self.state is ConnectionState.PAIRING_REQUIRED and not self._wake_requested:
|
||||||
|
self._reload_requested = False
|
||||||
|
reloaded = self._try_load_client_key()
|
||||||
|
if reloaded is not None:
|
||||||
|
self._client_key = reloaded
|
||||||
|
return next_idx
|
||||||
|
current_idx = next_idx
|
||||||
|
continue
|
||||||
|
return next_idx
|
||||||
|
return current_idx
|
||||||
|
|
||||||
|
async def _connect_and_subscribe(self) -> None:
|
||||||
|
if self._client_key is None:
|
||||||
|
self._client_key = self._try_load_client_key()
|
||||||
|
|
||||||
|
ssap = SsapClient(
|
||||||
|
f"wss://{self._config.tv_ip}:3001",
|
||||||
|
connect_fn=self._connect_fn,
|
||||||
|
on_disconnect=self._on_ssap_disconnect,
|
||||||
|
)
|
||||||
|
self._ssap = ssap
|
||||||
|
resolved_key = await ssap.connect_and_register(self._client_key)
|
||||||
|
if resolved_key:
|
||||||
|
self._client_key = resolved_key
|
||||||
|
|
||||||
|
await ssap.subscribe("ssap://audio/getStatus", self._handle_audio_status)
|
||||||
|
await ssap.subscribe(
|
||||||
|
"ssap://com.webos.applicationManager/getForegroundAppInfo",
|
||||||
|
self._handle_foreground_app,
|
||||||
|
)
|
||||||
|
self._pointer = PointerClient(ssap.request, connect_fn=self._connect_fn)
|
||||||
|
|
||||||
|
async def _teardown_transports(self, *, close_capture: bool) -> None:
|
||||||
|
pointer = self._pointer
|
||||||
|
self._pointer = None
|
||||||
|
if pointer is not None:
|
||||||
|
await pointer.close()
|
||||||
|
|
||||||
|
ssap = self._ssap
|
||||||
|
self._ssap = None
|
||||||
|
if ssap is not None:
|
||||||
|
await ssap.close()
|
||||||
|
|
||||||
|
if close_capture and self._capture_client is not None:
|
||||||
|
with suppress(Exception):
|
||||||
|
await self._capture_client.close()
|
||||||
|
|
||||||
|
def _on_ssap_disconnect(self, code: ErrorCode) -> None:
|
||||||
|
self._disconnect_code = code
|
||||||
|
self._disconnected_event.set()
|
||||||
|
|
||||||
|
def _try_load_client_key(self) -> str | None:
|
||||||
|
key_path = self._config.client_key_path
|
||||||
|
if not key_path.is_file():
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
raw: Any = json.loads(key_path.read_text(encoding="utf-8"))
|
||||||
|
except (OSError, json.JSONDecodeError) as exc:
|
||||||
|
logger.warning("Failed to read client key file %s: %s", key_path, exc)
|
||||||
|
return None
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
logger.warning("Client key file %s does not contain a JSON object", key_path)
|
||||||
|
return None
|
||||||
|
mapping = cast(dict[str, Any], raw)
|
||||||
|
val = mapping.get(self._config.tv_ip)
|
||||||
|
if isinstance(val, str) and val.strip():
|
||||||
|
return val.strip()
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _handle_audio_status(self, payload: dict[str, Any]) -> None:
|
||||||
|
volume = payload.get("volume")
|
||||||
|
if isinstance(volume, int) and not isinstance(volume, bool):
|
||||||
|
self._tv_state.volume = volume
|
||||||
|
|
||||||
|
mute = payload.get("mute")
|
||||||
|
if isinstance(mute, bool):
|
||||||
|
self._tv_state.muted = mute
|
||||||
|
|
||||||
|
volume_status = payload.get("volumeStatus")
|
||||||
|
if isinstance(volume_status, dict):
|
||||||
|
vs_dict = cast(dict[str, Any], volume_status)
|
||||||
|
sound_output = vs_dict.get("soundOutput")
|
||||||
|
if isinstance(sound_output, str):
|
||||||
|
self._tv_state.sound_output = sound_output
|
||||||
|
elif isinstance(payload.get("soundOutput"), str):
|
||||||
|
self._tv_state.sound_output = str(payload["soundOutput"])
|
||||||
|
|
||||||
|
self._tv_state.last_updated = time.time()
|
||||||
|
|
||||||
|
def _handle_foreground_app(self, payload: dict[str, Any]) -> None:
|
||||||
|
app_id = payload.get("appId")
|
||||||
|
if isinstance(app_id, str):
|
||||||
|
self._tv_state.foreground_app = app_id
|
||||||
|
self._tv_state.last_updated = time.time()
|
||||||
|
|
||||||
|
def _require_ssap(self) -> SsapClient:
|
||||||
|
if self.state is ConnectionState.PAIRING_REQUIRED:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.PAIRING_REQUIRED,
|
||||||
|
"TV requires pairing; run pair CLI and reload client key",
|
||||||
|
)
|
||||||
|
if self.state is not ConnectionState.CONNECTED or self._ssap is None:
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, "TV is offline or in standby")
|
||||||
|
return self._ssap
|
||||||
|
|
||||||
|
def _require_pointer(self) -> PointerClient:
|
||||||
|
self._require_ssap()
|
||||||
|
if self._pointer is None:
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, "Pointer client is not connected")
|
||||||
|
return self._pointer
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def _acquire_ui_lock(self) -> AsyncGenerator[None]:
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(self._ui_lock.acquire(), timeout=self._ui_lock_timeout)
|
||||||
|
except TimeoutError as exc:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.LOCK_TIMEOUT,
|
||||||
|
f"Timed out waiting {self._ui_lock_timeout:.0f}s for UI lock",
|
||||||
|
) from exc
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
self._ui_lock.release()
|
||||||
|
|
||||||
|
async def _capture_optional(self, ssap: SsapClient) -> tuple[CaptureResult | None, str | None]:
|
||||||
|
if self._capture_client is None:
|
||||||
|
return None, "SCREENSHOT_UNAVAILABLE: Developer Mode SSH is not configured"
|
||||||
|
try:
|
||||||
|
return await self._capture_client.capture_frame(ssap.request), None
|
||||||
|
except TvError as exc:
|
||||||
|
if exc.code is ErrorCode.SCREENSHOT_UNAVAILABLE:
|
||||||
|
return None, str(exc)
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def send_keys(
|
||||||
|
self,
|
||||||
|
keys: list[str],
|
||||||
|
delay_ms: int = 250,
|
||||||
|
settle_ms: int = 800,
|
||||||
|
capture: bool = False,
|
||||||
|
) -> KeysResult:
|
||||||
|
"""Validate, serialize, and send pointer button keys with optional capture."""
|
||||||
|
if not (1 <= len(keys) <= 20):
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
f"keys must contain between 1 and 20 items, got {len(keys)}",
|
||||||
|
)
|
||||||
|
if not (0 <= delay_ms <= 500):
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
f"delay_ms must be between 0 and 500, got {delay_ms}",
|
||||||
|
)
|
||||||
|
if not (0 <= settle_ms <= 2000):
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
f"settle_ms must be between 0 and 2000, got {settle_ms}",
|
||||||
|
)
|
||||||
|
normalize_button_keys(keys)
|
||||||
|
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
pointer = self._require_pointer()
|
||||||
|
|
||||||
|
async with self._acquire_ui_lock():
|
||||||
|
count = await pointer.send_buttons(keys, delay_ms=delay_ms)
|
||||||
|
if not capture:
|
||||||
|
return KeysResult(keys_sent=True, count=count)
|
||||||
|
if settle_ms > 0:
|
||||||
|
await asyncio.sleep(settle_ms / 1000.0)
|
||||||
|
cap, cap_err = await self._capture_optional(ssap)
|
||||||
|
return KeysResult(
|
||||||
|
keys_sent=True,
|
||||||
|
count=count,
|
||||||
|
frame_sha256=cap.frame_sha256 if cap is not None else None,
|
||||||
|
changed_since_last=cap.changed_since_last if cap is not None else None,
|
||||||
|
size_bytes=cap.size_bytes if cap is not None else None,
|
||||||
|
capture_error=cap_err,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def type_text(
|
||||||
|
self,
|
||||||
|
text: str,
|
||||||
|
send_enter: bool = True,
|
||||||
|
capture: bool = False,
|
||||||
|
) -> TextResult:
|
||||||
|
"""Send IME text input with optional enter key and screenshot capture."""
|
||||||
|
if not (1 <= len(text) <= 500):
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
f"text length must be between 1 and 500 characters, got {len(text)}",
|
||||||
|
)
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
async with self._acquire_ui_lock():
|
||||||
|
await ssap.request(
|
||||||
|
"ssap://com.webos.service.ime/insertText",
|
||||||
|
{"text": text, "replace": 0},
|
||||||
|
)
|
||||||
|
if send_enter:
|
||||||
|
await ssap.request("ssap://com.webos.service.ime/sendEnterKey", {})
|
||||||
|
if not capture:
|
||||||
|
return TextResult(text_sent=True, enter_sent=send_enter)
|
||||||
|
cap, cap_err = await self._capture_optional(ssap)
|
||||||
|
return TextResult(
|
||||||
|
text_sent=True,
|
||||||
|
enter_sent=send_enter,
|
||||||
|
frame_sha256=cap.frame_sha256 if cap is not None else None,
|
||||||
|
changed_since_last=cap.changed_since_last if cap is not None else None,
|
||||||
|
size_bytes=cap.size_bytes if cap is not None else None,
|
||||||
|
capture_error=cap_err,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def screenshot(self) -> CaptureResult:
|
||||||
|
"""Acquire ui_lock and capture a screenshot via Developer Mode SFTP."""
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
async with self._acquire_ui_lock():
|
||||||
|
if self._capture_client is None:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
||||||
|
"Developer Mode SSH is not configured",
|
||||||
|
)
|
||||||
|
return await self._capture_client.capture_frame(ssap.request)
|
||||||
|
|
||||||
|
async def launch_app(
|
||||||
|
self,
|
||||||
|
app_id: str,
|
||||||
|
content_target: str | None = None,
|
||||||
|
params: dict[str, Any] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Launch an installed webOS app with optional deep-link parameters."""
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
merged_params = dict(params or {})
|
||||||
|
if content_target is not None:
|
||||||
|
merged_params["contentTarget"] = content_target
|
||||||
|
payload: dict[str, Any] = {"id": app_id}
|
||||||
|
if merged_params:
|
||||||
|
payload["params"] = merged_params
|
||||||
|
return await ssap.request("ssap://system.launcher/launch", payload)
|
||||||
|
|
||||||
|
async def list_apps(self) -> list[dict[str, str]]:
|
||||||
|
"""Return installed launch points as [{id, title}]."""
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
resp = await ssap.request("ssap://com.webos.applicationManager/listLaunchPoints", {})
|
||||||
|
raw_points = resp.get("launchPoints", [])
|
||||||
|
if not isinstance(raw_points, list):
|
||||||
|
return []
|
||||||
|
apps: list[dict[str, str]] = []
|
||||||
|
for item_raw in cast(list[Any], raw_points):
|
||||||
|
if isinstance(item_raw, dict):
|
||||||
|
item = cast(dict[str, Any], item_raw)
|
||||||
|
apps.append({"id": str(item.get("id", "")), "title": str(item.get("title", ""))})
|
||||||
|
return apps
|
||||||
|
|
||||||
|
async def set_volume(self, level: int) -> dict[str, Any]:
|
||||||
|
"""Set TV volume within [0, config.max_volume]."""
|
||||||
|
if level < 0 or level > self._config.max_volume:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
f"Volume {level} must be between 0 and {self._config.max_volume}",
|
||||||
|
)
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
return await ssap.request("ssap://audio/setVolume", {"volume": level})
|
||||||
|
|
||||||
|
async def set_mute(self, muted: bool) -> dict[str, Any]:
|
||||||
|
"""Set TV mute state."""
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
return await ssap.request("ssap://audio/setMute", {"mute": muted})
|
||||||
|
|
||||||
|
async def list_inputs(self) -> list[dict[str, Any]]:
|
||||||
|
"""Return external inputs as [{id, label, connected}]."""
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
resp = await ssap.request("ssap://tv/getExternalInputList", {})
|
||||||
|
raw_devices = resp.get("devices", [])
|
||||||
|
if not isinstance(raw_devices, list):
|
||||||
|
return []
|
||||||
|
inputs: list[dict[str, Any]] = []
|
||||||
|
for item_raw in cast(list[Any], raw_devices):
|
||||||
|
if isinstance(item_raw, dict):
|
||||||
|
item = cast(dict[str, Any], item_raw)
|
||||||
|
inputs.append(
|
||||||
|
{
|
||||||
|
"id": str(item.get("id", "")),
|
||||||
|
"label": str(item.get("label", "")),
|
||||||
|
"connected": bool(item.get("connected", False)),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return inputs
|
||||||
|
|
||||||
|
async def switch_input(self, input_id: str) -> dict[str, Any]:
|
||||||
|
"""Switch active external input."""
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
return await ssap.request("ssap://tv/switchInput", {"inputId": input_id})
|
||||||
|
|
||||||
|
async def turn_off(self) -> dict[str, Any]:
|
||||||
|
"""Power off the TV into standby."""
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
return await ssap.request("ssap://system/turnOff", {})
|
||||||
|
|
||||||
|
async def raw_ssap(self, uri: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||||
|
"""Forward a raw SSAP request when enabled by configuration."""
|
||||||
|
if not self._config.enable_raw_ssap:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
"raw_ssap is disabled (ENABLE_RAW_SSAP=false)",
|
||||||
|
)
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
return await ssap.request(uri, payload)
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
"""Pointer input WebSocket client for LG webOS D-pad and remote buttons."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from collections.abc import Awaitable, Callable
|
||||||
|
from contextlib import suppress
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import (
|
||||||
|
WebSocketClosedError,
|
||||||
|
WebSocketConnectFn,
|
||||||
|
WebSocketTransport,
|
||||||
|
)
|
||||||
|
from lg_smtv_mcp.tv_core.ssap import websockets_connect
|
||||||
|
|
||||||
|
BUTTON_ALLOWLIST: frozenset[str] = frozenset(
|
||||||
|
{
|
||||||
|
"UP",
|
||||||
|
"DOWN",
|
||||||
|
"LEFT",
|
||||||
|
"RIGHT",
|
||||||
|
"ENTER",
|
||||||
|
"BACK",
|
||||||
|
"HOME",
|
||||||
|
"EXIT",
|
||||||
|
"PLAY",
|
||||||
|
"PAUSE",
|
||||||
|
"STOP",
|
||||||
|
"REWIND",
|
||||||
|
"FASTFORWARD",
|
||||||
|
"RED",
|
||||||
|
"GREEN",
|
||||||
|
"YELLOW",
|
||||||
|
"BLUE",
|
||||||
|
"VOLUMEUP",
|
||||||
|
"VOLUMEDOWN",
|
||||||
|
"MUTE",
|
||||||
|
"CHANNELUP",
|
||||||
|
"CHANNELDOWN",
|
||||||
|
"INFO",
|
||||||
|
"GUIDE",
|
||||||
|
"MENU",
|
||||||
|
"CC",
|
||||||
|
"0",
|
||||||
|
"1",
|
||||||
|
"2",
|
||||||
|
"3",
|
||||||
|
"4",
|
||||||
|
"5",
|
||||||
|
"6",
|
||||||
|
"7",
|
||||||
|
"8",
|
||||||
|
"9",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_button_keys(keys: list[str]) -> list[str]:
|
||||||
|
"""Validate and normalize a sequence of webOS button names."""
|
||||||
|
normalized: list[str] = []
|
||||||
|
for raw_key in keys:
|
||||||
|
if "\r" in raw_key or "\n" in raw_key:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
f"Button name must not contain newline characters: {raw_key!r}",
|
||||||
|
)
|
||||||
|
candidate = raw_key.strip().upper()
|
||||||
|
if candidate not in BUTTON_ALLOWLIST:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
f"Unsupported webOS button name: {raw_key!r}",
|
||||||
|
)
|
||||||
|
normalized.append(candidate)
|
||||||
|
return normalized
|
||||||
|
|
||||||
|
|
||||||
|
class PointerClient:
|
||||||
|
"""Manages the persistent webOS pointer input socket and button frame formatting."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
ssap_request_fn: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]],
|
||||||
|
connect_fn: WebSocketConnectFn = websockets_connect,
|
||||||
|
) -> None:
|
||||||
|
self._ssap_request_fn = ssap_request_fn
|
||||||
|
self._connect_fn = connect_fn
|
||||||
|
self._ws: WebSocketTransport | None = None
|
||||||
|
|
||||||
|
async def _ensure_socket(self) -> WebSocketTransport:
|
||||||
|
if self._ws is not None:
|
||||||
|
return self._ws
|
||||||
|
resp = await self._ssap_request_fn(
|
||||||
|
"ssap://com.webos.service.networkinput/getPointerInputSocket",
|
||||||
|
{},
|
||||||
|
)
|
||||||
|
socket_path = resp.get("socketPath")
|
||||||
|
if not isinstance(socket_path, str) or not socket_path:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.COMMAND_FAILED,
|
||||||
|
"getPointerInputSocket did not return a valid socketPath",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
self._ws = await self._connect_fn(socket_path)
|
||||||
|
except (TimeoutError, OSError, WebSocketClosedError) as exc:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.TV_OFFLINE_STANDBY,
|
||||||
|
f"Failed to connect pointer input socket: {exc}",
|
||||||
|
) from exc
|
||||||
|
return self._ws
|
||||||
|
|
||||||
|
async def send_buttons(self, keys: list[str], delay_ms: int = 250) -> int:
|
||||||
|
"""Validate, normalize, and send a sequence of button frames."""
|
||||||
|
normalized = normalize_button_keys(keys)
|
||||||
|
for index, key in enumerate(normalized):
|
||||||
|
frame = f"type:button\nname:{key}\n\n"
|
||||||
|
await self._send_frame_with_retry(frame)
|
||||||
|
if delay_ms > 0 and index < len(normalized) - 1:
|
||||||
|
await asyncio.sleep(delay_ms / 1000.0)
|
||||||
|
return len(normalized)
|
||||||
|
|
||||||
|
async def _send_frame_with_retry(self, frame: str) -> None:
|
||||||
|
ws = await self._ensure_socket()
|
||||||
|
try:
|
||||||
|
await ws.send(frame)
|
||||||
|
return
|
||||||
|
except WebSocketClosedError, OSError:
|
||||||
|
await self.close()
|
||||||
|
|
||||||
|
ws = await self._ensure_socket()
|
||||||
|
try:
|
||||||
|
await ws.send(frame)
|
||||||
|
except (WebSocketClosedError, OSError) as exc:
|
||||||
|
await self.close()
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.TV_OFFLINE_STANDBY,
|
||||||
|
f"Pointer input socket failed after retry: {exc}",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
"""Close the pointer WebSocket transport if open."""
|
||||||
|
ws = self._ws
|
||||||
|
self._ws = None
|
||||||
|
if ws is not None:
|
||||||
|
with suppress(Exception):
|
||||||
|
await ws.close()
|
||||||
@@ -8,11 +8,11 @@ from typing import Any, Literal, Protocol
|
|||||||
class WebSocketClosedError(Exception):
|
class WebSocketClosedError(Exception):
|
||||||
"""Raised when a WebSocket transport closes unexpectedly or is already closed."""
|
"""Raised when a WebSocket transport closes unexpectedly or is already closed."""
|
||||||
|
|
||||||
code: int
|
|
||||||
reason: str
|
|
||||||
|
|
||||||
def __init__(self, code: int, reason: str = "") -> None:
|
def __init__(self, code: int, reason: str = "") -> None:
|
||||||
raise NotImplementedError
|
message = f"WebSocket closed ({code}): {reason}" if reason else f"WebSocket closed ({code})"
|
||||||
|
super().__init__(message)
|
||||||
|
self.code = code
|
||||||
|
self.reason = reason
|
||||||
|
|
||||||
|
|
||||||
class WebSocketTransport(Protocol):
|
class WebSocketTransport(Protocol):
|
||||||
@@ -61,9 +61,6 @@ class TvStatus:
|
|||||||
status: Literal["connected", "already_connected"]
|
status: Literal["connected", "already_connected"]
|
||||||
elapsed_ms: int
|
elapsed_ms: int
|
||||||
|
|
||||||
def __post_init__(self) -> None:
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
class TvStateSnapshot:
|
class TvStateSnapshot:
|
||||||
@@ -77,9 +74,6 @@ class TvStateSnapshot:
|
|||||||
foreground_app: str | None
|
foreground_app: str | None
|
||||||
last_updated: float | None
|
last_updated: float | None
|
||||||
|
|
||||||
def __post_init__(self) -> None:
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
class CaptureResult:
|
class CaptureResult:
|
||||||
@@ -90,9 +84,6 @@ class CaptureResult:
|
|||||||
changed_since_last: bool
|
changed_since_last: bool
|
||||||
size_bytes: int
|
size_bytes: int
|
||||||
|
|
||||||
def __post_init__(self) -> None:
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
class KeysResult:
|
class KeysResult:
|
||||||
@@ -105,9 +96,6 @@ class KeysResult:
|
|||||||
size_bytes: int | None = None
|
size_bytes: int | None = None
|
||||||
capture_error: str | None = None
|
capture_error: str | None = None
|
||||||
|
|
||||||
def __post_init__(self) -> None:
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
class TextResult:
|
class TextResult:
|
||||||
@@ -119,6 +107,3 @@ class TextResult:
|
|||||||
changed_since_last: bool | None = None
|
changed_since_last: bool | None = None
|
||||||
size_bytes: int | None = None
|
size_bytes: int | None = None
|
||||||
capture_error: str | None = None
|
capture_error: str | None = None
|
||||||
|
|
||||||
def __post_init__(self) -> None:
|
|
||||||
raise NotImplementedError
|
|
||||||
@@ -0,0 +1,369 @@
|
|||||||
|
"""SSAP WebSocket client and msg['id'] frame multiplexer."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import inspect
|
||||||
|
import json
|
||||||
|
import ssl
|
||||||
|
from collections.abc import Awaitable, Callable
|
||||||
|
from contextlib import suppress
|
||||||
|
from typing import Any, cast
|
||||||
|
|
||||||
|
import websockets
|
||||||
|
from websockets.asyncio.client import ClientConnection
|
||||||
|
from websockets.exceptions import ConnectionClosed
|
||||||
|
|
||||||
|
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import (
|
||||||
|
WebSocketClosedError,
|
||||||
|
WebSocketConnectFn,
|
||||||
|
WebSocketTransport,
|
||||||
|
)
|
||||||
|
|
||||||
|
PERMISSIONS: tuple[str, ...] = (
|
||||||
|
"LAUNCH",
|
||||||
|
"CONTROL_AUDIO",
|
||||||
|
"CONTROL_DISPLAY",
|
||||||
|
"CONTROL_POWER",
|
||||||
|
"CONTROL_INPUT_TEXT",
|
||||||
|
"CONTROL_INPUT_MEDIA_PLAYBACK",
|
||||||
|
"CONTROL_INPUT_JOYSTICK",
|
||||||
|
"CONTROL_INPUT_TV",
|
||||||
|
"CONTROL_TV_MEDIA",
|
||||||
|
"CONTROL_MOUSE_AND_KEYBOARD",
|
||||||
|
"READ_INSTALLED_APPS",
|
||||||
|
"READ_RUNNING_APPS",
|
||||||
|
"READ_INPUT_DEVICE_LIST",
|
||||||
|
"READ_TV_CHANNEL_LIST",
|
||||||
|
"READ_POWER_STATE",
|
||||||
|
"WRITE_NOTIFICATION_TOAST",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_ssl_context() -> ssl.SSLContext:
|
||||||
|
"""Create an SSL context accepting the TV's self-signed WSS certificate."""
|
||||||
|
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||||
|
ctx.check_hostname = False
|
||||||
|
ctx.verify_mode = ssl.CERT_NONE
|
||||||
|
return ctx
|
||||||
|
|
||||||
|
|
||||||
|
def build_register_payload(
|
||||||
|
client_key: str | None,
|
||||||
|
*,
|
||||||
|
force_pairing: bool = False,
|
||||||
|
msg_id: str = "register_0",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Build the SSAP register handshake payload with all required permissions."""
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
"forcePairing": force_pairing,
|
||||||
|
"pairingType": "PROMPT",
|
||||||
|
"manifest": {
|
||||||
|
"manifestVersion": 1,
|
||||||
|
"appVersion": "0.1.0",
|
||||||
|
"permissions": list(PERMISSIONS),
|
||||||
|
"localizedAppNames": {"": "lg-smtv-mcp"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if client_key and not force_pairing:
|
||||||
|
payload["client-key"] = client_key
|
||||||
|
return {"type": "register", "id": msg_id, "payload": payload}
|
||||||
|
|
||||||
|
|
||||||
|
def _to_closed_error(exc: ConnectionClosed) -> WebSocketClosedError:
|
||||||
|
if exc.rcvd is not None:
|
||||||
|
return WebSocketClosedError(exc.rcvd.code, exc.rcvd.reason)
|
||||||
|
return WebSocketClosedError(1006, str(exc))
|
||||||
|
|
||||||
|
|
||||||
|
class _WebsocketsAdapter:
|
||||||
|
"""Adapt websockets.asyncio.client.ClientConnection to WebSocketTransport."""
|
||||||
|
|
||||||
|
def __init__(self, conn: ClientConnection) -> None:
|
||||||
|
self._conn = conn
|
||||||
|
|
||||||
|
async def send(self, data: str) -> None:
|
||||||
|
try:
|
||||||
|
await self._conn.send(data)
|
||||||
|
except ConnectionClosed as exc:
|
||||||
|
raise _to_closed_error(exc) from exc
|
||||||
|
|
||||||
|
async def recv(self) -> str:
|
||||||
|
try:
|
||||||
|
frame = await self._conn.recv()
|
||||||
|
except ConnectionClosed as exc:
|
||||||
|
raise _to_closed_error(exc) from exc
|
||||||
|
if isinstance(frame, bytes):
|
||||||
|
return frame.decode("utf-8", errors="replace")
|
||||||
|
return frame
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
await self._conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def websockets_connect(url: str) -> WebSocketTransport:
|
||||||
|
"""Connect to an LG webOS SSAP or pointer WebSocket endpoint."""
|
||||||
|
ssl_ctx = build_ssl_context() if url.startswith("wss://") else None
|
||||||
|
conn = await websockets.connect(
|
||||||
|
url,
|
||||||
|
ssl=ssl_ctx,
|
||||||
|
open_timeout=3.5,
|
||||||
|
ping_interval=10,
|
||||||
|
ping_timeout=5,
|
||||||
|
)
|
||||||
|
return _WebsocketsAdapter(conn)
|
||||||
|
|
||||||
|
|
||||||
|
def _is_permission_error(text: str) -> bool:
|
||||||
|
lowered = text.lower()
|
||||||
|
return "401" in lowered or "insufficient permissions" in lowered
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_error_text(msg: dict[str, Any]) -> str:
|
||||||
|
payload = msg.get("payload")
|
||||||
|
if isinstance(payload, dict):
|
||||||
|
payload_dict = cast(dict[str, Any], payload)
|
||||||
|
err_text = payload_dict.get("errorText") or payload_dict.get("errorCode")
|
||||||
|
if err_text:
|
||||||
|
return str(err_text)
|
||||||
|
if msg.get("error"):
|
||||||
|
return str(msg["error"])
|
||||||
|
return "SSAP request failed"
|
||||||
|
|
||||||
|
|
||||||
|
class SsapClient:
|
||||||
|
"""Persistent SSAP WebSocket client with msg['id'] request/subscribe demultiplexing."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
url: str,
|
||||||
|
connect_fn: WebSocketConnectFn = websockets_connect,
|
||||||
|
*,
|
||||||
|
on_disconnect: Callable[[ErrorCode], None] | None = None,
|
||||||
|
) -> None:
|
||||||
|
self._url = url
|
||||||
|
self._connect_fn = connect_fn
|
||||||
|
self._on_disconnect = on_disconnect
|
||||||
|
self._ws: WebSocketTransport | None = None
|
||||||
|
self._reader_task: asyncio.Task[None] | None = None
|
||||||
|
self._pending: dict[str, asyncio.Future[dict[str, Any]]] = {}
|
||||||
|
self._subscriptions: dict[str, Callable[[dict[str, Any]], Awaitable[None] | None]] = {}
|
||||||
|
self._next_id = 1
|
||||||
|
self._closing = False
|
||||||
|
|
||||||
|
async def connect_and_register(self, client_key: str | None) -> str:
|
||||||
|
"""Connect, perform SSAP register handshake, and start the reader loop."""
|
||||||
|
await self.close()
|
||||||
|
self._closing = False
|
||||||
|
|
||||||
|
try:
|
||||||
|
ws = await self._connect_fn(self._url)
|
||||||
|
except (TimeoutError, OSError, WebSocketClosedError) as exc:
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, f"Failed to connect to TV: {exc}") from exc
|
||||||
|
|
||||||
|
self._ws = ws
|
||||||
|
try:
|
||||||
|
await ws.send(json.dumps(build_register_payload(client_key)))
|
||||||
|
while True:
|
||||||
|
raw = await ws.recv()
|
||||||
|
msg_raw: Any = json.loads(raw)
|
||||||
|
if not isinstance(msg_raw, dict):
|
||||||
|
continue
|
||||||
|
msg = cast(dict[str, Any], msg_raw)
|
||||||
|
msg_type = msg.get("type")
|
||||||
|
payload_raw = msg.get("payload")
|
||||||
|
payload = cast(dict[str, Any], payload_raw) if isinstance(payload_raw, dict) else {}
|
||||||
|
|
||||||
|
if msg_type == "registered":
|
||||||
|
resolved_key = str(payload.get("client-key") or client_key or "")
|
||||||
|
self._reader_task = asyncio.create_task(self._reader_loop())
|
||||||
|
return resolved_key
|
||||||
|
|
||||||
|
if msg_type == "response" and payload.get("pairingType") == "PROMPT":
|
||||||
|
await self._safe_close_ws(ws)
|
||||||
|
self._ws = None
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.PAIRING_REQUIRED,
|
||||||
|
"TV requested interactive pairing prompt",
|
||||||
|
)
|
||||||
|
|
||||||
|
if msg_type == "error":
|
||||||
|
await self._safe_close_ws(ws)
|
||||||
|
self._ws = None
|
||||||
|
err_text = _extract_error_text(msg)
|
||||||
|
code = (
|
||||||
|
ErrorCode.PAIRING_REQUIRED
|
||||||
|
if _is_permission_error(err_text) or "pairing" in err_text.lower()
|
||||||
|
else ErrorCode.COMMAND_FAILED
|
||||||
|
)
|
||||||
|
raise TvError(code, err_text)
|
||||||
|
except TvError:
|
||||||
|
raise
|
||||||
|
except (TimeoutError, OSError, WebSocketClosedError, json.JSONDecodeError) as exc:
|
||||||
|
await self._safe_close_ws(ws)
|
||||||
|
self._ws = None
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.TV_OFFLINE_STANDBY,
|
||||||
|
f"SSAP handshake interrupted: {exc}",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
async def request(self, uri: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||||
|
"""Send a one-shot SSAP request and await its matched response payload."""
|
||||||
|
ws = self._ws
|
||||||
|
if ws is None:
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, "SSAP socket is not connected")
|
||||||
|
|
||||||
|
msg_id = f"req_{self._next_id}"
|
||||||
|
self._next_id += 1
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
fut: asyncio.Future[dict[str, Any]] = loop.create_future()
|
||||||
|
self._pending[msg_id] = fut
|
||||||
|
|
||||||
|
frame = json.dumps(
|
||||||
|
{
|
||||||
|
"type": "request",
|
||||||
|
"id": msg_id,
|
||||||
|
"uri": uri,
|
||||||
|
"payload": payload or {},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
await ws.send(frame)
|
||||||
|
except (WebSocketClosedError, OSError) as exc:
|
||||||
|
self._pending.pop(msg_id, None)
|
||||||
|
if not fut.done():
|
||||||
|
fut.cancel()
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, f"SSAP send failed: {exc}") from exc
|
||||||
|
|
||||||
|
msg = await fut
|
||||||
|
return self._unwrap_response(msg)
|
||||||
|
|
||||||
|
async def subscribe(
|
||||||
|
self,
|
||||||
|
uri: str,
|
||||||
|
callback: Callable[[dict[str, Any]], Awaitable[None] | None],
|
||||||
|
) -> None:
|
||||||
|
"""Subscribe to an SSAP endpoint and route push updates to callback."""
|
||||||
|
ws = self._ws
|
||||||
|
if ws is None:
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, "SSAP socket is not connected")
|
||||||
|
|
||||||
|
msg_id = f"sub_{self._next_id}"
|
||||||
|
self._next_id += 1
|
||||||
|
self._subscriptions[msg_id] = callback
|
||||||
|
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
fut: asyncio.Future[dict[str, Any]] = loop.create_future()
|
||||||
|
self._pending[msg_id] = fut
|
||||||
|
|
||||||
|
frame = json.dumps({"type": "subscribe", "id": msg_id, "uri": uri, "payload": {}})
|
||||||
|
try:
|
||||||
|
await ws.send(frame)
|
||||||
|
except (WebSocketClosedError, OSError) as exc:
|
||||||
|
self._pending.pop(msg_id, None)
|
||||||
|
self._subscriptions.pop(msg_id, None)
|
||||||
|
if not fut.done():
|
||||||
|
fut.cancel()
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, f"SSAP subscribe failed: {exc}") from exc
|
||||||
|
|
||||||
|
msg = await fut
|
||||||
|
payload = self._unwrap_response(msg)
|
||||||
|
await self._invoke_callback(callback, payload)
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
"""Close the SSAP transport and cancel the background reader loop."""
|
||||||
|
self._closing = True
|
||||||
|
ws = self._ws
|
||||||
|
self._ws = None
|
||||||
|
if ws is not None:
|
||||||
|
await self._safe_close_ws(ws)
|
||||||
|
|
||||||
|
task = self._reader_task
|
||||||
|
self._reader_task = None
|
||||||
|
if task is not None and not task.done():
|
||||||
|
task.cancel()
|
||||||
|
with suppress(asyncio.CancelledError):
|
||||||
|
await task
|
||||||
|
|
||||||
|
self._subscriptions.clear()
|
||||||
|
|
||||||
|
async def _reader_loop(self) -> None:
|
||||||
|
ws = self._ws
|
||||||
|
disconnect_code = ErrorCode.TV_OFFLINE_STANDBY
|
||||||
|
try:
|
||||||
|
while ws is not None:
|
||||||
|
raw = await ws.recv()
|
||||||
|
msg_raw: Any = json.loads(raw)
|
||||||
|
if not isinstance(msg_raw, dict):
|
||||||
|
continue
|
||||||
|
msg = cast(dict[str, Any], msg_raw)
|
||||||
|
msg_id = msg.get("id")
|
||||||
|
if not isinstance(msg_id, str):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if msg_id in self._pending:
|
||||||
|
fut = self._pending.pop(msg_id)
|
||||||
|
if not fut.done():
|
||||||
|
fut.set_result(msg)
|
||||||
|
elif msg_id in self._subscriptions:
|
||||||
|
if msg.get("type") == "error":
|
||||||
|
err_text = _extract_error_text(msg)
|
||||||
|
if _is_permission_error(err_text):
|
||||||
|
disconnect_code = ErrorCode.PAIRING_REQUIRED
|
||||||
|
break
|
||||||
|
continue
|
||||||
|
payload = msg.get("payload")
|
||||||
|
if isinstance(payload, dict):
|
||||||
|
payload_dict = cast(dict[str, Any], payload)
|
||||||
|
await self._invoke_callback(self._subscriptions[msg_id], payload_dict)
|
||||||
|
except WebSocketClosedError, OSError, json.JSONDecodeError, asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
for fut in list(self._pending.values()):
|
||||||
|
if not fut.done():
|
||||||
|
fut.set_exception(
|
||||||
|
TvError(ErrorCode.TV_OFFLINE_STANDBY, "SSAP connection closed")
|
||||||
|
)
|
||||||
|
self._pending.clear()
|
||||||
|
if ws is not None:
|
||||||
|
await self._safe_close_ws(ws)
|
||||||
|
if self._ws is ws:
|
||||||
|
self._ws = None
|
||||||
|
if not self._closing and self._on_disconnect is not None:
|
||||||
|
self._on_disconnect(disconnect_code)
|
||||||
|
|
||||||
|
def _unwrap_response(self, msg: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
if msg.get("type") == "error":
|
||||||
|
err_text = _extract_error_text(msg)
|
||||||
|
code = (
|
||||||
|
ErrorCode.PAIRING_REQUIRED
|
||||||
|
if _is_permission_error(err_text)
|
||||||
|
else ErrorCode.COMMAND_FAILED
|
||||||
|
)
|
||||||
|
raise TvError(code, err_text)
|
||||||
|
|
||||||
|
payload_raw = msg.get("payload")
|
||||||
|
if not isinstance(payload_raw, dict):
|
||||||
|
return {}
|
||||||
|
payload = cast(dict[str, Any], payload_raw)
|
||||||
|
if payload.get("returnValue") is False:
|
||||||
|
err_text = _extract_error_text(msg)
|
||||||
|
code = (
|
||||||
|
ErrorCode.PAIRING_REQUIRED
|
||||||
|
if _is_permission_error(err_text)
|
||||||
|
else ErrorCode.COMMAND_FAILED
|
||||||
|
)
|
||||||
|
raise TvError(code, err_text)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
async def _invoke_callback(
|
||||||
|
self,
|
||||||
|
callback: Callable[[dict[str, Any]], Awaitable[None] | None],
|
||||||
|
payload: dict[str, Any],
|
||||||
|
) -> None:
|
||||||
|
result = callback(payload)
|
||||||
|
if inspect.isawaitable(result):
|
||||||
|
await result
|
||||||
|
|
||||||
|
async def _safe_close_ws(self, ws: WebSocketTransport) -> None:
|
||||||
|
with suppress(Exception):
|
||||||
|
await ws.close()
|
||||||
Whitespace-only changes.
@@ -0,0 +1,61 @@
|
|||||||
|
"""Shared offline test fakes and fixtures for lg-smtv-mcp contract tests."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
from collections.abc import Callable
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import WebSocketClosedError
|
||||||
|
|
||||||
|
|
||||||
|
class FakeWebSocketTransport:
|
||||||
|
"""In-memory WebSocketTransport double for offline SSAP and pointer tests."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
on_send: Callable[[str, FakeWebSocketTransport], None] | None = None,
|
||||||
|
) -> None:
|
||||||
|
self.sent: list[str] = []
|
||||||
|
self.closed = False
|
||||||
|
self._on_send = on_send
|
||||||
|
self._incoming: asyncio.Queue[str | Exception] = asyncio.Queue()
|
||||||
|
|
||||||
|
def push_text(self, data: str) -> None:
|
||||||
|
"""Enqueue a raw text frame to be returned by recv()."""
|
||||||
|
self._incoming.put_nowait(data)
|
||||||
|
|
||||||
|
def push_json(self, payload: dict[str, Any]) -> None:
|
||||||
|
"""Enqueue a JSON-serialized frame to be returned by recv()."""
|
||||||
|
self._incoming.put_nowait(json.dumps(payload))
|
||||||
|
|
||||||
|
def push_error(self, exc: Exception) -> None:
|
||||||
|
"""Enqueue an exception to be raised by the next recv()."""
|
||||||
|
self._incoming.put_nowait(exc)
|
||||||
|
|
||||||
|
def push_close(self, code: int = 1000, reason: str = "") -> None:
|
||||||
|
"""Enqueue a WebSocketClosedError to simulate remote socket close."""
|
||||||
|
self._incoming.put_nowait(WebSocketClosedError(code, reason))
|
||||||
|
|
||||||
|
async def send(self, data: str) -> None:
|
||||||
|
"""Record an outgoing frame or raise WebSocketClosedError if closed."""
|
||||||
|
if self.closed:
|
||||||
|
raise WebSocketClosedError(1006, "transport closed")
|
||||||
|
self.sent.append(data)
|
||||||
|
if self._on_send is not None:
|
||||||
|
self._on_send(data, self)
|
||||||
|
|
||||||
|
async def recv(self) -> str:
|
||||||
|
"""Return the next queued frame or raise a queued exception."""
|
||||||
|
if self.closed and self._incoming.empty():
|
||||||
|
raise WebSocketClosedError(1006, "transport closed")
|
||||||
|
item = await self._incoming.get()
|
||||||
|
if isinstance(item, Exception):
|
||||||
|
raise item
|
||||||
|
return item
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
"""Mark the transport closed and wake any blocked recv()."""
|
||||||
|
if not self.closed:
|
||||||
|
self.closed = True
|
||||||
|
self._incoming.put_nowait(WebSocketClosedError(1000, "closed"))
|
||||||
@@ -0,0 +1,799 @@
|
|||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
from collections.abc import Awaitable, Callable
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from lg_smtv_mcp.config import TvConfig
|
||||||
|
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.tv_core.manager import ConnectionState, TvManager
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import CaptureResult, WebSocketClosedError
|
||||||
|
from tests.conftest import FakeWebSocketTransport
|
||||||
|
|
||||||
|
|
||||||
|
def _make_config(tmp_path: Path, **overrides: Any) -> TvConfig:
|
||||||
|
key_path = tmp_path / ".client_key.json"
|
||||||
|
if "client_key_path" not in overrides:
|
||||||
|
key_path.write_text(json.dumps({"192.0.2.10": "saved-key"}), encoding="utf-8")
|
||||||
|
defaults: dict[str, Any] = {
|
||||||
|
"tv_ip": "192.0.2.10",
|
||||||
|
"tv_mac": "00:11:22:33:44:55",
|
||||||
|
"client_key_path": key_path,
|
||||||
|
"max_volume": 40,
|
||||||
|
}
|
||||||
|
defaults.update(overrides)
|
||||||
|
return TvConfig(**defaults)
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeCapturer:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
error: TvError | None = None,
|
||||||
|
gate: asyncio.Event | None = None,
|
||||||
|
) -> None:
|
||||||
|
self.closed_count = 0
|
||||||
|
self.error = error
|
||||||
|
self.gate = gate
|
||||||
|
self.calls = 0
|
||||||
|
|
||||||
|
async def capture_frame(
|
||||||
|
self,
|
||||||
|
ssap_request_fn: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]],
|
||||||
|
) -> CaptureResult:
|
||||||
|
_ = ssap_request_fn
|
||||||
|
self.calls += 1
|
||||||
|
if self.gate is not None:
|
||||||
|
await self.gate.wait()
|
||||||
|
if self.error is not None:
|
||||||
|
raise self.error
|
||||||
|
return CaptureResult(
|
||||||
|
image_bytes=b"\xff\xd8\xff\xe0",
|
||||||
|
frame_sha256="deadbeef",
|
||||||
|
changed_since_last=True,
|
||||||
|
size_bytes=4,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
self.closed_count += 1
|
||||||
|
|
||||||
|
|
||||||
|
def _make_online_transport(
|
||||||
|
*,
|
||||||
|
volume: int = 22,
|
||||||
|
mute: bool = False,
|
||||||
|
sound_output: str = "tv_speaker",
|
||||||
|
app_id: str = "com.webos.app.livetv",
|
||||||
|
on_request: Callable[[dict[str, Any], FakeWebSocketTransport], None] | None = None,
|
||||||
|
) -> FakeWebSocketTransport:
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
msg_type = msg.get("type")
|
||||||
|
if msg_type == "register":
|
||||||
|
ws.push_json({"type": "registered", "id": msg["id"], "payload": {"client-key": "k"}})
|
||||||
|
elif msg_type == "subscribe":
|
||||||
|
uri = msg["uri"]
|
||||||
|
if uri == "ssap://audio/getStatus":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {
|
||||||
|
"returnValue": True,
|
||||||
|
"subscribed": True,
|
||||||
|
"volume": volume,
|
||||||
|
"mute": mute,
|
||||||
|
"volumeStatus": {"soundOutput": sound_output},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif uri == "ssap://com.webos.applicationManager/getForegroundAppInfo":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {
|
||||||
|
"returnValue": True,
|
||||||
|
"subscribed": True,
|
||||||
|
"appId": app_id,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif msg_type == "request" and on_request is not None:
|
||||||
|
on_request(msg, ws)
|
||||||
|
|
||||||
|
return FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_uses_stepped_reconnect_backoff_and_tears_down_capture_on_standby(
|
||||||
|
tmp_path: Path,
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
cfg = _make_config(tmp_path)
|
||||||
|
capturer = _FakeCapturer()
|
||||||
|
wait_timeouts: list[float] = []
|
||||||
|
real_wait_for = asyncio.wait_for
|
||||||
|
|
||||||
|
async def spy_wait_for(aw: Any, timeout: float | None = None) -> Any:
|
||||||
|
if timeout is not None and timeout >= 2.0:
|
||||||
|
wait_timeouts.append(timeout)
|
||||||
|
return await real_wait_for(aw, timeout=0.005)
|
||||||
|
return await real_wait_for(aw, timeout=timeout)
|
||||||
|
|
||||||
|
monkeypatch.setattr(asyncio, "wait_for", spy_wait_for)
|
||||||
|
|
||||||
|
attempts = 0
|
||||||
|
|
||||||
|
async def connect_standby(_url: str) -> FakeWebSocketTransport:
|
||||||
|
nonlocal attempts
|
||||||
|
attempts += 1
|
||||||
|
ws = FakeWebSocketTransport()
|
||||||
|
ws.push_close(1008, "Try Again Later (EWS)")
|
||||||
|
return ws
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
cfg,
|
||||||
|
connect_fn=connect_standby,
|
||||||
|
capture_client=capturer,
|
||||||
|
backoff_steps=(2.0, 5.0, 15.0, 30.0),
|
||||||
|
)
|
||||||
|
await mgr.start()
|
||||||
|
for _ in range(50):
|
||||||
|
if len(wait_timeouts) >= 5:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.005)
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
assert mgr.state is ConnectionState.STANDBY_OFFLINE
|
||||||
|
assert wait_timeouts[:5] == [2.0, 5.0, 15.0, 30.0, 30.0]
|
||||||
|
assert capturer.closed_count >= 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_wake_coalesces_concurrent_calls_and_handles_connected_and_pairing(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
cfg = _make_config(tmp_path)
|
||||||
|
wol_calls: list[tuple[str, str, int]] = []
|
||||||
|
online = False
|
||||||
|
|
||||||
|
def fake_wol(mac: str, broadcast: str, port: int) -> None:
|
||||||
|
wol_calls.append((mac, broadcast, port))
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
if not online:
|
||||||
|
ws = FakeWebSocketTransport()
|
||||||
|
ws.push_close(1008, "Try Again Later (EWS)")
|
||||||
|
return ws
|
||||||
|
return _make_online_transport()
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
cfg,
|
||||||
|
connect_fn=connect_fn,
|
||||||
|
wol_fn=fake_wol,
|
||||||
|
backoff_steps=(10.0,),
|
||||||
|
wake_poll_interval=0.01,
|
||||||
|
wake_timeout=2.0,
|
||||||
|
)
|
||||||
|
await mgr.start()
|
||||||
|
await asyncio.sleep(0.02)
|
||||||
|
assert mgr.state is ConnectionState.STANDBY_OFFLINE
|
||||||
|
|
||||||
|
async def flip_online() -> None:
|
||||||
|
nonlocal online
|
||||||
|
await asyncio.sleep(0.03)
|
||||||
|
online = True
|
||||||
|
|
||||||
|
flipper = asyncio.create_task(flip_online())
|
||||||
|
res1, res2 = await asyncio.gather(mgr.wake(), mgr.wake())
|
||||||
|
await flipper
|
||||||
|
|
||||||
|
assert len(wol_calls) == 1
|
||||||
|
assert res1.status == "connected"
|
||||||
|
assert res2.status == "connected"
|
||||||
|
assert mgr.state is ConnectionState.CONNECTED
|
||||||
|
|
||||||
|
already = await mgr.wake()
|
||||||
|
assert already.status == "already_connected"
|
||||||
|
assert already.elapsed_ms == 0
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
# PAIRING_REQUIRED fast-fail
|
||||||
|
def on_send_prompt(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"pairingType": "PROMPT", "returnValue": True},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
async def connect_prompt(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return FakeWebSocketTransport(on_send=on_send_prompt)
|
||||||
|
|
||||||
|
mgr_pair = TvManager(cfg, connect_fn=connect_prompt, wol_fn=fake_wol, backoff_steps=(10.0,))
|
||||||
|
await mgr_pair.start()
|
||||||
|
await asyncio.sleep(0.02)
|
||||||
|
assert mgr_pair.state is ConnectionState.PAIRING_REQUIRED
|
||||||
|
with pytest.raises(TvError) as exc_pair:
|
||||||
|
await mgr_pair.wake()
|
||||||
|
assert exc_pair.value.code is ErrorCode.PAIRING_REQUIRED
|
||||||
|
await mgr_pair.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _noop_wol(_mac: str, _broadcast: str, _port: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_wake_raises_wake_timeout_when_tv_never_comes_online(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
cfg = _make_config(tmp_path)
|
||||||
|
|
||||||
|
async def connect_standby(_url: str) -> FakeWebSocketTransport:
|
||||||
|
ws = FakeWebSocketTransport()
|
||||||
|
ws.push_close(1008, "Try Again Later (EWS)")
|
||||||
|
return ws
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
cfg,
|
||||||
|
connect_fn=connect_standby,
|
||||||
|
wol_fn=_noop_wol,
|
||||||
|
backoff_steps=(10.0,),
|
||||||
|
wake_poll_interval=0.01,
|
||||||
|
wake_timeout=0.05,
|
||||||
|
)
|
||||||
|
await mgr.start()
|
||||||
|
await asyncio.sleep(0.02)
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr.wake()
|
||||||
|
assert exc_info.value.code is ErrorCode.WAKE_TIMEOUT
|
||||||
|
assert mgr.state is ConnectionState.STANDBY_OFFLINE
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_reloads_client_key_on_sighup_and_stays_in_pairing_on_bad_json(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
key_path = tmp_path / ".client_key.json"
|
||||||
|
key_path.write_text("{not valid json", encoding="utf-8")
|
||||||
|
cfg = _make_config(tmp_path, client_key_path=key_path)
|
||||||
|
|
||||||
|
def on_send_check_key(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
if msg["payload"].get("client-key") == "fresh-key":
|
||||||
|
ws.push_json(
|
||||||
|
{"type": "registered", "id": msg["id"], "payload": {"client-key": "fresh-key"}}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"pairingType": "PROMPT", "returnValue": True},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif msg["type"] == "subscribe":
|
||||||
|
ws.push_json(
|
||||||
|
{"type": "response", "id": msg["id"], "payload": {"returnValue": True, "volume": 1}}
|
||||||
|
)
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return FakeWebSocketTransport(on_send=on_send_check_key)
|
||||||
|
|
||||||
|
mgr = TvManager(cfg, connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
await mgr.start()
|
||||||
|
await asyncio.sleep(0.02)
|
||||||
|
assert mgr.state is ConnectionState.PAIRING_REQUIRED
|
||||||
|
|
||||||
|
# Reload with malformed JSON stays in PAIRING_REQUIRED.
|
||||||
|
mgr.reload_client_key()
|
||||||
|
await asyncio.sleep(0.02)
|
||||||
|
assert mgr.state is ConnectionState.PAIRING_REQUIRED
|
||||||
|
|
||||||
|
# Write valid JSON and reload -> transitions to CONNECTED.
|
||||||
|
key_path.write_text(json.dumps({"192.0.2.10": "fresh-key"}), encoding="utf-8")
|
||||||
|
mgr.reload_client_key()
|
||||||
|
for _ in range(30):
|
||||||
|
if mgr.get_state().connected:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
assert mgr.get_state().connected is True
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_caches_subscribe_state_and_returns_lock_free_offline_snapshot(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
cfg = _make_config(tmp_path)
|
||||||
|
transport = _make_online_transport(
|
||||||
|
volume=27,
|
||||||
|
mute=True,
|
||||||
|
sound_output="external_arc",
|
||||||
|
app_id="netflix",
|
||||||
|
)
|
||||||
|
connects = 0
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
nonlocal connects
|
||||||
|
connects += 1
|
||||||
|
if connects == 1:
|
||||||
|
return transport
|
||||||
|
ws = FakeWebSocketTransport()
|
||||||
|
ws.push_close(1008, "Try Again Later (EWS)")
|
||||||
|
return ws
|
||||||
|
|
||||||
|
mgr = TvManager(cfg, connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
await mgr.start()
|
||||||
|
for _ in range(30):
|
||||||
|
if mgr.state is ConnectionState.CONNECTED:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
snap_online = mgr.get_state()
|
||||||
|
assert snap_online.connected is True
|
||||||
|
assert snap_online.stale is False
|
||||||
|
assert snap_online.volume == 27
|
||||||
|
assert snap_online.muted is True
|
||||||
|
assert snap_online.sound_output == "external_arc"
|
||||||
|
assert snap_online.foreground_app == "netflix"
|
||||||
|
assert snap_online.last_updated is not None
|
||||||
|
|
||||||
|
# Drop connection and verify cached values remain available offline.
|
||||||
|
transport.push_error(WebSocketClosedError(1008, "Try Again Later (EWS)"))
|
||||||
|
for _ in range(30):
|
||||||
|
if mgr.state is ConnectionState.STANDBY_OFFLINE:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
snap_offline = mgr.get_state()
|
||||||
|
assert snap_offline.connected is False
|
||||||
|
assert snap_offline.stale is True
|
||||||
|
assert snap_offline.volume == 27
|
||||||
|
assert snap_offline.sound_output == "external_arc"
|
||||||
|
assert snap_offline.foreground_app == "netflix"
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_transitions_to_pairing_required_on_subscription_401(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
cfg = _make_config(tmp_path)
|
||||||
|
|
||||||
|
def on_send_401(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
ws.push_json({"type": "registered", "id": msg["id"], "payload": {"client-key": "k"}})
|
||||||
|
elif msg["type"] == "subscribe":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "error",
|
||||||
|
"id": msg["id"],
|
||||||
|
"error": "401 insufficient permissions",
|
||||||
|
"payload": {"returnValue": False},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return FakeWebSocketTransport(on_send=on_send_401)
|
||||||
|
|
||||||
|
mgr = TvManager(cfg, connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
await mgr.start()
|
||||||
|
for _ in range(30):
|
||||||
|
if mgr.state is ConnectionState.PAIRING_REQUIRED:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
assert mgr.state is ConnectionState.PAIRING_REQUIRED
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_ui_lock_times_out_with_lock_timeout(tmp_path: Path) -> None:
|
||||||
|
cfg = _make_config(tmp_path)
|
||||||
|
gate = asyncio.Event()
|
||||||
|
capturer = _FakeCapturer(gate=gate)
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _make_online_transport()
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
cfg,
|
||||||
|
connect_fn=connect_fn,
|
||||||
|
capture_client=capturer,
|
||||||
|
backoff_steps=(10.0,),
|
||||||
|
ui_lock_timeout=0.02,
|
||||||
|
)
|
||||||
|
await mgr.start()
|
||||||
|
for _ in range(30):
|
||||||
|
if mgr.get_state().connected:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
holder = asyncio.create_task(mgr.screenshot())
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
try:
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr.screenshot()
|
||||||
|
assert exc_info.value.code is ErrorCode.LOCK_TIMEOUT
|
||||||
|
finally:
|
||||||
|
gate.set()
|
||||||
|
await holder
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("keys", "delay_ms", "settle_ms"),
|
||||||
|
[
|
||||||
|
([], 250, 0),
|
||||||
|
(["UP"] * 21, 250, 0),
|
||||||
|
(["UP"], -1, 0),
|
||||||
|
(["UP"], 501, 0),
|
||||||
|
(["UP"], 0, -1),
|
||||||
|
(["UP"], 0, 2001),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
async def test_manager_send_keys_validates_bounds_with_invalid_argument(
|
||||||
|
tmp_path: Path,
|
||||||
|
keys: list[str],
|
||||||
|
delay_ms: int,
|
||||||
|
settle_ms: int,
|
||||||
|
) -> None:
|
||||||
|
cfg = _make_config(tmp_path)
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _make_online_transport()
|
||||||
|
|
||||||
|
mgr = TvManager(cfg, connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
await mgr.start()
|
||||||
|
for _ in range(30):
|
||||||
|
if mgr.get_state().connected:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr.send_keys(keys, delay_ms=delay_ms, settle_ms=settle_ms)
|
||||||
|
assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_send_keys_capture_returns_partial_success_when_capture_unavailable(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
cfg = _make_config(tmp_path)
|
||||||
|
pointer_ws = FakeWebSocketTransport()
|
||||||
|
ssap_ws = _make_online_transport(
|
||||||
|
on_request=lambda msg, ws: ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"returnValue": True, "socketPath": "wss://192.0.2.10:3001/ptr"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
async def connect_fn(url: str) -> FakeWebSocketTransport:
|
||||||
|
return pointer_ws if "/ptr" in url else ssap_ws
|
||||||
|
|
||||||
|
# Case 1: capture_client is None
|
||||||
|
mgr_none = TvManager(cfg, connect_fn=connect_fn, capture_client=None, backoff_steps=(10.0,))
|
||||||
|
await mgr_none.start()
|
||||||
|
for _ in range(30):
|
||||||
|
if mgr_none.get_state().connected:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
res_none = await mgr_none.send_keys(["UP", "ENTER"], delay_ms=0, settle_ms=0, capture=True)
|
||||||
|
assert res_none.keys_sent is True
|
||||||
|
assert res_none.count == 2
|
||||||
|
assert res_none.capture_error is not None
|
||||||
|
assert "SCREENSHOT_UNAVAILABLE" in res_none.capture_error
|
||||||
|
await mgr_none.close()
|
||||||
|
|
||||||
|
# Case 2: capture_client raises SCREENSHOT_UNAVAILABLE
|
||||||
|
pointer_ws2 = FakeWebSocketTransport()
|
||||||
|
ssap_ws2 = _make_online_transport(
|
||||||
|
on_request=lambda msg, ws: ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"returnValue": True, "socketPath": "wss://192.0.2.10:3001/ptr"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
async def connect_fn2(url: str) -> FakeWebSocketTransport:
|
||||||
|
return pointer_ws2 if "/ptr" in url else ssap_ws2
|
||||||
|
|
||||||
|
failing_capturer = _FakeCapturer(
|
||||||
|
error=TvError(ErrorCode.SCREENSHOT_UNAVAILABLE, "Dev Mode expired")
|
||||||
|
)
|
||||||
|
mgr_err = TvManager(
|
||||||
|
cfg, connect_fn=connect_fn2, capture_client=failing_capturer, backoff_steps=(10.0,)
|
||||||
|
)
|
||||||
|
await mgr_err.start()
|
||||||
|
for _ in range(30):
|
||||||
|
if mgr_err.get_state().connected:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
res_err = await mgr_err.send_keys(["DOWN"], delay_ms=0, settle_ms=0, capture=True)
|
||||||
|
assert res_err.keys_sent is True
|
||||||
|
assert res_err.count == 1
|
||||||
|
assert res_err.capture_error == "SCREENSHOT_UNAVAILABLE: Dev Mode expired"
|
||||||
|
await mgr_err.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_screenshot_raises_unavailable_when_capture_client_is_none(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
cfg = _make_config(tmp_path)
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _make_online_transport()
|
||||||
|
|
||||||
|
mgr = TvManager(cfg, connect_fn=connect_fn, capture_client=None, backoff_steps=(10.0,))
|
||||||
|
await mgr.start()
|
||||||
|
for _ in range(30):
|
||||||
|
if mgr.get_state().connected:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr.screenshot()
|
||||||
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_set_volume_enforces_max_volume_guardrail(tmp_path: Path) -> None:
|
||||||
|
cfg = _make_config(tmp_path, max_volume=35)
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
|
||||||
|
def on_request(msg: dict[str, Any], ws: FakeWebSocketTransport) -> None:
|
||||||
|
sent_requests.append((msg["uri"], msg["payload"]))
|
||||||
|
ws.push_json({"type": "response", "id": msg["id"], "payload": {"returnValue": True}})
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _make_online_transport(on_request=on_request)
|
||||||
|
|
||||||
|
mgr = TvManager(cfg, connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
await mgr.start()
|
||||||
|
for _ in range(30):
|
||||||
|
if mgr.get_state().connected:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
for bad_level in (-1, 36):
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr.set_volume(bad_level)
|
||||||
|
assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT
|
||||||
|
|
||||||
|
await mgr.set_volume(20)
|
||||||
|
assert sent_requests == [("ssap://audio/setVolume", {"volume": 20})]
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_mvp_ssap_controls_launch_list_mute_and_turn_off(tmp_path: Path) -> None:
|
||||||
|
cfg = _make_config(tmp_path)
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
|
||||||
|
def on_request(msg: dict[str, Any], ws: FakeWebSocketTransport) -> None:
|
||||||
|
uri = msg["uri"]
|
||||||
|
sent_requests.append((uri, msg["payload"]))
|
||||||
|
if uri == "ssap://com.webos.applicationManager/listLaunchPoints":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {
|
||||||
|
"returnValue": True,
|
||||||
|
"launchPoints": [{"id": "netflix", "title": "Netflix"}],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
ws.push_json({"type": "response", "id": msg["id"], "payload": {"returnValue": True}})
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _make_online_transport(on_request=on_request)
|
||||||
|
|
||||||
|
mgr = TvManager(cfg, connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
await mgr.start()
|
||||||
|
for _ in range(30):
|
||||||
|
if mgr.get_state().connected:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
await mgr.launch_app("youtube.leanback.v4", content_target="v=abc&t=10s")
|
||||||
|
apps = await mgr.list_apps()
|
||||||
|
await mgr.set_mute(True)
|
||||||
|
await mgr.turn_off()
|
||||||
|
|
||||||
|
assert apps == [{"id": "netflix", "title": "Netflix"}]
|
||||||
|
assert sent_requests == [
|
||||||
|
(
|
||||||
|
"ssap://system.launcher/launch",
|
||||||
|
{"id": "youtube.leanback.v4", "params": {"contentTarget": "v=abc&t=10s"}},
|
||||||
|
),
|
||||||
|
("ssap://com.webos.applicationManager/listLaunchPoints", {}),
|
||||||
|
("ssap://audio/setMute", {"mute": True}),
|
||||||
|
("ssap://system/turnOff", {}),
|
||||||
|
]
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_wake_pairing_failure_clears_wake_requested_and_respects_backoff(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
cfg = _make_config(tmp_path)
|
||||||
|
connect_attempts = 0
|
||||||
|
return_prompt = False
|
||||||
|
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
if return_prompt:
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"pairingType": "PROMPT", "returnValue": True},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
ws.push_close(1008, "Try Again Later (EWS)")
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
nonlocal connect_attempts
|
||||||
|
connect_attempts += 1
|
||||||
|
return FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
cfg,
|
||||||
|
connect_fn=connect_fn,
|
||||||
|
wol_fn=_noop_wol,
|
||||||
|
backoff_steps=(1.0,),
|
||||||
|
wake_poll_interval=0.01,
|
||||||
|
wake_timeout=1.0,
|
||||||
|
)
|
||||||
|
await mgr.start()
|
||||||
|
await asyncio.sleep(0.02)
|
||||||
|
assert mgr.state is ConnectionState.STANDBY_OFFLINE
|
||||||
|
|
||||||
|
return_prompt = True
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr.wake()
|
||||||
|
assert exc_info.value.code is ErrorCode.PAIRING_REQUIRED
|
||||||
|
|
||||||
|
attempts_after_wake = connect_attempts
|
||||||
|
await asyncio.sleep(0.05)
|
||||||
|
assert connect_attempts == attempts_after_wake
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_type_text_bounds_and_capture_partial_success(tmp_path: Path) -> None:
|
||||||
|
cfg = _make_config(tmp_path)
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
|
||||||
|
def on_request(msg: dict[str, Any], ws: FakeWebSocketTransport) -> None:
|
||||||
|
sent_requests.append((msg["uri"], msg["payload"]))
|
||||||
|
ws.push_json({"type": "response", "id": msg["id"], "payload": {"returnValue": True}})
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _make_online_transport(on_request=on_request)
|
||||||
|
|
||||||
|
failing_capturer = _FakeCapturer(
|
||||||
|
error=TvError(ErrorCode.SCREENSHOT_UNAVAILABLE, "Dev Mode expired")
|
||||||
|
)
|
||||||
|
mgr = TvManager(
|
||||||
|
cfg,
|
||||||
|
connect_fn=connect_fn,
|
||||||
|
capture_client=failing_capturer,
|
||||||
|
backoff_steps=(10.0,),
|
||||||
|
)
|
||||||
|
await mgr.start()
|
||||||
|
for _ in range(30):
|
||||||
|
if mgr.get_state().connected:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
for bad_text in ("", "x" * 501):
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr.type_text(bad_text)
|
||||||
|
assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT
|
||||||
|
|
||||||
|
res = await mgr.type_text("anime", send_enter=True, capture=True)
|
||||||
|
assert res.text_sent is True
|
||||||
|
assert res.enter_sent is True
|
||||||
|
assert res.capture_error == "SCREENSHOT_UNAVAILABLE: Dev Mode expired"
|
||||||
|
assert sent_requests == [
|
||||||
|
("ssap://com.webos.service.ime/insertText", {"text": "anime", "replace": 0}),
|
||||||
|
("ssap://com.webos.service.ime/sendEnterKey", {}),
|
||||||
|
]
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_list_inputs_and_switch_input(tmp_path: Path) -> None:
|
||||||
|
cfg = _make_config(tmp_path)
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
|
||||||
|
def on_request(msg: dict[str, Any], ws: FakeWebSocketTransport) -> None:
|
||||||
|
uri = msg["uri"]
|
||||||
|
sent_requests.append((uri, msg["payload"]))
|
||||||
|
if uri == "ssap://tv/getExternalInputList":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {
|
||||||
|
"returnValue": True,
|
||||||
|
"devices": [{"id": "HDMI_1", "label": "HDMI 1", "connected": True}],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
ws.push_json({"type": "response", "id": msg["id"], "payload": {"returnValue": True}})
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _make_online_transport(on_request=on_request)
|
||||||
|
|
||||||
|
mgr = TvManager(cfg, connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
await mgr.start()
|
||||||
|
for _ in range(30):
|
||||||
|
if mgr.get_state().connected:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
inputs = await mgr.list_inputs()
|
||||||
|
await mgr.switch_input("HDMI_1")
|
||||||
|
|
||||||
|
assert inputs == [{"id": "HDMI_1", "label": "HDMI 1", "connected": True}]
|
||||||
|
assert sent_requests == [
|
||||||
|
("ssap://tv/getExternalInputList", {}),
|
||||||
|
("ssap://tv/switchInput", {"inputId": "HDMI_1"}),
|
||||||
|
]
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_raw_ssap_respects_enable_raw_ssap_gate(tmp_path: Path) -> None:
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _make_online_transport(
|
||||||
|
on_request=lambda msg, ws: ws.push_json(
|
||||||
|
{"type": "response", "id": msg["id"], "payload": {"returnValue": True, "ok": 1}}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
mgr_disabled = TvManager(
|
||||||
|
_make_config(tmp_path, enable_raw_ssap=False),
|
||||||
|
connect_fn=connect_fn,
|
||||||
|
backoff_steps=(10.0,),
|
||||||
|
)
|
||||||
|
await mgr_disabled.start()
|
||||||
|
for _ in range(30):
|
||||||
|
if mgr_disabled.get_state().connected:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr_disabled.raw_ssap("ssap://system/getSystemInfo")
|
||||||
|
assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT
|
||||||
|
await mgr_disabled.close()
|
||||||
|
|
||||||
|
mgr_enabled = TvManager(
|
||||||
|
_make_config(tmp_path, enable_raw_ssap=True),
|
||||||
|
connect_fn=connect_fn,
|
||||||
|
backoff_steps=(10.0,),
|
||||||
|
)
|
||||||
|
await mgr_enabled.start()
|
||||||
|
for _ in range(30):
|
||||||
|
if mgr_enabled.get_state().connected:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
resp = await mgr_enabled.raw_ssap("ssap://system/getSystemInfo", {"x": 1})
|
||||||
|
assert resp == {"returnValue": True, "ok": 1}
|
||||||
|
await mgr_enabled.close()
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.tv_core.pointer import BUTTON_ALLOWLIST, PointerClient
|
||||||
|
from tests.conftest import FakeWebSocketTransport
|
||||||
|
|
||||||
|
|
||||||
|
async def test_pointer_normalizes_keys_to_uppercase_and_formats_frames() -> None:
|
||||||
|
ws = FakeWebSocketTransport()
|
||||||
|
ssap_calls: list[str] = []
|
||||||
|
|
||||||
|
async def fake_ssap(uri: str, _payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
ssap_calls.append(uri)
|
||||||
|
return {"socketPath": "wss://192.0.2.10:3001/pointer/1"}
|
||||||
|
|
||||||
|
async def fake_connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return ws
|
||||||
|
|
||||||
|
client = PointerClient(fake_ssap, connect_fn=fake_connect)
|
||||||
|
count = await client.send_buttons(["up", "Enter", "home"], delay_ms=0)
|
||||||
|
await client.close()
|
||||||
|
|
||||||
|
assert count == 3
|
||||||
|
assert ssap_calls == ["ssap://com.webos.service.networkinput/getPointerInputSocket"]
|
||||||
|
assert ws.sent == [
|
||||||
|
"type:button\nname:UP\n\n",
|
||||||
|
"type:button\nname:ENTER\n\n",
|
||||||
|
"type:button\nname:HOME\n\n",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("bad_key", ["INVALID_KEY", "UP\nname:HOME", "ENTER\r", ""])
|
||||||
|
async def test_pointer_rejects_unknown_keys_and_newlines_with_invalid_argument(
|
||||||
|
bad_key: str,
|
||||||
|
) -> None:
|
||||||
|
assert "UP" in BUTTON_ALLOWLIST
|
||||||
|
ws = FakeWebSocketTransport()
|
||||||
|
|
||||||
|
async def fake_ssap(_uri: str, _payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {"socketPath": "wss://192.0.2.10:3001/pointer/1"}
|
||||||
|
|
||||||
|
async def fake_connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return ws
|
||||||
|
|
||||||
|
client = PointerClient(fake_ssap, connect_fn=fake_connect)
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await client.send_buttons(["UP", bad_key], delay_ms=0)
|
||||||
|
|
||||||
|
assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT
|
||||||
|
assert ws.sent == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_pointer_paces_buttons_by_delay_ms(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
ws = FakeWebSocketTransport()
|
||||||
|
sleeps: list[float] = []
|
||||||
|
|
||||||
|
async def fake_sleep(seconds: float) -> None:
|
||||||
|
sleeps.append(seconds)
|
||||||
|
|
||||||
|
monkeypatch.setattr(asyncio, "sleep", fake_sleep)
|
||||||
|
|
||||||
|
async def fake_ssap(_uri: str, _payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {"socketPath": "wss://192.0.2.10:3001/pointer/1"}
|
||||||
|
|
||||||
|
async def fake_connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return ws
|
||||||
|
|
||||||
|
client = PointerClient(fake_ssap, connect_fn=fake_connect)
|
||||||
|
await client.send_buttons(["LEFT", "RIGHT", "ENTER"], delay_ms=150)
|
||||||
|
await client.close()
|
||||||
|
|
||||||
|
assert sleeps == [pytest.approx(0.15), pytest.approx(0.15)]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_pointer_retries_once_on_mid_batch_socket_drop() -> None:
|
||||||
|
ws1 = FakeWebSocketTransport()
|
||||||
|
ws2 = FakeWebSocketTransport()
|
||||||
|
connects = 0
|
||||||
|
|
||||||
|
def drop_after_first(data: str, transport: FakeWebSocketTransport) -> None:
|
||||||
|
if "LEFT" in data:
|
||||||
|
transport.closed = True
|
||||||
|
|
||||||
|
ws1._on_send = drop_after_first # pyright: ignore[reportPrivateUsage]
|
||||||
|
|
||||||
|
async def fake_ssap(_uri: str, _payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {"socketPath": f"wss://192.0.2.10:3001/pointer/{connects + 1}"}
|
||||||
|
|
||||||
|
async def fake_connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
nonlocal connects
|
||||||
|
connects += 1
|
||||||
|
return ws1 if connects == 1 else ws2
|
||||||
|
|
||||||
|
client = PointerClient(fake_ssap, connect_fn=fake_connect)
|
||||||
|
count = await client.send_buttons(["LEFT", "ENTER"], delay_ms=0)
|
||||||
|
await client.close()
|
||||||
|
|
||||||
|
assert count == 2
|
||||||
|
assert connects == 2
|
||||||
|
assert ws1.sent == ["type:button\nname:LEFT\n\n"]
|
||||||
|
assert ws2.sent == ["type:button\nname:ENTER\n\n"]
|
||||||
@@ -12,7 +12,6 @@ from lg_smtv_mcp.tv_core.protocols import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.xfail(strict=True, reason="Red phase: protocols")
|
|
||||||
def test_websocket_closed_error_preserves_args_and_str_representation() -> None:
|
def test_websocket_closed_error_preserves_args_and_str_representation() -> None:
|
||||||
err = WebSocketClosedError(1008, "Try Again Later (EWS)")
|
err = WebSocketClosedError(1008, "Try Again Later (EWS)")
|
||||||
|
|
||||||
@@ -29,7 +28,6 @@ def test_websocket_closed_error_preserves_args_and_str_representation() -> None:
|
|||||||
assert "1000" in str(err_no_reason)
|
assert "1000" in str(err_no_reason)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.xfail(strict=True, reason="Red phase: protocols")
|
|
||||||
def test_result_dataclasses_are_frozen_and_expose_expected_fields() -> None:
|
def test_result_dataclasses_are_frozen_and_expose_expected_fields() -> None:
|
||||||
status = TvStatus(status="connected", elapsed_ms=120)
|
status = TvStatus(status="connected", elapsed_ms=120)
|
||||||
snapshot = TvStateSnapshot(
|
snapshot = TvStateSnapshot(
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import WebSocketClosedError
|
||||||
|
from lg_smtv_mcp.tv_core.ssap import PERMISSIONS, SsapClient
|
||||||
|
from tests.conftest import FakeWebSocketTransport
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ssap_register_sends_all_permissions_even_with_saved_client_key() -> None:
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "registered",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"client-key": "saved-key-123"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
transport = FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
async def connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return transport
|
||||||
|
|
||||||
|
client = SsapClient("wss://192.0.2.10:3001", connect_fn=connect)
|
||||||
|
key = await client.connect_and_register("saved-key-123")
|
||||||
|
await client.close()
|
||||||
|
|
||||||
|
assert key == "saved-key-123"
|
||||||
|
reg_msg = json.loads(transport.sent[0])
|
||||||
|
assert reg_msg["type"] == "register"
|
||||||
|
assert reg_msg["payload"]["client-key"] == "saved-key-123"
|
||||||
|
assert len(PERMISSIONS) == 16
|
||||||
|
assert reg_msg["payload"]["manifest"]["permissions"] == list(PERMISSIONS)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ssap_request_demuxes_interleaved_subscribe_push_frame() -> None:
|
||||||
|
sub_id_holder: list[str] = []
|
||||||
|
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
ws.push_json({"type": "registered", "id": msg["id"], "payload": {"client-key": "k"}})
|
||||||
|
elif msg["type"] == "subscribe":
|
||||||
|
sub_id_holder.append(msg["id"])
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"subscribed": True, "returnValue": True, "volume": 10},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif msg["type"] == "request":
|
||||||
|
# Push a subscribe update frame BEFORE the request response frame.
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": sub_id_holder[0],
|
||||||
|
"payload": {"returnValue": True, "volume": 10, "mute": True},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"returnValue": True, "muteApplied": True},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
transport = FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
async def connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return transport
|
||||||
|
|
||||||
|
client = SsapClient("wss://192.0.2.10:3001", connect_fn=connect)
|
||||||
|
await client.connect_and_register("k")
|
||||||
|
|
||||||
|
updates: list[dict[str, Any]] = []
|
||||||
|
await client.subscribe("ssap://audio/getStatus", updates.append)
|
||||||
|
resp = await client.request("ssap://audio/setMute", {"mute": True})
|
||||||
|
await asyncio.sleep(0)
|
||||||
|
await client.close()
|
||||||
|
|
||||||
|
assert resp == {"returnValue": True, "muteApplied": True}
|
||||||
|
assert updates[-1]["mute"] is True
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ssap_connect_maps_1008_and_timeout_to_tv_offline_standby() -> None:
|
||||||
|
transport_1008 = FakeWebSocketTransport()
|
||||||
|
transport_1008.push_close(1008, "Try Again Later (EWS)")
|
||||||
|
|
||||||
|
async def connect_1008(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return transport_1008
|
||||||
|
|
||||||
|
client_1008 = SsapClient("wss://192.0.2.10:3001", connect_fn=connect_1008)
|
||||||
|
with pytest.raises(TvError) as exc_1008:
|
||||||
|
await client_1008.connect_and_register("k")
|
||||||
|
assert exc_1008.value.code is ErrorCode.TV_OFFLINE_STANDBY
|
||||||
|
|
||||||
|
async def connect_timeout(_url: str) -> FakeWebSocketTransport:
|
||||||
|
raise TimeoutError("handshake timed out")
|
||||||
|
|
||||||
|
client_timeout = SsapClient("wss://192.0.2.10:3001", connect_fn=connect_timeout)
|
||||||
|
with pytest.raises(TvError) as exc_timeout:
|
||||||
|
await client_timeout.connect_and_register("k")
|
||||||
|
assert exc_timeout.value.code is ErrorCode.TV_OFFLINE_STANDBY
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ssap_register_maps_prompt_to_pairing_required() -> None:
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"pairingType": "PROMPT", "returnValue": True},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
transport = FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
async def connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return transport
|
||||||
|
|
||||||
|
client = SsapClient("wss://192.0.2.10:3001", connect_fn=connect)
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await client.connect_and_register(None)
|
||||||
|
assert exc_info.value.code is ErrorCode.PAIRING_REQUIRED
|
||||||
|
assert transport.closed is True
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ssap_request_maps_return_value_false_and_401_to_domain_errors() -> None:
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
ws.push_json({"type": "registered", "id": msg["id"], "payload": {"client-key": "k"}})
|
||||||
|
elif msg["type"] == "request":
|
||||||
|
if msg["uri"] == "ssap://fail/cmd":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"returnValue": False, "errorText": "bad target"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif msg["uri"] == "ssap://settings/getSystemSettings":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "error",
|
||||||
|
"id": msg["id"],
|
||||||
|
"error": "401 insufficient permissions",
|
||||||
|
"payload": {"returnValue": False},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
transport = FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
async def connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return transport
|
||||||
|
|
||||||
|
client = SsapClient("wss://192.0.2.10:3001", connect_fn=connect)
|
||||||
|
await client.connect_and_register("k")
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_cmd:
|
||||||
|
await client.request("ssap://fail/cmd")
|
||||||
|
assert exc_cmd.value.code is ErrorCode.COMMAND_FAILED
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_perm:
|
||||||
|
await client.request("ssap://settings/getSystemSettings")
|
||||||
|
assert exc_perm.value.code is ErrorCode.PAIRING_REQUIRED
|
||||||
|
|
||||||
|
await client.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ssap_reader_loop_finally_fails_pending_futures_with_standby_error() -> None:
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
ws.push_json({"type": "registered", "id": msg["id"], "payload": {"client-key": "k"}})
|
||||||
|
elif msg["type"] == "request":
|
||||||
|
# Drop the socket instead of answering the request.
|
||||||
|
ws.push_error(WebSocketClosedError(1008, "Try Again Later (EWS)"))
|
||||||
|
|
||||||
|
transport = FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
async def connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return transport
|
||||||
|
|
||||||
|
disconnected: list[ErrorCode] = []
|
||||||
|
client = SsapClient(
|
||||||
|
"wss://192.0.2.10:3001",
|
||||||
|
connect_fn=connect,
|
||||||
|
on_disconnect=disconnected.append,
|
||||||
|
)
|
||||||
|
await client.connect_and_register("k")
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await client.request("ssap://audio/getStatus")
|
||||||
|
assert exc_info.value.code is ErrorCode.TV_OFFLINE_STANDBY
|
||||||
|
await asyncio.sleep(0)
|
||||||
|
assert disconnected == [ErrorCode.TV_OFFLINE_STANDBY]
|
||||||
|
await client.close()
|
||||||
Reference in new issue
Block a user