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.
- led_controller_version_3-3.0.2.dist-info/METADATA +172 -0
- led_controller_version_3-3.0.2.dist-info/RECORD +52 -0
- led_controller_version_3-3.0.2.dist-info/WHEEL +4 -0
- led_controller_version_3-3.0.2.dist-info/entry_points.txt +13 -0
- lefx/device/respeaker/__init__.py +35 -0
- lefx/device/respeaker/cli.py +146 -0
- lefx/device/respeaker/contention.py +523 -0
- lefx/device/respeaker/provider.py +158 -0
- lefx/device/respeaker/registration.py +130 -0
- lefx/device/respeaker/sink.py +108 -0
- lefx/device/respeaker/transport.py +344 -0
- lefx/device/respeaker/xvf.py +313 -0
- lefx/engine/__init__.py +110 -0
- lefx/engine/composer.py +203 -0
- lefx/engine/config.py +27 -0
- lefx/engine/errors.py +84 -0
- lefx/engine/inputs.py +196 -0
- lefx/engine/invocation.py +129 -0
- lefx/engine/layers.py +114 -0
- lefx/engine/library.py +181 -0
- lefx/engine/packages/__init__.py +45 -0
- lefx/engine/packages/loader.py +375 -0
- lefx/engine/packages/manifest.py +308 -0
- lefx/engine/registry.py +347 -0
- lefx/engine/renderer.py +63 -0
- lefx/engine/runtime.py +393 -0
- lefx/engine/store.py +125 -0
- lefx/interfaces/__init__.py +40 -0
- lefx/interfaces/api.py +301 -0
- lefx/interfaces/cli.py +380 -0
- lefx/interfaces/client.py +165 -0
- lefx/interfaces/config.py +305 -0
- lefx/interfaces/discovery.py +308 -0
- lefx/interfaces/hosting.py +123 -0
- lefx/interfaces/paths.py +79 -0
- lefx/interfaces/presentation.py +118 -0
- lefx/interfaces/service.py +468 -0
- lefx/sdk/__init__.py +176 -0
- lefx/sdk/calibration.py +202 -0
- lefx/sdk/color.py +108 -0
- lefx/sdk/context.py +72 -0
- lefx/sdk/definitions.py +526 -0
- lefx/sdk/effects.py +63 -0
- lefx/sdk/errors.py +90 -0
- lefx/sdk/parameters.py +469 -0
- lefx/sdk/ports.py +76 -0
- lefx/sdk/validation.py +150 -0
- lefx/sdk/values.py +212 -0
- lefx/sets/core_set/__init__.py +32 -0
- lefx/sets/core_set/core-set.lefxset +0 -0
- lefx/sets/smartspeaker_set/__init__.py +32 -0
- lefx/sets/smartspeaker_set/smartspeaker-set.lefxset +0 -0
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""The XVF3800 USB control protocol, as a normal importable module.
|
|
2
|
+
|
|
3
|
+
Ported from the vendor's ``xvf_host.py``. The one substantive change is that it
|
|
4
|
+
is *imported* rather than loaded from a file path: the previous generation
|
|
5
|
+
reached for ``importlib.util.spec_from_file_location`` against a path resolved
|
|
6
|
+
at runtime, which works from a checkout and breaks in a frozen build, where
|
|
7
|
+
there is no such file. Nothing about the wire protocol changed.
|
|
8
|
+
|
|
9
|
+
The command-line front end of the original is deliberately not carried over;
|
|
10
|
+
this package talks to the device through :mod:`lefx.device.respeaker.transport`,
|
|
11
|
+
and a second, unmanaged access path to the same USB endpoint is exactly what
|
|
12
|
+
that transport exists to prevent.
|
|
13
|
+
|
|
14
|
+
``PARAMETERS`` maps a command name to ``(resid, cmdid, count, access, type,
|
|
15
|
+
description)``. It is also where the ring size comes from: ``LED_RING_COLOR``
|
|
16
|
+
declares how many colours the firmware expects, so :data:`RING_LED_COUNT` is
|
|
17
|
+
read off the protocol rather than asserted as a constant somewhere.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import struct
|
|
23
|
+
import sys
|
|
24
|
+
import time
|
|
25
|
+
|
|
26
|
+
import usb.core
|
|
27
|
+
import usb.util
|
|
28
|
+
|
|
29
|
+
CONTROL_SUCCESS = 0
|
|
30
|
+
SERVICER_COMMAND_RETRY = 64
|
|
31
|
+
|
|
32
|
+
VENDOR_ID = 0x2886
|
|
33
|
+
PRODUCT_ID = 0x001A
|
|
34
|
+
|
|
35
|
+
MAX_READ_ATTEMPTS = 100
|
|
36
|
+
"""How often a busy servicer may answer ``retry`` before the read gives up."""
|
|
37
|
+
|
|
38
|
+
# name, resid, cmdid, length, access, type, description
|
|
39
|
+
PARAMETERS = {
|
|
40
|
+
# APPLICATION_SERVICER_RESID commands
|
|
41
|
+
"VERSION": (48, 0, 3, "ro", "uint8", "The version number of the firmware. The format is VERSION_MAJOR VERSION_MINOR VERSION_PATCH"),
|
|
42
|
+
"BLD_MSG": (48, 1, 50, "ro", "char", "Retrieve the build message built in to the firmware, normally the build configuration name"),
|
|
43
|
+
"BLD_HOST": (48, 2, 30, "ro", "char", "Retrieve details of the CI build host used to build the firmware"),
|
|
44
|
+
"BLD_REPO_HASH": (48, 3, 40, "ro", "char", "Retrieve the GIT hash of the sw_xvf3800 repo used to build the firmware"),
|
|
45
|
+
"BLD_MODIFIED": (48, 4, 6, "ro", "char", "Show whether or not the current firmware repo has been modified from the official release. Requires use of a GIT repo"),
|
|
46
|
+
"BOOT_STATUS": (48, 5, 3, "ro", "char", "Shows whether or not the firmware has been booted via SPI or JTAG/FLASH"),
|
|
47
|
+
"TEST_CORE_BURN": (48, 6, 1, "rw", "uint8", "Set to enable core burn to exercise worst case timing. This will reboot the chip, reset all parameters to default and significantly increase power consumption."),
|
|
48
|
+
"REBOOT": (48, 7, 1, "wo", "uint8", "Set to any value to reboot the chip and reset all parameters to default."),
|
|
49
|
+
"USB_BIT_DEPTH": (48, 8, 2, "rw", "uint8", "Only relevant for the UA device variant. For the UA device, set or get the USB bit depth IN, OUT to either 16, 24 or 32. Setting will reboot the chip, resetting all other parameters to default. If issued to the INT device, a set is ignored and the device is not rebooted while a get always returns 0 as both IN and OUT bit depths."),
|
|
50
|
+
"SAVE_CONFIGURATION": (48, 9, 1, "wo", "uint8", "Set to any value to save the current configuration to flash."),
|
|
51
|
+
"CLEAR_CONFIGURATION": (48, 10, 1, "wo", "uint8", "Set to any value to clear the current configuration and revert to the default configuration."),
|
|
52
|
+
|
|
53
|
+
# AEC_RESID commands
|
|
54
|
+
"SHF_BYPASS": (33, 70, 1, "rw", "uint8", "AEC bypass"),
|
|
55
|
+
"AEC_NUM_MICS": (33, 71, 1, "ro", "int32", "Number of microphone inputs into the AEC"),
|
|
56
|
+
"AEC_NUM_FARENDS": (33, 72, 1, "ro", "int32", "Number of farend inputs into the AEC"),
|
|
57
|
+
"AEC_MIC_ARRAY_TYPE": (33, 73, 1, "ro", "int32", "Microphone array type (1 - linear, 2 - squarecular)"),
|
|
58
|
+
"AEC_MIC_ARRAY_GEO": (33, 74, 12, "ro", "float", "Microphone array geometry. Each microphone is represented by 3 XYZ coordinates in m."),
|
|
59
|
+
"AEC_AZIMUTH_VALUES": (33, 75, 4, "ro", "radians", "Azimuth values in radians - beam 1, beam 2, free-running beam, 3 - auto-select beam"),
|
|
60
|
+
"TEST_AEC_DISABLE_CONTROL": (33, 76, 1, "wo", "uint32", "Disable Control processing in the AEC resource. Only to be used for internal testing! Do not use in normal operation. When disabled, there's no way to bring back control without restarting the device."),
|
|
61
|
+
"AEC_CURRENT_IDLE_TIME": (33, 77, 1, "ro", "uint32", "AEC processing current idle time in 10ns ticks"),
|
|
62
|
+
"AEC_MIN_IDLE_TIME": (33, 78, 1, "ro", "uint32", "AEC processing minimum idle time in 10ns ticks"),
|
|
63
|
+
"AEC_RESET_MIN_IDLE_TIME": (33, 79, 1, "wo", "uint32", "Reset the AEC minimum idle time. The value of the argument passed is ignored."),
|
|
64
|
+
"AEC_SPENERGY_VALUES": (33, 80, 4, "ro", "float", "Speech energy level values for each beam. Any value above 0 indicates speech. Higher values indicates louder or closer speech, however noise, echo and reverb can cause the energy level to decrease. 0 - beam 1, 1 - beam 2, 2 - free-running beam, 3 - auto-select beam"),
|
|
65
|
+
"AEC_FIXEDBEAMSAZIMUTH_VALUES": (33, 81, 2, "rw", "radians", "Azimuth values in radians for beams in fixed mode - fixed beam 1, fixed beam 2"),
|
|
66
|
+
"AEC_FIXEDBEAMSELEVATION_VALUES": (33, 82, 2, "rw", "radians", "Elevation angles in radians for the beams in fixed mode. 0 - fixed beam 1, 1 - fixed beam 2"),
|
|
67
|
+
"AEC_FIXEDBEAMSGATING": (33, 83, 1, "rw", "uint8", "Enables/disables gating for beams in fixed mode. When enabled, speech energy is used to determine which beam should be active; inactive beams are silenced."),
|
|
68
|
+
"SPECIAL_CMD_AEC_FAR_MIC_INDEX": (33, 90, 2, "wo", "int32", "Set Far and Mic index for AEC filter read. Also used as a trigger command that starts a new filter read"),
|
|
69
|
+
"SPECIAL_CMD_AEC_FILTER_COEFF_START_OFFSET": (33, 91, 1, "rw", "int32", "start offset to get or set the filter coefficients from"),
|
|
70
|
+
"SPECIAL_CMD_AEC_FILTER_COEFFS": (33, 92, 15, "rw", "float", "get or set AEC filter coefficients"),
|
|
71
|
+
"SPECIAL_CMD_AEC_FILTER_LENGTH": (33, 93, 1, "ro", "int32", "get AEC filter length"),
|
|
72
|
+
"AEC_FILTER_CMD_ABORT": (33, 94, 1, "wo", "int32", "Reset the special command state machine. Used for safely exiting from an AEC filter read/write command sequence that has gone wrong."),
|
|
73
|
+
"AEC_AECPATHCHANGE": (33, 0, 1, "ro", "int32", "AEC Path Change Detection. Valid range: 0,1 (false,true)"),
|
|
74
|
+
"AEC_HPFONOFF": (33, 1, 1, "rw", "int32", "High-pass Filter on microphone signals. Valid range: 0,1,2,3,4 (0:Off, 1:on70, 2:on125, 3:on150, 4:on180)"),
|
|
75
|
+
"AEC_AECSILENCELEVEL": (33, 2, 2, "rw", "float", "Power threshold for signal detection in adaptive filter.(set,cur), Valid range (set): [0.0 .. 1.0] Valid range (cur): 0.05*set, 1e-6f or set."),
|
|
76
|
+
"AEC_AECCONVERGED": (33, 3, 1, "ro", "int32", "Flag indicating whether AEC is converged. Valid range: 0,1 (false,true)"),
|
|
77
|
+
"AEC_AECEMPHASISONOFF": (33, 4, 1, "rw", "int32", "Pre-emphasis and de-emphasis filtering for AEC. Valid range: 0,1,2 (off,on,on_eq)on: Emphasis filter for speech signals without modification of far-end ref. on_eq: Emphasis filter for far-end reference signals where the low frequencies are boosted by e.g. an equalizer."),
|
|
78
|
+
"AEC_FAR_EXTGAIN": (33, 5, 1, "rw", "float", "External gain in dB applied to the far-end reference signals. Valid range: [-inf .. inf]"),
|
|
79
|
+
"AEC_PCD_COUPLINGI": (33, 6, 1, "rw", "float", "Sensitivity parameter for PCD. Valid range: [0.0 .. 1.0]PCD can be disabled by setting a value outside the range"),
|
|
80
|
+
"AEC_PCD_MINTHR": (33, 7, 1, "rw", "float", "Minimum threshold value used in PCD. Valid range: [0.0 .. 0.02]"),
|
|
81
|
+
"AEC_PCD_MAXTHR": (33, 8, 1, "rw", "float", "Maximum threshold value used in PCD. Valid range: [0.025 .. 0.2]"),
|
|
82
|
+
"AEC_RT60": (33, 9, 1, "ro", "float", "Current RT60 estimate. Valid range: [0.250 .. 0.900] (seconds) A negative value indicates that the RT60 estimation is invalid."),
|
|
83
|
+
"AEC_ASROUTONOFF": (33, 35, 1, "rw", "int32", "Enables the automatic speech recognition (ASR) output: if set to 0, the AEC residuals are output, one channel per microphone, if set to 1, the ASR processed output is used, where each channel is associated with a beam from the beamformer. Valid range: 0,1 (off, on)"),
|
|
84
|
+
"AEC_ASROUTGAIN": (33, 36, 1, "rw", "float", "Fixed gain applied to qsr output, i.e., only applied if ASROUTONOFF==1.. Valid range: [0.0 .. 1000.0] (linear gain factor)"),
|
|
85
|
+
"AEC_FIXEDBEAMSONOFF": (33, 37, 1, "rw", "int32", "Enables or disables fixed focused beam mode. Valid range: 0,1 (off, on)"),
|
|
86
|
+
"AEC_FIXEDBEAMNOISETHR": (33, 38, 2, "rw", "float", "Threshold value for updating the noise canceller when fixed beam mode is enabled. A higher value indicates that the noise canceller may update when the free running beam is close to the fixed beam. A lower value indicates that the noise canceller may update when the free running beam is further away from the focused beam.[BECLEAR_NUMBER_OF_BEAMS], Valid range: [0.0 .. 1.0]"),
|
|
87
|
+
|
|
88
|
+
# AUDIO_MGR_RESID commands
|
|
89
|
+
"AUDIO_MGR_MIC_GAIN": (35, 0, 1, "rw", "float", "Audio Mgr pre SHF microphone gain"),
|
|
90
|
+
"AUDIO_MGR_REF_GAIN": (35, 1, 1, "rw", "float", "Audio Mgr pre SHF reference gain"),
|
|
91
|
+
"AUDIO_MGR_CURRENT_IDLE_TIME": (35, 2, 1, "ro", "int32", "Get audio manager current idle time in 10ns ticks"),
|
|
92
|
+
"AUDIO_MGR_MIN_IDLE_TIME": (35, 3, 1, "ro", "int32", "Get audio manager min idle time in 10ns ticks"),
|
|
93
|
+
"AUDIO_MGR_RESET_MIN_IDLE_TIME": (35, 4, 1, "wo", "int32", "Reset audio manager min idle time. The value of the argument passed is ignored."),
|
|
94
|
+
"MAX_CONTROL_TIME": (35, 5, 1, "ro", "int32", "Get audio manager max control time"),
|
|
95
|
+
"RESET_MAX_CONTROL_TIME": (35, 6, 1, "wo", "int32", "Reset audio manager max control time. The value of the argument passed is ignored."),
|
|
96
|
+
"I2S_CURRENT_IDLE_TIME": (35, 7, 1, "ro", "int32", "Get I2S current idle time in 10ns ticks"),
|
|
97
|
+
"I2S_MIN_IDLE_TIME": (35, 8, 1, "ro", "int32", "Get I2S min idle time in 10ns ticks"),
|
|
98
|
+
"I2S_RESET_MIN_IDLE_TIME": (35, 9, 1, "wo", "int32", "I2S reset idle time. The value of the argument passed is ignored."),
|
|
99
|
+
"I2S_INPUT_PACKED": (35, 10, 1, "rw", "uint8", "Will expect packed input on both I2S or USB channels if this is not 0. Note, could take up to 3 samples to take effect."),
|
|
100
|
+
"AUDIO_MGR_SELECTED_AZIMUTHS": (35, 11, 2, "ro", "radians", "This returns the azimuths determined by the beam_selection function in post_shf_dsp.c. The default implementation will provide a processed DoA at index 0 and the DoA of the auto select beam at index 1. The processed DoA uses speech energy to select from the DoA on each fixed beam to provide the direction of a speaker. NAN will be returned if neither of the fixed beams contain speech. Versions 2.0.0 and earlier of XVF3800 had a different default implementation of beam_selection which returned the DoA associated with the AUDIO_MGR_SELECTED_CHANNELS"),
|
|
101
|
+
"AUDIO_MGR_SELECTED_CHANNELS": (35, 12, 2, "rw", "uint8", "Default implementation of post processing will use this to select which channels should be output to MUX_USER_CHOSEN_CHANNELS. Note that a customer implementation of the beam selection stage could override this command. How this channel selection aligns with actual output depends on the mux configuration"),
|
|
102
|
+
"AUDIO_MGR_OP_PACKED": (35, 13, 2, "rw", "uint8", "<L>, <R>; Sets/gets packing status for L and R output channels"),
|
|
103
|
+
"AUDIO_MGR_OP_UPSAMPLE": (35, 14, 2, "rw", "uint8", "<L>, <R>; Sets/gets upsample status for L and R output channels, where appropriate"),
|
|
104
|
+
"AUDIO_MGR_OP_L": (35, 15, 2, "rw", "uint8", "<category>, <source>; Sets category and source for L output channel. Equivalent to AUDIO_MGR_OP_L_PK0"),
|
|
105
|
+
"AUDIO_MGR_OP_L_PK0": (35, 16, 2, "rw", "uint8", "<category>, <source>; Sets category and source for first (of three) sources on the L channel in packed mode. Equivalent to AUDIO_MGR_OP_L"),
|
|
106
|
+
"AUDIO_MGR_OP_L_PK1": (35, 17, 2, "rw", "uint8", "Sets category and source for second (of three) sources on the L channel in packed mode"),
|
|
107
|
+
"AUDIO_MGR_OP_L_PK2": (35, 18, 2, "rw", "uint8", "Sets category and source for third (of three) sources on the L channel in packed mode"),
|
|
108
|
+
"AUDIO_MGR_OP_R": (35, 19, 2, "rw", "uint8", "<category>, <source>; Sets category and source for R output channel. Equivalent to AUDIO_MGR_OP_R_PK0"),
|
|
109
|
+
"AUDIO_MGR_OP_R_PK0": (35, 20, 2, "rw", "uint8", "<category>, <source>; Sets category and source for first (of three) sources on the R channel in packed mode. Equivalent to AUDIO_MGR_OP_R"),
|
|
110
|
+
"AUDIO_MGR_OP_R_PK1": (35, 21, 2, "rw", "uint8", "Sets category and source for second (of three) sources on the R channel in packed mode"),
|
|
111
|
+
"AUDIO_MGR_OP_R_PK2": (35, 22, 2, "rw", "uint8", "Sets category and source for third (of three) sources on the R channel in packed mode"),
|
|
112
|
+
"AUDIO_MGR_OP_ALL": (35, 23, 12, "rw", "uint8", "Sets category and source for all 3 sources on L channel and all 3 sources for R channel. Equivalent to AUDIO_MGR_OP_[L,R]_PK[0,1,2] with successive pairs of arguments"),
|
|
113
|
+
"I2S_INACTIVE": (35, 24, 1, "ro", "uint8", "Returns whether the main audio loop is exchanging samples with I2S (0). If not (1), I2S is inactive"),
|
|
114
|
+
"AUDIO_MGR_FAR_END_DSP_ENABLE": (35, 25, 1, "rw", "uint8", "Enables/disables XVF3800 far-end DSP (if implemented). Write a 1 to enable, 0 to disable"),
|
|
115
|
+
"AUDIO_MGR_SYS_DELAY": (35, 26, 1, "rw", "int32", "Delay, measured in samples, that is applied to the reference signal before passing to SHF algorithm"),
|
|
116
|
+
"I2S_DAC_DSP_ENABLE": (35, 27, 1, "rw", "uint8", "Indicates if the DAC performs DSP on the far-end reference signal. If enabled (1), use the I2S signal as input to the audio pipeline, even in the UA configuration"),
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# GPO_SERVICER_RESID commands
|
|
120
|
+
"GPO_READ_VALUES": (20, 0, 5, "ro", "uint8", "Get current logic level of all GPO pins, in order of Pin X0D11, X0D30, X0D31, X0D33 and X0D39."),
|
|
121
|
+
"GPO_WRITE_VALUE": (20, 1, 2, "wo", "uint8", "Set current logic level of selected GPO pin. Supports Pin X0D11, X0D30, X0D31, X0D33 and X0D39."),
|
|
122
|
+
"GPO_PORT_PIN_INDEX": (20, 2, 2, "rw", "uint32", "GPO port index and pin index that the following commands would be directed to"),
|
|
123
|
+
"GPO_PIN_VAL": (20, 3, 3, "wo", "uint8", "value to write to one pin of a GPO port. Payload specifies port_index, pin_index and value to write to the pin"),
|
|
124
|
+
"GPO_PIN_ACTIVE_LEVEL": (20, 4, 1, "rw", "uint32", "Active level of the port/pin specified by the GPO_PORT_PIN_INDEX command. 1 = ACTIVE_HIGH, 0 = ACTIVE_LOW"),
|
|
125
|
+
"LED_EFFECT": (20, 12, 1, "rw", "uint8", "Set the LED effect mode, 0 = off, 1 = breath, 2 = rainbow, 3 = single color, 4 = doa, 5 = ring"),
|
|
126
|
+
"LED_BRIGHTNESS": (20, 13, 1, "rw", "uint8", "Set the brightness value of the LED for the breath and rainbow mode"),
|
|
127
|
+
"LED_GAMMIFY": (20, 14, 1, "rw", "uint8", "Set to enable gamma correction, 0 = disable, 1 = enable"),
|
|
128
|
+
"LED_SPEED": (20, 15, 1, "rw", "uint8", "Set the effect speed of breath and rainbow mode"),
|
|
129
|
+
"LED_COLOR": (20, 16, 1, "rw", "uint32", "Set the LED color of breath mode and single color mode"),
|
|
130
|
+
"LED_DOA_COLOR": (20, 17, 2, "rw", "uint32", "Set the LED color of doa mode, the first value is the base color and the second value is the doa color"),
|
|
131
|
+
"DOA_VALUE": (20, 18, 2, "ro", "uint16", "Get the doa value and if speech is detected, payload[0] = doa value, from 0 to 359, payload[1] = 1 if speech is detected, 0 if not"),
|
|
132
|
+
"LED_RING_COLOR": (20, 19, 12, "rw", "uint32", "Set the LED color of ring mode, each value is the color of one LED"),
|
|
133
|
+
|
|
134
|
+
# PP_RESID commands
|
|
135
|
+
"PP_CURRENT_IDLE_TIME": (17, 70, 1, "ro", "uint32", "PP processing current idle time in 10ns ticks"),
|
|
136
|
+
"PP_MIN_IDLE_TIME": (17, 71, 1, "ro", "uint32", "PP processing minimum idle time in 10ns ticks"),
|
|
137
|
+
"PP_RESET_MIN_IDLE_TIME": (17, 72, 1, "wo", "uint32", "Reset the PP minimum idle time. The value of the argument passed is ignored."),
|
|
138
|
+
"PP_NL_MODEL_CMD_ABORT": (17, 94, 1, "wo", "int32", "Reset the special command state machine. Used for safely exiting from a NL model read/write sequence that has gone wrong."),
|
|
139
|
+
"PP_EQUALIZATION_CMD_ABORT": (17, 100, 1, "wo", "int32", "Reset the special command state machine. Used for safely exiting from an equalization read/write sequence that has gone wrong."),
|
|
140
|
+
"PP_AGCONOFF": (17, 10, 1, "rw", "int32", "Automatic Gain Control. Valid range: 0,1 (off,on)"),
|
|
141
|
+
"PP_AGCMAXGAIN": (17, 11, 1, "rw", "float", "Maximum AGC gain factor. Valid range: [1.0 .. 1000.0] (linear gain factor)"),
|
|
142
|
+
"PP_AGCDESIREDLEVEL": (17, 12, 1, "rw", "float", "Target power level of the output signal. Valid range: [1e-8 .. 1.0] (power level)"),
|
|
143
|
+
"PP_AGCGAIN": (17, 13, 1, "rw", "float", "Current AGC gain factor. Valid range: [1.0 .. 1000.0] (linear gain factor)"),
|
|
144
|
+
"PP_AGCTIME": (17, 14, 1, "rw", "float", "Ramp-up/down time-constant. Valid range: [0.5 .. 4.0] (seconds)"),
|
|
145
|
+
"PP_AGCFASTTIME": (17, 15, 1, "rw", "float", "Ramp down time-constant in case of peaks. Valid range: [0.05 .. 4.0] (seconds)"),
|
|
146
|
+
"PP_AGCALPHAFASTGAIN": (17, 16, 1, "rw", "float", "Gain threshold enabling fast alpha mode. Valid range: [0.0 .. 1000.0] (linear gain factor)"),
|
|
147
|
+
"PP_AGCALPHASLOW": (17, 17, 1, "rw", "float", "Slow memory parameter for speech power. Valid range [0.0 .. 1.0]"),
|
|
148
|
+
"PP_AGCALPHAFAST": (17, 18, 1, "rw", "float", "Fast memory parameter for speech power. Valid range [0.0 .. 1.0]"),
|
|
149
|
+
"PP_LIMITONOFF": (17, 19, 1, "rw", "int32", "Limiter on communication output. Valid range: 0,1 (off,on)"),
|
|
150
|
+
"PP_LIMITPLIMIT": (17, 20, 1, "rw", "float", "Maximum limiter power. Valid range: [1e-8 .. 1.0] (power level)"),
|
|
151
|
+
"PP_MIN_NS": (17, 21, 1, "rw", "float", "Gain-floor for stationary noise suppression. Valid range: [0.0 .. 1.0]"),
|
|
152
|
+
"PP_MIN_NN": (17, 22, 1, "rw", "float", "Gain-floor for non-stationary noise suppression. Valid range: [0.0 .. 1.0]"),
|
|
153
|
+
"PP_ECHOONOFF": (17, 23, 1, "rw", "int32", "Echo suppression. Valid range: 0,1 (off,on)"),
|
|
154
|
+
"PP_GAMMA_E": (17, 24, 1, "rw", "float", "Over-subtraction factor of echo (direct and early components). Valid range: [0.0 .. 2.0]"),
|
|
155
|
+
"PP_GAMMA_ETAIL": (17, 25, 1, "rw", "float", "Over-subtraction factor of echo (tail components). Valid range: [0.0 .. 2.0]"),
|
|
156
|
+
"PP_GAMMA_ENL": (17, 26, 1, "rw", "float", "Over-subtraction factor of non-linear echo. Valid range: [0.0 .. 5.0]"),
|
|
157
|
+
"PP_NLATTENONOFF": (17, 27, 1, "rw", "int32", "Non-Linear echo attenuation. Valid range: 0,1 (off,on)"),
|
|
158
|
+
"PP_NLAEC_MODE": (17, 28, 1, "rw", "int32", "Non-Linear AEC training mode. Valid range: 0,1,2 (normal,train,train2)"),
|
|
159
|
+
"PP_MGSCALE": (17, 29, 3, "rw", "float", "Minimum gain scale for acoustic echo suppression.(max,min,cur), Valid range (max,min): [(1.0,0.0) .. (1e5,max)] Valid range (cur): min or max."),
|
|
160
|
+
"PP_FMIN_SPEINDEX": (17, 30, 1, "rw", "float", "In case of double talk, frequencies below SPEINDEX are more suppressed than frequencies above SPEINDEX. The actual suppression is depending on the setting of DTSENSITIVE. The parameter is not a taste parameter but needs to be tuned for a specific device. Valid range: [0.0 .. 7999.0]"),
|
|
161
|
+
"PP_DTSENSITIVE": (17, 31, 1, "rw", "int32", "Tradeoff between echo suppression and doubletalk performance. A lower value prefers high echo suppression (possibly at the cost of less doubletalk performance), a higher value prefers better doubletalk performance (possibly at the cost of good echo suppression). Good doubletalk performance is only possible for hardware without much non-linearities. When the value has 2 digits, for robustness an extra near-end speech detector is used. Valid range: [0 .. 5, 10 .. 15]"),
|
|
162
|
+
"PP_ATTNS_MODE": (17, 32, 1, "rw", "int32", "Additional reduction of AGC gain during non-speech. Valid range: 0,1 (off, on)"),
|
|
163
|
+
"PP_ATTNS_NOMINAL": (17, 33, 1, "rw", "float", "Amount of additional reduction during non-speech at nominal speech level. Valid range: [0.0 .. 1.0]"),
|
|
164
|
+
"PP_ATTNS_SLOPE": (17, 34, 1, "rw", "float", "Determines the extra amount of suppression during non-speech when the AGC level increases at lower speech level. The extra attenuation is given by (agcgain_nominal/agcgain_current)^attns_slope. With a value of 1.0 the amount of noise in the output remains approximately the same, independent of the agc gain. Valid range: [0.0 .. 5.0]"),
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
RING_LED_COUNT: int = PARAMETERS["LED_RING_COLOR"][2]
|
|
168
|
+
"""How many colours ``LED_RING_COLOR`` carries — the ring size of this device.
|
|
169
|
+
|
|
170
|
+
Read from the command table rather than written down again, so the number the
|
|
171
|
+
firmware accepts and the number this package sends cannot drift apart. The
|
|
172
|
+
engine's ``led_count`` is configuration; this is a property of the hardware, and
|
|
173
|
+
the sink reports a mismatch between the two instead of truncating a frame.
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
LED_EFFECT_RING_MODE = 5
|
|
177
|
+
"""The ``LED_EFFECT`` value that hands the ring over to per-LED colours."""
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class ReSpeaker:
|
|
181
|
+
"""One open USB device. Encodes and decodes the vendor control transfers.
|
|
182
|
+
|
|
183
|
+
Not thread-safe on its own — serialising access is the transport's job.
|
|
184
|
+
"""
|
|
185
|
+
|
|
186
|
+
TIMEOUT = 100000
|
|
187
|
+
|
|
188
|
+
def __init__(self, dev: object) -> None:
|
|
189
|
+
self.dev = dev
|
|
190
|
+
|
|
191
|
+
def write(self, name: str, data_list: list) -> None:
|
|
192
|
+
try:
|
|
193
|
+
resid, cmdid, count, access, data_type, _ = PARAMETERS[name]
|
|
194
|
+
except KeyError:
|
|
195
|
+
raise ValueError(f"Unknown command: {name}") from None
|
|
196
|
+
|
|
197
|
+
if access == "ro":
|
|
198
|
+
raise ValueError(f"{name} is read-only")
|
|
199
|
+
if len(data_list) != count:
|
|
200
|
+
raise ValueError(f"{name} value count is not {count}")
|
|
201
|
+
|
|
202
|
+
payload: list[int] | bytearray = []
|
|
203
|
+
if data_type in {"float", "radians"}:
|
|
204
|
+
for index in range(count):
|
|
205
|
+
payload += struct.pack(b"f", float(data_list[index]))
|
|
206
|
+
elif data_type == "char":
|
|
207
|
+
payload = (
|
|
208
|
+
bytearray(data_list, "utf-8")
|
|
209
|
+
if isinstance(data_list, str)
|
|
210
|
+
else bytearray(data_list)
|
|
211
|
+
)
|
|
212
|
+
elif data_type == "uint8":
|
|
213
|
+
for index in range(count):
|
|
214
|
+
payload += data_list[index].to_bytes(1, byteorder="little")
|
|
215
|
+
elif data_type in {"uint32", "int32"}:
|
|
216
|
+
code = b"I" if data_type == "uint32" else b"i"
|
|
217
|
+
for index in range(count):
|
|
218
|
+
payload += struct.pack(code, data_list[index])
|
|
219
|
+
else:
|
|
220
|
+
for index in range(count):
|
|
221
|
+
payload += struct.pack(b"i", data_list[index])
|
|
222
|
+
|
|
223
|
+
self.dev.ctrl_transfer(
|
|
224
|
+
usb.util.CTRL_OUT | usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_RECIPIENT_DEVICE,
|
|
225
|
+
0,
|
|
226
|
+
cmdid,
|
|
227
|
+
resid,
|
|
228
|
+
payload,
|
|
229
|
+
self.TIMEOUT,
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
def read(self, name: str) -> tuple:
|
|
233
|
+
try:
|
|
234
|
+
resid, cmdid, count, _access, data_type, _ = PARAMETERS[name]
|
|
235
|
+
except KeyError:
|
|
236
|
+
raise ValueError(f"Unknown command: {name}") from None
|
|
237
|
+
|
|
238
|
+
request = 0x80 | cmdid
|
|
239
|
+
# One extra byte carries the servicer status ahead of the payload.
|
|
240
|
+
if data_type in {"uint8", "char"}:
|
|
241
|
+
length = count + 1
|
|
242
|
+
elif data_type in {"float", "radians", "uint32", "int32"}:
|
|
243
|
+
length = count * 4 + 1
|
|
244
|
+
elif data_type == "uint16":
|
|
245
|
+
length = count * 2 + 1
|
|
246
|
+
else:
|
|
247
|
+
raise ValueError(f"Cannot size a read of type {data_type!r} for {name}")
|
|
248
|
+
|
|
249
|
+
response = self._transfer(request, resid, length)
|
|
250
|
+
attempts = 1
|
|
251
|
+
while response[0] != CONTROL_SUCCESS:
|
|
252
|
+
if response[0] != SERVICER_COMMAND_RETRY:
|
|
253
|
+
raise ValueError(f"Unknown status code: {response[0]}")
|
|
254
|
+
if attempts > MAX_READ_ATTEMPTS:
|
|
255
|
+
raise ValueError(f"Read attempt exceeds {MAX_READ_ATTEMPTS} times")
|
|
256
|
+
attempts += 1
|
|
257
|
+
time.sleep(0.01)
|
|
258
|
+
response = self._transfer(request, resid, length)
|
|
259
|
+
|
|
260
|
+
body = response.tobytes()[1:]
|
|
261
|
+
if data_type == "char":
|
|
262
|
+
return body.rstrip(b"\x00").decode("utf-8", errors="ignore")
|
|
263
|
+
code = {
|
|
264
|
+
"uint8": "B",
|
|
265
|
+
"float": "f",
|
|
266
|
+
"radians": "f",
|
|
267
|
+
"uint32": "I",
|
|
268
|
+
"int32": "i",
|
|
269
|
+
"uint16": "H",
|
|
270
|
+
}[data_type]
|
|
271
|
+
return struct.unpack("<" + code * count, body)
|
|
272
|
+
|
|
273
|
+
def _transfer(self, request: int, resid: int, length: int):
|
|
274
|
+
return self.dev.ctrl_transfer(
|
|
275
|
+
usb.util.CTRL_IN | usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_RECIPIENT_DEVICE,
|
|
276
|
+
0,
|
|
277
|
+
request,
|
|
278
|
+
resid,
|
|
279
|
+
length,
|
|
280
|
+
self.TIMEOUT,
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
def close(self) -> None:
|
|
284
|
+
usb.util.dispose_resources(self.dev)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def find(vid: int = VENDOR_ID, pid: int = PRODUCT_ID) -> ReSpeaker | None:
|
|
288
|
+
"""Return the connected device, or ``None`` when there is none.
|
|
289
|
+
|
|
290
|
+
Windows needs the backend that ``libusb-package`` ships; elsewhere the
|
|
291
|
+
system backend is already there. The import is local so that a machine
|
|
292
|
+
without the wheel can still import this module.
|
|
293
|
+
"""
|
|
294
|
+
if sys.platform.startswith("win"):
|
|
295
|
+
import libusb_package
|
|
296
|
+
|
|
297
|
+
dev = libusb_package.find(idVendor=vid, idProduct=pid)
|
|
298
|
+
else:
|
|
299
|
+
dev = usb.core.find(idVendor=vid, idProduct=pid)
|
|
300
|
+
return None if dev is None else ReSpeaker(dev)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
__all__ = [
|
|
304
|
+
"CONTROL_SUCCESS",
|
|
305
|
+
"LED_EFFECT_RING_MODE",
|
|
306
|
+
"PARAMETERS",
|
|
307
|
+
"PRODUCT_ID",
|
|
308
|
+
"RING_LED_COUNT",
|
|
309
|
+
"ReSpeaker",
|
|
310
|
+
"SERVICER_COMMAND_RETRY",
|
|
311
|
+
"VENDOR_ID",
|
|
312
|
+
"find",
|
|
313
|
+
]
|
lefx/engine/__init__.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""LEFX V3 engine — layers, lifecycles, composition and package loading.
|
|
2
|
+
|
|
3
|
+
The engine is generic. It decides by definition form — state, controlled
|
|
4
|
+
overlay, timed overlay, event — and never by identity. No branch here asks which
|
|
5
|
+
definition it is looking at; that meaning belongs to the package or to an
|
|
6
|
+
application integration.
|
|
7
|
+
|
|
8
|
+
It depends on the SDK and nothing else: no HTTP, no CLI, no USB, no Qt. Output
|
|
9
|
+
and input reach it through the SDK ports, so the same runtime drives real
|
|
10
|
+
hardware, a simulator or nothing at all.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from .composer import LayerFrame, SceneComposer, check_frame
|
|
16
|
+
from .config import EngineConfig
|
|
17
|
+
from .errors import (
|
|
18
|
+
AmbiguousTargetError,
|
|
19
|
+
ChannelNotFoundError,
|
|
20
|
+
CommandError,
|
|
21
|
+
EngineError,
|
|
22
|
+
PackageError,
|
|
23
|
+
RegistrationError,
|
|
24
|
+
RenderError,
|
|
25
|
+
TargetNotFoundError,
|
|
26
|
+
WrongTargetTypeError,
|
|
27
|
+
)
|
|
28
|
+
from .inputs import (
|
|
29
|
+
InputHealth,
|
|
30
|
+
PolledInputProvider,
|
|
31
|
+
effective_inputs,
|
|
32
|
+
evaluate_health,
|
|
33
|
+
input_status,
|
|
34
|
+
)
|
|
35
|
+
from .invocation import Invocation, duration_from_config
|
|
36
|
+
from .layers import (
|
|
37
|
+
COMPOSITION_ORDER,
|
|
38
|
+
LAYER_PRIORITIES,
|
|
39
|
+
LayerId,
|
|
40
|
+
layer_for,
|
|
41
|
+
parse_state_slot,
|
|
42
|
+
slot_for,
|
|
43
|
+
)
|
|
44
|
+
from .library import EffectLibrary, SourceEntry, discover_packages
|
|
45
|
+
from .packages import (
|
|
46
|
+
PACKAGE_FORMAT,
|
|
47
|
+
SET_FORMAT,
|
|
48
|
+
LoadedPackage,
|
|
49
|
+
LoadedSource,
|
|
50
|
+
build_package_manifest,
|
|
51
|
+
load_source,
|
|
52
|
+
serialize_definition,
|
|
53
|
+
)
|
|
54
|
+
from .registry import EffectRegistry, Preset, RegisteredEffect, ResolvedTarget, build_registry
|
|
55
|
+
from .renderer import OutputSettings, SceneRenderer
|
|
56
|
+
from .runtime import EffectRuntime, normalize_channel
|
|
57
|
+
from .store import LayerState, LayerStore
|
|
58
|
+
|
|
59
|
+
ENGINE_VERSION = "3.0.0"
|
|
60
|
+
|
|
61
|
+
__all__ = [
|
|
62
|
+
"AmbiguousTargetError",
|
|
63
|
+
"COMPOSITION_ORDER",
|
|
64
|
+
"ChannelNotFoundError",
|
|
65
|
+
"CommandError",
|
|
66
|
+
"ENGINE_VERSION",
|
|
67
|
+
"EffectLibrary",
|
|
68
|
+
"EffectRegistry",
|
|
69
|
+
"EffectRuntime",
|
|
70
|
+
"EngineConfig",
|
|
71
|
+
"EngineError",
|
|
72
|
+
"InputHealth",
|
|
73
|
+
"Invocation",
|
|
74
|
+
"LAYER_PRIORITIES",
|
|
75
|
+
"LayerFrame",
|
|
76
|
+
"LayerId",
|
|
77
|
+
"LayerState",
|
|
78
|
+
"LayerStore",
|
|
79
|
+
"LoadedPackage",
|
|
80
|
+
"LoadedSource",
|
|
81
|
+
"OutputSettings",
|
|
82
|
+
"PACKAGE_FORMAT",
|
|
83
|
+
"PackageError",
|
|
84
|
+
"PolledInputProvider",
|
|
85
|
+
"Preset",
|
|
86
|
+
"RegisteredEffect",
|
|
87
|
+
"RegistrationError",
|
|
88
|
+
"RenderError",
|
|
89
|
+
"ResolvedTarget",
|
|
90
|
+
"SET_FORMAT",
|
|
91
|
+
"SceneComposer",
|
|
92
|
+
"SceneRenderer",
|
|
93
|
+
"SourceEntry",
|
|
94
|
+
"TargetNotFoundError",
|
|
95
|
+
"WrongTargetTypeError",
|
|
96
|
+
"build_package_manifest",
|
|
97
|
+
"build_registry",
|
|
98
|
+
"check_frame",
|
|
99
|
+
"discover_packages",
|
|
100
|
+
"duration_from_config",
|
|
101
|
+
"effective_inputs",
|
|
102
|
+
"evaluate_health",
|
|
103
|
+
"input_status",
|
|
104
|
+
"layer_for",
|
|
105
|
+
"load_source",
|
|
106
|
+
"normalize_channel",
|
|
107
|
+
"parse_state_slot",
|
|
108
|
+
"serialize_definition",
|
|
109
|
+
"slot_for",
|
|
110
|
+
]
|
lefx/engine/composer.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""Turns active invocations into layer frames.
|
|
2
|
+
|
|
3
|
+
The composer owns one effect instance per invocation, samples pull sources when
|
|
4
|
+
their policy says so, and checks that what a definition returns matches what it
|
|
5
|
+
declared. There is no intermediate scene object: earlier generations wrapped a
|
|
6
|
+
closure in a dict inside a dataclass only for the renderer to unwrap it again.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from typing import Any, Callable, Mapping
|
|
14
|
+
|
|
15
|
+
from lefx.sdk import (
|
|
16
|
+
BaseEffect,
|
|
17
|
+
CompositionMode,
|
|
18
|
+
DefinitionBase,
|
|
19
|
+
InputContext,
|
|
20
|
+
InputMode,
|
|
21
|
+
RenderContext,
|
|
22
|
+
normalize_runtime_inputs,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
from .errors import RenderError
|
|
26
|
+
from .inputs import effective_inputs
|
|
27
|
+
from .invocation import Invocation
|
|
28
|
+
from .layers import LayerId
|
|
29
|
+
from .registry import EffectRegistry
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger("lefx.engine.composer")
|
|
32
|
+
|
|
33
|
+
InputProviderFn = Callable[[InputContext], Mapping[str, Any] | None]
|
|
34
|
+
|
|
35
|
+
MAX_COLOR = 0xFFFFFF
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(slots=True, frozen=True)
|
|
39
|
+
class LayerFrame:
|
|
40
|
+
"""One layer's contribution, bottom-to-top order preserved by the caller."""
|
|
41
|
+
|
|
42
|
+
layer: LayerId
|
|
43
|
+
invocation_id: str
|
|
44
|
+
pixels: list[int | None]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def check_frame(pixels: Any, definition: DefinitionBase, led_count: int) -> None:
|
|
48
|
+
"""Hold a definition to the contract it declared.
|
|
49
|
+
|
|
50
|
+
The opacity check matters as much as the length one: a definition that calls
|
|
51
|
+
itself opaque and then returns ``None`` claims to cover the layer below while
|
|
52
|
+
actually leaving it visible.
|
|
53
|
+
|
|
54
|
+
The build runs this too, so a package that breaks the contract is caught
|
|
55
|
+
before it is ever shipped rather than on the frame that happens to hit it.
|
|
56
|
+
"""
|
|
57
|
+
if not isinstance(pixels, (list, tuple)):
|
|
58
|
+
raise RenderError(f"{definition.id!r} returned {type(pixels).__name__}, expected a list")
|
|
59
|
+
if len(pixels) != led_count:
|
|
60
|
+
raise RenderError(
|
|
61
|
+
f"{definition.id!r} returned {len(pixels)} positions, expected {led_count}"
|
|
62
|
+
)
|
|
63
|
+
opaque = definition.composition is CompositionMode.OPAQUE
|
|
64
|
+
for index, value in enumerate(pixels):
|
|
65
|
+
if value is None:
|
|
66
|
+
if opaque:
|
|
67
|
+
raise RenderError(
|
|
68
|
+
f"{definition.id!r} is declared opaque but returned None at "
|
|
69
|
+
f"position {index}; use black to switch an LED off, or declare "
|
|
70
|
+
"the definition transparent to let the layer below show through"
|
|
71
|
+
)
|
|
72
|
+
continue
|
|
73
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
74
|
+
raise RenderError(
|
|
75
|
+
f"{definition.id!r} returned {value!r} at position {index}; "
|
|
76
|
+
"expected an RGB integer or None"
|
|
77
|
+
)
|
|
78
|
+
if not 0 <= value <= MAX_COLOR:
|
|
79
|
+
raise RenderError(
|
|
80
|
+
f"{definition.id!r} returned {value:#x} at position {index}, "
|
|
81
|
+
"outside 0x000000..0xFFFFFF"
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class SceneComposer:
|
|
86
|
+
def __init__(
|
|
87
|
+
self,
|
|
88
|
+
registry: EffectRegistry,
|
|
89
|
+
*,
|
|
90
|
+
input_providers: Mapping[str, InputProviderFn] | None = None,
|
|
91
|
+
) -> None:
|
|
92
|
+
self._registry = registry
|
|
93
|
+
self._input_providers = dict(input_providers or {})
|
|
94
|
+
self._instances: dict[str, BaseEffect] = {}
|
|
95
|
+
|
|
96
|
+
def set_input_providers(self, providers: Mapping[str, InputProviderFn]) -> None:
|
|
97
|
+
self._input_providers = dict(providers)
|
|
98
|
+
|
|
99
|
+
def set_registry(self, registry: EffectRegistry) -> None:
|
|
100
|
+
"""Swap in a rebuilt registry, dropping instances of what is gone."""
|
|
101
|
+
self._registry = registry
|
|
102
|
+
self._instances.clear()
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def provider_ids(self) -> tuple[str, ...]:
|
|
106
|
+
return tuple(sorted(self._input_providers))
|
|
107
|
+
|
|
108
|
+
def compose(
|
|
109
|
+
self, invocations: list[Invocation], now: float, led_count: int
|
|
110
|
+
) -> list[LayerFrame]:
|
|
111
|
+
frames = [
|
|
112
|
+
LayerFrame(
|
|
113
|
+
layer=invocation.layer,
|
|
114
|
+
invocation_id=invocation.invocation_id,
|
|
115
|
+
pixels=self._render(invocation, now, led_count),
|
|
116
|
+
)
|
|
117
|
+
for invocation in invocations
|
|
118
|
+
]
|
|
119
|
+
self._drop_stale_instances({item.invocation_id for item in invocations})
|
|
120
|
+
return frames
|
|
121
|
+
|
|
122
|
+
def _drop_stale_instances(self, live_ids: set[str]) -> None:
|
|
123
|
+
for invocation_id in [key for key in self._instances if key not in live_ids]:
|
|
124
|
+
del self._instances[invocation_id]
|
|
125
|
+
|
|
126
|
+
def _instance_for(self, invocation: Invocation) -> BaseEffect:
|
|
127
|
+
"""One instance per activation, so per-run Python state is safe to keep."""
|
|
128
|
+
registered = self._registry.get(invocation.effect_id)
|
|
129
|
+
instance = self._instances.get(invocation.invocation_id)
|
|
130
|
+
if instance is None or not isinstance(instance, registered.effect_class):
|
|
131
|
+
instance = registered.effect_class()
|
|
132
|
+
self._instances[invocation.invocation_id] = instance
|
|
133
|
+
return instance
|
|
134
|
+
|
|
135
|
+
def _render(self, invocation: Invocation, now: float, led_count: int) -> list[int | None]:
|
|
136
|
+
instance = self._instance_for(invocation)
|
|
137
|
+
definition = invocation.definition
|
|
138
|
+
self._sample_inputs(instance, invocation, now, led_count)
|
|
139
|
+
|
|
140
|
+
context = RenderContext(
|
|
141
|
+
now=now,
|
|
142
|
+
started_at=invocation.activated_at or invocation.created_at,
|
|
143
|
+
led_count=led_count,
|
|
144
|
+
definition=definition,
|
|
145
|
+
params=invocation.params,
|
|
146
|
+
inputs=effective_inputs(definition, invocation, now),
|
|
147
|
+
)
|
|
148
|
+
pixels = instance.render(context)
|
|
149
|
+
check_frame(pixels, definition, led_count)
|
|
150
|
+
return list(pixels)
|
|
151
|
+
|
|
152
|
+
def _sample_inputs(
|
|
153
|
+
self, instance: BaseEffect, invocation: Invocation, now: float, led_count: int
|
|
154
|
+
) -> None:
|
|
155
|
+
"""Pull values according to the declared policy, if it is due."""
|
|
156
|
+
definition = invocation.definition
|
|
157
|
+
policy = definition.input_sampling
|
|
158
|
+
if policy is None or policy.mode is not InputMode.PULL:
|
|
159
|
+
return
|
|
160
|
+
if invocation.input_last_attempt_at is not None:
|
|
161
|
+
elapsed_ms = (now - invocation.input_last_attempt_at) * 1000.0
|
|
162
|
+
if elapsed_ms < policy.interval_ms:
|
|
163
|
+
return
|
|
164
|
+
|
|
165
|
+
invocation.input_last_attempt_at = now
|
|
166
|
+
context = InputContext(
|
|
167
|
+
now=now,
|
|
168
|
+
led_count=led_count,
|
|
169
|
+
config=invocation.params,
|
|
170
|
+
previous_inputs=dict(invocation.inputs),
|
|
171
|
+
)
|
|
172
|
+
try:
|
|
173
|
+
if policy.provider_id is None:
|
|
174
|
+
sampled = instance.sample_inputs(context)
|
|
175
|
+
else:
|
|
176
|
+
provider = self._input_providers.get(policy.provider_id)
|
|
177
|
+
if provider is None:
|
|
178
|
+
raise RuntimeError(
|
|
179
|
+
f"input provider {policy.provider_id!r} is not available"
|
|
180
|
+
)
|
|
181
|
+
sampled = provider(context)
|
|
182
|
+
if sampled is None:
|
|
183
|
+
invocation.input_error = "input source returned no value"
|
|
184
|
+
return
|
|
185
|
+
normalized = normalize_runtime_inputs(definition, sampled)
|
|
186
|
+
except Exception as exc:
|
|
187
|
+
# A failing source is a health event, not a render failure. The last
|
|
188
|
+
# good values stay in place until the grace period runs out.
|
|
189
|
+
invocation.input_error = str(exc)
|
|
190
|
+
logger.warning(
|
|
191
|
+
"input sampling failed effect=%s invocation=%s error=%s",
|
|
192
|
+
definition.id,
|
|
193
|
+
invocation.invocation_id,
|
|
194
|
+
exc,
|
|
195
|
+
)
|
|
196
|
+
return
|
|
197
|
+
|
|
198
|
+
invocation.inputs.update(normalized)
|
|
199
|
+
invocation.input_last_success_at = now
|
|
200
|
+
invocation.input_error = None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
__all__ = ["LayerFrame", "SceneComposer", "check_frame"]
|
lefx/engine/config.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Runtime settings of one engine instance."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(slots=True, frozen=True)
|
|
9
|
+
class EngineConfig:
|
|
10
|
+
"""Ring size and render rate.
|
|
11
|
+
|
|
12
|
+
``led_count`` is a setting rather than a constant. Definitions read it from
|
|
13
|
+
the render context and size their frames accordingly, which is why the same
|
|
14
|
+
package runs on a twelve-LED ring and on a five-LED one.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
led_count: int = 12
|
|
18
|
+
fps: float = 30.0
|
|
19
|
+
|
|
20
|
+
def __post_init__(self) -> None:
|
|
21
|
+
if self.led_count < 1:
|
|
22
|
+
raise ValueError("led_count must be at least 1")
|
|
23
|
+
if self.fps <= 0:
|
|
24
|
+
raise ValueError("fps must be greater than zero")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
__all__ = ["EngineConfig"]
|