led-controller-version-3-effect-creation 3.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,307 @@
1
+ """The controller the studio drives, and the output it is pointed at.
2
+
3
+ No Qt in here, on purpose. Everything the studio *does* — pick a device, load a
4
+ catalogue, run an effect, watch the frames come out — is separable from the
5
+ window that shows it, and keeping it separable is what makes it testable without
6
+ a display.
7
+
8
+ The studio embeds a real :class:`ControllerService` rather than talking to a
9
+ running one over HTTP. That is a deliberate choice with one consequence worth
10
+ knowing: it means the studio can render a definition that has not been packaged
11
+ yet, which is the only way to edit one and watch it at the same time. The price
12
+ is that the studio and a running service both want the same USB device, and only
13
+ one of them can have it — hence :func:`device_in_use`.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ import os
20
+ from pathlib import Path
21
+ from typing import Any, Callable, Mapping, Sequence
22
+
23
+ from lefx.interfaces import ControllerService, describe, discovery, hosting, paths
24
+ from lefx.sdk import FrameSink, OutputFrame, SinkStatus
25
+
26
+ from .project import Project
27
+
28
+ logger = logging.getLogger("lefx.effect_creation.studio.session")
29
+
30
+ FrameListener = Callable[[tuple[int, ...]], None]
31
+
32
+ NULL_OUTPUT = "null"
33
+ STUDIO_CHANNEL = "studio"
34
+ """The overlay channel the studio keeps its work on, so it can clear its own
35
+ without touching a channel something else is using."""
36
+
37
+
38
+ class TappedSink:
39
+ """Sends every frame to the chosen device and to whoever is watching.
40
+
41
+ The studio shows a ring of its own next to the controls, and that ring has
42
+ to be the frames the device is being sent — not a second rendering of the
43
+ same effect, which could agree with the first right up until the moment it
44
+ mattered. So the frames are taken from the one path that leads to the
45
+ device, on the way past.
46
+
47
+ Watching must not be able to break sending. A listener that raises is
48
+ reported and dropped from that frame; the device still gets it.
49
+ """
50
+
51
+ def __init__(self, inner: FrameSink, listener: FrameListener | None = None) -> None:
52
+ self.inner = inner
53
+ self.listener = listener
54
+ self.name = getattr(inner, "name", type(inner).__name__)
55
+ self.frame_count = 0
56
+
57
+ def apply_frame(self, frame: OutputFrame) -> None:
58
+ self.inner.apply_frame(frame)
59
+ self.frame_count += 1
60
+ listener = self.listener
61
+ if listener is None:
62
+ return
63
+ try:
64
+ listener(tuple(frame.leds))
65
+ except Exception:
66
+ logger.exception("frame listener failed")
67
+
68
+ def status(self) -> SinkStatus:
69
+ return self.inner.status()
70
+
71
+ def close(self) -> None:
72
+ self.inner.close()
73
+
74
+
75
+ def available_outputs() -> list[str]:
76
+ """Every output that could be chosen, the null one first.
77
+
78
+ Read from the installed entry points, exactly as the service reads them, so
79
+ the list is what is actually installed rather than what this file knows
80
+ about. A machine without the hardware package does not offer the hardware.
81
+ """
82
+ installed = [item["name"] for item in describe()["sinks"] if item["name"] != NULL_OUTPUT]
83
+ return [NULL_OUTPUT, *sorted(installed)]
84
+
85
+
86
+ def device_in_use() -> str | None:
87
+ """Whether a service is already running, and where, or ``None``.
88
+
89
+ Two processes cannot hold one reSpeaker. Discovering that by watching writes
90
+ fail is a poor way to find out, so the studio asks first and says what it
91
+ found — the instance file is exactly the running service's own claim.
92
+ """
93
+ info = hosting.read_instance(paths.instance_file())
94
+ if info is None or info.status == "stopping":
95
+ return None
96
+ if info.pid == os.getpid():
97
+ return None
98
+ if not _process_alive(info.pid):
99
+ return None
100
+ return f"a lefx service is running on {info.host}:{info.port} (pid {info.pid})"
101
+
102
+
103
+ WINDOWS_INVALID_PARAMETER = 87
104
+ """What Windows answers when asked about a pid that does not exist."""
105
+
106
+
107
+ def _process_alive(pid: int) -> bool:
108
+ """Whether the instance file describes something still running.
109
+
110
+ A service killed rather than stopped leaves its file behind, and refusing to
111
+ start because of a note from a process that no longer exists would be a
112
+ worse failure than the one being prevented.
113
+
114
+ The three outcomes are the same everywhere but spelled differently. POSIX
115
+ raises :class:`ProcessLookupError` for a pid that is gone; Windows raises a
116
+ plain :class:`OSError` carrying ``winerror`` 87, which is not distinguishable
117
+ from a real failure by type alone. Anything else that goes wrong is treated
118
+ as "alive", because refusing to open a device is the recoverable mistake and
119
+ taking one out from under a running service is not.
120
+ """
121
+ if pid <= 0:
122
+ return False
123
+ try:
124
+ os.kill(pid, 0)
125
+ except ProcessLookupError:
126
+ return False
127
+ except PermissionError:
128
+ # Someone else's process, but a process.
129
+ return True
130
+ except OSError as exc:
131
+ return getattr(exc, "winerror", None) != WINDOWS_INVALID_PARAMETER
132
+ return True
133
+
134
+
135
+ class StudioSession:
136
+ """One embedded controller, pointed at one output at a time."""
137
+
138
+ def __init__(
139
+ self,
140
+ *,
141
+ led_count: int = 12,
142
+ fps: float = 30.0,
143
+ search_paths: Sequence[str | Path] | None = None,
144
+ state_file: str | Path | None = None,
145
+ project: Project | None = None,
146
+ ) -> None:
147
+ self.led_count = int(led_count)
148
+ self.fps = float(fps)
149
+ # A project answers all of these at once. Explicit paths still win, so
150
+ # a test can hand over an empty search path without inventing a tree.
151
+ self.project = project
152
+ if project is not None:
153
+ search_paths = project.package_search_paths if search_paths is None else search_paths
154
+ state_file = project.state_file if state_file is None else state_file
155
+ self.search_paths = None if search_paths is None else list(search_paths)
156
+ # The studio is a workbench, not the installation. Leaving a background
157
+ # state behind from an evening of trying things out would surprise
158
+ # whoever started the real service next.
159
+ self.state_file = state_file
160
+ self.service: ControllerService | None = None
161
+ self.output_name = NULL_OUTPUT
162
+ self.device_options: dict[str, Any] = {}
163
+ self._listener: FrameListener | None = None
164
+
165
+ # -- the output ---------------------------------------------------------
166
+
167
+ def set_frame_listener(self, listener: FrameListener | None) -> None:
168
+ self._listener = listener
169
+ sink = None if self.service is None else self.service.sink
170
+ if isinstance(sink, TappedSink):
171
+ sink.listener = listener
172
+
173
+ def use(self, project: Project) -> None:
174
+ """Point the studio at a different checkout, reopening the output on it."""
175
+ self.project = project
176
+ self.search_paths = project.package_search_paths
177
+ self.state_file = project.state_file
178
+ if self.service is not None:
179
+ self.open(self.output_name, **self.device_options)
180
+
181
+ def open(self, output: str, **device_options: Any) -> ControllerService:
182
+ """Point the studio at an output, replacing whatever it had.
183
+
184
+ Closing first is not tidiness: the previous device is still holding a
185
+ USB endpoint or a listening socket, and building the next one before
186
+ letting go would have them contend for it.
187
+ """
188
+ self.close()
189
+
190
+ sink: FrameSink
191
+ if output == NULL_OUTPUT:
192
+ sink = discovery.NullSink()
193
+ else:
194
+ options = {"led_count": self.led_count, **device_options}
195
+ sink = discovery.create_sink(output, **options)
196
+
197
+ if self.project is not None:
198
+ # Providers read their calibration from a file; which file is a
199
+ # property of the project, not of the working directory.
200
+ device_options.setdefault("calibration_file", str(self.project.calibration_file))
201
+
202
+ service = ControllerService(
203
+ sink=TappedSink(sink, self._listener),
204
+ led_count=self.led_count,
205
+ fps=self.fps,
206
+ search_paths=self.search_paths,
207
+ state_file=self.state_file,
208
+ sink_options=device_options,
209
+ # The sink is handed over as an object, so the service cannot infer
210
+ # which device it is; name it, or the input providers of the chosen
211
+ # device would not be the ones started.
212
+ input_device=output,
213
+ )
214
+ service.start()
215
+
216
+ self.service = service
217
+ self.output_name = output
218
+ self.device_options = dict(device_options)
219
+ logger.info("studio output is now %s", output)
220
+ return service
221
+
222
+ def close(self) -> None:
223
+ if self.service is None:
224
+ return
225
+ try:
226
+ self.service.stop()
227
+ except Exception:
228
+ logger.exception("stopping the studio service failed")
229
+ self.service = None
230
+
231
+ def __enter__(self) -> "StudioSession":
232
+ return self
233
+
234
+ def __exit__(self, *exc: object) -> None:
235
+ self.close()
236
+
237
+ # -- what is loaded -----------------------------------------------------
238
+
239
+ @property
240
+ def registry(self):
241
+ if self.service is None:
242
+ raise RuntimeError("no output is open")
243
+ return self.service.library.registry
244
+
245
+ def reload_sources(self) -> dict[str, Any]:
246
+ if self.service is None:
247
+ raise RuntimeError("no output is open")
248
+ return self.service.reload_sources()
249
+
250
+ def status(self) -> dict[str, Any]:
251
+ return {} if self.service is None else self.service.status()
252
+
253
+ def sink_status(self) -> SinkStatus:
254
+ if self.service is None:
255
+ return SinkStatus(available=False, detail="no output is open")
256
+ return self.service.sink.status()
257
+
258
+ # -- driving ------------------------------------------------------------
259
+
260
+ def play_state(self, effect_id: str, config: Mapping[str, Any]) -> dict[str, Any]:
261
+ return self._require().set_state(effect_id, dict(config))
262
+
263
+ def play_overlay(
264
+ self,
265
+ effect_id: str,
266
+ config: Mapping[str, Any],
267
+ inputs: Mapping[str, Any] | None = None,
268
+ *,
269
+ channel: str | None = STUDIO_CHANNEL,
270
+ ) -> dict[str, Any]:
271
+ return self._require().set_overlay(
272
+ effect_id, channel=channel, config=dict(config), inputs=dict(inputs or {})
273
+ )
274
+
275
+ def update_inputs(
276
+ self, inputs: Mapping[str, Any], *, channel: str = STUDIO_CHANNEL
277
+ ) -> dict[str, Any]:
278
+ return self._require().update_overlay(channel, dict(inputs))
279
+
280
+ def emit(self, effect_id: str, config: Mapping[str, Any], **extra: Any) -> dict[str, Any]:
281
+ return self._require().emit_event(effect_id, dict(config), **extra)
282
+
283
+ def clear_overlay(self, *, channel: str = STUDIO_CHANNEL) -> dict[str, Any]:
284
+ return self._require().clear_overlay(channel)
285
+
286
+ def clear_everything(self) -> dict[str, Any]:
287
+ return self._require().clear_all()
288
+
289
+ def set_output(self, **settings: Any) -> dict[str, Any]:
290
+ return self._require().set_output(**settings)
291
+
292
+ def _require(self) -> ControllerService:
293
+ if self.service is None:
294
+ raise RuntimeError("no output is open")
295
+ return self.service
296
+
297
+
298
+ __all__ = [
299
+ "NULL_OUTPUT",
300
+ "STUDIO_CHANNEL",
301
+ "FrameListener",
302
+ "Project",
303
+ "StudioSession",
304
+ "TappedSink",
305
+ "available_outputs",
306
+ "device_in_use",
307
+ ]