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,143 @@
1
+ """The import boundary that keeps packages self-contained.
2
+
3
+ A package must build, ship and load on its own. It may use the standard library
4
+ and the SDK, and it may import its own local modules — nothing else. Reaching
5
+ into the engine, the service, or another package would mean the archive is not
6
+ actually the unit it claims to be.
7
+
8
+ There is deliberately no shared effect library. A ``common.py`` sitting beside
9
+ several definitions is the shape this always takes, and it is exactly what makes
10
+ packages stop being independently installable.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import ast
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+
19
+ ALLOWED_STDLIB: frozenset[str] = frozenset(
20
+ {
21
+ "__future__",
22
+ "abc",
23
+ "bisect",
24
+ "cmath",
25
+ "collections",
26
+ "colorsys",
27
+ "dataclasses",
28
+ "enum",
29
+ "fractions",
30
+ "functools",
31
+ "hashlib",
32
+ "itertools",
33
+ "math",
34
+ "numbers",
35
+ "operator",
36
+ "random",
37
+ "statistics",
38
+ "types",
39
+ "typing",
40
+ }
41
+ )
42
+
43
+ ALLOWED_ROOTS: frozenset[str] = frozenset({"lefx.sdk"})
44
+
45
+ FORBIDDEN_MODULE_NAMES: frozenset[str] = frozenset({"common", "shared", "utils", "helpers"})
46
+
47
+
48
+ @dataclass(slots=True, frozen=True)
49
+ class ImportViolation:
50
+ file: str
51
+ line: int
52
+ module: str
53
+ reason: str
54
+
55
+ def __str__(self) -> str:
56
+ return f"{self.file}:{self.line}: {self.module} — {self.reason}"
57
+
58
+
59
+ def _is_allowed(module: str) -> tuple[bool, str]:
60
+ root = module.split(".", 1)[0]
61
+ if module in ALLOWED_ROOTS or module.startswith("lefx.sdk."):
62
+ return True, ""
63
+ # Every part of this system now lives under ``lefx.``, so one rule covers
64
+ # the engine, the control surface and both device packages: a definition
65
+ # names the authoring contract and nothing else, which is what lets the same
66
+ # source run against hardware, against the simulator, or inside the studio.
67
+ if root == "lefx":
68
+ return False, "only lefx.sdk is available to a package; nothing else in lefx is importable"
69
+ if root in ALLOWED_STDLIB:
70
+ return True, ""
71
+ return False, "not in the allowed standard library subset or the LEFX SDK"
72
+
73
+
74
+ def check_imports(root: Path) -> list[ImportViolation]:
75
+ """Every import in every Python file of the source, checked against the list."""
76
+ violations: list[ImportViolation] = []
77
+ for path in sorted(root.rglob("*.py")):
78
+ relative = path.relative_to(root).as_posix()
79
+ if path.stem in FORBIDDEN_MODULE_NAMES:
80
+ violations.append(
81
+ ImportViolation(
82
+ file=relative,
83
+ line=0,
84
+ module=path.stem,
85
+ reason=(
86
+ "generic shared modules are not allowed; give the module a "
87
+ "concrete name describing what this definition does with it"
88
+ ),
89
+ )
90
+ )
91
+ try:
92
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
93
+ except SyntaxError as exc:
94
+ violations.append(
95
+ ImportViolation(file=relative, line=exc.lineno or 0, module="", reason=str(exc))
96
+ )
97
+ continue
98
+
99
+ for node in ast.walk(tree):
100
+ if isinstance(node, ast.Import):
101
+ for alias in node.names:
102
+ allowed, reason = _is_allowed(alias.name)
103
+ if not allowed:
104
+ violations.append(
105
+ ImportViolation(relative, node.lineno, alias.name, reason)
106
+ )
107
+ elif isinstance(node, ast.ImportFrom):
108
+ if node.level:
109
+ # Relative imports stay inside the source; that is the point.
110
+ continue
111
+ module = node.module or ""
112
+ allowed, reason = _is_allowed(module)
113
+ if not allowed:
114
+ violations.append(ImportViolation(relative, node.lineno, module, reason))
115
+ return violations
116
+
117
+
118
+ def find_effect_classes(path: Path) -> list[str]:
119
+ """Names of classes defined in this file that derive from ``BaseEffect``.
120
+
121
+ Read from the syntax tree rather than by importing, so a source with a
122
+ layout problem still gives a useful message instead of an import traceback.
123
+ """
124
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
125
+ names: list[str] = []
126
+ for node in tree.body:
127
+ if not isinstance(node, ast.ClassDef):
128
+ continue
129
+ for base in node.bases:
130
+ if isinstance(base, ast.Name) and base.id == "BaseEffect":
131
+ names.append(node.name)
132
+ elif isinstance(base, ast.Attribute) and base.attr == "BaseEffect":
133
+ names.append(node.name)
134
+ return names
135
+
136
+
137
+ __all__ = [
138
+ "ALLOWED_ROOTS",
139
+ "ALLOWED_STDLIB",
140
+ "ImportViolation",
141
+ "check_imports",
142
+ "find_effect_classes",
143
+ ]
@@ -0,0 +1,330 @@
1
+ """Templates for new sources.
2
+
3
+ Every scaffold validates and packs as generated. Starting from something that
4
+ already works means the first error an author sees comes from their own change,
5
+ not from the starting point.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from lefx.sdk import DefinitionKind
14
+
15
+ from .source import SourceError
16
+
17
+ _KIND_ALIASES = {
18
+ "state": DefinitionKind.STATE,
19
+ "overlay": DefinitionKind.CONTROLLED_OVERLAY,
20
+ "controlled": DefinitionKind.CONTROLLED_OVERLAY,
21
+ "controlled_overlay": DefinitionKind.CONTROLLED_OVERLAY,
22
+ "timed": DefinitionKind.TIMED_OVERLAY,
23
+ "timed_overlay": DefinitionKind.TIMED_OVERLAY,
24
+ "event": DefinitionKind.EVENT,
25
+ }
26
+
27
+
28
+ def parse_kind(value: str) -> DefinitionKind:
29
+ normalized = str(value or "").strip().lower().replace("-", "_")
30
+ if normalized not in _KIND_ALIASES:
31
+ options = ", ".join(sorted({"state", "controlled_overlay", "timed_overlay", "event"}))
32
+ raise SourceError(f"Unknown definition kind {value!r}. Expected one of: {options}")
33
+ return _KIND_ALIASES[normalized]
34
+
35
+
36
+ def _class_name(effect_id: str) -> str:
37
+ return "".join(part.capitalize() for part in effect_id.split("_")) or "Effect"
38
+
39
+
40
+ _MANIFEST = """\
41
+ # The class in effect.py is the source of truth for the contract. This manifest
42
+ # only says where the definition belongs and where to find it.
43
+ source_id: {source_id}
44
+ entry_file: effect.py
45
+ entry_class: {class_name}
46
+ """
47
+
48
+ _PRESETS = """\
49
+ presets:
50
+ {effect_id}_default:
51
+ title: {title} (Default)
52
+ description: A starting point; every value stays overridable.
53
+ params:
54
+ color: "{color}"
55
+ """
56
+
57
+ _STATE = '''\
58
+ from lefx.sdk import (
59
+ BaseEffect,
60
+ ColorModel,
61
+ ParamDefinition,
62
+ ParamType,
63
+ RenderContext,
64
+ StateDefinition,
65
+ StateSlot,
66
+ parse_color,
67
+ scale_color,
68
+ )
69
+
70
+
71
+ class {class_name}(BaseEffect):
72
+ """A persistent ground state: runs until it is replaced or cleared."""
73
+
74
+ definition = StateDefinition(
75
+ id="{effect_id}",
76
+ title="{title}",
77
+ description="Describe what this state shows and when it applies.",
78
+ parameter_schema={{
79
+ "color": ParamDefinition(
80
+ name="color", type=ParamType.COLOR, default="{color}",
81
+ description="Ring colour.",
82
+ ),
83
+ "brightness": ParamDefinition(
84
+ name="brightness", type=ParamType.FLOAT, default=1.0,
85
+ minimum=0.0, maximum=1.0, description="Brightness factor.",
86
+ ),
87
+ }},
88
+ color_model=ColorModel.MONO,
89
+ slots=(StateSlot.PRIMARY,),
90
+ )
91
+
92
+ def render(self, ctx: RenderContext) -> list[int | None]:
93
+ # ctx.params always holds every declared key, already canonical.
94
+ color = scale_color(parse_color(ctx.params["color"]), ctx.params["brightness"])
95
+ return [color] * ctx.led_count
96
+ '''
97
+
98
+ _CONTROLLED = '''\
99
+ from lefx.sdk import (
100
+ BaseEffect,
101
+ ColorModel,
102
+ CompositionMode,
103
+ ControlledOverlayDefinition,
104
+ ParamDefinition,
105
+ ParamType,
106
+ RenderContext,
107
+ parse_color,
108
+ position_for_angle,
109
+ scale_color,
110
+ )
111
+
112
+
113
+ class {class_name}(BaseEffect):
114
+ """A controlled overlay: runs until its channel is cleared, fed at runtime."""
115
+
116
+ definition = ControlledOverlayDefinition(
117
+ id="{effect_id}",
118
+ title="{title}",
119
+ description="Describe what this overlay shows and who supplies its data.",
120
+ parameter_schema={{
121
+ "color": ParamDefinition(
122
+ name="color", type=ParamType.COLOR, default="{color}",
123
+ description="Marker colour.",
124
+ ),
125
+ "brightness": ParamDefinition(
126
+ name="brightness", type=ParamType.FLOAT, default=1.0,
127
+ minimum=0.0, maximum=1.0, description="Brightness factor.",
128
+ ),
129
+ }},
130
+ runtime_inputs={{
131
+ "direction_deg": ParamDefinition(
132
+ name="direction_deg", type=ParamType.ANGLE_DEG,
133
+ required=True, nullable=True, unit="deg",
134
+ description="Direction supplied while the overlay runs.",
135
+ ),
136
+ }},
137
+ color_model=ColorModel.MONO,
138
+ composition=CompositionMode.TRANSPARENT,
139
+ )
140
+
141
+ def render(self, ctx: RenderContext) -> list[int | None]:
142
+ # None leaves the layers below visible; black would hide them.
143
+ frame = ctx.transparent_frame()
144
+ direction = ctx.inputs["direction_deg"]
145
+ if direction is None:
146
+ # No value yet, or the source went quiet. Show nothing.
147
+ return frame
148
+ color = scale_color(parse_color(ctx.params["color"]), ctx.params["brightness"])
149
+ frame[position_for_angle(direction, ctx.led_count)] = color
150
+ return frame
151
+ '''
152
+
153
+ _TIMED = '''\
154
+ from lefx.sdk import (
155
+ BaseEffect,
156
+ ColorModel,
157
+ CompositionMode,
158
+ ParamDefinition,
159
+ ParamType,
160
+ RenderContext,
161
+ TimedOverlayDefinition,
162
+ parse_color,
163
+ scale_color,
164
+ )
165
+
166
+
167
+ class {class_name}(BaseEffect):
168
+ """A timed overlay: activated once, removed by the engine when its time is up."""
169
+
170
+ definition = TimedOverlayDefinition(
171
+ id="{effect_id}",
172
+ title="{title}",
173
+ description="Describe what this overlay shows for its short lifetime.",
174
+ parameter_schema={{
175
+ "color": ParamDefinition(
176
+ name="color", type=ParamType.COLOR, default="{color}",
177
+ description="Overlay colour.",
178
+ ),
179
+ "brightness": ParamDefinition(
180
+ name="brightness", type=ParamType.FLOAT, default=1.0,
181
+ minimum=0.0, maximum=1.0, description="Brightness factor.",
182
+ ),
183
+ "duration_ms": ParamDefinition(
184
+ name="duration_ms", type=ParamType.DURATION_MS, default=1200,
185
+ minimum=1, unit="ms", description="How long it stays visible.",
186
+ ),
187
+ }},
188
+ color_model=ColorModel.MONO,
189
+ composition=CompositionMode.TRANSPARENT,
190
+ )
191
+
192
+ def render(self, ctx: RenderContext) -> list[int | None]:
193
+ # Progress comes from the clock, never from a frame counter.
194
+ total = ctx.params["duration_ms"] / 1000.0
195
+ progress = min(1.0, ctx.elapsed / total) if total > 0 else 1.0
196
+ lit = max(1, int(round(progress * ctx.led_count)))
197
+ color = scale_color(parse_color(ctx.params["color"]), ctx.params["brightness"])
198
+ frame = ctx.transparent_frame()
199
+ for index in range(lit):
200
+ frame[index] = color
201
+ return frame
202
+ '''
203
+
204
+ _EVENT = '''\
205
+ from lefx.sdk import (
206
+ BaseEffect,
207
+ ColorModel,
208
+ CompositionMode,
209
+ EventDefinition,
210
+ ParamDefinition,
211
+ ParamType,
212
+ RenderContext,
213
+ parse_color,
214
+ scale_color,
215
+ )
216
+
217
+
218
+ class {class_name}(BaseEffect):
219
+ """An event: a single prioritized signal the engine ends on its own."""
220
+
221
+ definition = EventDefinition(
222
+ id="{effect_id}",
223
+ title="{title}",
224
+ description="Describe the signal this event conveys.",
225
+ parameter_schema={{
226
+ "color": ParamDefinition(
227
+ name="color", type=ParamType.COLOR, default="{color}",
228
+ description="Signal colour.",
229
+ ),
230
+ "brightness": ParamDefinition(
231
+ name="brightness", type=ParamType.FLOAT, default=1.0,
232
+ minimum=0.0, maximum=1.0, description="Brightness factor.",
233
+ ),
234
+ "duration_ms": ParamDefinition(
235
+ name="duration_ms", type=ParamType.DURATION_MS, default=600,
236
+ minimum=1, unit="ms", description="How long the signal lasts.",
237
+ ),
238
+ }},
239
+ color_model=ColorModel.MONO,
240
+ composition=CompositionMode.TRANSPARENT,
241
+ )
242
+
243
+ def render(self, ctx: RenderContext) -> list[int | None]:
244
+ total = ctx.params["duration_ms"] / 1000.0
245
+ fade = 1.0 - min(1.0, ctx.elapsed / total) if total > 0 else 0.0
246
+ color = scale_color(
247
+ parse_color(ctx.params["color"]), ctx.params["brightness"] * fade
248
+ )
249
+ return [color] * ctx.led_count
250
+ '''
251
+
252
+ _TEMPLATES = {
253
+ DefinitionKind.STATE: (_STATE, "#3399FF"),
254
+ DefinitionKind.CONTROLLED_OVERLAY: (_CONTROLLED, "#00C066"),
255
+ DefinitionKind.TIMED_OVERLAY: (_TIMED, "#FFB347"),
256
+ DefinitionKind.EVENT: (_EVENT, "#FF3B30"),
257
+ }
258
+
259
+ _SET_MANIFEST = """\
260
+ set_id: {set_id}
261
+ source_id: {source_id}
262
+ title: {title}
263
+ version: 1
264
+ description: Describe what belongs in this set.
265
+ """
266
+
267
+
268
+ def init_effect_source(
269
+ directory: str | Path,
270
+ *,
271
+ effect_id: str,
272
+ source_id: str,
273
+ kind: str = "state",
274
+ title: str | None = None,
275
+ class_name: str | None = None,
276
+ force: bool = False,
277
+ ) -> dict[str, Any]:
278
+ """Write a source directory that already validates and packs."""
279
+ root = Path(directory).expanduser().resolve()
280
+ if root.exists() and any(root.iterdir()) and not force:
281
+ raise SourceError(f"{root} is not empty; pass force to write into it anyway")
282
+
283
+ resolved_kind = parse_kind(kind)
284
+ template, color = _TEMPLATES[resolved_kind]
285
+ name = class_name or _class_name(effect_id)
286
+ display = title or effect_id.replace("_", " ").title()
287
+
288
+ root.mkdir(parents=True, exist_ok=True)
289
+ (root / "effect.yaml").write_text(
290
+ _MANIFEST.format(source_id=source_id, class_name=name), encoding="utf-8"
291
+ )
292
+ (root / "effect.py").write_text(
293
+ template.format(class_name=name, effect_id=effect_id, title=display, color=color),
294
+ encoding="utf-8",
295
+ )
296
+ (root / "presets.yaml").write_text(
297
+ _PRESETS.format(effect_id=effect_id, title=display, color=color), encoding="utf-8"
298
+ )
299
+ return {
300
+ "ok": True,
301
+ "kind": resolved_kind.value,
302
+ "path": str(root),
303
+ "effect_id": effect_id,
304
+ "source_id": source_id,
305
+ "entry_class": name,
306
+ }
307
+
308
+
309
+ def init_effect_set_source(
310
+ directory: str | Path,
311
+ *,
312
+ set_id: str,
313
+ source_id: str,
314
+ title: str | None = None,
315
+ force: bool = False,
316
+ ) -> dict[str, Any]:
317
+ root = Path(directory).expanduser().resolve()
318
+ if root.exists() and any(root.iterdir()) and not force:
319
+ raise SourceError(f"{root} is not empty; pass force to write into it anyway")
320
+
321
+ root.mkdir(parents=True, exist_ok=True)
322
+ (root / "effects").mkdir(exist_ok=True)
323
+ (root / "set.yaml").write_text(
324
+ _SET_MANIFEST.format(set_id=set_id, source_id=source_id, title=title or set_id),
325
+ encoding="utf-8",
326
+ )
327
+ return {"ok": True, "kind": "set", "path": str(root), "set_id": set_id, "source_id": source_id}
328
+
329
+
330
+ __all__ = ["init_effect_set_source", "init_effect_source", "parse_kind"]