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,165 @@
1
+ """A thin HTTP client for the local service.
2
+
3
+ Uses the standard library so that talking to the service costs no dependency.
4
+ Failures come back as a result object rather than an exception, because the CLI
5
+ reports them as JSON like any other outcome.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import urllib.error
12
+ import urllib.request
13
+ from dataclasses import dataclass
14
+ from typing import Any, Mapping
15
+
16
+ from .api import API_PREFIX
17
+
18
+
19
+ @dataclass(slots=True, frozen=True)
20
+ class Result:
21
+ ok: bool
22
+ status: int | None = None
23
+ data: Any = None
24
+ error: str | None = None
25
+
26
+ def to_dict(self) -> dict[str, Any]:
27
+ if self.ok:
28
+ return {"ok": True, "data": self.data}
29
+ return {"ok": False, "status": self.status, "error": self.error, "detail": self.data}
30
+
31
+
32
+ class ControllerClient:
33
+ def __init__(self, *, host: str = "127.0.0.1", port: int = 8765, timeout: float = 5.0) -> None:
34
+ self.base = f"http://{host}:{port}"
35
+ self.timeout = timeout
36
+
37
+ def _call(self, method: str, path: str, payload: Mapping[str, Any] | None = None) -> Result:
38
+ url = f"{self.base}{path}"
39
+ body = None if payload is None else json.dumps(payload).encode("utf-8")
40
+ request = urllib.request.Request(url, data=body, method=method)
41
+ if body is not None:
42
+ request.add_header("Content-Type", "application/json")
43
+ try:
44
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
45
+ text = response.read().decode("utf-8")
46
+ return Result(ok=True, status=response.status, data=json.loads(text) if text else None)
47
+ except urllib.error.HTTPError as exc:
48
+ text = exc.read().decode("utf-8", errors="replace")
49
+ try:
50
+ detail = json.loads(text)
51
+ except json.JSONDecodeError:
52
+ detail = text
53
+ return Result(ok=False, status=exc.code, data=detail, error=_message(detail, exc))
54
+ except urllib.error.URLError as exc:
55
+ return Result(ok=False, error=f"cannot reach the service at {self.base}: {exc.reason}")
56
+ except OSError as exc:
57
+ return Result(ok=False, error=f"cannot reach the service at {self.base}: {exc}")
58
+
59
+ # -- reads --------------------------------------------------------------
60
+
61
+ def health(self) -> Result:
62
+ return self._call("GET", "/health")
63
+
64
+ def status(self) -> Result:
65
+ return self._call("GET", f"{API_PREFIX}/status")
66
+
67
+ def list(self, kind: str, *, details: bool = False) -> Result:
68
+ query = "?details=true" if details else ""
69
+ return self._call("GET", f"{API_PREFIX}/{kind}{query}")
70
+
71
+ def show(self, target: str) -> Result:
72
+ return self._call("GET", f"{API_PREFIX}/show/{target}")
73
+
74
+ # -- commands -----------------------------------------------------------
75
+
76
+ def set_state(self, target: str, config: Mapping[str, Any], *, slot: str, action: str) -> Result:
77
+ return self._call(
78
+ "POST",
79
+ f"{API_PREFIX}/set/state",
80
+ {"target": target, "config": dict(config), "slot": slot, "action": action},
81
+ )
82
+
83
+ def clear_state(self, *, slot: str) -> Result:
84
+ return self._call("POST", f"{API_PREFIX}/clear/state", {"slot": slot})
85
+
86
+ def set_overlay(
87
+ self, target: str, *, channel: str | None, config: Mapping[str, Any],
88
+ inputs: Mapping[str, Any], action: str,
89
+ ) -> Result:
90
+ return self._call(
91
+ "POST",
92
+ f"{API_PREFIX}/set/overlay",
93
+ {
94
+ "target": target,
95
+ "channel": channel,
96
+ "config": dict(config),
97
+ "inputs": dict(inputs),
98
+ "action": action,
99
+ },
100
+ )
101
+
102
+ def update_overlay(self, channel: str, inputs: Mapping[str, Any]) -> Result:
103
+ return self._call(
104
+ "POST", f"{API_PREFIX}/update/overlay", {"channel": channel, "inputs": dict(inputs)}
105
+ )
106
+
107
+ def clear_overlay(self, channel: str) -> Result:
108
+ return self._call("POST", f"{API_PREFIX}/clear/overlay", {"channel": channel})
109
+
110
+ def emit_event(
111
+ self, target: str, config: Mapping[str, Any], *, priority: int | None,
112
+ duration_ms: int | None,
113
+ ) -> Result:
114
+ return self._call(
115
+ "POST",
116
+ f"{API_PREFIX}/emit/event",
117
+ {
118
+ "target": target,
119
+ "config": dict(config),
120
+ "priority": priority,
121
+ "duration_ms": duration_ms,
122
+ },
123
+ )
124
+
125
+ def clear_all(self) -> Result:
126
+ return self._call("POST", f"{API_PREFIX}/clear/all")
127
+
128
+ def set_output(self, *, brightness: float | None, enabled: bool | None) -> Result:
129
+ return self._call(
130
+ "POST", f"{API_PREFIX}/output", {"brightness": brightness, "enabled": enabled}
131
+ )
132
+
133
+ # -- sources ------------------------------------------------------------
134
+
135
+ def list_sources(self) -> Result:
136
+ return self._call("GET", f"{API_PREFIX}/sources")
137
+
138
+ def register_source(self, path: str, *, enabled: bool = True) -> Result:
139
+ return self._call(
140
+ "POST", f"{API_PREFIX}/sources/register", {"path": path, "enabled": enabled}
141
+ )
142
+
143
+ def reload_sources(self) -> Result:
144
+ return self._call("POST", f"{API_PREFIX}/sources/reload")
145
+
146
+ def remove_source(self, source_id: str) -> Result:
147
+ return self._call("DELETE", f"{API_PREFIX}/sources/{source_id}")
148
+
149
+ def shutdown(self) -> Result:
150
+ return self._call("POST", f"{API_PREFIX}/shutdown")
151
+
152
+
153
+ def _message(detail: Any, exc: urllib.error.HTTPError) -> str:
154
+ if isinstance(detail, Mapping):
155
+ inner = detail.get("detail", detail)
156
+ if isinstance(inner, Mapping):
157
+ if "message" in inner:
158
+ return str(inner["message"])
159
+ issues = inner.get("issues")
160
+ if isinstance(issues, list) and issues:
161
+ return "; ".join(str(item.get("message", item)) for item in issues)
162
+ return f"{exc.code} {exc.reason}"
163
+
164
+
165
+ __all__ = ["ControllerClient", "Result"]
@@ -0,0 +1,305 @@
1
+ """Project-wide settings: one file, one environment convention, one table.
2
+
3
+ Every knob this system has is a row in ``SETTINGS`` below. A row states the
4
+ slug, the type, the default and what the setting means, and everything else
5
+ follows from it: the ``config.yaml`` key is the slug, the environment variables
6
+ are the slug in upper case with and without a ``LEFX_`` prefix, and the value is
7
+ coerced to the declared type wherever it came from. Adding a setting is adding a
8
+ row; there is no second place to register it and no way to add one that the
9
+ file, the environment and the documentation do not all reach.
10
+
11
+ Precedence, highest first:
12
+
13
+ 1. ``LEFX_<SLUG>`` in the environment
14
+ 2. ``<SLUG>`` in the environment
15
+ 3. the key in ``config.yaml``
16
+ 4. the default in the table
17
+
18
+ The prefixed form exists because the bare one is what was asked for and what is
19
+ commonly done, and because ``PORT`` and ``SINK`` are words other software also
20
+ uses. In a container that runs only this service the bare form is the pleasant
21
+ one; in a shared environment the prefixed form is the one that cannot be
22
+ misread. Both are supported so neither situation needs a workaround.
23
+
24
+ Which ``config.yaml``: ``LEFX_CONFIG`` if set, otherwise ``config.yaml`` beside
25
+ the working directory, otherwise ``~/.lefx/config.yaml``. The first one that
26
+ exists wins outright — configuration files that merge are configuration files
27
+ nobody can predict.
28
+
29
+ The file is cached per path and modification time; the environment is read on
30
+ every access. That is the right way round, because the file is a deployment
31
+ decision and the environment is how a single run is varied.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import logging
37
+ import os
38
+ from dataclasses import dataclass
39
+ from pathlib import Path
40
+ from typing import Any, Callable
41
+
42
+ import yaml
43
+
44
+ logger = logging.getLogger("lefx.interfaces.config")
45
+
46
+ ENV_CONFIG_FILE = "LEFX_CONFIG"
47
+ ENV_PREFIX = "LEFX_"
48
+
49
+
50
+ # -- coercion ---------------------------------------------------------------
51
+
52
+
53
+ def _as_bool(value: Any) -> bool:
54
+ if isinstance(value, bool):
55
+ return value
56
+ if isinstance(value, (int, float)):
57
+ return bool(value)
58
+ return str(value).strip().casefold() in {"1", "true", "yes", "on"}
59
+
60
+
61
+ def _as_str_list(value: Any) -> list[str]:
62
+ """A list of names from a list, or from the many ways one gets written.
63
+
64
+ ``[core, smartspeaker]``, ``core,smartspeaker`` and ``core smartspeaker``
65
+ all mean the same thing to a person, so they mean the same thing here.
66
+ """
67
+ if value is None:
68
+ return []
69
+ if isinstance(value, (list, tuple, set)):
70
+ return [str(item).strip() for item in value if str(item).strip()]
71
+ text = str(value).strip()
72
+ if not text:
73
+ return []
74
+ return [item.strip() for item in text.replace(",", " ").split() if item.strip()]
75
+
76
+
77
+ def _as_path_list(value: Any) -> list[str]:
78
+ """Directories, which unlike names may contain spaces.
79
+
80
+ So this splits on the platform path separator like ``PATH`` does, and never
81
+ on whitespace — ``C:\\Program Files\\effects`` is one directory.
82
+ """
83
+ if value is None:
84
+ return []
85
+ if isinstance(value, (list, tuple)):
86
+ return [str(item).strip() for item in value if str(item).strip()]
87
+ return [item.strip() for item in str(value).split(os.pathsep) if item.strip()]
88
+
89
+
90
+ def _as_mapping(value: Any) -> dict[str, Any]:
91
+ if value is None:
92
+ return {}
93
+ if isinstance(value, dict):
94
+ return {str(key): item for key, item in value.items()}
95
+ raise ValueError(f"expected a mapping, got {type(value).__name__}")
96
+
97
+
98
+ def _as_optional_str(value: Any) -> str | None:
99
+ if value is None:
100
+ return None
101
+ text = str(value).strip()
102
+ return text or None
103
+
104
+
105
+ # -- the table --------------------------------------------------------------
106
+
107
+
108
+ @dataclass(slots=True, frozen=True)
109
+ class Setting:
110
+ slug: str
111
+ coerce: Callable[[Any], Any]
112
+ default: Any
113
+ doc: str
114
+
115
+ @property
116
+ def env_names(self) -> tuple[str, str]:
117
+ bare = self.slug.upper()
118
+ return f"{ENV_PREFIX}{bare}", bare
119
+
120
+
121
+ SETTINGS: tuple[Setting, ...] = (
122
+ Setting("led_count", int, 12,
123
+ "How many LEDs the ring has. The renderer checks every frame against it."),
124
+ Setting("fps", float, 30.0,
125
+ "Render loop rate."),
126
+ Setting("host", str, "127.0.0.1",
127
+ "Address 'lefx serve' binds to."),
128
+ Setting("port", int, 8765,
129
+ "Port 'lefx serve' asks for. A busy one falls through to the pool."),
130
+ Setting("sink", str, "null",
131
+ "Which frame sink to use: respeaker, simulator, null, or anything installed."),
132
+ Setting("sink_options", _as_mapping, {},
133
+ "Extra keywords handed to the chosen device's factories, e.g. {port: 8770}."),
134
+ Setting("input_device", _as_optional_str, None,
135
+ "Device whose input providers run. Defaults to the sink's device."),
136
+ Setting("state_root", _as_optional_str, None,
137
+ "Where logs, the instance file and persisted state go. Defaults to a temp directory."),
138
+ Setting("package_path", _as_path_list, [],
139
+ "Extra directories scanned for .lefx and .lefxset files, separated like PATH."),
140
+ Setting("included_lefxset", _as_str_list, [],
141
+ "Which installed effect sets to load, e.g. [core, smartspeaker]. Empty means all."),
142
+ Setting("log_level", str, "INFO",
143
+ "Logging level for the service process."),
144
+ )
145
+
146
+ BY_SLUG: dict[str, Setting] = {setting.slug: setting for setting in SETTINGS}
147
+
148
+
149
+ # -- the file ---------------------------------------------------------------
150
+
151
+
152
+ def config_file() -> Path | None:
153
+ """The configuration file in effect, or None when there is none.
154
+
155
+ An explicitly named file that does not exist is an error rather than a
156
+ silent fall-through: someone who sets LEFX_CONFIG has said which file they
157
+ mean, and starting with defaults instead would be the wrong kind of helpful.
158
+ """
159
+ named = os.environ.get(ENV_CONFIG_FILE)
160
+ if named:
161
+ path = Path(named).expanduser()
162
+ if not path.is_file():
163
+ raise FileNotFoundError(f"{ENV_CONFIG_FILE} points at {path}, which is not a file")
164
+ return path
165
+ for candidate in (Path.cwd() / "config.yaml", Path.home() / ".lefx" / "config.yaml"):
166
+ if candidate.is_file():
167
+ return candidate
168
+ return None
169
+
170
+
171
+ _FILE_CACHE: dict[tuple[Path, int, int], dict[str, Any]] = {}
172
+
173
+
174
+ def _file_values() -> dict[str, Any]:
175
+ path = config_file()
176
+ if path is None:
177
+ return {}
178
+ stat = path.stat()
179
+ key = (path, stat.st_mtime_ns, stat.st_size)
180
+ cached = _FILE_CACHE.get(key)
181
+ if cached is not None:
182
+ return cached
183
+
184
+ loaded = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
185
+ if not isinstance(loaded, dict):
186
+ raise ValueError(f"{path} must contain a mapping at the top level")
187
+
188
+ values = {str(key_): value for key_, value in loaded.items()}
189
+ unknown = sorted(set(values) - set(BY_SLUG))
190
+ if unknown:
191
+ # A warning rather than an error: a typo should be visible, but a file
192
+ # written for a newer version must not stop an older one from starting.
193
+ logger.warning(
194
+ "%s has keys this version does not know: %s (known: %s)",
195
+ path, ", ".join(unknown), ", ".join(sorted(BY_SLUG)),
196
+ )
197
+
198
+ _FILE_CACHE.clear()
199
+ _FILE_CACHE[key] = values
200
+ return values
201
+
202
+
203
+ def forget_file() -> None:
204
+ """Drop the cached file. For tests, and for a process that rewrote its own."""
205
+ _FILE_CACHE.clear()
206
+
207
+
208
+ # -- reading ----------------------------------------------------------------
209
+
210
+
211
+ def _from_environment(setting: Setting) -> tuple[bool, Any]:
212
+ for name in setting.env_names:
213
+ raw = os.environ.get(name)
214
+ if raw is None:
215
+ continue
216
+ # YAML first so that [core, smartspeaker], 12 and true arrive as what
217
+ # they look like; the raw string otherwise, because a Windows path is
218
+ # not YAML and should not be treated as though it might be.
219
+ try:
220
+ parsed = yaml.safe_load(raw)
221
+ except yaml.YAMLError:
222
+ parsed = raw
223
+ return True, raw if parsed is None and raw.strip() else parsed
224
+ return False, None
225
+
226
+
227
+ def get(slug: str) -> Any:
228
+ """One setting, resolved through the whole precedence chain."""
229
+ setting = BY_SLUG[slug]
230
+ found, raw = _from_environment(setting)
231
+ source = "environment"
232
+ if not found:
233
+ values = _file_values()
234
+ if slug in values:
235
+ found, raw, source = True, values[slug], "config file"
236
+ if not found:
237
+ return setting.default
238
+ try:
239
+ return setting.coerce(raw)
240
+ except (TypeError, ValueError) as exc:
241
+ raise ValueError(f"{slug} from the {source} is not usable: {raw!r} ({exc})") from exc
242
+
243
+
244
+ @dataclass(slots=True, frozen=True)
245
+ class Settings:
246
+ """Every setting resolved at one moment, so one run cannot disagree with itself."""
247
+
248
+ values: dict[str, Any]
249
+
250
+ def __getattr__(self, name: str) -> Any:
251
+ try:
252
+ return self.values[name]
253
+ except KeyError:
254
+ raise AttributeError(name) from None
255
+
256
+ def __getitem__(self, name: str) -> Any:
257
+ return self.values[name]
258
+
259
+ def to_dict(self) -> dict[str, Any]:
260
+ return dict(self.values)
261
+
262
+
263
+ def settings() -> Settings:
264
+ """Read everything now. Cheap enough to call at construction, and only there."""
265
+ return Settings({setting.slug: get(setting.slug) for setting in SETTINGS})
266
+
267
+
268
+ def describe() -> dict[str, Any]:
269
+ """What is set, where each value came from, for 'lefx config' and /status."""
270
+ file_values = _file_values()
271
+ rows = []
272
+ for setting in SETTINGS:
273
+ found, _ = _from_environment(setting)
274
+ if found:
275
+ source = next(name for name in setting.env_names if name in os.environ)
276
+ elif setting.slug in file_values:
277
+ source = "config.yaml"
278
+ else:
279
+ source = "default"
280
+ rows.append(
281
+ {
282
+ "slug": setting.slug,
283
+ "value": get(setting.slug),
284
+ "source": source,
285
+ "env": list(setting.env_names),
286
+ "doc": setting.doc,
287
+ }
288
+ )
289
+ path = config_file()
290
+ return {"file": None if path is None else str(path), "settings": rows}
291
+
292
+
293
+ __all__ = [
294
+ "BY_SLUG",
295
+ "ENV_CONFIG_FILE",
296
+ "ENV_PREFIX",
297
+ "SETTINGS",
298
+ "Setting",
299
+ "Settings",
300
+ "config_file",
301
+ "describe",
302
+ "forget_file",
303
+ "get",
304
+ "settings",
305
+ ]