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,523 @@
1
+ """Finding out who else is holding the reSpeaker, and — on request — taking it.
2
+
3
+ A WinUSB device handle is exclusive. A second process that opens the reSpeaker
4
+ does not queue behind the first; it gets ``Errno 13``, which reads like a
5
+ permission or driver problem and sends you looking in the wrong place. The usual
6
+ cause is far more ordinary: another controller is already running.
7
+
8
+ Windows offers no supported way to ask "which process holds this device". What
9
+ it does offer is what each process has *loaded*, and that turns out to be a
10
+ sharp signal. ``WinUSB.dll`` is mapped when a WinUSB handle is actually opened,
11
+ not merely when a program is capable of USB — so a process carrying it is
12
+ holding *a* WinUSB device, and one also carrying a libusb backend is holding it
13
+ the same way we would.
14
+
15
+ That is evidence, not proof: it identifies a process talking to some WinUSB
16
+ device, not necessarily to this one. Which is why nothing here kills a set of
17
+ processes. :func:`release_device` stops one candidate, asks the device whether
18
+ it is free, and stops only if it is not — so the process actually in the way is
19
+ the one that goes, and a bystander with an unrelated USB device survives.
20
+
21
+ Nothing in this module runs unless it is asked for. Terminating another person's
22
+ program is not something a render loop should ever decide on its own.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import ctypes
28
+ import ctypes.wintypes as wintypes
29
+ import logging
30
+ import os
31
+ import sys
32
+ import time
33
+ from dataclasses import dataclass, field
34
+ from typing import Callable, Collection, Iterable
35
+
36
+ logger = logging.getLogger("lefx.device.respeaker.contention")
37
+
38
+ WINDOWS = sys.platform.startswith("win")
39
+
40
+ STRONG_MODULES = ("winusb.dll",)
41
+ """Mapped when a WinUSB handle is open — the process is holding a device now."""
42
+
43
+ BACKEND_MODULES = ("libusb-1.0.dll", "libusb0.dll", "libusbk.dll", "usbdk_helper.dll")
44
+ """A USB backend. Says the process speaks USB, not that it is speaking it."""
45
+
46
+ INTERESTING_TERMS = ("respeaker", "xvf", "lefx", "led_controller")
47
+ """What marks a process as *this* device's software rather than some other's.
48
+
49
+ Not proof — a name is not a handle — but it is the difference that matters when
50
+ deciding what may be stopped. On an ordinary desktop the USB evidence alone
51
+ matches mouse and keyboard software: Logitech Options+ and Corsair iCUE both
52
+ carry an open WinUSB handle at all times, for devices that are emphatically not
53
+ a reSpeaker. Stopping either to free a microphone array would be absurd, so by
54
+ default nothing without one of these terms is ever terminated.
55
+ """
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class Holder:
60
+ """A process that looks like it is holding a USB device."""
61
+
62
+ pid: int
63
+ executable: str | None
64
+ command_line: str | None
65
+ evidence: tuple[str, ...]
66
+ confidence: str
67
+ """``"strong"`` for an open WinUSB handle, ``"likely"`` for a loaded backend."""
68
+
69
+ @property
70
+ def related(self) -> bool:
71
+ """Whether this looks like reSpeaker software rather than some other USB app."""
72
+ haystack = f"{self.command_line or ''} {self.executable or ''}".casefold()
73
+ return any(term in haystack for term in INTERESTING_TERMS)
74
+
75
+ @property
76
+ def rank(self) -> tuple[int, int, int]:
77
+ """Sort key: most-certainly-in-the-way first.
78
+
79
+ Ordering matters more than usual here, because candidates are stopped
80
+ one at a time until the device answers — so the first one is usually the
81
+ only one.
82
+ """
83
+ return (0 if self.related else 1, 0 if self.confidence == "strong" else 1, self.pid)
84
+
85
+ def describe(self) -> str:
86
+ what = self.command_line or self.executable or "unknown"
87
+ kind = "reSpeaker software" if self.related else "unrelated USB software"
88
+ return f"pid {self.pid} [{self.confidence}, {kind}] {what} ({', '.join(self.evidence)})"
89
+
90
+
91
+ @dataclass
92
+ class ReleaseReport:
93
+ """What was attempted and what came of it."""
94
+
95
+ reachable_before: bool
96
+ reachable_after: bool
97
+ terminated: list[Holder] = field(default_factory=list)
98
+ candidates: list[Holder] = field(default_factory=list)
99
+ """On a dry run: what would be stopped, in the order it would be tried."""
100
+
101
+ skipped: list[Holder] = field(default_factory=list)
102
+ """Holders deliberately left alone."""
103
+
104
+ failures: list[tuple[Holder, str]] = field(default_factory=list)
105
+ note: str | None = None
106
+ dry_run: bool = False
107
+
108
+ @property
109
+ def changed_anything(self) -> bool:
110
+ return bool(self.terminated)
111
+
112
+ def summary(self) -> str:
113
+ if self.reachable_before:
114
+ return "the reSpeaker was already reachable; nothing was stopped"
115
+ if self.dry_run:
116
+ if not self.candidates:
117
+ return "dry run: nothing would be stopped"
118
+ first = self.candidates[0]
119
+ return (
120
+ f"dry run: nothing was stopped; would try pid {first.pid} first, "
121
+ f"then re-check the device"
122
+ )
123
+ if self.reachable_after:
124
+ names = ", ".join(str(holder.pid) for holder in self.terminated)
125
+ return f"the reSpeaker is reachable after stopping pid {names}"
126
+ if not self.terminated:
127
+ return "the reSpeaker is unreachable and nothing eligible was found to stop"
128
+ return "the reSpeaker is still unreachable after stopping what looked responsible"
129
+
130
+
131
+ # -- Windows plumbing -------------------------------------------------------
132
+
133
+ if WINDOWS: # pragma: no branch
134
+ _k32 = ctypes.WinDLL("kernel32", use_last_error=True)
135
+ _ntdll = ctypes.WinDLL("ntdll", use_last_error=True)
136
+
137
+ TH32CS_SNAPPROCESS = 0x00000002
138
+ TH32CS_SNAPMODULE = 0x00000008
139
+ TH32CS_SNAPMODULE32 = 0x00000010
140
+
141
+ PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
142
+ PROCESS_VM_READ = 0x0010
143
+ PROCESS_TERMINATE = 0x0001
144
+ SYNCHRONIZE = 0x00100000
145
+
146
+ _INVALID_HANDLE = ctypes.c_void_p(-1).value
147
+
148
+ class PROCESSENTRY32(ctypes.Structure):
149
+ _fields_ = [
150
+ ("dwSize", wintypes.DWORD),
151
+ ("cntUsage", wintypes.DWORD),
152
+ ("th32ProcessID", wintypes.DWORD),
153
+ ("th32DefaultHeapID", ctypes.POINTER(ctypes.c_ulong)),
154
+ ("th32ModuleID", wintypes.DWORD),
155
+ ("cntThreads", wintypes.DWORD),
156
+ ("th32ParentProcessID", wintypes.DWORD),
157
+ ("pcPriClassBase", ctypes.c_long),
158
+ ("dwFlags", wintypes.DWORD),
159
+ ("szExeFile", ctypes.c_char * 260),
160
+ ]
161
+
162
+ class MODULEENTRY32(ctypes.Structure):
163
+ _fields_ = [
164
+ ("dwSize", wintypes.DWORD),
165
+ ("th32ModuleID", wintypes.DWORD),
166
+ ("th32ProcessID", wintypes.DWORD),
167
+ ("GlblcntUsage", wintypes.DWORD),
168
+ ("ProccntUsage", wintypes.DWORD),
169
+ ("modBaseAddr", ctypes.POINTER(ctypes.c_byte)),
170
+ ("modBaseSize", wintypes.DWORD),
171
+ ("hModule", wintypes.HMODULE),
172
+ ("szModule", ctypes.c_char * 256),
173
+ ("szExePath", ctypes.c_char * 260),
174
+ ]
175
+
176
+ class UNICODE_STRING(ctypes.Structure):
177
+ _fields_ = [
178
+ ("Length", ctypes.c_ushort),
179
+ ("MaximumLength", ctypes.c_ushort),
180
+ ("Buffer", ctypes.c_void_p),
181
+ ]
182
+
183
+ class PROCESS_BASIC_INFORMATION(ctypes.Structure):
184
+ _fields_ = [
185
+ ("Reserved1", ctypes.c_void_p),
186
+ ("PebBaseAddress", ctypes.c_void_p),
187
+ ("Reserved2", ctypes.c_void_p * 2),
188
+ ("UniqueProcessId", ctypes.c_void_p),
189
+ ("Reserved3", ctypes.c_void_p),
190
+ ]
191
+
192
+ _k32.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
193
+ _k32.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
194
+ _k32.CloseHandle.argtypes = [wintypes.HANDLE]
195
+ _k32.Process32First.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32)]
196
+ _k32.Process32Next.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32)]
197
+ _k32.Module32First.argtypes = [wintypes.HANDLE, ctypes.POINTER(MODULEENTRY32)]
198
+ _k32.Module32Next.argtypes = [wintypes.HANDLE, ctypes.POINTER(MODULEENTRY32)]
199
+ _k32.OpenProcess.restype = wintypes.HANDLE
200
+ _k32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
201
+ _k32.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT]
202
+ _k32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
203
+ _k32.ReadProcessMemory.argtypes = [
204
+ wintypes.HANDLE,
205
+ ctypes.c_void_p,
206
+ ctypes.c_void_p,
207
+ ctypes.c_size_t,
208
+ ctypes.POINTER(ctypes.c_size_t),
209
+ ]
210
+
211
+ # x64 layout, stable from Windows 7 through 11. Read defensively anyway:
212
+ # a wrong offset must degrade to "no command line", never to a crash.
213
+ _PEB_PROCESS_PARAMETERS = 0x20
214
+ _PARAMS_COMMAND_LINE = 0x70
215
+
216
+
217
+ def _snapshot_processes() -> list[tuple[int, str]]:
218
+ snap = _k32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
219
+ if not snap or snap == _INVALID_HANDLE:
220
+ return []
221
+ try:
222
+ entry = PROCESSENTRY32()
223
+ entry.dwSize = ctypes.sizeof(entry)
224
+ found: list[tuple[int, str]] = []
225
+ if not _k32.Process32First(snap, ctypes.byref(entry)):
226
+ return found
227
+ while True:
228
+ found.append((entry.th32ProcessID, entry.szExeFile.decode("mbcs", "replace")))
229
+ if not _k32.Process32Next(snap, ctypes.byref(entry)):
230
+ return found
231
+ finally:
232
+ _k32.CloseHandle(snap)
233
+
234
+
235
+ def _snapshot_modules(pid: int) -> tuple[list[str], str | None]:
236
+ """Loaded module names and the main image path, or empty when unreadable.
237
+
238
+ A snapshot fails for protected processes and across a bitness boundary.
239
+ That is not an error worth reporting: it means this process cannot be
240
+ judged, and one that cannot be judged is never a candidate.
241
+ """
242
+ snap = _k32.CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid)
243
+ if not snap or snap == _INVALID_HANDLE:
244
+ return [], None
245
+ try:
246
+ entry = MODULEENTRY32()
247
+ entry.dwSize = ctypes.sizeof(entry)
248
+ if not _k32.Module32First(snap, ctypes.byref(entry)):
249
+ return [], None
250
+ image = entry.szExePath.decode("mbcs", "replace") or None
251
+ names: list[str] = []
252
+ while True:
253
+ names.append(entry.szModule.decode("mbcs", "replace").casefold())
254
+ if not _k32.Module32Next(snap, ctypes.byref(entry)):
255
+ return names, image
256
+ finally:
257
+ _k32.CloseHandle(snap)
258
+
259
+
260
+ def _command_line(pid: int) -> str | None:
261
+ """Read a process's command line out of its PEB.
262
+
263
+ Worth the trouble because every candidate here is likely to be
264
+ ``python.exe``: without the arguments, a report would name four identical
265
+ processes and leave the choice of which to stop to a coin toss.
266
+ """
267
+ handle = _k32.OpenProcess(
268
+ PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ, False, pid
269
+ )
270
+ if not handle:
271
+ return None
272
+ try:
273
+ info = PROCESS_BASIC_INFORMATION()
274
+ if _ntdll.NtQueryInformationProcess(
275
+ handle, 0, ctypes.byref(info), ctypes.sizeof(info), None
276
+ ):
277
+ return None
278
+ if not info.PebBaseAddress:
279
+ return None
280
+
281
+ params = ctypes.c_void_p()
282
+ if not _read(handle, info.PebBaseAddress + _PEB_PROCESS_PARAMETERS, params):
283
+ return None
284
+ if not params.value:
285
+ return None
286
+
287
+ command = UNICODE_STRING()
288
+ if not _read(handle, params.value + _PARAMS_COMMAND_LINE, command):
289
+ return None
290
+ if not command.Buffer or not command.Length:
291
+ return None
292
+
293
+ buffer = ctypes.create_string_buffer(command.Length)
294
+ if not _read_into(handle, command.Buffer, buffer, command.Length):
295
+ return None
296
+ return buffer.raw.decode("utf-16-le", "replace").strip()
297
+ except Exception: # pragma: no cover — defensive; layout is version-dependent
298
+ return None
299
+ finally:
300
+ _k32.CloseHandle(handle)
301
+
302
+
303
+ def _read(handle, address: int, target) -> bool:
304
+ return _read_into(handle, address, ctypes.byref(target), ctypes.sizeof(target))
305
+
306
+
307
+ def _read_into(handle, address: int, target, size: int) -> bool:
308
+ read = ctypes.c_size_t(0)
309
+ ok = _k32.ReadProcessMemory(
310
+ handle, ctypes.c_void_p(address), target, size, ctypes.byref(read)
311
+ )
312
+ return bool(ok) and read.value == size
313
+
314
+
315
+ # -- identification ---------------------------------------------------------
316
+
317
+
318
+ def find_holders(*, exclude: Collection[int] = ()) -> list[Holder]:
319
+ """Processes that look like they are holding a USB device, best guess first.
320
+
321
+ Never includes this process. Returns an empty list on anything but Windows,
322
+ where the exclusivity this exists to work around does not arise.
323
+ """
324
+ if not WINDOWS:
325
+ return []
326
+
327
+ skip = {0, 4, os.getpid(), *exclude}
328
+ holders: list[Holder] = []
329
+
330
+ for pid, name in _snapshot_processes():
331
+ if pid in skip:
332
+ continue
333
+ modules, image = _snapshot_modules(pid)
334
+ if not modules:
335
+ continue
336
+
337
+ evidence = [module for module in modules if module in STRONG_MODULES]
338
+ confidence = "strong" if evidence else ""
339
+ backends = [module for module in modules if module in BACKEND_MODULES]
340
+ if backends:
341
+ evidence.extend(backends)
342
+ confidence = confidence or "likely"
343
+ if not confidence:
344
+ continue
345
+
346
+ holders.append(
347
+ Holder(
348
+ pid=pid,
349
+ executable=image or name,
350
+ command_line=_command_line(pid),
351
+ evidence=tuple(sorted(evidence)),
352
+ confidence=confidence,
353
+ )
354
+ )
355
+
356
+ holders.sort(key=lambda holder: holder.rank)
357
+ return holders
358
+
359
+
360
+ # -- taking the device ------------------------------------------------------
361
+
362
+
363
+ def release_device(
364
+ probe: Callable[[], bool],
365
+ *,
366
+ dry_run: bool = False,
367
+ only_related: bool = True,
368
+ limit: int = 4,
369
+ settle_s: float = 1.5,
370
+ exclude: Collection[int] = (),
371
+ ) -> ReleaseReport:
372
+ """Stop whatever is holding the device, one process at a time.
373
+
374
+ ``probe`` answers "can the reSpeaker be talked to now". It is asked before
375
+ anything is stopped, and again after each one — so the process actually in
376
+ the way is the last one stopped, and a bystander holding some other USB
377
+ device is never reached.
378
+
379
+ ``only_related`` is the default because the USB evidence alone is not
380
+ selective enough to kill on: peripheral software holds WinUSB handles
381
+ permanently, and it is never holding this device. Processes it excludes are
382
+ still reported, so a genuinely unknown holder can be seen and acted on
383
+ deliberately rather than being terminated by a guess.
384
+
385
+ ``limit`` caps how many processes may be stopped in one attempt. Reaching it
386
+ means the guess was wrong, and going further would be flailing at a machine
387
+ rather than solving anything.
388
+ """
389
+ if probe():
390
+ return ReleaseReport(reachable_before=True, reachable_after=True)
391
+
392
+ found = find_holders(exclude=exclude)
393
+ report = ReleaseReport(reachable_before=False, reachable_after=False, dry_run=dry_run)
394
+ if not found:
395
+ report.note = (
396
+ "no process on this machine has a USB backend loaded, so something "
397
+ "other than contention is in the way — a driver binding, or a "
398
+ "permission this account does not have"
399
+ )
400
+ logger.warning("%s", report.note)
401
+ return report
402
+
403
+ holders = [holder for holder in found if holder.related] if only_related else found
404
+ report.skipped = [holder for holder in found if holder not in holders]
405
+ if not holders:
406
+ report.note = (
407
+ "the processes holding USB devices are not reSpeaker software, so "
408
+ "none was stopped; look at them and, if one really is in the way, "
409
+ "allow it explicitly"
410
+ )
411
+ logger.warning("%s", report.note)
412
+ return report
413
+
414
+ if dry_run:
415
+ report.candidates = holders
416
+ return report
417
+
418
+ for index, holder in enumerate(holders):
419
+ if len(report.terminated) >= limit:
420
+ report.skipped.extend(holders[index:])
421
+ report.note = f"stopped at the limit of {limit} processes"
422
+ break
423
+
424
+ logger.warning("stopping %s to take the reSpeaker", holder.describe())
425
+ error = _terminate(holder.pid, settle_s)
426
+ if error is not None:
427
+ report.failures.append((holder, error))
428
+ logger.warning("could not stop pid %s: %s", holder.pid, error)
429
+ continue
430
+ report.terminated.append(holder)
431
+
432
+ # Give the driver a moment to tear the old handle down: the process is
433
+ # gone before its device handle is, and probing into that window would
434
+ # blame the wrong process for still holding it.
435
+ deadline = time.monotonic() + settle_s
436
+ while time.monotonic() < deadline:
437
+ if probe():
438
+ report.reachable_after = True
439
+ logger.info("the reSpeaker is reachable again")
440
+ return report
441
+ time.sleep(0.1)
442
+
443
+ report.reachable_after = probe()
444
+ return report
445
+
446
+
447
+ def _terminate(pid: int, timeout_s: float) -> str | None:
448
+ """Stop one process. Returns why not, or ``None`` when it is gone."""
449
+ handle = _k32.OpenProcess(PROCESS_TERMINATE | SYNCHRONIZE, False, pid)
450
+ if not handle:
451
+ code = ctypes.get_last_error()
452
+ if code == 5:
453
+ return "access denied — it runs as another user or elevated"
454
+ return f"cannot open the process (error {code})"
455
+ try:
456
+ if not _k32.TerminateProcess(handle, 1):
457
+ return f"terminate failed (error {ctypes.get_last_error()})"
458
+ # 0x102 is WAIT_TIMEOUT: asked to stop, still there.
459
+ if _k32.WaitForSingleObject(handle, int(timeout_s * 1000)) == 0x102:
460
+ return "it did not exit in time"
461
+ return None
462
+ finally:
463
+ _k32.CloseHandle(handle)
464
+
465
+
466
+ def device_probe(vid: int | None = None, pid: int | None = None) -> Callable[[], bool]:
467
+ """A probe that answers whether this reSpeaker can actually be talked to.
468
+
469
+ Enumeration is not the question — a held device still enumerates. The probe
470
+ performs a real read, which is the thing that returns ``Errno 13`` while
471
+ somebody else has the handle.
472
+ """
473
+ from . import xvf
474
+
475
+ def probe() -> bool:
476
+ try:
477
+ device = xvf.find(
478
+ vid if vid is not None else xvf.VENDOR_ID,
479
+ pid if pid is not None else xvf.PRODUCT_ID,
480
+ )
481
+ except Exception:
482
+ return False
483
+ if device is None:
484
+ return False
485
+ try:
486
+ device.read("VERSION")
487
+ return True
488
+ except Exception:
489
+ return False
490
+ finally:
491
+ try:
492
+ device.close()
493
+ except Exception:
494
+ pass
495
+
496
+ return probe
497
+
498
+
499
+ def as_dicts(holders: Iterable[Holder]) -> list[dict]:
500
+ """Holders in a shape the CLI can print as JSON."""
501
+ return [
502
+ {
503
+ "pid": holder.pid,
504
+ "confidence": holder.confidence,
505
+ "related": holder.related,
506
+ "executable": holder.executable,
507
+ "command_line": holder.command_line,
508
+ "evidence": list(holder.evidence),
509
+ }
510
+ for holder in holders
511
+ ]
512
+
513
+
514
+ __all__ = [
515
+ "BACKEND_MODULES",
516
+ "Holder",
517
+ "ReleaseReport",
518
+ "STRONG_MODULES",
519
+ "as_dicts",
520
+ "device_probe",
521
+ "find_holders",
522
+ "release_device",
523
+ ]
@@ -0,0 +1,158 @@
1
+ """The direction-of-arrival input half of the device.
2
+
3
+ Reading is split in two on purpose. :meth:`ReSpeakerDoaProvider.refresh` is
4
+ called once per rendered frame and is the only thing that touches USB, at a rate
5
+ of its own choosing; :meth:`ReSpeakerDoaProvider.sample` hands out the cached
6
+ snapshot and never blocks. Ten overlays watching the direction therefore cost
7
+ one device read per interval, not ten per frame.
8
+
9
+ An inactive VAD is a valid, healthy reading — the microphones heard nothing.
10
+ Only an unreachable or malformed device counts as a failure.
11
+
12
+ The bearing handed out is expressed on the LED ring, not on the microphone
13
+ array: the rotation between the two is a property of this board and is applied
14
+ here, so that an effect asking for ``doa`` gets a direction it can point at
15
+ without knowing which way round the array was fitted.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import logging
21
+ import math
22
+ import threading
23
+ from typing import Any, Mapping
24
+
25
+ from lefx.sdk import DoaCalibration, InputContext
26
+
27
+ from .transport import UsbTransport
28
+
29
+ logger = logging.getLogger("lefx.device.respeaker.provider")
30
+
31
+ DEFAULT_MAX_HZ = 30.0
32
+ """Ceiling on device reads per second, independent of the render rate."""
33
+
34
+
35
+ def decode_doa(payload: Any) -> dict[str, Any]:
36
+ """Turn a raw ``DOA_VALUE`` payload into the declared runtime inputs.
37
+
38
+ Two ``uint16``: the angle in whole degrees, and the voice activity flag.
39
+ Kept a free function so the wire format can be tested without a device.
40
+ """
41
+ if not isinstance(payload, (tuple, list)) or len(payload) != 2:
42
+ raise ValueError(f"Unexpected DOA_VALUE payload: {payload!r}")
43
+
44
+ raw_direction = payload[0]
45
+ if isinstance(raw_direction, bool) or not isinstance(raw_direction, (int, float)):
46
+ raise ValueError(f"Invalid DOA_VALUE direction: {raw_direction!r}")
47
+ direction = float(raw_direction)
48
+ if not math.isfinite(direction) or not 0.0 <= direction < 360.0:
49
+ raise ValueError(f"DOA_VALUE direction is out of range: {raw_direction!r}")
50
+
51
+ raw_vad = payload[1]
52
+ if isinstance(raw_vad, bool):
53
+ active = raw_vad
54
+ elif isinstance(raw_vad, int) and raw_vad in {0, 1}:
55
+ active = bool(raw_vad)
56
+ else:
57
+ raise ValueError(f"Invalid DOA_VALUE VAD flag: {raw_vad!r}")
58
+
59
+ return {
60
+ "direction_deg": direction,
61
+ # The firmware distinguishes sound from silence, not speech from sound.
62
+ # Claiming "speech" here would report more than the device measured.
63
+ "detection_state": "sound" if active else "none",
64
+ }
65
+
66
+
67
+ class ReSpeakerDoaProvider:
68
+ """Caches the device's direction reading on its own schedule."""
69
+
70
+ name = "respeaker.doa"
71
+ capability = "doa"
72
+
73
+ def __init__(
74
+ self,
75
+ transport: UsbTransport,
76
+ *,
77
+ max_hz: float = DEFAULT_MAX_HZ,
78
+ calibration: DoaCalibration | None = None,
79
+ ) -> None:
80
+ if max_hz <= 0:
81
+ raise ValueError("max_hz must be greater than zero")
82
+ self.transport = transport
83
+ self.max_hz = float(max_hz)
84
+ self.interval_s = 1.0 / self.max_hz
85
+ self.calibration = calibration if calibration is not None else DoaCalibration()
86
+
87
+ self._lock = threading.RLock()
88
+ self._snapshot: dict[str, Any] | None = None
89
+ self._last_attempt_at: float | None = None
90
+ self._last_success_at: float | None = None
91
+ self._last_error: str | None = None
92
+ self._poll_count = 0
93
+ self._closed = False
94
+
95
+ def refresh(self, now: float) -> bool:
96
+ """Read the device if the interval has elapsed. Returns whether it tried."""
97
+ with self._lock:
98
+ if self._closed:
99
+ return False
100
+ if self._last_attempt_at is not None and now - self._last_attempt_at < self.interval_s:
101
+ return False
102
+ self._last_attempt_at = now
103
+ self._poll_count += 1
104
+
105
+ try:
106
+ snapshot = decode_doa(self.transport.read("DOA_VALUE"))
107
+ snapshot["direction_deg"] = self.calibration.apply(snapshot["direction_deg"])
108
+ except Exception as exc:
109
+ with self._lock:
110
+ self._last_error = str(exc)
111
+ # A disconnected device has no current direction. Keeping the
112
+ # last one would let the ring point somewhere on stale data.
113
+ self._snapshot = None
114
+ return True
115
+
116
+ with self._lock:
117
+ self._snapshot = snapshot
118
+ self._last_success_at = now
119
+ self._last_error = None
120
+ return True
121
+
122
+ def sample(self, ctx: InputContext) -> Mapping[str, Any] | None:
123
+ """Hand out the cached snapshot. Never touches the device itself.
124
+
125
+ ``None`` means "no reading available" — the same answer the simulator
126
+ gives with no window attached, and what the engine turns into ``waiting``
127
+ and then ``failed``. Why there is none is in :meth:`status`.
128
+ """
129
+ del ctx
130
+ with self._lock:
131
+ return None if self._snapshot is None else dict(self._snapshot)
132
+
133
+ def status(self, now: float) -> dict[str, Any]:
134
+ with self._lock:
135
+ age_ms = (
136
+ None
137
+ if self._last_success_at is None
138
+ else max(0, int(round((now - self._last_success_at) * 1000.0)))
139
+ )
140
+ return {
141
+ "provider_id": self.capability,
142
+ "device": self.name,
143
+ "max_hz": self.max_hz,
144
+ "poll_count": self._poll_count,
145
+ "age_ms": age_ms,
146
+ "last_error": self._last_error,
147
+ "available": self._snapshot is not None,
148
+ "calibration": self.calibration.to_dict(),
149
+ }
150
+
151
+ def close(self) -> None:
152
+ """Idempotent. The transport is shared, so closing it is not our call."""
153
+ with self._lock:
154
+ self._closed = True
155
+ self._snapshot = None
156
+
157
+
158
+ __all__ = ["DEFAULT_MAX_HZ", "ReSpeakerDoaProvider", "decode_doa"]