led-controller-version-3 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.
- led_controller_version_3-3.0.2.dist-info/METADATA +172 -0
- led_controller_version_3-3.0.2.dist-info/RECORD +52 -0
- led_controller_version_3-3.0.2.dist-info/WHEEL +4 -0
- led_controller_version_3-3.0.2.dist-info/entry_points.txt +13 -0
- lefx/device/respeaker/__init__.py +35 -0
- lefx/device/respeaker/cli.py +146 -0
- lefx/device/respeaker/contention.py +523 -0
- lefx/device/respeaker/provider.py +158 -0
- lefx/device/respeaker/registration.py +130 -0
- lefx/device/respeaker/sink.py +108 -0
- lefx/device/respeaker/transport.py +344 -0
- lefx/device/respeaker/xvf.py +313 -0
- lefx/engine/__init__.py +110 -0
- lefx/engine/composer.py +203 -0
- lefx/engine/config.py +27 -0
- lefx/engine/errors.py +84 -0
- lefx/engine/inputs.py +196 -0
- lefx/engine/invocation.py +129 -0
- lefx/engine/layers.py +114 -0
- lefx/engine/library.py +181 -0
- lefx/engine/packages/__init__.py +45 -0
- lefx/engine/packages/loader.py +375 -0
- lefx/engine/packages/manifest.py +308 -0
- lefx/engine/registry.py +347 -0
- lefx/engine/renderer.py +63 -0
- lefx/engine/runtime.py +393 -0
- lefx/engine/store.py +125 -0
- lefx/interfaces/__init__.py +40 -0
- lefx/interfaces/api.py +301 -0
- lefx/interfaces/cli.py +380 -0
- lefx/interfaces/client.py +165 -0
- lefx/interfaces/config.py +305 -0
- lefx/interfaces/discovery.py +308 -0
- lefx/interfaces/hosting.py +123 -0
- lefx/interfaces/paths.py +79 -0
- lefx/interfaces/presentation.py +118 -0
- lefx/interfaces/service.py +468 -0
- lefx/sdk/__init__.py +176 -0
- lefx/sdk/calibration.py +202 -0
- lefx/sdk/color.py +108 -0
- lefx/sdk/context.py +72 -0
- lefx/sdk/definitions.py +526 -0
- lefx/sdk/effects.py +63 -0
- lefx/sdk/errors.py +90 -0
- lefx/sdk/parameters.py +469 -0
- lefx/sdk/ports.py +76 -0
- lefx/sdk/validation.py +150 -0
- lefx/sdk/values.py +212 -0
- lefx/sets/core_set/__init__.py +32 -0
- lefx/sets/core_set/core-set.lefxset +0 -0
- lefx/sets/smartspeaker_set/__init__.py +32 -0
- lefx/sets/smartspeaker_set/smartspeaker-set.lefxset +0 -0
lefx/interfaces/api.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
"""The HTTP control surface.
|
|
2
|
+
|
|
3
|
+
Only ``/api/v3``. There is no compatibility route: an older client gets a clear
|
|
4
|
+
404 rather than a shape that silently means something else now.
|
|
5
|
+
|
|
6
|
+
Every endpoint is a thin call into the service. Validation errors come back as
|
|
7
|
+
422 with the field paths the SDK produced, so a caller learns which field was
|
|
8
|
+
wrong and what was suggested instead.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import threading
|
|
14
|
+
from contextlib import asynccontextmanager
|
|
15
|
+
from typing import Any, Callable, Literal
|
|
16
|
+
|
|
17
|
+
from fastapi import FastAPI, HTTPException, Request
|
|
18
|
+
from fastapi.responses import JSONResponse
|
|
19
|
+
from pydantic import BaseModel, Field
|
|
20
|
+
|
|
21
|
+
from lefx.engine import (
|
|
22
|
+
AmbiguousTargetError,
|
|
23
|
+
ChannelNotFoundError,
|
|
24
|
+
CommandError,
|
|
25
|
+
PackageError,
|
|
26
|
+
TargetNotFoundError,
|
|
27
|
+
)
|
|
28
|
+
from lefx.sdk import DefinitionType, ParameterValidationError
|
|
29
|
+
|
|
30
|
+
from .service import ControllerService
|
|
31
|
+
|
|
32
|
+
API_PREFIX = "/api/v3"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class SetStateRequest(BaseModel):
|
|
36
|
+
target: str
|
|
37
|
+
config: dict[str, Any] = Field(default_factory=dict)
|
|
38
|
+
slot: Literal["primary", "background"] = "primary"
|
|
39
|
+
action: Literal["on", "off", "toggle"] = "on"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ClearStateRequest(BaseModel):
|
|
43
|
+
slot: Literal["primary", "background"] = "primary"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class SetOverlayRequest(BaseModel):
|
|
47
|
+
target: str
|
|
48
|
+
channel: str | None = None
|
|
49
|
+
config: dict[str, Any] = Field(default_factory=dict)
|
|
50
|
+
inputs: dict[str, Any] = Field(default_factory=dict)
|
|
51
|
+
action: Literal["on", "off", "toggle"] = "on"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class UpdateOverlayRequest(BaseModel):
|
|
55
|
+
channel: str
|
|
56
|
+
inputs: dict[str, Any] = Field(default_factory=dict)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class ClearOverlayRequest(BaseModel):
|
|
60
|
+
channel: str
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class EmitEventRequest(BaseModel):
|
|
64
|
+
target: str
|
|
65
|
+
config: dict[str, Any] = Field(default_factory=dict)
|
|
66
|
+
priority: int | None = None
|
|
67
|
+
duration_ms: int | None = None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class OutputRequest(BaseModel):
|
|
71
|
+
brightness: float | None = None
|
|
72
|
+
enabled: bool | None = None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class RegisterSourceRequest(BaseModel):
|
|
76
|
+
path: str
|
|
77
|
+
enabled: bool = True
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def create_app(
|
|
81
|
+
service: ControllerService | None = None,
|
|
82
|
+
*,
|
|
83
|
+
lifecycle_callback: Callable[[str], None] | None = None,
|
|
84
|
+
**service_options: Any,
|
|
85
|
+
) -> FastAPI:
|
|
86
|
+
controller = service if service is not None else ControllerService(**service_options)
|
|
87
|
+
|
|
88
|
+
@asynccontextmanager
|
|
89
|
+
async def lifespan(app: FastAPI):
|
|
90
|
+
controller.start()
|
|
91
|
+
if lifecycle_callback is not None:
|
|
92
|
+
lifecycle_callback("started")
|
|
93
|
+
try:
|
|
94
|
+
yield
|
|
95
|
+
finally:
|
|
96
|
+
if lifecycle_callback is not None:
|
|
97
|
+
lifecycle_callback("stopping")
|
|
98
|
+
controller.stop()
|
|
99
|
+
|
|
100
|
+
app = FastAPI(
|
|
101
|
+
title="LEFX Controller API",
|
|
102
|
+
version="3.0.0",
|
|
103
|
+
summary="Control surface for the LEFX V3 effect engine",
|
|
104
|
+
lifespan=lifespan,
|
|
105
|
+
)
|
|
106
|
+
app.state.service = controller
|
|
107
|
+
app.state.shutdown_server = None
|
|
108
|
+
|
|
109
|
+
def get(request: Request) -> ControllerService:
|
|
110
|
+
return request.app.state.service
|
|
111
|
+
|
|
112
|
+
# -- error translation --------------------------------------------------
|
|
113
|
+
|
|
114
|
+
@app.exception_handler(ParameterValidationError)
|
|
115
|
+
async def _validation(request: Request, exc: ParameterValidationError):
|
|
116
|
+
del request
|
|
117
|
+
return JSONResponse(status_code=422, content={"detail": exc.to_dict()})
|
|
118
|
+
|
|
119
|
+
@app.exception_handler(TargetNotFoundError)
|
|
120
|
+
async def _not_found(request: Request, exc: TargetNotFoundError):
|
|
121
|
+
del request
|
|
122
|
+
return JSONResponse(
|
|
123
|
+
status_code=404,
|
|
124
|
+
content={
|
|
125
|
+
"detail": {
|
|
126
|
+
"code": "target_not_found",
|
|
127
|
+
"message": str(exc),
|
|
128
|
+
"target": exc.target,
|
|
129
|
+
"suggestions": list(exc.suggestions),
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
@app.exception_handler(ChannelNotFoundError)
|
|
135
|
+
async def _channel(request: Request, exc: ChannelNotFoundError):
|
|
136
|
+
del request
|
|
137
|
+
return JSONResponse(
|
|
138
|
+
status_code=404,
|
|
139
|
+
content={
|
|
140
|
+
"detail": {
|
|
141
|
+
"code": "channel_not_found",
|
|
142
|
+
"message": str(exc),
|
|
143
|
+
"channel": exc.channel,
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
@app.exception_handler(AmbiguousTargetError)
|
|
149
|
+
async def _ambiguous(request: Request, exc: AmbiguousTargetError):
|
|
150
|
+
del request
|
|
151
|
+
return JSONResponse(
|
|
152
|
+
status_code=409,
|
|
153
|
+
content={
|
|
154
|
+
"detail": {
|
|
155
|
+
"code": "ambiguous_target",
|
|
156
|
+
"message": str(exc),
|
|
157
|
+
"matches": list(exc.matches),
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
@app.exception_handler(CommandError)
|
|
163
|
+
async def _command(request: Request, exc: CommandError):
|
|
164
|
+
del request
|
|
165
|
+
return JSONResponse(
|
|
166
|
+
status_code=422, content={"detail": {"code": "invalid_command", "message": str(exc)}}
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
@app.exception_handler(PackageError)
|
|
170
|
+
async def _package(request: Request, exc: PackageError):
|
|
171
|
+
del request
|
|
172
|
+
return JSONResponse(
|
|
173
|
+
status_code=422, content={"detail": {"code": "invalid_package", "message": str(exc)}}
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
# -- meta ---------------------------------------------------------------
|
|
177
|
+
|
|
178
|
+
@app.get("/")
|
|
179
|
+
def root(request: Request):
|
|
180
|
+
controller = get(request)
|
|
181
|
+
return {
|
|
182
|
+
"service": "LEFX Controller API",
|
|
183
|
+
"version": app.version,
|
|
184
|
+
"api_base": API_PREFIX,
|
|
185
|
+
"docs": "/docs",
|
|
186
|
+
"health": "/health",
|
|
187
|
+
"sink": controller.sink_name,
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
@app.get("/health")
|
|
191
|
+
def health(request: Request):
|
|
192
|
+
return get(request).health()
|
|
193
|
+
|
|
194
|
+
@app.get(f"{API_PREFIX}/status")
|
|
195
|
+
def status(request: Request):
|
|
196
|
+
return get(request).status()
|
|
197
|
+
|
|
198
|
+
# -- listings -----------------------------------------------------------
|
|
199
|
+
|
|
200
|
+
@app.get(f"{API_PREFIX}/states")
|
|
201
|
+
def states(request: Request, details: bool = False):
|
|
202
|
+
return get(request).list_definitions(DefinitionType.STATE, details=details)
|
|
203
|
+
|
|
204
|
+
@app.get(f"{API_PREFIX}/overlays")
|
|
205
|
+
def overlays(request: Request, details: bool = False):
|
|
206
|
+
return get(request).list_definitions(DefinitionType.OVERLAY, details=details)
|
|
207
|
+
|
|
208
|
+
@app.get(f"{API_PREFIX}/events")
|
|
209
|
+
def events(request: Request, details: bool = False):
|
|
210
|
+
return get(request).list_definitions(DefinitionType.EVENT, details=details)
|
|
211
|
+
|
|
212
|
+
@app.get(f"{API_PREFIX}/presets")
|
|
213
|
+
def presets(
|
|
214
|
+
request: Request,
|
|
215
|
+
type: Literal["state", "overlay", "event"] | None = None,
|
|
216
|
+
details: bool = False,
|
|
217
|
+
):
|
|
218
|
+
wanted = None if type is None else DefinitionType(type)
|
|
219
|
+
return get(request).list_presets(wanted, details=details)
|
|
220
|
+
|
|
221
|
+
@app.get(f"{API_PREFIX}/show/{{target:path}}")
|
|
222
|
+
def show(target: str, request: Request):
|
|
223
|
+
return get(request).show(target)
|
|
224
|
+
|
|
225
|
+
# -- commands -----------------------------------------------------------
|
|
226
|
+
|
|
227
|
+
@app.post(f"{API_PREFIX}/set/state")
|
|
228
|
+
def set_state(payload: SetStateRequest, request: Request):
|
|
229
|
+
return get(request).set_state(
|
|
230
|
+
payload.target, payload.config, slot=payload.slot, action=payload.action
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
@app.post(f"{API_PREFIX}/clear/state")
|
|
234
|
+
def clear_state(payload: ClearStateRequest, request: Request):
|
|
235
|
+
return get(request).clear_state(slot=payload.slot)
|
|
236
|
+
|
|
237
|
+
@app.post(f"{API_PREFIX}/set/overlay")
|
|
238
|
+
def set_overlay(payload: SetOverlayRequest, request: Request):
|
|
239
|
+
return get(request).set_overlay(
|
|
240
|
+
payload.target,
|
|
241
|
+
channel=payload.channel,
|
|
242
|
+
config=payload.config,
|
|
243
|
+
inputs=payload.inputs,
|
|
244
|
+
action=payload.action,
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
@app.post(f"{API_PREFIX}/update/overlay")
|
|
248
|
+
def update_overlay(payload: UpdateOverlayRequest, request: Request):
|
|
249
|
+
return get(request).update_overlay(payload.channel, payload.inputs)
|
|
250
|
+
|
|
251
|
+
@app.post(f"{API_PREFIX}/clear/overlay")
|
|
252
|
+
def clear_overlay(payload: ClearOverlayRequest, request: Request):
|
|
253
|
+
return get(request).clear_overlay(payload.channel)
|
|
254
|
+
|
|
255
|
+
@app.post(f"{API_PREFIX}/emit/event")
|
|
256
|
+
def emit_event(payload: EmitEventRequest, request: Request):
|
|
257
|
+
return get(request).emit_event(
|
|
258
|
+
payload.target,
|
|
259
|
+
payload.config,
|
|
260
|
+
priority=payload.priority,
|
|
261
|
+
duration_ms=payload.duration_ms,
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
@app.post(f"{API_PREFIX}/clear/all")
|
|
265
|
+
def clear_all(request: Request):
|
|
266
|
+
return get(request).clear_all()
|
|
267
|
+
|
|
268
|
+
@app.post(f"{API_PREFIX}/output")
|
|
269
|
+
def output(payload: OutputRequest, request: Request):
|
|
270
|
+
return get(request).set_output(brightness=payload.brightness, enabled=payload.enabled)
|
|
271
|
+
|
|
272
|
+
# -- package sources ----------------------------------------------------
|
|
273
|
+
|
|
274
|
+
@app.get(f"{API_PREFIX}/sources")
|
|
275
|
+
def sources(request: Request):
|
|
276
|
+
return {"items": get(request).list_sources()}
|
|
277
|
+
|
|
278
|
+
@app.post(f"{API_PREFIX}/sources/register")
|
|
279
|
+
def register_source(payload: RegisterSourceRequest, request: Request):
|
|
280
|
+
return get(request).register_source(payload.path, enabled=payload.enabled)
|
|
281
|
+
|
|
282
|
+
@app.post(f"{API_PREFIX}/sources/reload")
|
|
283
|
+
def reload_sources(request: Request):
|
|
284
|
+
return get(request).reload_sources()
|
|
285
|
+
|
|
286
|
+
@app.delete(f"{API_PREFIX}/sources/{{source_id}}")
|
|
287
|
+
def remove_source(source_id: str, request: Request):
|
|
288
|
+
return get(request).remove_source(source_id)
|
|
289
|
+
|
|
290
|
+
@app.post(f"{API_PREFIX}/shutdown")
|
|
291
|
+
def shutdown(request: Request):
|
|
292
|
+
payload = get(request).health()
|
|
293
|
+
stop = getattr(request.app.state, "shutdown_server", None)
|
|
294
|
+
if callable(stop):
|
|
295
|
+
threading.Thread(target=stop, daemon=True).start()
|
|
296
|
+
return {"ok": True, "operation": "shutdown", "status": payload}
|
|
297
|
+
|
|
298
|
+
return app
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
__all__ = ["API_PREFIX", "create_app"]
|
lefx/interfaces/cli.py
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
"""The ``lefx`` command line.
|
|
2
|
+
|
|
3
|
+
Verb first, subject second: ``lefx set state ready_state``. The same wording as
|
|
4
|
+
the HTTP API, because both carry the same commands and neither holds logic of
|
|
5
|
+
its own.
|
|
6
|
+
|
|
7
|
+
Plain ``set`` always means on. An implicit toggle would make a repeated command
|
|
8
|
+
or a retry do the opposite of what it did the first time, so switching something
|
|
9
|
+
off is spelled out.
|
|
10
|
+
|
|
11
|
+
Flag defaults come from :mod:`lefx.interfaces.config`, so a config.yaml or an
|
|
12
|
+
environment variable moves the default and an explicit flag still wins. That is
|
|
13
|
+
the whole of the interaction: there is no flag that reads configuration itself,
|
|
14
|
+
and no setting that only some commands honour.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import json
|
|
21
|
+
import sys
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from . import config
|
|
25
|
+
from .client import ControllerClient, Result
|
|
26
|
+
|
|
27
|
+
LIST_KINDS = {
|
|
28
|
+
"state": "states",
|
|
29
|
+
"states": "states",
|
|
30
|
+
"overlay": "overlays",
|
|
31
|
+
"overlays": "overlays",
|
|
32
|
+
"event": "events",
|
|
33
|
+
"events": "events",
|
|
34
|
+
"preset": "presets",
|
|
35
|
+
"presets": "presets",
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def parse_json_object(value: str | None, *, label: str) -> dict[str, Any]:
|
|
40
|
+
if not value:
|
|
41
|
+
return {}
|
|
42
|
+
try:
|
|
43
|
+
parsed = json.loads(value)
|
|
44
|
+
except json.JSONDecodeError as exc:
|
|
45
|
+
raise argparse.ArgumentTypeError(f"{label} is not valid JSON: {exc}") from exc
|
|
46
|
+
if not isinstance(parsed, dict):
|
|
47
|
+
raise argparse.ArgumentTypeError(f"{label} must be a JSON object")
|
|
48
|
+
return parsed
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def parse_option(value: str) -> tuple[str, str]:
|
|
52
|
+
"""Parse one ``key=value`` pair for ``--sink-option``.
|
|
53
|
+
|
|
54
|
+
Values stay strings. What type a given sink wants for a given option is
|
|
55
|
+
known to that sink and to nothing here, so converting would mean guessing.
|
|
56
|
+
"""
|
|
57
|
+
key, separator, raw = value.partition("=")
|
|
58
|
+
if not separator or not key.strip():
|
|
59
|
+
raise argparse.ArgumentTypeError(f"--sink-option wants key=value, got {value!r}")
|
|
60
|
+
return key.strip(), raw
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def parse_bool(value: str) -> bool:
|
|
64
|
+
text = str(value).strip().casefold()
|
|
65
|
+
if text in {"1", "true", "yes", "on", "ja", "an"}:
|
|
66
|
+
return True
|
|
67
|
+
if text in {"0", "false", "no", "off", "nein", "aus"}:
|
|
68
|
+
return False
|
|
69
|
+
raise argparse.ArgumentTypeError(f"Not a boolean: {value!r}")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def add_connection(parser: argparse.ArgumentParser) -> None:
|
|
73
|
+
"""Where a client command looks for the service.
|
|
74
|
+
|
|
75
|
+
The same two settings the service binds to, so configuring a port once
|
|
76
|
+
moves both ends of the conversation rather than one.
|
|
77
|
+
"""
|
|
78
|
+
parser.add_argument("--host", default=config.get("host"))
|
|
79
|
+
parser.add_argument("--port", type=int, default=config.get("port"))
|
|
80
|
+
parser.add_argument("--timeout", type=float, default=5.0)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
84
|
+
parser = argparse.ArgumentParser(
|
|
85
|
+
prog="lefx", description="Control the LEFX V3 effect engine."
|
|
86
|
+
)
|
|
87
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
88
|
+
|
|
89
|
+
serve = sub.add_parser("serve", help="Run the controller service")
|
|
90
|
+
serve.add_argument("--host", default=config.get("host"))
|
|
91
|
+
serve.add_argument("--port", type=int, default=config.get("port"))
|
|
92
|
+
serve.add_argument("--port-pool", default="", help="Fallback ports, e.g. 8765,8770-8774")
|
|
93
|
+
serve.add_argument("--sink", default=config.get("sink"), help="Frame sink to use, or 'null'")
|
|
94
|
+
serve.add_argument(
|
|
95
|
+
"--sink-option",
|
|
96
|
+
type=parse_option,
|
|
97
|
+
action="append",
|
|
98
|
+
default=[],
|
|
99
|
+
metavar="KEY=VALUE",
|
|
100
|
+
dest="sink_options",
|
|
101
|
+
help=(
|
|
102
|
+
"Device option, passed to the sink and its input providers, repeatable "
|
|
103
|
+
"(e.g. port=8770 for the simulator, angle_offset_deg=129.1 for the DoA)"
|
|
104
|
+
),
|
|
105
|
+
)
|
|
106
|
+
serve.add_argument(
|
|
107
|
+
"--input-device",
|
|
108
|
+
default=config.get("input_device"),
|
|
109
|
+
help="Take inputs from this device instead of the one providing the sink",
|
|
110
|
+
)
|
|
111
|
+
serve.add_argument("--led-count", type=int, default=config.get("led_count"))
|
|
112
|
+
serve.add_argument("--fps", type=float, default=config.get("fps"))
|
|
113
|
+
|
|
114
|
+
sinks = sub.add_parser("sinks", help="List installed frame sinks, providers and effect sets")
|
|
115
|
+
|
|
116
|
+
settings = sub.add_parser(
|
|
117
|
+
"config", help="Show every setting, its value and where the value came from"
|
|
118
|
+
)
|
|
119
|
+
settings.add_argument("--json", action="store_true")
|
|
120
|
+
|
|
121
|
+
status = sub.add_parser("status", help="Show the service status")
|
|
122
|
+
add_connection(status)
|
|
123
|
+
status.add_argument("--json", action="store_true")
|
|
124
|
+
|
|
125
|
+
listing = sub.add_parser("list", help="List states, overlays, events or presets")
|
|
126
|
+
add_connection(listing)
|
|
127
|
+
listing.add_argument("kind", choices=sorted(LIST_KINDS))
|
|
128
|
+
listing.add_argument("--details", action="store_true")
|
|
129
|
+
listing.add_argument("--json", action="store_true")
|
|
130
|
+
|
|
131
|
+
show = sub.add_parser("show", help="Show one definition or preset")
|
|
132
|
+
add_connection(show)
|
|
133
|
+
show.add_argument("target")
|
|
134
|
+
|
|
135
|
+
setter = sub.add_parser("set", help="Set a state or an overlay")
|
|
136
|
+
add_connection(setter)
|
|
137
|
+
setter.add_argument("subject", choices=("state", "overlay"))
|
|
138
|
+
setter.add_argument("target")
|
|
139
|
+
setter.add_argument("--slot", choices=("primary", "background"), default="primary")
|
|
140
|
+
setter.add_argument("--channel")
|
|
141
|
+
setter.add_argument("--config", default="")
|
|
142
|
+
setter.add_argument("--inputs", default="")
|
|
143
|
+
mode = setter.add_mutually_exclusive_group()
|
|
144
|
+
mode.add_argument("--on", dest="action", action="store_const", const="on")
|
|
145
|
+
mode.add_argument("--off", dest="action", action="store_const", const="off")
|
|
146
|
+
mode.add_argument("--toggle", dest="action", action="store_const", const="toggle")
|
|
147
|
+
setter.set_defaults(action="on")
|
|
148
|
+
|
|
149
|
+
clear = sub.add_parser("clear", help="Clear a state slot, an overlay channel or everything")
|
|
150
|
+
add_connection(clear)
|
|
151
|
+
clear.add_argument("subject", choices=("state", "overlay", "all"))
|
|
152
|
+
clear.add_argument("channel", nargs="?")
|
|
153
|
+
clear.add_argument("--slot", choices=("primary", "background"), default="primary")
|
|
154
|
+
|
|
155
|
+
update = sub.add_parser("update", help="Update a controlled overlay")
|
|
156
|
+
add_connection(update)
|
|
157
|
+
update.add_argument("subject", choices=("overlay",))
|
|
158
|
+
update.add_argument("channel")
|
|
159
|
+
update.add_argument("--inputs", default="")
|
|
160
|
+
|
|
161
|
+
emit = sub.add_parser("emit", help="Emit an event")
|
|
162
|
+
add_connection(emit)
|
|
163
|
+
emit.add_argument("subject", choices=("event",))
|
|
164
|
+
emit.add_argument("target")
|
|
165
|
+
emit.add_argument("--config", default="")
|
|
166
|
+
emit.add_argument("--priority", type=int)
|
|
167
|
+
emit.add_argument("--duration-ms", type=int)
|
|
168
|
+
|
|
169
|
+
output = sub.add_parser("output", help="Adjust global brightness or switch output off")
|
|
170
|
+
add_connection(output)
|
|
171
|
+
output.add_argument("--brightness", type=float)
|
|
172
|
+
output.add_argument("--enabled", type=parse_bool)
|
|
173
|
+
|
|
174
|
+
sources = sub.add_parser("sources", help="Manage effect package sources")
|
|
175
|
+
add_connection(sources)
|
|
176
|
+
sources.add_argument(
|
|
177
|
+
"action", choices=("list", "register", "reload", "remove"), nargs="?", default="list"
|
|
178
|
+
)
|
|
179
|
+
sources.add_argument("value", nargs="?", help="Path to register, or source id to remove")
|
|
180
|
+
|
|
181
|
+
shutdown = sub.add_parser("shutdown", help="Ask the service to stop")
|
|
182
|
+
add_connection(shutdown)
|
|
183
|
+
|
|
184
|
+
return parser
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def emit_result(result: Result, *, plain: list[str] | None = None) -> int:
|
|
188
|
+
if result.ok and plain is not None:
|
|
189
|
+
for line in plain:
|
|
190
|
+
print(line)
|
|
191
|
+
return 0
|
|
192
|
+
payload = result.to_dict()
|
|
193
|
+
stream = sys.stdout if result.ok else sys.stderr
|
|
194
|
+
print(json.dumps(payload["data"] if result.ok else payload, indent=2, sort_keys=True), file=stream)
|
|
195
|
+
return 0 if result.ok else 1
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def run_serve(args: argparse.Namespace) -> int:
|
|
199
|
+
from uvicorn.config import Config
|
|
200
|
+
from uvicorn.server import Server
|
|
201
|
+
|
|
202
|
+
from . import hosting, paths
|
|
203
|
+
from .api import create_app
|
|
204
|
+
from .service import ControllerService
|
|
205
|
+
|
|
206
|
+
pool = hosting.parse_pool(args.port_pool) or hosting.DEFAULT_POOL
|
|
207
|
+
port = hosting.select_port(args.host, args.port, pool)
|
|
208
|
+
instance = hosting.create_instance(host=args.host, port=port, requested_port=args.port)
|
|
209
|
+
instance_path = paths.instance_file()
|
|
210
|
+
hosting.write_instance(instance_path, instance)
|
|
211
|
+
|
|
212
|
+
# Configured options first, flags on top: --sink-option overrides one key
|
|
213
|
+
# rather than replacing the whole mapping, which is what a person setting
|
|
214
|
+
# a single port on the command line means by it.
|
|
215
|
+
options = {**config.get("sink_options"), **dict(args.sink_options)}
|
|
216
|
+
service = ControllerService(
|
|
217
|
+
sink=args.sink,
|
|
218
|
+
led_count=args.led_count,
|
|
219
|
+
fps=args.fps,
|
|
220
|
+
sink_options=options,
|
|
221
|
+
input_device=args.input_device,
|
|
222
|
+
)
|
|
223
|
+
app = create_app(
|
|
224
|
+
service,
|
|
225
|
+
lifecycle_callback=lambda phase: hosting.update_instance_status(
|
|
226
|
+
instance_path, "ready" if phase == "started" else "stopping"
|
|
227
|
+
),
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
print(
|
|
231
|
+
json.dumps(
|
|
232
|
+
{
|
|
233
|
+
"event": "service_listening",
|
|
234
|
+
"host": args.host,
|
|
235
|
+
"port": port,
|
|
236
|
+
"sink": service.sink_name,
|
|
237
|
+
"input_device": service.input_device,
|
|
238
|
+
"effects": len(service.library.registry),
|
|
239
|
+
}
|
|
240
|
+
),
|
|
241
|
+
flush=True,
|
|
242
|
+
)
|
|
243
|
+
server = Server(Config(app, host=args.host, port=port, log_level="info", lifespan="on"))
|
|
244
|
+
app.state.shutdown_server = lambda: setattr(server, "should_exit", True)
|
|
245
|
+
try:
|
|
246
|
+
server.run()
|
|
247
|
+
return 0
|
|
248
|
+
finally:
|
|
249
|
+
hosting.clear_instance(instance_path, pid=instance.pid)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def run_sinks() -> int:
|
|
253
|
+
from . import discovery
|
|
254
|
+
|
|
255
|
+
print(json.dumps(discovery.describe(), indent=2, sort_keys=True))
|
|
256
|
+
return 0
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def run_config(args: argparse.Namespace) -> int:
|
|
260
|
+
"""Every setting, its value, and which of the four places it came from.
|
|
261
|
+
|
|
262
|
+
The question this answers is not "what can be configured" — that is the
|
|
263
|
+
table in config.py and the documentation generated from it — but "why is
|
|
264
|
+
this machine behaving like that", which needs the source as much as the
|
|
265
|
+
value.
|
|
266
|
+
"""
|
|
267
|
+
described = config.describe()
|
|
268
|
+
if args.json:
|
|
269
|
+
print(json.dumps(described, indent=2, sort_keys=True, default=str))
|
|
270
|
+
return 0
|
|
271
|
+
|
|
272
|
+
print(f"config file: {described['file'] or 'none'}")
|
|
273
|
+
width = max(len(row["slug"]) for row in described["settings"])
|
|
274
|
+
for row in described["settings"]:
|
|
275
|
+
print(f" {row['slug']:<{width}} {row['value']!r:<28} from {row['source']}")
|
|
276
|
+
return 0
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def main(argv: list[str] | None = None) -> int:
|
|
280
|
+
parser = build_parser()
|
|
281
|
+
args = parser.parse_args(argv)
|
|
282
|
+
try:
|
|
283
|
+
return _dispatch(parser, args)
|
|
284
|
+
except argparse.ArgumentTypeError as exc:
|
|
285
|
+
# Malformed --config or --inputs. Report it the way argparse reports any
|
|
286
|
+
# other bad argument rather than letting a traceback out.
|
|
287
|
+
parser.error(str(exc))
|
|
288
|
+
return 2
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _dispatch(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
|
292
|
+
|
|
293
|
+
if args.command == "serve":
|
|
294
|
+
return run_serve(args)
|
|
295
|
+
if args.command == "sinks":
|
|
296
|
+
return run_sinks()
|
|
297
|
+
if args.command == "config":
|
|
298
|
+
return run_config(args)
|
|
299
|
+
|
|
300
|
+
client = ControllerClient(host=args.host, port=args.port, timeout=args.timeout)
|
|
301
|
+
|
|
302
|
+
if args.command == "status":
|
|
303
|
+
return emit_result(client.status())
|
|
304
|
+
|
|
305
|
+
if args.command == "list":
|
|
306
|
+
result = client.list(LIST_KINDS[args.kind], details=args.details)
|
|
307
|
+
plain = None
|
|
308
|
+
if result.ok and not args.details and not args.json and isinstance(result.data, list):
|
|
309
|
+
plain = [str(item) for item in result.data]
|
|
310
|
+
return emit_result(result, plain=plain)
|
|
311
|
+
|
|
312
|
+
if args.command == "show":
|
|
313
|
+
return emit_result(client.show(args.target))
|
|
314
|
+
|
|
315
|
+
if args.command == "set":
|
|
316
|
+
# Not named "config": that is the settings module, imported above.
|
|
317
|
+
values = parse_json_object(args.config, label="--config")
|
|
318
|
+
if args.subject == "state":
|
|
319
|
+
return emit_result(
|
|
320
|
+
client.set_state(args.target, values, slot=args.slot, action=args.action)
|
|
321
|
+
)
|
|
322
|
+
return emit_result(
|
|
323
|
+
client.set_overlay(
|
|
324
|
+
args.target,
|
|
325
|
+
channel=args.channel,
|
|
326
|
+
config=values,
|
|
327
|
+
inputs=parse_json_object(args.inputs, label="--inputs"),
|
|
328
|
+
action=args.action,
|
|
329
|
+
)
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
if args.command == "clear":
|
|
333
|
+
if args.subject == "state":
|
|
334
|
+
return emit_result(client.clear_state(slot=args.slot))
|
|
335
|
+
if args.subject == "all":
|
|
336
|
+
return emit_result(client.clear_all())
|
|
337
|
+
if not args.channel:
|
|
338
|
+
parser.error("clear overlay needs a channel")
|
|
339
|
+
return emit_result(client.clear_overlay(args.channel))
|
|
340
|
+
|
|
341
|
+
if args.command == "update":
|
|
342
|
+
return emit_result(
|
|
343
|
+
client.update_overlay(args.channel, parse_json_object(args.inputs, label="--inputs"))
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
if args.command == "emit":
|
|
347
|
+
return emit_result(
|
|
348
|
+
client.emit_event(
|
|
349
|
+
args.target,
|
|
350
|
+
parse_json_object(args.config, label="--config"),
|
|
351
|
+
priority=args.priority,
|
|
352
|
+
duration_ms=args.duration_ms,
|
|
353
|
+
)
|
|
354
|
+
)
|
|
355
|
+
|
|
356
|
+
if args.command == "output":
|
|
357
|
+
if args.brightness is None and args.enabled is None:
|
|
358
|
+
parser.error("output needs --brightness or --enabled")
|
|
359
|
+
return emit_result(client.set_output(brightness=args.brightness, enabled=args.enabled))
|
|
360
|
+
|
|
361
|
+
if args.command == "sources":
|
|
362
|
+
if args.action == "list":
|
|
363
|
+
return emit_result(client.list_sources())
|
|
364
|
+
if args.action == "reload":
|
|
365
|
+
return emit_result(client.reload_sources())
|
|
366
|
+
if not args.value:
|
|
367
|
+
parser.error(f"sources {args.action} needs a value")
|
|
368
|
+
if args.action == "register":
|
|
369
|
+
return emit_result(client.register_source(args.value))
|
|
370
|
+
return emit_result(client.remove_source(args.value))
|
|
371
|
+
|
|
372
|
+
if args.command == "shutdown":
|
|
373
|
+
return emit_result(client.shutdown())
|
|
374
|
+
|
|
375
|
+
parser.error(f"Unsupported command {args.command!r}")
|
|
376
|
+
return 2
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
if __name__ == "__main__": # pragma: no cover
|
|
380
|
+
raise SystemExit(main())
|