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.
Files changed (52) hide show
  1. led_controller_version_3-3.0.2.dist-info/METADATA +172 -0
  2. led_controller_version_3-3.0.2.dist-info/RECORD +52 -0
  3. led_controller_version_3-3.0.2.dist-info/WHEEL +4 -0
  4. led_controller_version_3-3.0.2.dist-info/entry_points.txt +13 -0
  5. lefx/device/respeaker/__init__.py +35 -0
  6. lefx/device/respeaker/cli.py +146 -0
  7. lefx/device/respeaker/contention.py +523 -0
  8. lefx/device/respeaker/provider.py +158 -0
  9. lefx/device/respeaker/registration.py +130 -0
  10. lefx/device/respeaker/sink.py +108 -0
  11. lefx/device/respeaker/transport.py +344 -0
  12. lefx/device/respeaker/xvf.py +313 -0
  13. lefx/engine/__init__.py +110 -0
  14. lefx/engine/composer.py +203 -0
  15. lefx/engine/config.py +27 -0
  16. lefx/engine/errors.py +84 -0
  17. lefx/engine/inputs.py +196 -0
  18. lefx/engine/invocation.py +129 -0
  19. lefx/engine/layers.py +114 -0
  20. lefx/engine/library.py +181 -0
  21. lefx/engine/packages/__init__.py +45 -0
  22. lefx/engine/packages/loader.py +375 -0
  23. lefx/engine/packages/manifest.py +308 -0
  24. lefx/engine/registry.py +347 -0
  25. lefx/engine/renderer.py +63 -0
  26. lefx/engine/runtime.py +393 -0
  27. lefx/engine/store.py +125 -0
  28. lefx/interfaces/__init__.py +40 -0
  29. lefx/interfaces/api.py +301 -0
  30. lefx/interfaces/cli.py +380 -0
  31. lefx/interfaces/client.py +165 -0
  32. lefx/interfaces/config.py +305 -0
  33. lefx/interfaces/discovery.py +308 -0
  34. lefx/interfaces/hosting.py +123 -0
  35. lefx/interfaces/paths.py +79 -0
  36. lefx/interfaces/presentation.py +118 -0
  37. lefx/interfaces/service.py +468 -0
  38. lefx/sdk/__init__.py +176 -0
  39. lefx/sdk/calibration.py +202 -0
  40. lefx/sdk/color.py +108 -0
  41. lefx/sdk/context.py +72 -0
  42. lefx/sdk/definitions.py +526 -0
  43. lefx/sdk/effects.py +63 -0
  44. lefx/sdk/errors.py +90 -0
  45. lefx/sdk/parameters.py +469 -0
  46. lefx/sdk/ports.py +76 -0
  47. lefx/sdk/validation.py +150 -0
  48. lefx/sdk/values.py +212 -0
  49. lefx/sets/core_set/__init__.py +32 -0
  50. lefx/sets/core_set/core-set.lefxset +0 -0
  51. lefx/sets/smartspeaker_set/__init__.py +32 -0
  52. lefx/sets/smartspeaker_set/smartspeaker-set.lefxset +0 -0
lefx/sdk/parameters.py ADDED
@@ -0,0 +1,469 @@
1
+ """Parameter declarations and the rules for which options are allowed when.
2
+
3
+ Two things happen here that did not happen in earlier generations:
4
+
5
+ 1. ``type`` is an enum, not a free string. A typo is a construction error, not a
6
+ value that silently never matches.
7
+ 2. Every declaration is checked in ``__post_init__``. An invalid parameter is
8
+ not constructible, so no code path can hold one.
9
+
10
+ The matrix below is the single source of truth for which companion fields a type
11
+ accepts. ``minimum``/``maximum`` on a colour is not "ignored" — it is rejected.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass, field
17
+ from enum import Enum
18
+ from typing import Any, Final, Mapping
19
+
20
+ from .errors import SchemaError, ValueNormalizationError
21
+ from .values import (
22
+ format_color,
23
+ parse_angle_degrees,
24
+ parse_bool,
25
+ parse_duration_ms,
26
+ parse_ratio,
27
+ )
28
+
29
+
30
+ class _Missing:
31
+ """Sentinel for "no default declared".
32
+
33
+ ``None`` cannot serve this role: a nullable runtime input may legitimately
34
+ default to ``None``, and the two cases must stay distinguishable.
35
+ """
36
+
37
+ _instance: "_Missing | None" = None
38
+
39
+ def __new__(cls) -> "_Missing":
40
+ if cls._instance is None:
41
+ cls._instance = super().__new__(cls)
42
+ return cls._instance
43
+
44
+ def __repr__(self) -> str:
45
+ return "MISSING"
46
+
47
+ def __bool__(self) -> bool:
48
+ return False
49
+
50
+
51
+ MISSING: Final = _Missing()
52
+
53
+
54
+ class ParamType(str, Enum):
55
+ """The complete set of value types a declaration may use."""
56
+
57
+ BOOL = "bool"
58
+ INT = "int"
59
+ FLOAT = "float"
60
+ DURATION_MS = "duration_ms"
61
+ ANGLE_DEG = "angle_deg"
62
+ ENUM = "enum"
63
+ COLOR = "color"
64
+ COLOR_LIST = "color_list"
65
+ GRADIENT = "gradient"
66
+ COLOR_RANGE = "color_range"
67
+
68
+
69
+ @dataclass(slots=True, frozen=True)
70
+ class _TypeRules:
71
+ """Which companion fields a parameter type accepts."""
72
+
73
+ bounds: bool = False
74
+ bounds_are_integers: bool = False
75
+ enum_values: bool = False
76
+ units: frozenset[str] | None = None # ``None`` means "no unit allowed"
77
+
78
+
79
+ # The zulässigkeit matrix. Anything not listed as allowed is rejected.
80
+ _TYPE_RULES: Final[Mapping[ParamType, _TypeRules]] = {
81
+ ParamType.BOOL: _TypeRules(),
82
+ ParamType.INT: _TypeRules(bounds=True, bounds_are_integers=True, units=frozenset({"ms", "deg", "px", "count", "index", "ratio", "multiplier", "percent"})),
83
+ ParamType.FLOAT: _TypeRules(bounds=True, units=frozenset({"ms", "deg", "px", "count", "ratio", "multiplier", "percent", "hz"})),
84
+ ParamType.DURATION_MS: _TypeRules(bounds=True, bounds_are_integers=True, units=frozenset({"ms"})),
85
+ ParamType.ANGLE_DEG: _TypeRules(units=frozenset({"deg"})),
86
+ ParamType.ENUM: _TypeRules(enum_values=True),
87
+ ParamType.COLOR: _TypeRules(),
88
+ ParamType.COLOR_LIST: _TypeRules(bounds=True, bounds_are_integers=True, units=frozenset({"count"})),
89
+ ParamType.GRADIENT: _TypeRules(),
90
+ ParamType.COLOR_RANGE: _TypeRules(),
91
+ }
92
+
93
+
94
+ @dataclass(slots=True, frozen=True)
95
+ class _ReservedParam:
96
+ """A parameter name whose meaning is fixed system-wide."""
97
+
98
+ type: ParamType
99
+ exact_minimum: float | None = None
100
+ exact_maximum: float | None = None
101
+ minimum_at_least: float | None = None
102
+ minimum_above_zero: bool = False
103
+
104
+
105
+ # Reserved names carry the same meaning in every definition, so their type and
106
+ # range are not left to each author. This is what lets the CLI, the API and the
107
+ # documentation talk about "brightness" without qualification.
108
+ RESERVED_PARAMETERS: Final[Mapping[str, _ReservedParam]] = {
109
+ "brightness": _ReservedParam(ParamType.FLOAT, exact_minimum=0.0, exact_maximum=1.0),
110
+ "min_brightness": _ReservedParam(ParamType.FLOAT, exact_minimum=0.0, exact_maximum=1.0),
111
+ "speed": _ReservedParam(ParamType.FLOAT, minimum_above_zero=True),
112
+ "reverse": _ReservedParam(ParamType.BOOL),
113
+ "progress": _ReservedParam(ParamType.FLOAT, exact_minimum=0.0, exact_maximum=100.0),
114
+ "direction_deg": _ReservedParam(ParamType.ANGLE_DEG),
115
+ "duration_ms": _ReservedParam(ParamType.DURATION_MS, minimum_at_least=1),
116
+ "total_ms": _ReservedParam(ParamType.DURATION_MS, minimum_at_least=1),
117
+ "remaining_ms": _ReservedParam(ParamType.DURATION_MS, minimum_at_least=0),
118
+ "color": _ReservedParam(ParamType.COLOR),
119
+ "secondary_color": _ReservedParam(ParamType.COLOR),
120
+ "background_color": _ReservedParam(ParamType.COLOR),
121
+ "colors": _ReservedParam(ParamType.COLOR_LIST),
122
+ "gradient": _ReservedParam(ParamType.GRADIENT),
123
+ "color_range": _ReservedParam(ParamType.COLOR_RANGE),
124
+ "random_seed": _ReservedParam(ParamType.INT),
125
+ }
126
+
127
+
128
+ def _is_valid_name(value: str) -> bool:
129
+ return (
130
+ bool(value)
131
+ and value.isidentifier()
132
+ and not value.startswith("_")
133
+ and value == value.lower()
134
+ )
135
+
136
+
137
+ @dataclass(slots=True, frozen=True)
138
+ class ParamDefinition:
139
+ """One declared field of a configuration or runtime input schema.
140
+
141
+ ``required`` and ``default`` are mutually exclusive: a field that always
142
+ falls back to a value is not required, and a field the caller must supply
143
+ cannot have a fallback. Declaring both is a contradiction, not a preference.
144
+ """
145
+
146
+ name: str
147
+ type: ParamType
148
+ default: Any = MISSING
149
+ required: bool = False
150
+ description: str = ""
151
+ minimum: float | int | None = None
152
+ maximum: float | int | None = None
153
+ enum_values: tuple[Any, ...] = ()
154
+ unit: str | None = None
155
+ nullable: bool = False
156
+ aliases: tuple[str, ...] = field(default_factory=tuple)
157
+
158
+ def __post_init__(self) -> None:
159
+ self._check_name()
160
+ self._check_type()
161
+ rules = _TYPE_RULES[self.type]
162
+ self._check_bounds(rules)
163
+ self._check_enum_values(rules)
164
+ self._check_unit(rules)
165
+ self._check_aliases()
166
+ self._check_reserved()
167
+ self._check_required_and_default()
168
+ self._canonicalize_default()
169
+
170
+ @property
171
+ def has_default(self) -> bool:
172
+ return self.default is not MISSING
173
+
174
+ # -- construction checks ------------------------------------------------
175
+
176
+ def _check_name(self) -> None:
177
+ if not _is_valid_name(self.name):
178
+ raise SchemaError(
179
+ f"Parameter name {self.name!r} must be lowercase snake_case "
180
+ "and must not start with an underscore"
181
+ )
182
+
183
+ def _check_type(self) -> None:
184
+ if not isinstance(self.type, ParamType):
185
+ raise SchemaError(
186
+ f"Parameter {self.name!r} declares type {self.type!r}; "
187
+ f"expected one of: {', '.join(item.value for item in ParamType)}"
188
+ )
189
+
190
+ def _check_bounds(self, rules: _TypeRules) -> None:
191
+ has_bounds = self.minimum is not None or self.maximum is not None
192
+ if has_bounds and not rules.bounds:
193
+ raise SchemaError(
194
+ f"Parameter {self.name!r} of type {self.type.value!r} "
195
+ "does not accept minimum or maximum"
196
+ )
197
+ if not has_bounds:
198
+ return
199
+ for label, bound in (("minimum", self.minimum), ("maximum", self.maximum)):
200
+ if bound is None:
201
+ continue
202
+ if isinstance(bound, bool) or not isinstance(bound, (int, float)):
203
+ raise SchemaError(f"Parameter {self.name!r} {label} must be numeric")
204
+ if rules.bounds_are_integers and float(bound) != int(bound):
205
+ raise SchemaError(
206
+ f"Parameter {self.name!r} of type {self.type.value!r} "
207
+ f"requires an integral {label}"
208
+ )
209
+ if self.minimum is not None and self.maximum is not None and self.minimum > self.maximum:
210
+ raise SchemaError(
211
+ f"Parameter {self.name!r} minimum {self.minimum} exceeds maximum {self.maximum}"
212
+ )
213
+ if self.type is ParamType.COLOR_LIST and self.minimum is not None and self.minimum < 0:
214
+ raise SchemaError(f"Parameter {self.name!r} list length minimum must be >= 0")
215
+
216
+ def _check_enum_values(self, rules: _TypeRules) -> None:
217
+ if not rules.enum_values:
218
+ if self.enum_values:
219
+ raise SchemaError(
220
+ f"Parameter {self.name!r} of type {self.type.value!r} "
221
+ "does not accept enum_values"
222
+ )
223
+ return
224
+ if not self.enum_values:
225
+ raise SchemaError(f"Enum parameter {self.name!r} must declare enum_values")
226
+ if len(set(self.enum_values)) != len(self.enum_values):
227
+ raise SchemaError(f"Enum parameter {self.name!r} has duplicate enum_values")
228
+
229
+ def _check_unit(self, rules: _TypeRules) -> None:
230
+ if self.unit is None:
231
+ return
232
+ if rules.units is None:
233
+ raise SchemaError(
234
+ f"Parameter {self.name!r} of type {self.type.value!r} does not accept a unit"
235
+ )
236
+ if self.unit not in rules.units:
237
+ allowed = ", ".join(sorted(rules.units))
238
+ raise SchemaError(
239
+ f"Parameter {self.name!r} declares unit {self.unit!r}; "
240
+ f"type {self.type.value!r} allows: {allowed}"
241
+ )
242
+
243
+ def _check_aliases(self) -> None:
244
+ seen: set[str] = set()
245
+ for alias in self.aliases:
246
+ if not isinstance(alias, str) or not _is_valid_name(alias):
247
+ raise SchemaError(
248
+ f"Parameter {self.name!r} declares invalid alias {alias!r}"
249
+ )
250
+ if alias == self.name:
251
+ raise SchemaError(
252
+ f"Parameter {self.name!r} declares an alias equal to its own name"
253
+ )
254
+ if alias in seen:
255
+ raise SchemaError(f"Parameter {self.name!r} declares alias {alias!r} twice")
256
+ seen.add(alias)
257
+
258
+ def _check_reserved(self) -> None:
259
+ reserved = RESERVED_PARAMETERS.get(self.name)
260
+ if reserved is None:
261
+ return
262
+ if self.type is not reserved.type:
263
+ raise SchemaError(
264
+ f"Reserved parameter {self.name!r} must use type "
265
+ f"{reserved.type.value!r}, not {self.type.value!r}"
266
+ )
267
+ if reserved.exact_minimum is not None and self.minimum != reserved.exact_minimum:
268
+ raise SchemaError(
269
+ f"Reserved parameter {self.name!r} must declare minimum "
270
+ f"{reserved.exact_minimum}"
271
+ )
272
+ if reserved.exact_maximum is not None and self.maximum != reserved.exact_maximum:
273
+ raise SchemaError(
274
+ f"Reserved parameter {self.name!r} must declare maximum "
275
+ f"{reserved.exact_maximum}"
276
+ )
277
+ if reserved.minimum_at_least is not None and (
278
+ self.minimum is None or self.minimum < reserved.minimum_at_least
279
+ ):
280
+ raise SchemaError(
281
+ f"Reserved parameter {self.name!r} must declare minimum "
282
+ f">= {reserved.minimum_at_least}"
283
+ )
284
+ if reserved.minimum_above_zero and (self.minimum is None or self.minimum <= 0):
285
+ raise SchemaError(
286
+ f"Reserved parameter {self.name!r} must declare a minimum greater than zero"
287
+ )
288
+
289
+ def _check_required_and_default(self) -> None:
290
+ if self.required and self.has_default:
291
+ raise SchemaError(
292
+ f"Parameter {self.name!r} is required and declares a default; "
293
+ "a required field has no fallback"
294
+ )
295
+
296
+ def _canonicalize_default(self) -> None:
297
+ """Store the default in the same canonical form a caller's value gets.
298
+
299
+ Validating here means a broken default surfaces when the definition is
300
+ written, not on the first activation that happens to omit the field.
301
+ """
302
+ if not self.has_default:
303
+ return
304
+ try:
305
+ canonical = normalize_parameter_value(self, self.default)
306
+ except (ValueError, TypeError) as exc:
307
+ raise SchemaError(
308
+ f"Parameter {self.name!r} has an invalid default {self.default!r}: {exc}"
309
+ ) from exc
310
+ object.__setattr__(self, "default", canonical)
311
+
312
+
313
+ def normalize_parameter_value(definition: ParamDefinition, value: Any) -> Any:
314
+ """Bring one incoming value into the canonical form of its declared type."""
315
+ if value is None:
316
+ if definition.nullable:
317
+ return None
318
+ raise ValueError(f"{definition.name} must not be null")
319
+
320
+ kind = definition.type
321
+ if kind is ParamType.BOOL:
322
+ normalized: Any = parse_bool(value)
323
+ elif kind is ParamType.INT:
324
+ normalized = _normalize_int(definition, value)
325
+ elif kind is ParamType.FLOAT:
326
+ normalized = _normalize_float(definition, value)
327
+ elif kind is ParamType.DURATION_MS:
328
+ normalized = parse_duration_ms(value, minimum=max(0, int(definition.minimum or 0)))
329
+ elif kind is ParamType.ANGLE_DEG:
330
+ normalized = parse_angle_degrees(value)
331
+ elif kind is ParamType.ENUM:
332
+ normalized = _normalize_enum(definition, value)
333
+ elif kind is ParamType.COLOR:
334
+ normalized = format_color(value)
335
+ elif kind is ParamType.COLOR_LIST:
336
+ normalized = _normalize_color_list(definition, value)
337
+ elif kind is ParamType.GRADIENT:
338
+ normalized = _normalize_gradient(definition, value)
339
+ elif kind is ParamType.COLOR_RANGE:
340
+ normalized = _normalize_color_range(definition, value)
341
+ else: # pragma: no cover - ParamType is exhaustive
342
+ raise ValueError(f"Unsupported parameter type {kind!r} for {definition.name!r}")
343
+
344
+ if isinstance(normalized, (int, float)) and not isinstance(normalized, bool):
345
+ if definition.minimum is not None and normalized < definition.minimum:
346
+ raise ValueError(f"{definition.name} must be >= {definition.minimum}")
347
+ if definition.maximum is not None and normalized > definition.maximum:
348
+ raise ValueError(f"{definition.name} must be <= {definition.maximum}")
349
+ return normalized
350
+
351
+
352
+ def _normalize_int(definition: ParamDefinition, value: Any) -> int:
353
+ if isinstance(value, bool):
354
+ raise ValueError(f"{definition.name} must be an integer")
355
+ try:
356
+ return int(value)
357
+ except (TypeError, ValueError) as exc:
358
+ raise ValueError(f"{definition.name} must be an integer") from exc
359
+
360
+
361
+ def _normalize_float(definition: ParamDefinition, value: Any) -> float:
362
+ if isinstance(value, bool):
363
+ raise ValueError(f"{definition.name} must be numeric")
364
+ if isinstance(value, str) and value.strip().endswith("%"):
365
+ # A percentage is only unambiguous when the declared range says what it
366
+ # is a percentage of: 0..1 means a ratio, 0..100 means percent points.
367
+ if definition.minimum == 0.0 and definition.maximum == 1.0:
368
+ return parse_ratio(value)
369
+ if definition.minimum == 0.0 and definition.maximum == 100.0:
370
+ try:
371
+ return float(value.strip()[:-1])
372
+ except ValueError as exc:
373
+ raise ValueError(f"{definition.name} must be numeric or a percentage") from exc
374
+ raise ValueError(
375
+ f"{definition.name} does not accept a percentage; its range is not 0..1 or 0..100"
376
+ )
377
+ try:
378
+ return float(value)
379
+ except (TypeError, ValueError) as exc:
380
+ raise ValueError(f"{definition.name} must be numeric") from exc
381
+
382
+
383
+ def _normalize_enum(definition: ParamDefinition, value: Any) -> Any:
384
+ if value in definition.enum_values:
385
+ return value
386
+ if isinstance(value, str):
387
+ matches = [
388
+ candidate
389
+ for candidate in definition.enum_values
390
+ if isinstance(candidate, str) and candidate.casefold() == value.strip().casefold()
391
+ ]
392
+ if len(matches) == 1:
393
+ return matches[0]
394
+ expected = ", ".join(repr(item) for item in definition.enum_values)
395
+ raise ValueError(f"{definition.name} must be one of: {expected}")
396
+
397
+
398
+ def _normalize_color_list(definition: ParamDefinition, value: Any) -> list[str]:
399
+ if isinstance(value, (str, bytes)) or not isinstance(value, (list, tuple)):
400
+ raise ValueError(f"{definition.name} must be a list of colors")
401
+ normalized = [format_color(item) for item in value]
402
+ if definition.minimum is not None and len(normalized) < definition.minimum:
403
+ raise ValueError(
404
+ f"{definition.name} must contain at least {int(definition.minimum)} colors"
405
+ )
406
+ if definition.maximum is not None and len(normalized) > definition.maximum:
407
+ raise ValueError(
408
+ f"{definition.name} must contain at most {int(definition.maximum)} colors"
409
+ )
410
+ return normalized
411
+
412
+
413
+ def _normalize_gradient(definition: ParamDefinition, value: Any) -> list[dict[str, Any]]:
414
+ if not isinstance(value, (list, tuple)) or not 2 <= len(value) <= 16:
415
+ raise ValueError(f"{definition.name} must contain between 2 and 16 color stops")
416
+ stops: list[dict[str, Any]] = []
417
+ for index, item in enumerate(value):
418
+ if not isinstance(item, Mapping) or set(item) != {"at", "color"}:
419
+ raise ValueError(f"{definition.name}[{index}] must contain exactly 'at' and 'color'")
420
+ try:
421
+ at = float(item["at"])
422
+ except (TypeError, ValueError) as exc:
423
+ raise ValueError(f"{definition.name}[{index}].at must be numeric") from exc
424
+ if not 0.0 <= at <= 1.0:
425
+ raise ValueError(f"{definition.name}[{index}].at must be between 0 and 1")
426
+ stops.append({"at": at, "color": format_color(item["color"])})
427
+ positions = [item["at"] for item in stops]
428
+ if positions != sorted(positions) or positions[0] != 0.0 or positions[-1] != 1.0:
429
+ raise ValueError(f"{definition.name} stops must be sorted and include positions 0 and 1")
430
+ return stops
431
+
432
+
433
+ def _normalize_color_range(definition: ParamDefinition, value: Any) -> dict[str, list[float]]:
434
+ if not isinstance(value, Mapping):
435
+ raise ValueError(f"{definition.name} must be an HSV range object")
436
+ if set(value) != {"hue", "saturation", "brightness"}:
437
+ raise ValueError(f"{definition.name} must contain exactly hue, saturation and brightness")
438
+ limits = {
439
+ "hue": (0.0, 360.0),
440
+ "saturation": (0.0, 1.0),
441
+ "brightness": (0.0, 1.0),
442
+ }
443
+ normalized: dict[str, list[float]] = {}
444
+ for name, (minimum, maximum) in limits.items():
445
+ raw = value[name]
446
+ if not isinstance(raw, (list, tuple)) or len(raw) != 2:
447
+ raise ValueError(f"{definition.name}.{name} must be a [minimum, maximum] pair")
448
+ try:
449
+ low, high = float(raw[0]), float(raw[1])
450
+ except (TypeError, ValueError) as exc:
451
+ raise ValueError(f"{definition.name}.{name} bounds must be numeric") from exc
452
+ if low > high or low < minimum or high > maximum:
453
+ raise ValueError(
454
+ f"{definition.name}.{name} must satisfy "
455
+ f"{minimum} <= minimum <= maximum <= {maximum}"
456
+ )
457
+ normalized[name] = [low, high]
458
+ return normalized
459
+
460
+
461
+ __all__ = [
462
+ "MISSING",
463
+ "RESERVED_PARAMETERS",
464
+ "ParamDefinition",
465
+ "ParamType",
466
+ "SchemaError",
467
+ "ValueNormalizationError",
468
+ "normalize_parameter_value",
469
+ ]
lefx/sdk/ports.py ADDED
@@ -0,0 +1,76 @@
1
+ """The two ports between the engine and the outside world.
2
+
3
+ Both live in the SDK rather than in the engine so that a hardware integration
4
+ can be written against the contract without installing the runtime, and so that
5
+ the engine never has to know which implementation exists. Implementations are
6
+ discovered through the entry point groups ``lefx.frame_sinks`` and
7
+ ``lefx.input_providers``.
8
+
9
+ That a single device serves both directions over one transport — as the
10
+ reSpeaker does with USB — is a detail of that integration. Keeping the ports
11
+ separate means a failing DoA read cannot take the LED output down with it.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass
17
+ from typing import Any, Mapping, Protocol, runtime_checkable
18
+
19
+ from .context import InputContext
20
+
21
+
22
+ @dataclass(slots=True, frozen=True)
23
+ class OutputFrame:
24
+ """A fully composed frame ready for output. One opaque colour per LED."""
25
+
26
+ leds: tuple[int, ...]
27
+ timestamp: float
28
+
29
+
30
+ @dataclass(slots=True, frozen=True)
31
+ class SinkStatus:
32
+ """Whether a sink can currently deliver, and why not if it cannot.
33
+
34
+ Every sink answers this, so the service reports connection state uniformly
35
+ instead of type-checking its way to an answer.
36
+ """
37
+
38
+ available: bool
39
+ detail: str | None = None
40
+
41
+ def to_dict(self) -> dict[str, Any]:
42
+ return {"available": self.available, "detail": self.detail}
43
+
44
+
45
+ @runtime_checkable
46
+ class FrameSink(Protocol):
47
+ """Receives composed frames. The engine's only way out."""
48
+
49
+ def apply_frame(self, frame: OutputFrame) -> None:
50
+ """Deliver one frame. Must not raise on a transient device problem."""
51
+ ...
52
+
53
+ def status(self) -> SinkStatus:
54
+ """Report current deliverability without attempting a write."""
55
+ ...
56
+
57
+ def close(self) -> None:
58
+ """Release the underlying resource. Called once on shutdown."""
59
+ ...
60
+
61
+
62
+ @runtime_checkable
63
+ class InputProvider(Protocol):
64
+ """Supplies runtime input values for pull-sampled controlled overlays."""
65
+
66
+ def sample(self, ctx: InputContext) -> Mapping[str, Any] | None:
67
+ """Return current values, or ``None`` when nothing new is available.
68
+
69
+ Must not block. A provider that talks to shared hardware caches its own
70
+ snapshot on its own schedule, so the number of active effect instances
71
+ never multiplies the number of device reads.
72
+ """
73
+ ...
74
+
75
+
76
+ __all__ = ["FrameSink", "InputProvider", "OutputFrame", "SinkStatus"]
lefx/sdk/validation.py ADDED
@@ -0,0 +1,150 @@
1
+ """Schema-level validation of incoming payloads.
2
+
3
+ Single values are normalized in :mod:`lefx.sdk.parameters`. This module works on
4
+ whole payloads: it resolves aliases, rejects unknown fields with suggestions,
5
+ and collects every problem before raising, so one round trip reports everything
6
+ that is wrong rather than the first thing.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import difflib
12
+ from typing import Any, Mapping
13
+
14
+ from .definitions import DefinitionBase
15
+ from .errors import ParameterValidationError, ValidationIssue, ValueNormalizationError
16
+ from .parameters import ParamDefinition, normalize_parameter_value
17
+
18
+
19
+ def resolve_configuration(
20
+ definition: DefinitionBase,
21
+ *,
22
+ preset: Mapping[str, Any] | None = None,
23
+ overrides: Mapping[str, Any] | None = None,
24
+ ) -> dict[str, Any]:
25
+ """Merge defaults, an optional preset and explicit values into canonical config.
26
+
27
+ Precedence is defaults, then preset, then explicit values. Because every
28
+ configuration field declares a default, the result always contains every
29
+ declared key — a renderer never has to guess a fallback.
30
+ """
31
+ merged: dict[str, Any] = {
32
+ name: param.default for name, param in definition.parameter_schema.items()
33
+ }
34
+ supplied: dict[str, Any] = {}
35
+ supplied.update(dict(preset or {}))
36
+ supplied.update(dict(overrides or {}))
37
+
38
+ normalized_supplied = normalize_values(
39
+ definition.parameter_schema,
40
+ supplied,
41
+ field_prefix="config",
42
+ )
43
+ merged.update(normalized_supplied)
44
+ return merged
45
+
46
+
47
+ def initial_runtime_inputs(definition: DefinitionBase) -> dict[str, Any]:
48
+ """The starting runtime input map of a fresh instance.
49
+
50
+ Required inputs begin as ``None`` because no value has arrived yet; the
51
+ rest begin at their declared default. Every declared key is present, which
52
+ is what lets a renderer index ``ctx.inputs`` directly.
53
+ """
54
+ values: dict[str, Any] = {}
55
+ for name, param in definition.runtime_input_schema.items():
56
+ values[name] = None if param.required else param.default
57
+ return values
58
+
59
+
60
+ def normalize_runtime_inputs(
61
+ definition: DefinitionBase,
62
+ values: Mapping[str, Any] | None,
63
+ ) -> dict[str, Any]:
64
+ """Normalize a partial runtime input update.
65
+
66
+ Only supplied fields are returned. An empty update is valid and means "still
67
+ alive" — the caller treats it as a heartbeat. A single unknown or invalid
68
+ field rejects the whole update, so an instance never ends up half applied.
69
+ """
70
+ return normalize_values(
71
+ definition.runtime_input_schema,
72
+ values,
73
+ field_prefix="inputs",
74
+ )
75
+
76
+
77
+ def normalize_values(
78
+ schema: Mapping[str, ParamDefinition],
79
+ values: Mapping[str, Any] | None,
80
+ *,
81
+ field_prefix: str,
82
+ ) -> dict[str, Any]:
83
+ """Resolve aliases, reject unknown fields and normalize what remains."""
84
+ raw = dict(values or {})
85
+ issues: list[ValidationIssue] = []
86
+
87
+ alias_map = {
88
+ alias: name for name, param in schema.items() for alias in param.aliases
89
+ }
90
+ for alias, name in alias_map.items():
91
+ if alias not in raw:
92
+ continue
93
+ if name in raw:
94
+ issues.append(
95
+ ValidationIssue(
96
+ code="conflicting_fields",
97
+ field=f"{field_prefix}.{alias}",
98
+ value=raw[alias],
99
+ message=f"Fields {name!r} and its alias {alias!r} cannot be used together",
100
+ )
101
+ )
102
+ raw.pop(alias)
103
+ continue
104
+ raw[name] = raw.pop(alias)
105
+
106
+ accepted = sorted(set(schema) | set(alias_map))
107
+ for name in sorted(set(raw) - set(schema)):
108
+ suggestions = tuple(difflib.get_close_matches(name, accepted, n=3, cutoff=0.55))
109
+ issues.append(
110
+ ValidationIssue(
111
+ code="unknown_field",
112
+ field=f"{field_prefix}.{name}",
113
+ value=raw[name],
114
+ message=f"Unknown field {name!r}",
115
+ suggestions=suggestions,
116
+ )
117
+ )
118
+
119
+ normalized: dict[str, Any] = {}
120
+ for name, param in schema.items():
121
+ if name not in raw:
122
+ continue
123
+ try:
124
+ normalized[name] = normalize_parameter_value(param, raw[name])
125
+ except (ValueError, TypeError) as exc:
126
+ code = exc.code if isinstance(exc, ValueNormalizationError) else "invalid_value"
127
+ suggestions = (
128
+ exc.suggestions if isinstance(exc, ValueNormalizationError) else ()
129
+ )
130
+ issues.append(
131
+ ValidationIssue(
132
+ code=code,
133
+ field=f"{field_prefix}.{name}",
134
+ value=raw[name],
135
+ message=str(exc),
136
+ suggestions=tuple(suggestions),
137
+ )
138
+ )
139
+
140
+ if issues:
141
+ raise ParameterValidationError(issues)
142
+ return normalized
143
+
144
+
145
+ __all__ = [
146
+ "initial_runtime_inputs",
147
+ "normalize_runtime_inputs",
148
+ "normalize_values",
149
+ "resolve_configuration",
150
+ ]