|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import threading |
| 4 | +from abc import ABC, abstractmethod |
| 5 | +from logging import getLogger |
| 6 | +from queue import Queue |
| 7 | +from typing import TYPE_CHECKING |
| 8 | + |
| 9 | + |
| 10 | +if TYPE_CHECKING: |
| 11 | + from collections.abc import Generator |
| 12 | + from typing import Any, ClassVar |
| 13 | + |
| 14 | + from typing_extensions import TypeIs |
| 15 | + |
| 16 | + from streamdeck.models.events import EventBase |
| 17 | + |
| 18 | + |
| 19 | + |
| 20 | +logger = getLogger("streamdeck.event_listener") |
| 21 | + |
| 22 | + |
| 23 | +class _SENTINAL: |
| 24 | + """A sentinel object used to signal the end of the event stream. |
| 25 | +
|
| 26 | + Not meant to be instantiated, but rather used as a singleton (e.g. `_SENTINAL`). |
| 27 | + """ |
| 28 | + @classmethod |
| 29 | + def is_sentinal(cls, event: str | bytes | type[_SENTINAL]) -> TypeIs[type[_SENTINAL]]: |
| 30 | + """Check if an event is the sentinal object. Provided to enable better type-checking.""" |
| 31 | + return event is cls |
| 32 | + |
| 33 | + |
| 34 | +class StopStreaming(Exception): # noqa: N818 |
| 35 | + """Raised by an EventListener implementation to signal that the entire EventManagerListener should stop streaming events.""" |
| 36 | + |
| 37 | + |
| 38 | +class EventListenerManager: |
| 39 | + """Manages event listeners and provides a shared event queue for them to push events into. |
| 40 | +
|
| 41 | + With this class, a single event stream can be created from multiple listeners. |
| 42 | + This allows for us to listen for not only Stream Deck events, but also other events plugin-developer -defined events. |
| 43 | + """ |
| 44 | + def __init__(self) -> None: |
| 45 | + self.event_queue: Queue[str | bytes | type[_SENTINAL]] = Queue() |
| 46 | + self.listeners_lookup_by_thread: dict[threading.Thread, EventListener] = {} |
| 47 | + self._running = False |
| 48 | + |
| 49 | + def add_listener(self, listener: EventListener) -> None: |
| 50 | + """Registers a listener function that yields events. |
| 51 | +
|
| 52 | + Args: |
| 53 | + listener: A function that yields events. |
| 54 | + """ |
| 55 | + # Create a thread for the listener |
| 56 | + thread = threading.Thread( |
| 57 | + target=self._listener_wrapper, |
| 58 | + args=(listener,), |
| 59 | + daemon=True, |
| 60 | + ) |
| 61 | + self.listeners_lookup_by_thread[thread] = listener |
| 62 | + |
| 63 | + def _listener_wrapper(self, listener: EventListener) -> None: |
| 64 | + """Wraps the listener function: for each event yielded, push it into the shared queue.""" |
| 65 | + try: |
| 66 | + for event in listener.listen(): |
| 67 | + self.event_queue.put(event) |
| 68 | + |
| 69 | + if not self.running: |
| 70 | + break |
| 71 | + |
| 72 | + except StopStreaming: |
| 73 | + logger.debug("Event listener requested to stop streaming.") |
| 74 | + self.event_queue.put(_SENTINAL) |
| 75 | + |
| 76 | + except Exception: |
| 77 | + logger.exception("Unexpected error in wrapped listener %s. Stopping just this listener.", listener) |
| 78 | + |
| 79 | + def stop(self) -> None: |
| 80 | + """Stops the event generation loop and waits for all threads to finish. |
| 81 | +
|
| 82 | + Listeners will check the running flag if implemented to stop listening. |
| 83 | + """ |
| 84 | + # Set the running flag to False to stop the listeners running in separate threads. |
| 85 | + self.running = False |
| 86 | + # Push the sentinel to immediately unblock the queue.get() in event_stream. |
| 87 | + self.event_queue.put(_SENTINAL) |
| 88 | + |
| 89 | + for thread in self.listeners_lookup_by_thread: |
| 90 | + logger.debug("Stopping listener %s.") |
| 91 | + self.listeners_lookup_by_thread[thread].stop() |
| 92 | + if thread.is_alive(): |
| 93 | + thread.join() |
| 94 | + |
| 95 | + logger.info("All listeners have been stopped.") |
| 96 | + |
| 97 | + def event_stream(self) -> Generator[str | bytes, None, None]: |
| 98 | + """Starts all registered listeners, sets the running flag to True, and yields events from the shared queue.""" |
| 99 | + logger.info("Starting event stream.") |
| 100 | + # Set the running flag to True and start the listeners in their separate threads. |
| 101 | + self.running = True |
| 102 | + for thread in self.listeners_lookup_by_thread: |
| 103 | + thread.start() |
| 104 | + |
| 105 | + try: |
| 106 | + while True: |
| 107 | + event = self.event_queue.get() |
| 108 | + if _SENTINAL.is_sentinal(event): |
| 109 | + logger.debug("Sentinal received, stopping event stream.") |
| 110 | + break # Exit loop immediately if the sentinal is received |
| 111 | + yield event |
| 112 | + finally: |
| 113 | + self.stop() |
| 114 | + |
| 115 | + |
| 116 | +class EventListener(ABC): |
| 117 | + """Base class for event listeners. |
| 118 | +
|
| 119 | + Event listeners are classes that listen for events and simply yield them as they come. |
| 120 | + The EventListenerManager will handle the threading and pushing the events yielded into a shared queue. |
| 121 | + """ |
| 122 | + event_models: ClassVar[list[type[EventBase]]] |
| 123 | + """A list of event models that the listener can yield. Read in by the PluginManager to model the incoming event data off of. |
| 124 | +
|
| 125 | + The plugin-developer must define this list in their subclass. |
| 126 | + """ |
| 127 | + |
| 128 | + @abstractmethod |
| 129 | + def listen(self) -> Generator[str | bytes, Any, None]: |
| 130 | + """Start listening for events and yield them as they come. |
| 131 | +
|
| 132 | + This is the method that run in a separate thread. |
| 133 | + """ |
| 134 | + |
| 135 | + @abstractmethod |
| 136 | + def stop(self) -> None: |
| 137 | + """Stop the listener. This could set an internal flag, close a connection, etc.""" |
0 commit comments