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
@@ -0,0 +1,202 @@
1
+ """How a device's measured direction relates to its LED ring.
2
+
3
+ A microphone array and an LED ring are two things screwed to one board, and
4
+ nothing guarantees that the array's zero points at LED zero. On the reSpeaker it
5
+ does not: the cable enters between the twelfth LED and the first, and the array
6
+ is rotated against the ring by whatever the layout happened to be. The number is
7
+ a property of the hardware, measured once.
8
+
9
+ That is why it lives here and is applied by the device rather than by an effect.
10
+ An effect asks for the capability ``doa`` and gets a bearing on the ring it is
11
+ drawing on; it does not ask which way round the board was assembled. Were the
12
+ offset an effect parameter, every definition that reads a direction and every
13
+ preset built from one would carry a copy of the same physical fact, and a second
14
+ device would need a second copy of each.
15
+
16
+ Both device packages need this and neither may import the other, so the shared
17
+ value belongs to the SDK — the same reason :class:`SinkStatus` does.
18
+
19
+ The effect's own ``angle_offset_deg`` stays what it always was: a deliberate
20
+ rotation of the picture, applied on top of a bearing that is already correct.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import os
27
+ from dataclasses import dataclass
28
+ from pathlib import Path
29
+ from typing import Any, Mapping
30
+
31
+ ENV_CALIBRATION_PATH = "LEFX_DOA_CALIBRATION"
32
+ DEFAULT_CALIBRATION_FILE = "doa_calibration.json"
33
+
34
+
35
+ @dataclass(slots=True, frozen=True)
36
+ class DoaCalibration:
37
+ """The rotation between a device's measured zero and its LED zero."""
38
+
39
+ angle_offset_deg: float = 0.0
40
+ reverse: bool = False
41
+ """Whether the array counts angles the other way round the ring."""
42
+
43
+ def __post_init__(self) -> None:
44
+ if not isinstance(self.reverse, bool):
45
+ raise ValueError(f"reverse must be a boolean, got {self.reverse!r}")
46
+ try:
47
+ offset = float(self.angle_offset_deg)
48
+ except (TypeError, ValueError):
49
+ raise ValueError(
50
+ f"angle_offset_deg must be a number, got {self.angle_offset_deg!r}"
51
+ ) from None
52
+ if offset != offset or offset in (float("inf"), float("-inf")):
53
+ raise ValueError(f"angle_offset_deg must be finite, got {offset!r}")
54
+ # Normalised on construction so two calibrations that mean the same
55
+ # rotation compare equal and report the same number.
56
+ object.__setattr__(self, "angle_offset_deg", offset % 360.0)
57
+
58
+ @property
59
+ def identity(self) -> bool:
60
+ """Whether this changes nothing — an uncalibrated device."""
61
+ return self.angle_offset_deg == 0.0 and not self.reverse
62
+
63
+ def apply(self, direction_deg: float | None) -> float | None:
64
+ """Turn a measured bearing into one expressed on the ring.
65
+
66
+ Mirroring comes first and the offset second. The other order would
67
+ mirror the mounting rotation along with the measurement, which is a
68
+ different device and not this one.
69
+
70
+ ``None`` stays ``None``: nothing measured cannot be rotated.
71
+ """
72
+ if direction_deg is None:
73
+ return None
74
+ measured = float(direction_deg) % 360.0
75
+ if self.reverse:
76
+ measured = (-measured) % 360.0
77
+ return (measured + self.angle_offset_deg) % 360.0
78
+
79
+ def to_dict(self) -> dict[str, Any]:
80
+ return {"angle_offset_deg": self.angle_offset_deg, "reverse": self.reverse}
81
+
82
+ @classmethod
83
+ def from_mapping(cls, payload: Mapping[str, Any]) -> "DoaCalibration":
84
+ unknown = set(payload) - {"angle_offset_deg", "reverse"}
85
+ if unknown:
86
+ raise ValueError(f"Unknown calibration keys: {sorted(unknown)}")
87
+ return cls(
88
+ angle_offset_deg=payload.get("angle_offset_deg", 0.0),
89
+ reverse=bool(payload.get("reverse", False)),
90
+ )
91
+
92
+
93
+ def calibration_path(path: str | Path | None = None) -> Path:
94
+ """Where calibrations are kept: the argument, the environment, or the cwd."""
95
+ if path is not None:
96
+ return Path(path).expanduser()
97
+ configured = os.environ.get(ENV_CALIBRATION_PATH)
98
+ if configured:
99
+ return Path(configured).expanduser()
100
+ return Path.cwd() / DEFAULT_CALIBRATION_FILE
101
+
102
+
103
+ def load_calibration(device: str, *, path: str | Path | None = None) -> DoaCalibration:
104
+ """The calibration recorded for one device, or the identity if there is none.
105
+
106
+ Entries are keyed by device, because the file describes devices and there
107
+ can be more than one — a reSpeaker on a desk and a simulator standing in
108
+ for it do not share a mounting angle.
109
+
110
+ A missing file means an uncalibrated device and is not an error. A file that
111
+ exists and cannot be read *is* one: quietly falling back to the identity
112
+ would leave every direction wrong by the offset that was supposed to fix
113
+ it, and it would look exactly like a device that had never been calibrated.
114
+ """
115
+ target = calibration_path(path)
116
+ if not target.is_file():
117
+ return DoaCalibration()
118
+
119
+ try:
120
+ payload = json.loads(target.read_text(encoding="utf-8"))
121
+ except (OSError, json.JSONDecodeError) as exc:
122
+ raise ValueError(f"Cannot read the calibration at {target}: {exc}") from exc
123
+ if not isinstance(payload, dict):
124
+ raise ValueError(f"{target} must contain an object keyed by device name")
125
+
126
+ entry = payload.get(device)
127
+ if entry is None:
128
+ return DoaCalibration()
129
+ if not isinstance(entry, Mapping):
130
+ raise ValueError(f"{target}: entry for {device!r} must be an object")
131
+ try:
132
+ return DoaCalibration.from_mapping(entry)
133
+ except ValueError as exc:
134
+ raise ValueError(f"{target}: entry for {device!r} is invalid: {exc}") from exc
135
+
136
+
137
+ def as_flag(value: Any) -> bool:
138
+ """Coerce a command-line style value to a flag.
139
+
140
+ ``--sink-option reverse=true`` arrives as text. The caller passing it cannot
141
+ know what type a given option wants, so the conversion belongs beside the
142
+ type that wants it.
143
+ """
144
+ if isinstance(value, bool):
145
+ return value
146
+ return str(value).strip().casefold() in {"1", "true", "yes", "on", "ja", "an"}
147
+
148
+
149
+ def resolve_calibration(
150
+ device: str,
151
+ *,
152
+ angle_offset_deg: Any = None,
153
+ reverse: Any = None,
154
+ path: str | Path | None = None,
155
+ ) -> DoaCalibration:
156
+ """The calibration to use: the recorded one, with explicit options on top.
157
+
158
+ Options override individually rather than wholesale, so overriding the
159
+ offset for one run does not silently discard a recorded ``reverse``.
160
+ """
161
+ recorded = load_calibration(device, path=path)
162
+ if angle_offset_deg is None and reverse is None:
163
+ return recorded
164
+ return DoaCalibration(
165
+ angle_offset_deg=(
166
+ recorded.angle_offset_deg if angle_offset_deg is None else float(angle_offset_deg)
167
+ ),
168
+ reverse=recorded.reverse if reverse is None else as_flag(reverse),
169
+ )
170
+
171
+
172
+ def save_calibration(
173
+ device: str, calibration: DoaCalibration, *, path: str | Path | None = None
174
+ ) -> Path:
175
+ """Record one device's calibration, leaving the other devices' alone."""
176
+ target = calibration_path(path)
177
+ payload: dict[str, Any] = {}
178
+ if target.is_file():
179
+ try:
180
+ existing = json.loads(target.read_text(encoding="utf-8"))
181
+ except (OSError, json.JSONDecodeError) as exc:
182
+ raise ValueError(f"Cannot read the calibration at {target}: {exc}") from exc
183
+ if not isinstance(existing, dict):
184
+ raise ValueError(f"{target} must contain an object keyed by device name")
185
+ payload = existing
186
+
187
+ payload[device] = calibration.to_dict()
188
+ target.parent.mkdir(parents=True, exist_ok=True)
189
+ target.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8")
190
+ return target
191
+
192
+
193
+ __all__ = [
194
+ "DEFAULT_CALIBRATION_FILE",
195
+ "ENV_CALIBRATION_PATH",
196
+ "DoaCalibration",
197
+ "as_flag",
198
+ "calibration_path",
199
+ "load_calibration",
200
+ "resolve_calibration",
201
+ "save_calibration",
202
+ ]
lefx/sdk/color.py ADDED
@@ -0,0 +1,108 @@
1
+ """Generic colour and ring geometry maths available to effect packages.
2
+
3
+ Everything here is free of concrete meaning: no defaults for named effects, no
4
+ per-definition branches, no ring size baked in. Functions that depend on the
5
+ ring take ``led_count`` as an argument, because the ring size is a runtime
6
+ setting and not a property of this module.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+
12
+ def clamp_channel(value: float) -> int:
13
+ return max(0, min(255, int(value)))
14
+
15
+
16
+ def rgb(r: float, g: float, b: float) -> int:
17
+ return (clamp_channel(r) << 16) | (clamp_channel(g) << 8) | clamp_channel(b)
18
+
19
+
20
+ def scale_color(color: int, factor: float) -> int:
21
+ """Multiply every channel by ``factor``, clamping at full brightness."""
22
+ factor = max(0.0, factor)
23
+ return rgb(
24
+ ((color >> 16) & 0xFF) * factor,
25
+ ((color >> 8) & 0xFF) * factor,
26
+ (color & 0xFF) * factor,
27
+ )
28
+
29
+
30
+ def blend(color_a: int, color_b: int, mix: float) -> int:
31
+ """Linear interpolation; ``mix=0`` yields ``color_a``, ``mix=1`` ``color_b``."""
32
+ mix = max(0.0, min(1.0, mix))
33
+ inverse = 1.0 - mix
34
+ return rgb(
35
+ ((color_a >> 16) & 0xFF) * inverse + ((color_b >> 16) & 0xFF) * mix,
36
+ ((color_a >> 8) & 0xFF) * inverse + ((color_b >> 8) & 0xFF) * mix,
37
+ (color_a & 0xFF) * inverse + (color_b & 0xFF) * mix,
38
+ )
39
+
40
+
41
+ def segment_lengths(count: int, led_count: int) -> list[int]:
42
+ """Split a ring of ``led_count`` LEDs into ``count`` segments as evenly as possible.
43
+
44
+ The remainder is distributed to the leading segments, so the lengths differ
45
+ by at most one and always sum to ``led_count``.
46
+ """
47
+ if count <= 0 or led_count <= 0:
48
+ return []
49
+ base = led_count // count
50
+ remainder = led_count % count
51
+ return [base + (1 if index < remainder else 0) for index in range(count)]
52
+
53
+
54
+ def evenly_spaced_positions(count: int, led_count: int) -> list[int]:
55
+ """LED indices for ``count`` markers spread evenly around the ring."""
56
+ if count <= 0 or led_count <= 0:
57
+ return []
58
+ step = led_count / float(count)
59
+ return [int(round(index * step)) % led_count for index in range(count)]
60
+
61
+
62
+ def position_for_angle(angle_deg: float, led_count: int) -> int:
63
+ """Map an angle in degrees to the nearest LED index.
64
+
65
+ Rounds half away from zero rather than using :func:`round`, whose
66
+ banker's rounding would make ``0.5`` and ``1.5`` land on the same side.
67
+ """
68
+ if led_count <= 0:
69
+ raise ValueError("led_count must be greater than zero")
70
+ degrees_per_led = 360.0 / led_count
71
+ position = (angle_deg % 360.0) / degrees_per_led
72
+ return int(position + 0.5) % led_count
73
+
74
+
75
+ def sector_for_angle(angle_deg: float, led_count: int) -> int:
76
+ """Map an angle to one of ``2 * led_count`` sectors around the ring.
77
+
78
+ An LED covers ``360 / led_count`` degrees, and a direction is just as
79
+ likely to point *between* two of them as at one. Halving the step gives a
80
+ scale on which both are expressible: on a twelve-LED ring the sectors are
81
+ 15° wide, even sectors sit on an LED and odd ones sit in the gap.
82
+
83
+ That is not a detail of the ring but of how a direction is read off it. A
84
+ marker that can only land on an LED reports an angle up to half an LED away
85
+ from the one measured, and always in the same direction for the same
86
+ physical bearing — which is exactly the error a calibration is trying to
87
+ remove.
88
+ """
89
+ if led_count <= 0:
90
+ raise ValueError("led_count must be greater than zero")
91
+ sectors = 2 * led_count
92
+ degrees_per_sector = 360.0 / sectors
93
+ position = (angle_deg % 360.0) / degrees_per_sector
94
+ return int(position + 0.5) % sectors
95
+
96
+
97
+ def positions_for_angle(angle_deg: float, led_count: int) -> tuple[int, ...]:
98
+ """The LED or LEDs that mark an angle.
99
+
100
+ One index when the direction sits on an LED, two when it falls between
101
+ them. Lighting both is how a ring says "between these" rather than
102
+ silently rounding to whichever is nearer.
103
+ """
104
+ sector = sector_for_angle(angle_deg, led_count)
105
+ lower = (sector // 2) % led_count
106
+ if sector % 2 == 0:
107
+ return (lower,)
108
+ return (lower, (lower + 1) % led_count)
lefx/sdk/context.py ADDED
@@ -0,0 +1,72 @@
1
+ """What a definition receives when it renders or samples.
2
+
3
+ Both contexts are deliberately narrow. Earlier generations handed the renderer
4
+ the whole runtime invocation and the layer it happened to sit on, which invited
5
+ effects to branch on placement — the one thing the layer model exists to
6
+ prevent. A definition needs the clock, the ring size and its values; that is
7
+ what it gets.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+ from typing import Any, Mapping
14
+
15
+ from .definitions import DefinitionBase
16
+
17
+
18
+ @dataclass(slots=True, frozen=True)
19
+ class RenderContext:
20
+ """Everything a definition needs to produce one frame.
21
+
22
+ ``params`` and ``inputs`` are complete: every key the definition declared is
23
+ present and already canonical. ``inputs`` values may be ``None`` while a
24
+ source has not delivered yet or has gone stale.
25
+ """
26
+
27
+ now: float
28
+ """Monotonic engine time. Never wall-clock — animations must survive a clock change."""
29
+
30
+ started_at: float
31
+ """Monotonic time at which this instance became active."""
32
+
33
+ led_count: int
34
+ """Number of positions the returned frame must have."""
35
+
36
+ definition: DefinitionBase
37
+
38
+ params: Mapping[str, Any]
39
+ """Stable configuration, canonical and complete."""
40
+
41
+ inputs: Mapping[str, Any]
42
+ """Mutable runtime inputs; empty for every form but the controlled overlay."""
43
+
44
+ @property
45
+ def elapsed(self) -> float:
46
+ """Seconds since activation — the basis for every time-based animation.
47
+
48
+ Using this rather than a frame counter keeps a definition's timing
49
+ independent of the render rate.
50
+ """
51
+ return self.now - self.started_at
52
+
53
+ def transparent_frame(self) -> list[int | None]:
54
+ """A frame that changes nothing; the neutral result for a transparent form."""
55
+ return [None] * self.led_count
56
+
57
+ def blank_frame(self) -> list[int | None]:
58
+ """A frame of black; opaque and therefore hiding everything below."""
59
+ return [0] * self.led_count
60
+
61
+
62
+ @dataclass(slots=True, frozen=True)
63
+ class InputContext:
64
+ """What a pull source receives when the engine asks it for values."""
65
+
66
+ now: float
67
+ led_count: int
68
+ config: Mapping[str, Any]
69
+ previous_inputs: Mapping[str, Any]
70
+
71
+
72
+ __all__ = ["InputContext", "RenderContext"]