Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 95 additions & 20 deletions streamdeck/command_sender.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
from __future__ import annotations

from logging import getLogger
from typing import TYPE_CHECKING, Protocol
from typing import TYPE_CHECKING, overload

from streamdeck.models.events.settings import DidReceiveGlobalSettings, DidReceiveSettings


if TYPE_CHECKING:
from collections.abc import Awaitable
from typing import Any, Literal

from pydantic import JsonValue

from streamdeck.request_broker import RequestBroker
from streamdeck.types import (
ActionInstanceUUIDStr,
ActionUUIDStr,
Expand All @@ -19,25 +21,18 @@
)



logger = getLogger("streamdeck.command_sender")


class AsyncEventSender(Protocol):
"""Narrow async capability required by the command sender."""

def send_event(self, data: dict[str, JsonValue]) -> Awaitable[None]: ...


class StreamDeckCommandSender:
"""Class for sending command event messages to the Stream Deck software through a WebSocket client."""
"""Send Stream Deck commands and await correlated response events."""

def __init__(self, client: AsyncEventSender, plugin_registration_uuid: str):
self._client = client
def __init__(self, request_broker: RequestBroker, plugin_registration_uuid: str):
self._request_broker = request_broker
self._plugin_registration_uuid = plugin_registration_uuid

async def _send_event(self, event: EventNameStr, **kwargs: Any) -> None:
await self._client.send_event({
await self._request_broker.send_event({
"event": event,
**kwargs,
})
Expand All @@ -49,10 +44,49 @@ async def set_settings(self, context: ActionInstanceUUIDStr, payload: PluginDefi
payload=payload,
)

async def get_settings(self, context: ActionInstanceUUIDStr) -> None:
await self._send_event(
event="getSettings",
@overload
async def get_settings(
self,
context: ActionInstanceUUIDStr,
*,
wait_for_response: Literal[True],
timeout: float | None = 5.0,
) -> DidReceiveSettings: ...

@overload
async def get_settings(
self,
context: ActionInstanceUUIDStr,
*,
wait_for_response: Literal[False] = False,
timeout: float | None = 5.0,
) -> None: ...

@overload
async def get_settings(
self,
context: ActionInstanceUUIDStr,
*,
wait_for_response: bool,
timeout: float | None = 5.0,
) -> DidReceiveSettings | None: ...

async def get_settings(
self,
context: ActionInstanceUUIDStr,
*,
wait_for_response: bool = False,
timeout: float | None = 5.0,
) -> DidReceiveSettings | None:
if not wait_for_response:
await self._send_event("getSettings", context=context)
return None

return await self._request_broker.request(
response_type=DidReceiveSettings,
context=context,
timeout=timeout,
command={"event": "getSettings", "context": context},
)

async def set_global_settings(self, payload: PluginDefinedData) -> None:
Expand All @@ -62,10 +96,51 @@ async def set_global_settings(self, payload: PluginDefinedData) -> None:
payload=payload,
)

async def get_global_settings(self) -> None:
await self._send_event(
event="getGlobalSettings",
context=self._plugin_registration_uuid,
@overload
async def get_global_settings(
self,
*,
wait_for_response: Literal[True],
timeout: float | None = 5.0,
) -> DidReceiveGlobalSettings: ...

@overload
async def get_global_settings(
self,
*,
wait_for_response: Literal[False] = False,
timeout: float | None = 5.0,
) -> None: ...

@overload
async def get_global_settings(
self,
*,
wait_for_response: bool,
timeout: float | None = 5.0,
) -> DidReceiveGlobalSettings | None: ...

async def get_global_settings(
self,
*,
wait_for_response: bool = False,
timeout: float | None = 5.0,
) -> DidReceiveGlobalSettings | None:
if not wait_for_response:
await self._send_event(
"getGlobalSettings",
context=self._plugin_registration_uuid,
)
return None

return await self._request_broker.request(
response_type=DidReceiveGlobalSettings,
context=None,
timeout=timeout,
command={
"event": "getGlobalSettings",
"context": self._plugin_registration_uuid,
},
)

async def open_url(self, context: ActionInstanceUUIDStr, url: str) -> None:
Expand Down
29 changes: 22 additions & 7 deletions streamdeck/event_stream_processor.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Process a stream of validated events with sequential dispatch."""
"""Route validated events to request waiters and sequential handlers."""

from __future__ import annotations

Expand All @@ -21,29 +21,44 @@
if TYPE_CHECKING:
from collections.abc import AsyncGenerator, Awaitable, Callable

from streamdeck.request_broker import RequestBroker


_END_DISPATCH = sentinel("_END_DISPATCH")


class EventStreamProcessor:
"""Read events concurrently with sequential dispatch."""
"""Coordinate response routing and sequential event dispatch."""

def __init__(
self,
request_broker: RequestBroker,
dispatch: Callable[[EventBase], Awaitable[None]],
) -> None:
self._request_broker = request_broker
self._dispatch = dispatch

async def _route_events(
self,
events: AsyncGenerator[EventBase, None],
dispatch_queue: asyncio.Queue[object],
) -> None:
"""Queue validated events in stream order."""
async with aclosing(events):
async for event in events:
await dispatch_queue.put(event)
await dispatch_queue.put(_END_DISPATCH)
"""Resolve response waiters, then queue events for normal dispatch."""
try:
async with aclosing(events):
async for event in events:
self._request_broker.resolve(event)
await dispatch_queue.put(event)
except asyncio.CancelledError:
raise
except Exception as exc:
self._request_broker.fail_all(exc)
raise
else:
self._request_broker.fail_all(
RuntimeError("The event stream ended before the request completed.")
)
await dispatch_queue.put(_END_DISPATCH)

async def _dispatch_events(self, dispatch_queue: asyncio.Queue[object]) -> None:
"""Dispatch queued events one at a time, awaiting each handler."""
Expand Down
8 changes: 7 additions & 1 deletion streamdeck/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from streamdeck.event_stream_processor import EventStreamProcessor
from streamdeck.models.events.adapter import EventAdapter
from streamdeck.models.events.common import ActionInstanceEventMixin
from streamdeck.request_broker import RequestBroker
from streamdeck.utils.logging import configure_streamdeck_logger
from streamdeck.websocket import WebSocketEventListener, WebSocketTransport

Expand Down Expand Up @@ -189,7 +190,8 @@ async def run(self) -> None:
ExceptionGroup: If event processing or runtime cleanup fails.
"""
transport = WebSocketTransport(port=self._port)
command_sender = StreamDeckCommandSender(transport, plugin_registration_uuid=self._registration_uuid)
request_broker = RequestBroker(transport)
command_sender = StreamDeckCommandSender(request_broker, plugin_registration_uuid=self._registration_uuid)
self._injectable_handler_param_store.register(
"command_sender",
lambda _event_data: command_sender,
Expand All @@ -206,6 +208,7 @@ async def run(self) -> None:
await command_sender.send_action_registration(register_event=self._register_event)

await EventStreamProcessor(
request_broker=request_broker,
dispatch=self._dispatch_event,
).run(self._stream_event_data())

Expand All @@ -214,6 +217,9 @@ async def run(self) -> None:
primary_error = exc
raise
finally:
request_broker.fail_all(
RuntimeError("The plugin runtime stopped before the request completed.")
)
try:
await self._event_listener_manager.stop()
except BaseException as cleanup_error:
Expand Down
7 changes: 7 additions & 0 deletions streamdeck/models/events/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ class DeviceSpecificEventMixin:
"""Unique identifier of the Stream Deck device that this event is associated with."""


class RequestCorrelationMixin:
"""Mixin for response events that may include the originating request ID."""

id: str | None = None
"""Request identifier, absent for unsolicited updates."""


## Payload models and metadata used by multiple event models.

EncoderControllerType = Literal["Encoder"]
Expand Down
5 changes: 3 additions & 2 deletions streamdeck/models/events/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
DeviceSpecificEventMixin,
KeypadControllerType,
MultiActionPayloadMixin,
RequestCorrelationMixin,
SettingsPayloadMixin,
SingleActionPayloadMixin,
StatefulActionPayloadMixin,
Expand Down Expand Up @@ -40,7 +41,7 @@ class MultiActionSettingsPayload(
"""


class DidReceiveSettings(EventBase[Literal["didReceiveSettings"]], ActionInstancePayloadEventMixin[CardinalityDiscriminated[SingleActionSettingsPayload, MultiActionSettingsPayload]], DeviceSpecificEventMixin): # fmt: skip
class DidReceiveSettings(EventBase[Literal["didReceiveSettings"]], RequestCorrelationMixin, ActionInstancePayloadEventMixin[CardinalityDiscriminated[SingleActionSettingsPayload, MultiActionSettingsPayload]], DeviceSpecificEventMixin): # fmt: skip
"""Occurs when the settings associated with an action instance are requested, or when the the settings were updated by the property inspector."""

payload: CardinalityDiscriminated[SingleActionSettingsPayload, MultiActionSettingsPayload]
Expand All @@ -54,7 +55,7 @@ class GlobalSettingsPayload(ConfiguredBaseModel, SettingsPayloadMixin):
"""Additional information about the didReceiveGlobalSettings event that occurred."""


class DidReceiveGlobalSettings(EventBase[Literal["didReceiveGlobalSettings"]]):
class DidReceiveGlobalSettings(EventBase[Literal["didReceiveGlobalSettings"]], RequestCorrelationMixin):
"""Occurs when the plugin receives the global settings from the Stream Deck."""

payload: GlobalSettingsPayload
Expand Down
Loading