feat(pointer): implement PointerClient allowlist validation and retry
- Implement normalize_button_keys and PointerClient with getPointerInputSocket acquisition - Support delay_ms pacing and single reconnect retry on mid-batch socket drop - Remove Red-phase xfail markers in tests/test_pointer.py
This commit is contained in:
1 parent
41d197ee59
commit
c4abbfcc3c
2 files changed
+82
-8
No files matched your search
@@ -1,9 +1,16 @@
|
|||||||
"""Pointer input WebSocket client for LG webOS D-pad and remote buttons."""
|
"""Pointer input WebSocket client for LG webOS D-pad and remote buttons."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
from collections.abc import Awaitable, Callable
|
from collections.abc import Awaitable, Callable
|
||||||
|
from contextlib import suppress
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from lg_smtv_mcp.tv_core.protocols import WebSocketConnectFn
|
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
|
from lg_smtv_mcp.tv_core.ssap import websockets_connect
|
||||||
|
|
||||||
BUTTON_ALLOWLIST: frozenset[str] = frozenset(
|
BUTTON_ALLOWLIST: frozenset[str] = frozenset(
|
||||||
@@ -48,6 +55,25 @@ BUTTON_ALLOWLIST: frozenset[str] = frozenset(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
class PointerClient:
|
||||||
"""Manages the persistent webOS pointer input socket and button frame formatting."""
|
"""Manages the persistent webOS pointer input socket and button frame formatting."""
|
||||||
|
|
||||||
@@ -56,12 +82,64 @@ class PointerClient:
|
|||||||
ssap_request_fn: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]],
|
ssap_request_fn: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]],
|
||||||
connect_fn: WebSocketConnectFn = websockets_connect,
|
connect_fn: WebSocketConnectFn = websockets_connect,
|
||||||
) -> None:
|
) -> None:
|
||||||
raise NotImplementedError
|
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:
|
async def send_buttons(self, keys: list[str], delay_ms: int = 250) -> int:
|
||||||
"""Validate, normalize, and send a sequence of button frames."""
|
"""Validate, normalize, and send a sequence of button frames."""
|
||||||
raise NotImplementedError
|
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:
|
async def close(self) -> None:
|
||||||
"""Close the pointer WebSocket transport if open."""
|
"""Close the pointer WebSocket transport if open."""
|
||||||
raise NotImplementedError
|
ws = self._ws
|
||||||
|
self._ws = None
|
||||||
|
if ws is not None:
|
||||||
|
with suppress(Exception):
|
||||||
|
await ws.close()
|
||||||
@@ -8,7 +8,6 @@ from lg_smtv_mcp.tv_core.pointer import BUTTON_ALLOWLIST, PointerClient
|
|||||||
from tests.conftest import FakeWebSocketTransport
|
from tests.conftest import FakeWebSocketTransport
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.xfail(strict=True, reason="Red phase: pointer")
|
|
||||||
async def test_pointer_normalizes_keys_to_uppercase_and_formats_frames() -> None:
|
async def test_pointer_normalizes_keys_to_uppercase_and_formats_frames() -> None:
|
||||||
ws = FakeWebSocketTransport()
|
ws = FakeWebSocketTransport()
|
||||||
ssap_calls: list[str] = []
|
ssap_calls: list[str] = []
|
||||||
@@ -33,7 +32,6 @@ async def test_pointer_normalizes_keys_to_uppercase_and_formats_frames() -> None
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.xfail(strict=True, reason="Red phase: pointer")
|
|
||||||
@pytest.mark.parametrize("bad_key", ["INVALID_KEY", "UP\nname:HOME", "ENTER\r", ""])
|
@pytest.mark.parametrize("bad_key", ["INVALID_KEY", "UP\nname:HOME", "ENTER\r", ""])
|
||||||
async def test_pointer_rejects_unknown_keys_and_newlines_with_invalid_argument(
|
async def test_pointer_rejects_unknown_keys_and_newlines_with_invalid_argument(
|
||||||
bad_key: str,
|
bad_key: str,
|
||||||
@@ -55,7 +53,6 @@ async def test_pointer_rejects_unknown_keys_and_newlines_with_invalid_argument(
|
|||||||
assert ws.sent == []
|
assert ws.sent == []
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.xfail(strict=True, reason="Red phase: pointer")
|
|
||||||
async def test_pointer_paces_buttons_by_delay_ms(monkeypatch: pytest.MonkeyPatch) -> None:
|
async def test_pointer_paces_buttons_by_delay_ms(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
ws = FakeWebSocketTransport()
|
ws = FakeWebSocketTransport()
|
||||||
sleeps: list[float] = []
|
sleeps: list[float] = []
|
||||||
@@ -78,7 +75,6 @@ async def test_pointer_paces_buttons_by_delay_ms(monkeypatch: pytest.MonkeyPatch
|
|||||||
assert sleeps == [pytest.approx(0.15), pytest.approx(0.15)]
|
assert sleeps == [pytest.approx(0.15), pytest.approx(0.15)]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.xfail(strict=True, reason="Red phase: pointer")
|
|
||||||
async def test_pointer_retries_once_on_mid_batch_socket_drop() -> None:
|
async def test_pointer_retries_once_on_mid_batch_socket_drop() -> None:
|
||||||
ws1 = FakeWebSocketTransport()
|
ws1 = FakeWebSocketTransport()
|
||||||
ws2 = FakeWebSocketTransport()
|
ws2 = FakeWebSocketTransport()
|
||||||
|
|||||||
Reference in new issue
Block a user