Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3fcade1abd | |||
| 7c2aa6daf1 | |||
| 2e6e654960 | |||
| 846f930eb7 | |||
| ed64397189 | |||
| 50761a4b37 | |||
| 5bb31e3f6a | |||
| edd23fc115 | |||
| 19a01e404c | |||
| efb55050c0 | |||
| c82a17016e |
@@ -13,6 +13,7 @@ auracast.egg-info/
|
||||
|
||||
# Ignore virtual environment data
|
||||
venv/
|
||||
.venv/
|
||||
env/
|
||||
|
||||
# Ignore any IDE configurations or project-specific metadata
|
||||
@@ -53,3 +54,9 @@ src/scripts/temperature_log*
|
||||
|
||||
src/auracast/server/recordings/
|
||||
src/auracast/server/led_settings.json
|
||||
|
||||
|
||||
# Dante license files
|
||||
*.lic
|
||||
src/dep/dante_package/dante_data/activation/device.lic
|
||||
src/dep/dante_package/dante_data/activation/manufacturer.cert
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
[submodule "firmware"]
|
||||
path = firmware
|
||||
url = ssh://git@gitea.summitwave.work:222/auracaster/hci_uart_beacon.git
|
||||
@@ -0,0 +1,60 @@
|
||||
# CLAUDE.md
|
||||
|
||||
Guidance for Claude Code when working in this repo.
|
||||
|
||||
## Deploying to a beacon dev device
|
||||
|
||||
Devices (e.g. **beacon29**) run the Auracast frontend + backend as systemd services.
|
||||
The deploy workflow is a **whole-tree rsync** of the local working copy onto the device,
|
||||
followed by re-running the service update script. The device's `.git` is pinned to an old
|
||||
commit while its files drift ahead, so `git status` on the device looks noisy — that is
|
||||
expected, do not try to "fix" it with `git pull`/checkout.
|
||||
|
||||
### 1. Sync (laptop -> device)
|
||||
|
||||
```bash
|
||||
rsync -avz \
|
||||
--filter=':- .gitignore' \
|
||||
--exclude='.git/' \
|
||||
--exclude='firmware/' \
|
||||
--exclude='src/dep/dante_package/bundle/' \
|
||||
--exclude='src/dep/dante_package/dante_data/activation/' \
|
||||
--delete \
|
||||
/home/paul/Documents/bumble-auracast/ \
|
||||
caster@beacon29.local:/home/caster/bumble-auracast/
|
||||
```
|
||||
|
||||
- ⚠️ **NEVER delete or overwrite the Dante activation files/dir**
|
||||
(`src/dep/dante_package/dante_data/activation/` — contains `device.lic`,
|
||||
`manufacturer.cert`). It is per-device licensing and is unrecoverable if lost.
|
||||
The `--exclude` rules above protect it (with `--delete`, excluded paths are left
|
||||
untouched). Keep those excludes, and never use `--delete-excluded`.
|
||||
- Always **dry-run first** (`rsync -avzn ...`) and confirm there are no `deleting`
|
||||
lines touching `activation/` or `bundle/` before doing the real sync.
|
||||
- Target by hostname. **beacon29 = `beacon29.local` (10.11.0.59).** Don't blindly reuse
|
||||
IPs from old commands (an earlier example used `10.11.0.48`, a different device).
|
||||
- The `firmware/` submodule (nRF firmware source + ~GB nRF Connect SDK build tree) is
|
||||
**excluded** — devices only need the committed `src/openocd/merged.hex`, which still
|
||||
syncs. Rebuild the hex on the laptop with `src/openocd/update_firmware.sh`; never build
|
||||
firmware on the device.
|
||||
|
||||
### 2. Restart services on the device
|
||||
|
||||
```bash
|
||||
ssh caster@beacon29.local '
|
||||
export XDG_RUNTIME_DIR=/run/user/$(id -u) # needed for the `systemctl --user` backend restart over SSH
|
||||
cd ~/bumble-auracast
|
||||
bash src/service/update_and_run_server_and_frontend.sh
|
||||
'
|
||||
```
|
||||
|
||||
This restarts `dep.service`, `auracast-frontend.service` (system), and
|
||||
`auracast-server.service` (user). For a **frontend-only** change you can instead just
|
||||
`sudo systemctl restart auracast-frontend.service`. A benign
|
||||
`Failed to bring up Wired connection 2` line is normal when the 2nd ethernet port is
|
||||
unplugged.
|
||||
|
||||
### 3. Verify
|
||||
|
||||
- Frontend serves HTTPS: `curl -sk -o /dev/null -w "%{http_code}\n" https://beacon29.local/` → `200`.
|
||||
- `caster@beacon29.local` has passwordless SSH and passwordless sudo.
|
||||
@@ -61,6 +61,43 @@ sudo ./provision_domain_hostname.sh <new_hostname> <new_domain>
|
||||
- If you have issues with mDNS name resolution, check for conflicting mDNS stacks (e.g., systemd-resolved, Bonjour, or other daemons).
|
||||
- Some Linux clients may not resolve multi-label mDNS names via NSS—test with `avahi-resolve-host-name` and try from another device if needed.
|
||||
|
||||
## Beacon firmware (nRF54L15)
|
||||
|
||||
The two nRF54L15 radios on a beacon are flashed with `src/openocd/merged.hex`
|
||||
(via `src/openocd/flash.sh`, driven by `src/auracast/server/system_update.sh`).
|
||||
|
||||
- **Firmware source** lives in the `firmware/` git submodule (`hci_uart_beacon`).
|
||||
Clone with submodules:
|
||||
```bash
|
||||
git clone --recurse-submodules <repo>
|
||||
# or, in an existing clone:
|
||||
git submodule update --init firmware
|
||||
```
|
||||
- **`src/openocd/merged.hex` is a committed build artifact.** Beacon devices have no
|
||||
nRF Connect SDK toolchain, so they flash this prebuilt hex directly — you do **not**
|
||||
need the submodule or the toolchain just to deploy.
|
||||
- **To rebuild the firmware and refresh `merged.hex`** (requires the nRF Connect SDK
|
||||
under `~/ncs`):
|
||||
```bash
|
||||
git submodule update --init firmware
|
||||
# optional: check out a different firmware commit inside firmware/
|
||||
src/openocd/update_firmware.sh --build
|
||||
git add firmware src/openocd/merged.hex src/openocd/merged.hex.version
|
||||
```
|
||||
`--build` is a one-shot: it configures **and** builds the `build_nrf54_radio0_radio1`
|
||||
sysbuild image from the checked-out firmware commit (via
|
||||
`nrfutil toolchain-manager launch --ncs-version v3.0.2` → `west build --sysbuild`),
|
||||
copies the resulting `merged.hex` into `src/openocd/`, and records provenance in
|
||||
`src/openocd/merged.hex.version`. BOARD and the conf/overlay files are read straight
|
||||
from `firmware/CMakePresets.json`, so it stays in sync with the nRF Connect VS Code
|
||||
preset. Override with `--preset NAME` / `--ncs-version VER`. `merged.hex` is a
|
||||
*sysbuild* output — the script refuses a plain `zephyr.hex` fallback.
|
||||
- **To just re-export** an already-built tree (no rebuild), run
|
||||
`src/openocd/update_firmware.sh` with no `--build`.
|
||||
- **Deploy note:** the whole-tree rsync deploy must exclude the firmware tree
|
||||
(`--exclude='firmware/'`) — devices only need the committed hex, not the GB-scale
|
||||
toolchain / build tree.
|
||||
|
||||
# record audio and save to file for debugging
|
||||
pw-record --target="AVIOUSB-8f6326 : 2:receive_Left" --rate=48000 --channels=1 --format=s24 /tmp/aes67_test.wav &
|
||||
RECORD_PID=$!
|
||||
|
||||
Submodule
+1
Submodule firmware added at 52d034e58e
@@ -1,5 +1,11 @@
|
||||
from typing import List
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, field_validator
|
||||
|
||||
# Discrete TX power levels (dBm) supported by the Nordic SoftDevice Controller
|
||||
# for the nRF radio PA. The HCI controller will clamp requested values to the
|
||||
# nearest supported step. The maximum is bounded by CONFIG_BT_CTLR_TX_PWR_*
|
||||
# in the hci_uart firmware (currently +8 dBm).
|
||||
TX_POWER_VALID = [8, 7, 6, 5, 4, 3, 2, 0, -4, -8, -12, -16, -20]
|
||||
|
||||
# Define some base to hold the relevant parameters
|
||||
class AuracastQoSConfig(BaseModel):
|
||||
@@ -28,13 +34,24 @@ class AuracastGlobalConfig(BaseModel):
|
||||
octets_per_frame: int = 40 #48kbps@24kHz # bitrate = octets_per_frame * 8 / frame len
|
||||
frame_duration_us: int = 10000
|
||||
presentation_delay_us: int = 40000
|
||||
# TODO:pydantic does not support bytes serialization - use .hex and np.fromhex()
|
||||
manufacturer_data: tuple[int, bytes] | tuple[None, None] = (None, None)
|
||||
# LE Audio: Broadcast Audio Immediate Rendering (metadata type 0x09)
|
||||
# When true, include a zero-length LTV with type 0x09 in the subgroup metadata
|
||||
# so receivers may render earlier than the presentation delay for lower latency.
|
||||
immediate_rendering: bool = False
|
||||
assisted_listening_stream: bool = False
|
||||
# Bluetooth advertising TX power for this radio in dBm (per advertising set).
|
||||
# Sent through HCI_LE_Set_Extended_Advertising_Parameters; the SDC clamps to
|
||||
# nearest supported hardware step and propagates to primary/secondary adv,
|
||||
# the periodic advertising train and the BIS ISO PDUs.
|
||||
advertising_tx_power: int = 8
|
||||
|
||||
@field_validator('advertising_tx_power')
|
||||
@classmethod
|
||||
def _snap_tx_power(cls, v: int) -> int:
|
||||
# Snap to the nearest supported discrete step in TX_POWER_VALID.
|
||||
if v in TX_POWER_VALID:
|
||||
return v
|
||||
return min(TX_POWER_VALID, key=lambda s: abs(s - v))
|
||||
|
||||
# "Audio input. "
|
||||
# "'device' -> use the host's default sound input device, "
|
||||
@@ -62,7 +79,7 @@ class AuracastBigConfigDeu(AuracastBigConfig):
|
||||
name: str = 'Hörsaal A'
|
||||
language: str ='deu'
|
||||
program_info: str = 'Vorlesung DE'
|
||||
audio_source: str = 'file:./testdata/wave_particle_5min_de.wav'
|
||||
audio_source: str = 'file:./testdata/wave_particle_5min_de.lc3'
|
||||
|
||||
class AuracastBigConfigEng(AuracastBigConfig):
|
||||
id: int = 123
|
||||
@@ -70,7 +87,7 @@ class AuracastBigConfigEng(AuracastBigConfig):
|
||||
name: str = 'Lecture Hall A'
|
||||
language: str ='eng'
|
||||
program_info: str = 'Lecture EN'
|
||||
audio_source: str = 'file:./testdata/wave_particle_5min_en.wav'
|
||||
audio_source: str = 'file:./testdata/wave_particle_5min_en.lc3'
|
||||
|
||||
class AuracastBigConfigFra(AuracastBigConfig):
|
||||
id: int = 1234
|
||||
@@ -79,7 +96,7 @@ class AuracastBigConfigFra(AuracastBigConfig):
|
||||
name: str = 'Auditoire A'
|
||||
language: str ='fra'
|
||||
program_info: str = 'Auditoire FR'
|
||||
audio_source: str = 'file:./testdata/wave_particle_5min_fr.wav'
|
||||
audio_source: str = 'file:./testdata/wave_particle_5min_fr.lc3'
|
||||
|
||||
class AuracastBigConfigSpa(AuracastBigConfig):
|
||||
id: int =12345
|
||||
@@ -87,7 +104,7 @@ class AuracastBigConfigSpa(AuracastBigConfig):
|
||||
name: str = 'Auditorio A'
|
||||
language: str ='spa'
|
||||
program_info: str = 'Auditorio ES'
|
||||
audio_source: str = 'file:./testdata/wave_particle_5min_es.wav'
|
||||
audio_source: str = 'file:./testdata/wave_particle_5min_es.lc3'
|
||||
|
||||
class AuracastBigConfigIta(AuracastBigConfig):
|
||||
id: int =1234567
|
||||
@@ -95,7 +112,7 @@ class AuracastBigConfigIta(AuracastBigConfig):
|
||||
name: str = 'Aula A'
|
||||
language: str ='ita'
|
||||
program_info: str = 'Aula IT'
|
||||
audio_source: str = 'file:./testdata/wave_particle_5min_it.wav'
|
||||
audio_source: str = 'file:./testdata/wave_particle_5min_it.lc3'
|
||||
|
||||
|
||||
class AuracastBigConfigPol(AuracastBigConfig):
|
||||
@@ -104,7 +121,7 @@ class AuracastBigConfigPol(AuracastBigConfig):
|
||||
name: str = 'Sala Wykładowa'
|
||||
language: str ='pol'
|
||||
program_info: str = 'Sala Wykładowa PL'
|
||||
audio_source: str = 'file:./testdata/wave_particle_5min_pl.wav'
|
||||
audio_source: str = 'file:./testdata/wave_particle_5min_pl.lc3'
|
||||
|
||||
|
||||
class AuracastConfigGroup(AuracastGlobalConfig):
|
||||
|
||||
+99
-28
@@ -49,6 +49,7 @@ import bumble.transport
|
||||
import bumble.utils
|
||||
from bumble.device import Host, AdvertisingChannelMap
|
||||
from bumble.audio import io as audio_io
|
||||
from bumble.vendor.zephyr.hci import HCI_Write_Tx_Power_Level_Command
|
||||
|
||||
from auracast import auracast_config
|
||||
from auracast.utils.read_lc3_file import read_lc3_file
|
||||
@@ -206,7 +207,7 @@ class PyAlsaAudioInput(audio_io.ThreadedAudioInput):
|
||||
length, data = self._pcm.read_sw(frame_size + self._bang_bang)
|
||||
avail = self._pcm.avail()
|
||||
SETPOINT = 120
|
||||
TOLERANCE = 40
|
||||
TOLERANCE = 80
|
||||
if avail < SETPOINT - TOLERANCE:
|
||||
self._bang_bang = -1
|
||||
elif avail > SETPOINT + TOLERANCE:
|
||||
@@ -462,21 +463,6 @@ async def init_broadcast(
|
||||
],
|
||||
)
|
||||
logger.info('Setup Advertising')
|
||||
advertising_manufacturer_data = (
|
||||
b''
|
||||
if global_config.manufacturer_data == (None, None)
|
||||
else bytes(
|
||||
core.AdvertisingData(
|
||||
[
|
||||
(
|
||||
core.AdvertisingData.MANUFACTURER_SPECIFIC_DATA,
|
||||
struct.pack('<H', global_config.manufacturer_data[0])
|
||||
+ global_config.manufacturer_data[1],
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
)
|
||||
bigs[f'big{i}']['broadcast_audio_announcement'] = bap.BroadcastAudioAnnouncement(conf.id)
|
||||
|
||||
# Build advertising data types list
|
||||
@@ -519,23 +505,84 @@ async def init_broadcast(
|
||||
advertising_sid=i,
|
||||
primary_advertising_phy=hci.Phy.LE_1M, # 2m phy config throws error - because for primary advertising channels, 1mbit is only supported
|
||||
secondary_advertising_phy=hci.Phy.LE_1M, # this is the secondary advertising beeing send on non advertising channels (extendend advertising)
|
||||
#advertising_tx_power= # tx power in dbm (max 20)
|
||||
# Pass NO_PREFERENCE (0x7F) here for two reasons:
|
||||
# 1. The Nordic SoftDevice Controller ignores this field for
|
||||
# advertising sets and always returns the compile-time
|
||||
# CONFIG_BT_CTLR_TX_PWR_* value. The real TX power is
|
||||
# applied via the Zephyr VS Write_Tx_Power_Level command
|
||||
# issued right after create_advertising_set() returns.
|
||||
# 2. Bumble's HCI metadata declares this field as 1-byte
|
||||
# *unsigned* (a bumble bug — the BT spec defines it as
|
||||
# signed int8), so negative values would raise
|
||||
# "bytes must be in range(0, 256)" at serialization.
|
||||
advertising_tx_power=hci.HCI_LE_Set_Extended_Advertising_Parameters_Command.TX_POWER_NO_PREFERENCE,
|
||||
#secondary_advertising_max_skip=10,
|
||||
),
|
||||
advertising_data=(
|
||||
bigs[f'big{i}']['broadcast_audio_announcement'].get_advertising_data()
|
||||
+ bytes(core.AdvertisingData(advertising_data_types))
|
||||
+ advertising_manufacturer_data
|
||||
),
|
||||
periodic_advertising_parameters=bumble.device.PeriodicAdvertisingParameters(
|
||||
periodic_advertising_interval_min=80,
|
||||
periodic_advertising_interval_max=160,
|
||||
# 113 * 1.25 ms = 141.25 ms. Deliberately NON-commensurate with the
|
||||
# 10 ms ISO interval (14.125x, a 1/8-ISO fractional step) so the PA
|
||||
# anchor walks through the ISO cycle instead of standing on it. A
|
||||
# commensurate value (e.g. 80 = 100 ms = 10x) freezes the PA/BIG phase
|
||||
# once the broadcaster clock is stable (LFXO), so every PA event
|
||||
# collides with a BIG subevent and gets dropped in favour of the
|
||||
# audio -> receivers that keep the PA synced during streaming starve
|
||||
# it out and hit the 10 s supervision timeout (PA drop). The walk keeps
|
||||
# the PA landing in free slots so the sync holds. Verified with an HCI
|
||||
# sniffer: commensurate -> PA 0/s, lost @10 s; 141.25 ms -> ~2/s, holds.
|
||||
periodic_advertising_interval_min=113,
|
||||
periodic_advertising_interval_max=113,
|
||||
),
|
||||
periodic_advertising_data=bigs[f'big{i}']['basic_audio_announcement'].get_advertising_data(),
|
||||
auto_restart=True,
|
||||
auto_start=True,
|
||||
)
|
||||
bigs[f'big{i}']['advertising_set'] = advertising_set
|
||||
# NOTE: selected_tx_power below reflects the SDC's compile-time max
|
||||
# (LE_Set_Ext_Adv_Params was sent with NO_PREFERENCE). The actual
|
||||
# transmit power is set by the VS Write_Tx_Power_Level call below.
|
||||
logging.debug(
|
||||
'LE_Set_Ext_Adv_Params reports controller fallback TX power: %+d dBm (handle=%d)',
|
||||
getattr(advertising_set, 'selected_tx_power', 0),
|
||||
i,
|
||||
)
|
||||
|
||||
# The Nordic SoftDevice Controller does not honor the per-set
|
||||
# advertising_tx_power passed in HCI_LE_Set_Extended_Advertising_Parameters
|
||||
# (it returns the compile-time CONFIG_BT_CTLR_TX_PWR_* value regardless).
|
||||
# Apply the requested level via the Zephyr Vendor-Specific HCI command
|
||||
# Write_Tx_Power_Level (opcode 0xFC0E), which the SDC honors per
|
||||
# advertising handle. The SDC clamps the value to the nearest supported
|
||||
# hardware step (max bounded by CONFIG_BT_CTLR_TX_PWR_PLUS_8).
|
||||
try:
|
||||
adv_handle = getattr(advertising_set, 'advertising_handle', i)
|
||||
response = await device.send_command(
|
||||
HCI_Write_Tx_Power_Level_Command(
|
||||
handle_type=HCI_Write_Tx_Power_Level_Command.TX_POWER_HANDLE_TYPE_ADV,
|
||||
connection_handle=adv_handle,
|
||||
tx_power_level=global_config.advertising_tx_power,
|
||||
)
|
||||
)
|
||||
rp = getattr(response, 'return_parameters', None)
|
||||
status = getattr(rp, 'status', 0xFF) if rp is not None else 0xFF
|
||||
selected = getattr(rp, 'selected_tx_power_level', None) if rp is not None else None
|
||||
if status == 0 and selected is not None:
|
||||
logging.info(
|
||||
'Advertising TX power (VS Write_Tx_Power_Level): requested=%+d dBm, controller selected=%+d dBm (handle=%d)',
|
||||
global_config.advertising_tx_power,
|
||||
selected,
|
||||
adv_handle,
|
||||
)
|
||||
else:
|
||||
logging.warning(
|
||||
'VS Write_Tx_Power_Level failed: status=0x%02X handle=%d requested=%+d dBm',
|
||||
status, adv_handle, global_config.advertising_tx_power,
|
||||
)
|
||||
except Exception as e:
|
||||
logging.warning('VS Write_Tx_Power_Level not supported by controller: %s', e)
|
||||
|
||||
logging.info('Start Periodic Advertising')
|
||||
await advertising_set.start_periodic()
|
||||
@@ -602,6 +649,29 @@ async def init_broadcast(
|
||||
return bigs
|
||||
|
||||
|
||||
def _lc3_file_byte_gen(filename: str, loop: bool = False):
|
||||
"""Stream LC3 frames from disk as individual bytes, with optional looping.
|
||||
|
||||
Yields one byte (int) at a time so it is compatible with the existing
|
||||
``bytes(itertools.islice(gen, bytes_per_frame))`` consumer without loading
|
||||
the whole file into memory.
|
||||
"""
|
||||
while True:
|
||||
with open(filename, 'rb') as f:
|
||||
f.read(18) # skip 18-byte LC3 header
|
||||
while True:
|
||||
size_b = f.read(2)
|
||||
if len(size_b) < 2:
|
||||
break
|
||||
frame_size = struct.unpack('=H', size_b)[0]
|
||||
frame = f.read(frame_size)
|
||||
if len(frame) < frame_size:
|
||||
break
|
||||
yield from frame
|
||||
if not loop:
|
||||
return
|
||||
|
||||
|
||||
class Streamer():
|
||||
"""
|
||||
Streamer class that supports multiple input formats. See bumble for streaming from wav or device
|
||||
@@ -757,13 +827,7 @@ class Streamer():
|
||||
big['precoded'] = True
|
||||
big['lc3_bytes_per_frame'] = global_config.octets_per_frame
|
||||
filename = big_config[i].audio_source.replace('file:', '')
|
||||
|
||||
lc3_bytes = read_lc3_file(filename)
|
||||
lc3_frames = iter(lc3_bytes)
|
||||
|
||||
if big_config[i].loop:
|
||||
lc3_frames = itertools.cycle(lc3_frames)
|
||||
big['lc3_frames'] = lc3_frames
|
||||
big['lc3_frames'] = _lc3_file_byte_gen(filename, loop=big_config[i].loop)
|
||||
|
||||
# use wav files and code them entirely before streaming
|
||||
elif big_config[i].precode_wav and big_config[i].audio_source.endswith('.wav'):
|
||||
@@ -811,7 +875,11 @@ class Streamer():
|
||||
if input_format == 'auto':
|
||||
raise ValueError('input format details required for alsa input')
|
||||
pcm = audio_io.PcmFormat.from_str(input_format)
|
||||
audio_input = AlsaArecordAudioInput(audio_source[5:], pcm)
|
||||
device_name = audio_source[5:]
|
||||
if device_name.startswith('dante_'):
|
||||
audio_input = PyAlsaAudioInput(device_name, pcm)
|
||||
else:
|
||||
audio_input = AlsaArecordAudioInput(device_name, pcm)
|
||||
else:
|
||||
audio_input = await audio_io.create_audio_input(audio_source, input_format)
|
||||
# Store early so stop_streaming can close even if open() fails
|
||||
@@ -880,6 +948,9 @@ class Streamer():
|
||||
if lc3_frame == b'': # Not all streams may stop at the same time
|
||||
stream_finished[i] = True
|
||||
continue
|
||||
|
||||
for q_idx in range(big.get('num_bis', 1)):
|
||||
await big['iso_queues'][q_idx].write(lc3_frame)
|
||||
else: # code lc3 on the fly with perf counters
|
||||
# Ensure frames generator exists (so we can aclose() on stop)
|
||||
frames_gen = big.get('frames_gen')
|
||||
|
||||
@@ -71,6 +71,10 @@ if not is_pw_disabled():
|
||||
with st.form("signin_form"):
|
||||
pw = st.text_input("Password", type="password")
|
||||
submitted = st.form_submit_button("Sign in")
|
||||
st.components.v1.html(
|
||||
"<script>setTimeout(()=>window.parent.document.querySelector('input[type=\"password\"]')?.focus(),100)</script>",
|
||||
height=0
|
||||
)
|
||||
if submitted:
|
||||
if verify_password(pw, pw_rec):
|
||||
st.session_state['frontend_authenticated'] = True
|
||||
@@ -96,6 +100,36 @@ QOS_PRESET_MAP = {
|
||||
"Robust": auracast_config.AuracastQosRobust(),
|
||||
}
|
||||
|
||||
# Discrete advertising TX power steps in dBm supported by the Nordic SDC radio
|
||||
# PA. Sent through HCI_LE_Set_Extended_Advertising_Parameters; the controller
|
||||
# clamps to the nearest hardware step.
|
||||
TX_POWER_OPTIONS = [8, 7, 6, 5, 4, 3, 2, 0, -4, -8, -12, -16, -20]
|
||||
TX_POWER_DEFAULT = 8
|
||||
|
||||
|
||||
def _coerce_tx_power(value, default: int = TX_POWER_DEFAULT) -> int:
|
||||
try:
|
||||
v = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
if v in TX_POWER_OPTIONS:
|
||||
return v
|
||||
return min(TX_POWER_OPTIONS, key=lambda s: abs(s - v))
|
||||
|
||||
|
||||
def _tx_power_selectbox(label: str, key: str, default: int, disabled: bool, help_text: str | None = None) -> int:
|
||||
snapped = _coerce_tx_power(default)
|
||||
idx = TX_POWER_OPTIONS.index(snapped)
|
||||
return st.selectbox(
|
||||
label,
|
||||
TX_POWER_OPTIONS,
|
||||
index=idx,
|
||||
key=key,
|
||||
format_func=lambda v: f"{v:+d} dBm",
|
||||
disabled=disabled,
|
||||
help=help_text or "Bluetooth advertising TX power for this radio. Higher values increase range; lower values reduce interference and power draw.",
|
||||
)
|
||||
|
||||
# Try loading persisted settings from backend
|
||||
saved_settings = {}
|
||||
try:
|
||||
@@ -351,6 +385,17 @@ if audio_mode == "Demo":
|
||||
disabled=is_streaming,
|
||||
help="Select the demo stream configuration."
|
||||
)
|
||||
demo_content_options = ["Program material", "1 kHz test tone"]
|
||||
saved_demo_content = saved_settings.get('demo_content', 'Program material')
|
||||
if saved_demo_content not in demo_content_options:
|
||||
saved_demo_content = 'Program material'
|
||||
demo_content = st.selectbox(
|
||||
"Demo Content",
|
||||
demo_content_options,
|
||||
index=demo_content_options.index(saved_demo_content),
|
||||
disabled=is_streaming,
|
||||
help="Select whether demo streams use program audio files or a continuous 1 kHz test tone."
|
||||
)
|
||||
# Stream password and flags (same as USB/AES67)
|
||||
saved_pwd = saved_settings.get('stream_password', '') or ''
|
||||
stream_passwort = st.text_input(
|
||||
@@ -394,6 +439,22 @@ if audio_mode == "Demo":
|
||||
disabled=is_streaming,
|
||||
help="Fast: 2 retransmissions, lower latency. Robust: 4 retransmissions, better reliability."
|
||||
)
|
||||
# Per-radio TX power for Demo (independent for R1 and R2)
|
||||
col_tx_r1, col_tx_r2 = st.columns(2, gap="small")
|
||||
with col_tx_r1:
|
||||
tx_power_r1 = _tx_power_selectbox(
|
||||
"TX Power (R1)",
|
||||
key="demo_tx_power_r1",
|
||||
default=saved_settings.get('advertising_tx_power', TX_POWER_DEFAULT),
|
||||
disabled=is_streaming,
|
||||
)
|
||||
with col_tx_r2:
|
||||
tx_power_r2 = _tx_power_selectbox(
|
||||
"TX Power (R2)",
|
||||
key="demo_tx_power_r2",
|
||||
default=saved_settings.get('secondary', {}).get('advertising_tx_power', TX_POWER_DEFAULT),
|
||||
disabled=is_streaming,
|
||||
)
|
||||
#st.info(f"Demo mode selected: {demo_selected} (Streams: {demo_stream_map[demo_selected]['streams']}, Rate: {demo_stream_map[demo_selected]['rate']} Hz)")
|
||||
quality = None # Not used in demo mode
|
||||
else:
|
||||
@@ -425,21 +486,52 @@ else:
|
||||
help="Radio 1 is always enabled, Radio 2 can be turned on or off."
|
||||
)
|
||||
|
||||
# Stereo mode toggle for analog
|
||||
stereo_enabled = st.checkbox(
|
||||
"🎧 Stereo Mode",
|
||||
value=bool(saved_settings.get('analog_stereo_mode', False)),
|
||||
help="Enable stereo streaming for analog inputs. When enabled, ch1 becomes left channel and ch2 becomes right channel in a single stereo stream. Radio 2 will be disabled in stereo mode.",
|
||||
disabled=is_streaming
|
||||
)
|
||||
|
||||
# Use analog-specific defaults (not from saved settings which may have Dante values)
|
||||
default_name = "Analog_Radio_1"
|
||||
default_program_info = "Analog Radio Broadcast"
|
||||
default_lang = "deu"
|
||||
# Stereo mode toggle for analog (temporarily hidden from the UI)
|
||||
stereo_enabled = False
|
||||
# stereo_enabled = st.checkbox(
|
||||
# "🎧 Stereo Mode",
|
||||
# value=bool(saved_settings.get('analog_stereo_mode', False)),
|
||||
# help="Enable stereo streaming for analog inputs. When enabled, ch1 becomes left channel and ch2 becomes right channel in a single stereo stream. Radio 2 will be disabled in stereo mode.",
|
||||
# disabled=is_streaming
|
||||
# )
|
||||
|
||||
quality_options = list(QUALITY_MAP.keys())
|
||||
default_quality = "Medium (24kHz)" if "Medium (24kHz)" in quality_options else quality_options[0]
|
||||
|
||||
# Use saved settings if audio_mode matches, otherwise use analog-specific defaults
|
||||
saved_audio_mode = saved_settings.get('audio_mode')
|
||||
if saved_audio_mode == 'Analog':
|
||||
default_name = saved_settings.get('channel_names', ["Analog_Radio_1"])[0]
|
||||
raw_program_info = saved_settings.get('program_info', default_name)
|
||||
if isinstance(raw_program_info, list) and raw_program_info:
|
||||
default_program_info = raw_program_info[0]
|
||||
else:
|
||||
default_program_info = raw_program_info
|
||||
default_lang = saved_settings.get('languages', ["deu"])[0]
|
||||
|
||||
# Map saved sampling rate to quality label
|
||||
saved_rate = saved_settings.get('auracast_sampling_rate_hz')
|
||||
if saved_rate == 48000:
|
||||
default_quality = "High (48kHz)"
|
||||
elif saved_rate == 32000:
|
||||
default_quality = "Good (32kHz)"
|
||||
elif saved_rate == 24000:
|
||||
default_quality = "Medium (24kHz)"
|
||||
elif saved_rate == 16000:
|
||||
default_quality = "Fair (16kHz)"
|
||||
else:
|
||||
default_quality = "Medium (24kHz)"
|
||||
|
||||
saved_pwd = saved_settings.get('stream_password', '')
|
||||
else:
|
||||
# Use analog-specific defaults when switching from another mode
|
||||
default_name = "Analog_Radio_1"
|
||||
default_program_info = "Analog Radio Broadcast"
|
||||
default_lang = "deu"
|
||||
default_quality = "Medium (24kHz)" if "Medium (24kHz)" in quality_options else quality_options[0]
|
||||
saved_pwd = ''
|
||||
|
||||
if default_quality not in quality_options:
|
||||
default_quality = quality_options[0]
|
||||
quality1 = st.selectbox(
|
||||
"Stream Quality (Radio 1)",
|
||||
quality_options,
|
||||
@@ -450,7 +542,7 @@ else:
|
||||
|
||||
stream_passwort1 = st.text_input(
|
||||
"Stream Passwort (Radio 1)",
|
||||
value="",
|
||||
value=saved_pwd,
|
||||
type="password",
|
||||
disabled=is_streaming,
|
||||
help="Optional: Set a broadcast code for Radio 1."
|
||||
@@ -490,6 +582,13 @@ else:
|
||||
help="Fast: 2 retransmissions, lower latency. Robust: 4 retransmissions, better reliability."
|
||||
)
|
||||
|
||||
tx_power_r1 = _tx_power_selectbox(
|
||||
"TX Power (R1)",
|
||||
key="analog_tx_power_r1",
|
||||
default=saved_settings.get('advertising_tx_power', TX_POWER_DEFAULT),
|
||||
disabled=is_streaming,
|
||||
)
|
||||
|
||||
col_r1_name, col_r1_lang = st.columns([2, 1])
|
||||
with col_r1_name:
|
||||
stream_name1 = st.text_input(
|
||||
@@ -557,7 +656,10 @@ else:
|
||||
input_device1 = None
|
||||
else:
|
||||
# Mono mode: show all available channels
|
||||
saved_input_device = saved_settings.get('input_device')
|
||||
default_r1_idx = 0
|
||||
if saved_input_device in analog_names:
|
||||
default_r1_idx = analog_names.index(saved_input_device)
|
||||
input_device1 = st.selectbox(
|
||||
"Input Device (Radio 1)",
|
||||
analog_names,
|
||||
@@ -606,22 +708,53 @@ else:
|
||||
)
|
||||
|
||||
if radio2_enabled and not stereo_enabled:
|
||||
# Use analog-specific defaults for Radio 2
|
||||
default_name_r2 = "Analog_Radio_2"
|
||||
default_program_info_r2 = "Analog Radio Broadcast"
|
||||
default_lang_r2 = "deu"
|
||||
# Use saved settings if audio_mode matches, otherwise use analog-specific defaults for Radio 2
|
||||
secondary_settings = saved_settings.get('secondary', {})
|
||||
saved_audio_mode = saved_settings.get('audio_mode')
|
||||
if saved_audio_mode == 'Analog' and secondary_settings:
|
||||
default_name_r2 = secondary_settings.get('channel_names', ["Analog_Radio_2"])[0] if isinstance(secondary_settings.get('channel_names'), list) else secondary_settings.get('channel_names', "Analog_Radio_2")
|
||||
raw_program_info_r2 = secondary_settings.get('program_info', default_name_r2)
|
||||
if isinstance(raw_program_info_r2, list) and raw_program_info_r2:
|
||||
default_program_info_r2 = raw_program_info_r2[0]
|
||||
else:
|
||||
default_program_info_r2 = raw_program_info_r2
|
||||
default_lang_r2 = secondary_settings.get('languages', ["deu"])[0] if isinstance(secondary_settings.get('languages'), list) else secondary_settings.get('languages', 'deu')
|
||||
|
||||
# Map saved sampling rate to quality label
|
||||
saved_rate_r2 = secondary_settings.get('auracast_sampling_rate_hz')
|
||||
if saved_rate_r2 == 48000:
|
||||
default_quality_r2 = "High (48kHz)"
|
||||
elif saved_rate_r2 == 32000:
|
||||
default_quality_r2 = "Good (32kHz)"
|
||||
elif saved_rate_r2 == 24000:
|
||||
default_quality_r2 = "Medium (24kHz)"
|
||||
elif saved_rate_r2 == 16000:
|
||||
default_quality_r2 = "Fair (16kHz)"
|
||||
else:
|
||||
default_quality_r2 = "Medium (24kHz)"
|
||||
|
||||
saved_pwd_r2 = secondary_settings.get('stream_password', '')
|
||||
else:
|
||||
# Use analog-specific defaults when switching from another mode
|
||||
default_name_r2 = "Analog_Radio_2"
|
||||
default_program_info_r2 = "Analog Radio Broadcast"
|
||||
default_lang_r2 = "deu"
|
||||
default_quality_r2 = "Medium (24kHz)" if "Medium (24kHz)" in quality_options else quality_options[0]
|
||||
saved_pwd_r2 = ''
|
||||
|
||||
if default_quality_r2 not in quality_options:
|
||||
default_quality_r2 = quality_options[0]
|
||||
quality2 = st.selectbox(
|
||||
"Stream Quality (Radio 2)",
|
||||
quality_options,
|
||||
index=quality_options.index(default_quality),
|
||||
index=quality_options.index(default_quality_r2),
|
||||
disabled=is_streaming,
|
||||
help="Select the audio sampling rate for Radio 2."
|
||||
)
|
||||
|
||||
stream_passwort2 = st.text_input(
|
||||
"Stream Passwort (Radio 2)",
|
||||
value="",
|
||||
value=saved_pwd_r2,
|
||||
type="password",
|
||||
disabled=is_streaming,
|
||||
help="Optional: Set a broadcast code for Radio 2."
|
||||
@@ -658,6 +791,13 @@ else:
|
||||
help="Fast: 2 retransmissions, lower latency. Robust: 4 retransmissions, better reliability."
|
||||
)
|
||||
|
||||
tx_power_r2 = _tx_power_selectbox(
|
||||
"TX Power (R2)",
|
||||
key="analog_tx_power_r2",
|
||||
default=saved_settings.get('secondary', {}).get('advertising_tx_power', TX_POWER_DEFAULT),
|
||||
disabled=is_streaming,
|
||||
)
|
||||
|
||||
col_r2_name, col_r2_lang = st.columns([2, 1])
|
||||
with col_r2_name:
|
||||
stream_name2 = st.text_input(
|
||||
@@ -682,7 +822,11 @@ else:
|
||||
|
||||
if not is_streaming:
|
||||
if analog_names:
|
||||
secondary_settings = saved_settings.get('secondary', {})
|
||||
saved_input_device2 = secondary_settings.get('input_device')
|
||||
default_r2_idx = 1 if len(analog_names) > 1 else 0
|
||||
if saved_input_device2 in analog_names:
|
||||
default_r2_idx = analog_names.index(saved_input_device2)
|
||||
input_device2 = st.selectbox(
|
||||
"Input Device (Radio 2)",
|
||||
analog_names,
|
||||
@@ -692,7 +836,7 @@ else:
|
||||
else:
|
||||
input_device2 = None
|
||||
else:
|
||||
input_device2 = saved_settings.get('input_device')
|
||||
input_device2 = saved_settings.get('secondary', {}).get('input_device')
|
||||
st.selectbox(
|
||||
"Input Device (Radio 2)",
|
||||
[input_device2 or "No device selected"],
|
||||
@@ -713,6 +857,7 @@ else:
|
||||
'immediate_rendering': immediate_rendering2,
|
||||
'presentation_delay_ms': presentation_delay_ms2,
|
||||
'qos_preset': qos_preset2,
|
||||
'tx_power': tx_power_r2,
|
||||
'analog_gain_db_left': analog_gain_db_left,
|
||||
'analog_gain_db_right': analog_gain_db_right,
|
||||
}
|
||||
@@ -729,6 +874,7 @@ else:
|
||||
'immediate_rendering': immediate_rendering1,
|
||||
'presentation_delay_ms': presentation_delay_ms1,
|
||||
'qos_preset': qos_preset1,
|
||||
'tx_power': tx_power_r1,
|
||||
'stereo_mode': stereo_enabled,
|
||||
'analog_gain_db_left': analog_gain_db_left,
|
||||
'analog_gain_db_right': analog_gain_db_right,
|
||||
@@ -773,14 +919,19 @@ else:
|
||||
help="Radio 1 is always enabled, Radio 2 can be turned on or off."
|
||||
)
|
||||
|
||||
# Dante stereo mode toggle
|
||||
saved_r1_config = saved_settings.get('dante_radio1', {})
|
||||
dante_stereo_enabled = st.checkbox(
|
||||
"🎧 Stereo Mode",
|
||||
value=bool(saved_r1_config.get('dante_stereo_mode', False)),
|
||||
help="Enable stereo streaming for Dante inputs. Select left and right channels from ASRC channels 1-6. Radio 2 and multi-stream configurations will be disabled in stereo mode.",
|
||||
disabled=is_streaming
|
||||
)
|
||||
# Dante stereo mode toggle (temporarily hidden from the UI)
|
||||
saved_audio_mode = saved_settings.get('audio_mode')
|
||||
dante_stereo_enabled = False
|
||||
# if saved_audio_mode == 'Network - Dante':
|
||||
# # Check if any input device starts with dante_stereo_ to detect stereo mode
|
||||
# input_device = saved_settings.get('input_device', '')
|
||||
# dante_stereo_enabled = input_device.startswith('dante_stereo_')
|
||||
# dante_stereo_enabled = st.checkbox(
|
||||
# "🎧 Stereo Mode",
|
||||
# value=dante_stereo_enabled,
|
||||
# help="Enable stereo streaming for Dante inputs. Select left and right channels from ASRC channels 1-6. Radio 2 and multi-stream configurations will be disabled in stereo mode.",
|
||||
# disabled=is_streaming
|
||||
# )
|
||||
|
||||
# Dante stereo channel selectors
|
||||
dante_left_channel = None
|
||||
@@ -790,9 +941,19 @@ else:
|
||||
"dante_asrc_ch4", "dante_asrc_ch5", "dante_asrc_ch6"]
|
||||
dante_channel_labels = ["CH1", "CH2", "CH3", "CH4", "CH5", "CH6"]
|
||||
|
||||
# Parse saved stereo device name to extract left and right channels
|
||||
input_device = saved_settings.get('input_device', '')
|
||||
saved_left = 'dante_asrc_ch1'
|
||||
saved_right = 'dante_asrc_ch2'
|
||||
if input_device.startswith('dante_stereo_'):
|
||||
# Format: dante_stereo_<left>_<right>
|
||||
parts = input_device.split('_')
|
||||
if len(parts) >= 4:
|
||||
saved_left = f"dante_asrc_ch{parts[2]}"
|
||||
saved_right = f"dante_asrc_ch{parts[3]}"
|
||||
|
||||
col_left, col_right = st.columns(2)
|
||||
with col_left:
|
||||
saved_left = saved_r1_config.get('dante_stereo_left', 'dante_asrc_ch1')
|
||||
left_idx = dante_channel_options.index(saved_left) if saved_left in dante_channel_options else 0
|
||||
dante_left_channel = st.selectbox(
|
||||
"Left Channel",
|
||||
@@ -803,7 +964,6 @@ else:
|
||||
help="Select the Dante ASRC channel for the left stereo channel"
|
||||
)
|
||||
with col_right:
|
||||
saved_right = saved_r1_config.get('dante_stereo_right', 'dante_asrc_ch2')
|
||||
right_idx = dante_channel_options.index(saved_right) if saved_right in dante_channel_options else 1
|
||||
dante_right_channel = st.selectbox(
|
||||
"Right Channel",
|
||||
@@ -821,7 +981,22 @@ else:
|
||||
|
||||
# Stream count dropdown for Radio 1 (disabled in stereo mode - forced to 1 stream at 48kHz)
|
||||
r1_stream_options = list(dante_stream_options.keys())
|
||||
saved_r1_streams = saved_r1_config.get('stream_config', '1x48')
|
||||
# Infer stream configuration from saved sampling rate
|
||||
saved_rate = saved_settings.get('auracast_sampling_rate_hz')
|
||||
saved_r1_streams = '1 × 48kHz' # default
|
||||
if saved_rate:
|
||||
if saved_rate == 48000:
|
||||
channel_names = saved_settings.get('channel_names', [])
|
||||
if len(channel_names) == 2:
|
||||
saved_r1_streams = '2 × 24kHz'
|
||||
elif len(channel_names) == 3:
|
||||
saved_r1_streams = '3 × 16kHz'
|
||||
else:
|
||||
saved_r1_streams = '1 × 48kHz'
|
||||
elif saved_rate == 24000:
|
||||
saved_r1_streams = '2 × 24kHz'
|
||||
elif saved_rate == 16000:
|
||||
saved_r1_streams = '3 × 16kHz'
|
||||
default_r1_idx = r1_stream_options.index(saved_r1_streams) if saved_r1_streams in r1_stream_options else 0
|
||||
|
||||
if dante_stereo_enabled:
|
||||
@@ -856,7 +1031,17 @@ else:
|
||||
(r1_max_quality == "Fair (16kHz)" and quality == "Fair (16kHz)")):
|
||||
r1_available_qualities.append(quality)
|
||||
|
||||
saved_r1_quality = saved_r1_config.get('radio_quality', r1_max_quality)
|
||||
# Map saved sampling rate to quality label
|
||||
saved_r1_quality = r1_max_quality
|
||||
saved_rate = saved_settings.get('auracast_sampling_rate_hz')
|
||||
if saved_rate == 48000:
|
||||
saved_r1_quality = "High (48kHz)"
|
||||
elif saved_rate == 32000:
|
||||
saved_r1_quality = "Good (32kHz)"
|
||||
elif saved_rate == 24000:
|
||||
saved_r1_quality = "Medium (24kHz)"
|
||||
elif saved_rate == 16000:
|
||||
saved_r1_quality = "Fair (16kHz)"
|
||||
if saved_r1_quality not in r1_available_qualities:
|
||||
saved_r1_quality = r1_max_quality
|
||||
|
||||
@@ -875,7 +1060,7 @@ else:
|
||||
with col_r1_flags1:
|
||||
r1_assisted_listening = st.checkbox(
|
||||
"Assistive (R1)",
|
||||
value=bool(saved_r1_config.get('assisted_listening', False)),
|
||||
value=bool(saved_settings.get('assisted_listening_stream', False)),
|
||||
disabled=is_streaming,
|
||||
help="Assistive listening stream"
|
||||
)
|
||||
@@ -883,13 +1068,13 @@ else:
|
||||
with col_r1_flags2:
|
||||
r1_immediate_rendering = st.checkbox(
|
||||
"Immediate (R1)",
|
||||
value=bool(saved_r1_config.get('immediate_rendering', False)),
|
||||
value=bool(saved_settings.get('immediate_rendering', False)),
|
||||
disabled=is_streaming,
|
||||
help="Ignore presentation delay"
|
||||
)
|
||||
|
||||
with col_r1_pdelay:
|
||||
default_pdelay = int(saved_r1_config.get('presentation_delay_us', 40000) or 40000)
|
||||
default_pdelay = int(saved_settings.get('presentation_delay_us', 40000) or 40000)
|
||||
default_pdelay_ms = max(10, min(200, default_pdelay // 1000))
|
||||
r1_presentation_delay_ms = st.number_input(
|
||||
"Delay (ms, R1)",
|
||||
@@ -900,7 +1085,7 @@ else:
|
||||
|
||||
with col_r1_qos:
|
||||
qos_options = list(QOS_PRESET_MAP.keys())
|
||||
saved_qos = saved_r1_config.get('qos_preset', 'Fast')
|
||||
saved_qos = saved_settings.get('qos_preset', 'Fast')
|
||||
default_qos_idx = qos_options.index(saved_qos) if saved_qos in qos_options else 0
|
||||
r1_qos_preset = st.selectbox(
|
||||
"QoS (R1)", options=qos_options, index=default_qos_idx,
|
||||
@@ -908,6 +1093,13 @@ else:
|
||||
help="Quality of Service preset for Radio 1"
|
||||
)
|
||||
|
||||
r1_tx_power = _tx_power_selectbox(
|
||||
"TX Power (R1)",
|
||||
key="dante_tx_power_r1",
|
||||
default=saved_settings.get('advertising_tx_power', TX_POWER_DEFAULT),
|
||||
disabled=is_streaming,
|
||||
)
|
||||
|
||||
# Per-stream configuration for Radio 1
|
||||
if dante_stereo_enabled:
|
||||
st.write("**Stereo Stream Configuration (Radio 1)**")
|
||||
@@ -918,8 +1110,15 @@ else:
|
||||
if dante_stereo_enabled:
|
||||
# Stereo mode: single stream with combined L+R channels
|
||||
with st.expander("Stereo Stream - Radio 1", expanded=True):
|
||||
saved_streams = saved_r1_config.get('streams', [])
|
||||
saved_stream = saved_streams[0] if saved_streams else {}
|
||||
# Read from flat settings structure
|
||||
channel_names = saved_settings.get('channel_names', [])
|
||||
program_infos = saved_settings.get('program_info', [])
|
||||
languages = saved_settings.get('languages', [])
|
||||
|
||||
saved_name = channel_names[0] if channel_names else 'Dante_Stereo'
|
||||
saved_program_info = program_infos[0] if program_infos else saved_name
|
||||
saved_language = languages[0] if languages else 'eng'
|
||||
saved_password = saved_settings.get('stream_password', '')
|
||||
|
||||
# First row: Channel name and password
|
||||
col_name, col_pwd = st.columns([2, 1])
|
||||
@@ -927,7 +1126,7 @@ else:
|
||||
with col_name:
|
||||
stream_name = st.text_input(
|
||||
"Channel Name",
|
||||
value=saved_stream.get('name', 'Dante_Stereo'),
|
||||
value=saved_name,
|
||||
disabled=is_streaming,
|
||||
key="r1_stereo_name"
|
||||
)
|
||||
@@ -935,7 +1134,7 @@ else:
|
||||
with col_pwd:
|
||||
stream_password = st.text_input(
|
||||
"Stream Password",
|
||||
value=saved_stream.get('stream_password', ''),
|
||||
value=saved_password,
|
||||
type="password",
|
||||
disabled=is_streaming,
|
||||
key="r1_stereo_password",
|
||||
@@ -948,7 +1147,7 @@ else:
|
||||
with col_prog:
|
||||
program_info = st.text_input(
|
||||
"Program Info",
|
||||
value=saved_stream.get('program_info', 'Dante Stereo Broadcast'),
|
||||
value=saved_program_info,
|
||||
disabled=is_streaming,
|
||||
key="r1_stereo_program"
|
||||
)
|
||||
@@ -956,7 +1155,7 @@ else:
|
||||
with col_lang_code:
|
||||
language = st.text_input(
|
||||
"Language",
|
||||
value=saved_stream.get('language', 'eng'),
|
||||
value=saved_language,
|
||||
disabled=is_streaming,
|
||||
key="r1_stereo_lang",
|
||||
help="ISO 639-3 language code"
|
||||
@@ -990,10 +1189,21 @@ else:
|
||||
})
|
||||
else:
|
||||
# Normal mono mode: multiple streams with individual channels
|
||||
# Read from flat settings structure
|
||||
channel_names = saved_settings.get('channel_names', [])
|
||||
program_infos = saved_settings.get('program_info', [])
|
||||
languages = saved_settings.get('languages', [])
|
||||
input_devices = saved_settings.get('input_devices', [])
|
||||
stream_passwords = saved_settings.get('stream_passwords', []) if 'stream_passwords' in saved_settings else []
|
||||
|
||||
for i in range(r1_num_streams):
|
||||
with st.expander(f"Stream {i+1} - Radio 1", expanded=True):
|
||||
saved_streams = saved_r1_config.get('streams', [])
|
||||
saved_stream = saved_streams[i] if i < len(saved_streams) else {}
|
||||
# Get saved values from flat structure
|
||||
saved_name = channel_names[i] if i < len(channel_names) else f'Dante_R1_S{i+1}'
|
||||
saved_program_info = program_infos[i] if i < len(program_infos) else f'Dante Radio 1 Stream {i+1}'
|
||||
saved_language = languages[i] if i < len(languages) else 'eng'
|
||||
saved_password = stream_passwords[i] if i < len(stream_passwords) else ''
|
||||
saved_input_device = input_devices[i] if i < len(input_devices) else None
|
||||
|
||||
# First row: Channel name and language
|
||||
col_name, col_lang = st.columns([2, 1])
|
||||
@@ -1001,7 +1211,7 @@ else:
|
||||
with col_name:
|
||||
stream_name = st.text_input(
|
||||
f"Channel Name",
|
||||
value=saved_stream.get('name', f'Dante_R1_S{i+1}'),
|
||||
value=saved_name,
|
||||
disabled=is_streaming,
|
||||
key=f"r1_stream_{i}_name"
|
||||
)
|
||||
@@ -1009,7 +1219,7 @@ else:
|
||||
with col_lang:
|
||||
stream_password = st.text_input(
|
||||
f"Stream Password",
|
||||
value=saved_stream.get('stream_password', ''),
|
||||
value=saved_password,
|
||||
type="password",
|
||||
disabled=is_streaming,
|
||||
key=f"r1_stream_{i}_password",
|
||||
@@ -1022,7 +1232,7 @@ else:
|
||||
with col_prog:
|
||||
program_info = st.text_input(
|
||||
f"Program Info",
|
||||
value=saved_stream.get('program_info', f'Dante Radio 1 Stream {i+1}'),
|
||||
value=saved_program_info,
|
||||
disabled=is_streaming,
|
||||
key=f"r1_stream_{i}_program"
|
||||
)
|
||||
@@ -1030,7 +1240,7 @@ else:
|
||||
with col_lang_code:
|
||||
language = st.text_input(
|
||||
f"Language",
|
||||
value=saved_stream.get('language', 'eng'),
|
||||
value=saved_language,
|
||||
disabled=is_streaming,
|
||||
key=f"r1_stream_{i}_lang",
|
||||
help="ISO 639-3 language code"
|
||||
@@ -1045,7 +1255,7 @@ else:
|
||||
|
||||
if not is_streaming and input_options:
|
||||
# Get default from session state first, then from saved settings
|
||||
default_input_name = st.session_state.get(device_session_key, saved_stream.get('input_device'))
|
||||
default_input_name = st.session_state.get(device_session_key, saved_input_device)
|
||||
default_input_label = None
|
||||
for label, name in option_name_map.items():
|
||||
if name == default_input_name:
|
||||
@@ -1066,7 +1276,7 @@ else:
|
||||
st.session_state[device_session_key] = input_device
|
||||
else:
|
||||
# When streaming, get the device from session state
|
||||
current_device = st.session_state.get(device_session_key, saved_stream.get('input_device', 'No device'))
|
||||
current_device = st.session_state.get(device_session_key, saved_input_device or 'No device')
|
||||
|
||||
# Convert internal name to display label
|
||||
display_label = current_device
|
||||
@@ -1097,13 +1307,17 @@ else:
|
||||
st.subheader("Radio 2")
|
||||
|
||||
# Disable Radio 2 in stereo mode
|
||||
saved_r2_config = saved_settings.get('dante_radio2', {})
|
||||
secondary_settings = saved_settings.get('secondary', {})
|
||||
if dante_stereo_enabled:
|
||||
st.info("🎧 Radio 2 is automatically disabled in stereo mode")
|
||||
radio2_enabled = False
|
||||
else:
|
||||
# Enable/disable checkbox for Radio 2
|
||||
# Use saved settings or streaming state to determine default
|
||||
radio2_enabled_default = secondary_is_streaming
|
||||
# Check if secondary radio has saved settings (indicates it was enabled)
|
||||
if secondary_settings.get('auracast_sampling_rate_hz') or secondary_settings.get('channel_names'):
|
||||
radio2_enabled_default = True
|
||||
radio2_enabled = st.checkbox(
|
||||
"Enable Radio 2",
|
||||
value=radio2_enabled_default,
|
||||
@@ -1114,7 +1328,22 @@ else:
|
||||
if radio2_enabled:
|
||||
# Stream count dropdown for Radio 2
|
||||
r2_stream_options = r1_stream_options
|
||||
saved_r2_streams = saved_r2_config.get('stream_config', '1x48')
|
||||
# Infer stream configuration from saved secondary sampling rate
|
||||
saved_rate2 = secondary_settings.get('auracast_sampling_rate_hz')
|
||||
saved_r2_streams = '1 × 48kHz' # default
|
||||
if saved_rate2:
|
||||
if saved_rate2 == 48000:
|
||||
channel_names2 = secondary_settings.get('channel_names', [])
|
||||
if len(channel_names2) == 2:
|
||||
saved_r2_streams = '2 × 24kHz'
|
||||
elif len(channel_names2) == 3:
|
||||
saved_r2_streams = '3 × 16kHz'
|
||||
else:
|
||||
saved_r2_streams = '1 × 48kHz'
|
||||
elif saved_rate2 == 24000:
|
||||
saved_r2_streams = '2 × 24kHz'
|
||||
elif saved_rate2 == 16000:
|
||||
saved_r2_streams = '3 × 16kHz'
|
||||
default_r2_idx = r2_stream_options.index(saved_r2_streams) if saved_r2_streams in r2_stream_options else 0
|
||||
|
||||
r2_stream_config = st.selectbox(
|
||||
@@ -1137,7 +1366,16 @@ else:
|
||||
(r2_max_quality == "Fair (16kHz)" and quality == "Fair (16kHz)")):
|
||||
r2_available_qualities.append(quality)
|
||||
|
||||
saved_r2_quality = saved_r2_config.get('radio_quality', r2_max_quality)
|
||||
# Map saved secondary sampling rate to quality label
|
||||
saved_r2_quality = r2_max_quality
|
||||
if saved_rate2 == 48000:
|
||||
saved_r2_quality = "High (48kHz)"
|
||||
elif saved_rate2 == 32000:
|
||||
saved_r2_quality = "Good (32kHz)"
|
||||
elif saved_rate2 == 24000:
|
||||
saved_r2_quality = "Medium (24kHz)"
|
||||
elif saved_rate2 == 16000:
|
||||
saved_r2_quality = "Fair (16kHz)"
|
||||
if saved_r2_quality not in r2_available_qualities:
|
||||
saved_r2_quality = r2_max_quality
|
||||
|
||||
@@ -1150,13 +1388,12 @@ else:
|
||||
)
|
||||
|
||||
# Radio-level settings for Radio 2
|
||||
# First row: Assistive listening, immediate rendering, presentation delay, QoS
|
||||
col_r2_flags1, col_r2_flags2, col_r2_pdelay, col_r2_qos = st.columns([1, 1, 0.7, 0.6], gap="small")
|
||||
|
||||
with col_r2_flags1:
|
||||
r2_assisted_listening = st.checkbox(
|
||||
"Assistive (R2)",
|
||||
value=bool(saved_r2_config.get('assisted_listening', False)),
|
||||
value=bool(secondary_settings.get('assisted_listening_stream', False)),
|
||||
disabled=is_streaming,
|
||||
help="Assistive listening stream"
|
||||
)
|
||||
@@ -1164,13 +1401,13 @@ else:
|
||||
with col_r2_flags2:
|
||||
r2_immediate_rendering = st.checkbox(
|
||||
"Immediate (R2)",
|
||||
value=bool(saved_r2_config.get('immediate_rendering', False)),
|
||||
value=bool(secondary_settings.get('immediate_rendering', False)),
|
||||
disabled=is_streaming,
|
||||
help="Ignore presentation delay"
|
||||
)
|
||||
|
||||
with col_r2_pdelay:
|
||||
default_pdelay = int(saved_r2_config.get('presentation_delay_us', 40000) or 40000)
|
||||
default_pdelay = int(secondary_settings.get('presentation_delay_us', 40000) or 40000)
|
||||
default_pdelay_ms = max(10, min(200, default_pdelay // 1000))
|
||||
r2_presentation_delay_ms = st.number_input(
|
||||
"Delay (ms, R2)",
|
||||
@@ -1181,22 +1418,40 @@ else:
|
||||
|
||||
with col_r2_qos:
|
||||
qos_options = list(QOS_PRESET_MAP.keys())
|
||||
saved_qos = saved_r2_config.get('qos_preset', 'Fast')
|
||||
default_qos_idx = qos_options.index(saved_qos) if saved_qos in qos_options else 0
|
||||
saved_qos = secondary_settings.get('qos_preset', 'Fast')
|
||||
default_qos_idx2 = qos_options.index(saved_qos) if saved_qos in qos_options else 0
|
||||
r2_qos_preset = st.selectbox(
|
||||
"QoS (R2)", options=qos_options, index=default_qos_idx,
|
||||
"QoS (R2)", options=qos_options, index=default_qos_idx2,
|
||||
disabled=is_streaming,
|
||||
help="Quality of Service preset for Radio 2"
|
||||
)
|
||||
|
||||
r2_tx_power = _tx_power_selectbox(
|
||||
"TX Power (R2)",
|
||||
key="dante_tx_power_r2",
|
||||
default=saved_settings.get('secondary', {}).get('advertising_tx_power', TX_POWER_DEFAULT),
|
||||
disabled=is_streaming,
|
||||
)
|
||||
|
||||
# Per-stream configuration for Radio 2
|
||||
st.write("**Stream Configuration (Radio 2)**")
|
||||
r2_streams = []
|
||||
|
||||
# Read from flat secondary settings structure
|
||||
channel_names2 = secondary_settings.get('channel_names', [])
|
||||
program_infos2 = secondary_settings.get('program_info', [])
|
||||
languages2 = secondary_settings.get('languages', [])
|
||||
input_devices2 = secondary_settings.get('input_devices', [])
|
||||
stream_passwords2 = secondary_settings.get('stream_passwords', []) if 'stream_passwords' in secondary_settings else []
|
||||
|
||||
for i in range(r2_num_streams):
|
||||
with st.expander(f"Stream {i+1} - Radio 2", expanded=True):
|
||||
saved_streams = saved_r2_config.get('streams', [])
|
||||
saved_stream = saved_streams[i] if i < len(saved_streams) else {}
|
||||
# Get saved values from flat secondary structure
|
||||
saved_name2 = channel_names2[i] if i < len(channel_names2) else f'Dante_R2_S{i+1}'
|
||||
saved_program_info2 = program_infos2[i] if i < len(program_infos2) else f'Dante Radio 2 Stream {i+1}'
|
||||
saved_language2 = languages2[i] if i < len(languages2) else 'eng'
|
||||
saved_password2 = stream_passwords2[i] if i < len(stream_passwords2) else ''
|
||||
saved_input_device2 = input_devices2[i] if i < len(input_devices2) else None
|
||||
|
||||
# First row: Channel name and password
|
||||
col_name, col_pwd = st.columns([2, 1])
|
||||
@@ -1204,7 +1459,7 @@ else:
|
||||
with col_name:
|
||||
stream_name = st.text_input(
|
||||
f"Channel Name",
|
||||
value=saved_stream.get('name', f'Dante_R2_S{i+1}'),
|
||||
value=saved_name2,
|
||||
disabled=is_streaming,
|
||||
key=f"r2_stream_{i}_name"
|
||||
)
|
||||
@@ -1212,7 +1467,7 @@ else:
|
||||
with col_pwd:
|
||||
stream_password = st.text_input(
|
||||
f"Stream Password",
|
||||
value=saved_stream.get('stream_password', ''),
|
||||
value=saved_password2,
|
||||
type="password",
|
||||
disabled=is_streaming,
|
||||
key=f"r2_stream_{i}_password",
|
||||
@@ -1225,7 +1480,7 @@ else:
|
||||
with col_prog:
|
||||
program_info = st.text_input(
|
||||
f"Program Info",
|
||||
value=saved_stream.get('program_info', f'Dante Radio 2 Stream {i+1}'),
|
||||
value=saved_program_info2,
|
||||
disabled=is_streaming,
|
||||
key=f"r2_stream_{i}_program"
|
||||
)
|
||||
@@ -1233,7 +1488,7 @@ else:
|
||||
with col_lang:
|
||||
language = st.text_input(
|
||||
f"Language",
|
||||
value=saved_stream.get('language', 'eng'),
|
||||
value=saved_language2,
|
||||
disabled=is_streaming,
|
||||
key=f"r2_stream_{i}_lang",
|
||||
help="ISO 639-3 language code"
|
||||
@@ -1248,7 +1503,7 @@ else:
|
||||
|
||||
if not is_streaming and input_options:
|
||||
# Get default from session state first, then from saved settings
|
||||
default_input_name = st.session_state.get(device_session_key, saved_stream.get('input_device'))
|
||||
default_input_name = st.session_state.get(device_session_key, saved_input_device2)
|
||||
default_input_label = None
|
||||
for label, name in option_name_map.items():
|
||||
if name == default_input_name:
|
||||
@@ -1269,7 +1524,7 @@ else:
|
||||
st.session_state[device_session_key] = input_device
|
||||
else:
|
||||
# When streaming, get the device from session state
|
||||
current_device = st.session_state.get(device_session_key, saved_stream.get('input_device', 'No device'))
|
||||
current_device = st.session_state.get(device_session_key, saved_input_device2 or 'No device')
|
||||
|
||||
# Convert internal name to display label
|
||||
display_label = current_device
|
||||
@@ -1304,6 +1559,7 @@ else:
|
||||
r2_immediate_rendering = False
|
||||
r2_presentation_delay_ms = 40
|
||||
r2_qos_preset = 'Fast'
|
||||
r2_tx_power = TX_POWER_DEFAULT
|
||||
|
||||
# Validate unique input devices for Network - Dante mode
|
||||
if audio_mode == "Network - Dante":
|
||||
@@ -1335,6 +1591,7 @@ else:
|
||||
'immediate_rendering': r1_immediate_rendering,
|
||||
'presentation_delay_ms': r1_presentation_delay_ms,
|
||||
'qos_preset': r1_qos_preset,
|
||||
'tx_power': r1_tx_power,
|
||||
'dante_stereo_mode': dante_stereo_enabled,
|
||||
'dante_stereo_left': dante_left_channel,
|
||||
'dante_stereo_right': dante_right_channel,
|
||||
@@ -1350,12 +1607,34 @@ else:
|
||||
'immediate_rendering': r2_immediate_rendering if radio2_enabled else False,
|
||||
'presentation_delay_ms': r2_presentation_delay_ms if radio2_enabled else 40000,
|
||||
'qos_preset': r2_qos_preset if radio2_enabled else 'Fast',
|
||||
'tx_power': r2_tx_power if radio2_enabled else TX_POWER_DEFAULT,
|
||||
} if radio2_enabled else None
|
||||
|
||||
if audio_mode in ("USB", "Network"):
|
||||
# USB/Network: single set of controls shared with the single channel
|
||||
# Use saved settings if audio_mode matches, otherwise use defaults
|
||||
quality_options = list(QUALITY_MAP.keys())
|
||||
default_quality = "Medium (24kHz)" if "Medium (24kHz)" in quality_options else quality_options[0]
|
||||
saved_audio_mode = saved_settings.get('audio_mode')
|
||||
if saved_audio_mode in ("USB", "Network"):
|
||||
# Map saved sampling rate to quality label
|
||||
saved_rate = saved_settings.get('auracast_sampling_rate_hz')
|
||||
if saved_rate == 48000:
|
||||
default_quality = "High (48kHz)"
|
||||
elif saved_rate == 32000:
|
||||
default_quality = "Good (32kHz)"
|
||||
elif saved_rate == 24000:
|
||||
default_quality = "Medium (24kHz)"
|
||||
elif saved_rate == 16000:
|
||||
default_quality = "Fair (16kHz)"
|
||||
else:
|
||||
default_quality = "Medium (24kHz)"
|
||||
saved_pwd = saved_settings.get('stream_password', '')
|
||||
else:
|
||||
# Use defaults when switching from another mode
|
||||
default_quality = "Medium (24kHz)" if "Medium (24kHz)" in quality_options else quality_options[0]
|
||||
saved_pwd = ''
|
||||
if default_quality not in quality_options:
|
||||
default_quality = quality_options[0]
|
||||
quality = st.selectbox(
|
||||
"Stream Quality (Sampling Rate)",
|
||||
quality_options,
|
||||
@@ -1366,7 +1645,7 @@ else:
|
||||
|
||||
stream_passwort = st.text_input(
|
||||
"Stream Passwort",
|
||||
value="",
|
||||
value=saved_pwd,
|
||||
type="password",
|
||||
disabled=is_streaming,
|
||||
help="Optional: Set a broadcast code to protect your stream. Leave empty for an open (uncoded) broadcast."
|
||||
@@ -1406,6 +1685,13 @@ else:
|
||||
help="Fast: 2 retransmissions, lower latency. Robust: 4 retransmissions, better reliability."
|
||||
)
|
||||
|
||||
tx_power = _tx_power_selectbox(
|
||||
"TX Power",
|
||||
key="usb_tx_power",
|
||||
default=saved_settings.get('advertising_tx_power', TX_POWER_DEFAULT),
|
||||
disabled=is_streaming,
|
||||
)
|
||||
|
||||
stream_name = st.text_input(
|
||||
"Channel Name",
|
||||
value=default_name,
|
||||
@@ -1537,12 +1823,22 @@ if start_stream:
|
||||
bigs1 = []
|
||||
for i in range(demo_cfg['streams']):
|
||||
cfg_cls, lang = lang_cfgs[i % len(lang_cfgs)]
|
||||
if demo_content == "1 kHz test tone":
|
||||
source_file = f'../testdata/test_tone_1k_{int(q["rate"]/1000)}kHz_mono.lc3'
|
||||
big_kwargs = {
|
||||
'name': 'test tone',
|
||||
'program_info': '1khz',
|
||||
}
|
||||
else:
|
||||
source_file = f'../testdata/wave_particle_5min_{lang}_{int(q["rate"]/1000)}kHz_mono.lc3'
|
||||
big_kwargs = {}
|
||||
bigs1.append(cfg_cls(
|
||||
code=(stream_passwort.strip() or None),
|
||||
audio_source=f'file:../testdata/wave_particle_5min_{lang}_{int(q["rate"]/1000)}kHz_mono.wav',
|
||||
audio_source=f'file:{source_file}',
|
||||
iso_que_len=32,
|
||||
sampling_frequency=q['rate'],
|
||||
octets_per_frame=q['octets'],
|
||||
**big_kwargs,
|
||||
))
|
||||
|
||||
max_per_mc = {48000: 1, 24000: 2, 16000: 3}
|
||||
@@ -1559,6 +1855,7 @@ if start_stream:
|
||||
immediate_rendering=immediate_rendering,
|
||||
presentation_delay_us=int(presentation_delay_ms * 1000),
|
||||
qos_config=QOS_PRESET_MAP[qos_preset],
|
||||
advertising_tx_power=tx_power_r1,
|
||||
bigs=bigs1
|
||||
)
|
||||
config2 = None
|
||||
@@ -1571,6 +1868,7 @@ if start_stream:
|
||||
immediate_rendering=immediate_rendering,
|
||||
presentation_delay_us=int(presentation_delay_ms * 1000),
|
||||
qos_config=QOS_PRESET_MAP[qos_preset],
|
||||
advertising_tx_power=tx_power_r2,
|
||||
bigs=bigs2
|
||||
)
|
||||
|
||||
@@ -1603,7 +1901,9 @@ if start_stream:
|
||||
q = QUALITY_MAP[cfg['quality']]
|
||||
|
||||
# Determine if this is stereo mode (only applicable for analog)
|
||||
stereo_mode = cfg.get('stereo_mode', False)
|
||||
# Stereo is temporarily disabled in the UI; force mono regardless of any
|
||||
# lingering saved 'stereo_mode' flag.
|
||||
stereo_mode = False # cfg.get('stereo_mode', False)
|
||||
channels = 2 if stereo_mode else 1
|
||||
|
||||
return auracast_config.AuracastConfigGroup(
|
||||
@@ -1614,11 +1914,12 @@ if start_stream:
|
||||
immediate_rendering=bool(cfg['immediate_rendering']),
|
||||
presentation_delay_us=int(cfg['presentation_delay_ms'] * 1000),
|
||||
qos_config=QOS_PRESET_MAP[cfg['qos_preset']],
|
||||
advertising_tx_power=int(cfg.get('tx_power', TX_POWER_DEFAULT)),
|
||||
analog_gain_db_left=cfg.get('analog_gain_db_left', 0.0),
|
||||
analog_gain_db_right=cfg.get('analog_gain_db_right', 0.0),
|
||||
bigs=[
|
||||
auracast_config.AuracastBigConfig(
|
||||
code=(cfg['stream_passwort'].strip() or None),
|
||||
code=((cfg['stream_passwort'] or '').strip() or None),
|
||||
name=cfg['name'],
|
||||
program_info=cfg['program_info'],
|
||||
language=cfg['language'],
|
||||
@@ -1665,7 +1966,9 @@ if start_stream:
|
||||
bigs = []
|
||||
|
||||
# Check if stereo mode is enabled for this radio
|
||||
is_stereo_mode = bool(radio_cfg.get('dante_stereo_mode', False))
|
||||
# Stereo is temporarily disabled in the UI; force mono regardless of any
|
||||
# lingering saved 'dante_stereo_mode' flag or 'dante_stereo_' input device.
|
||||
is_stereo_mode = False # bool(radio_cfg.get('dante_stereo_mode', False))
|
||||
|
||||
for i, stream in enumerate(radio_cfg['streams']):
|
||||
if not stream.get('input_device'):
|
||||
@@ -1673,7 +1976,7 @@ if start_stream:
|
||||
|
||||
# Check if this specific stream uses stereo (dante_stereo_X_Y device)
|
||||
input_device = stream['input_device']
|
||||
stream_is_stereo = is_stereo_mode or input_device.startswith('dante_stereo_')
|
||||
stream_is_stereo = False # is_stereo_mode or input_device.startswith('dante_stereo_')
|
||||
num_bis = 2 if stream_is_stereo else 1
|
||||
num_channels = 2 if stream_is_stereo else 1
|
||||
|
||||
@@ -1701,6 +2004,7 @@ if start_stream:
|
||||
immediate_rendering=bool(radio_cfg['immediate_rendering']),
|
||||
presentation_delay_us=int(radio_cfg['presentation_delay_ms'] * 1000),
|
||||
qos_config=QOS_PRESET_MAP[radio_cfg['qos_preset']],
|
||||
advertising_tx_power=int(radio_cfg.get('tx_power', TX_POWER_DEFAULT)),
|
||||
bigs=bigs
|
||||
)
|
||||
|
||||
@@ -1736,6 +2040,7 @@ if start_stream:
|
||||
immediate_rendering=immediate_rendering,
|
||||
presentation_delay_us=int(presentation_delay_ms * 1000),
|
||||
qos_config=QOS_PRESET_MAP[qos_preset],
|
||||
advertising_tx_power=tx_power,
|
||||
bigs=[
|
||||
auracast_config.AuracastBigConfig(
|
||||
code=(stream_passwort.strip() or None),
|
||||
|
||||
@@ -10,6 +10,7 @@ from datetime import datetime
|
||||
import asyncio
|
||||
import random
|
||||
import subprocess
|
||||
import threading
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from fastapi import FastAPI, HTTPException
|
||||
@@ -208,6 +209,28 @@ multicaster1: multicast_control.Multicaster | None = None
|
||||
multicaster2: multicast_control.Multicaster | None = None
|
||||
_stream_lock = asyncio.Lock() # serialize initialize/stop_audio on API side
|
||||
|
||||
# BLE / audio event loop – set in __main__ before uvicorn starts.
|
||||
# All coroutines that touch Bumble objects or the audio pipeline MUST run
|
||||
# on this loop. HTTP handlers call _on_ble_loop() to cross into it.
|
||||
_ble_loop: asyncio.AbstractEventLoop | None = None
|
||||
|
||||
|
||||
async def _on_ble_loop(coro):
|
||||
"""Submit *coro* to the BLE event loop and await the result.
|
||||
|
||||
Called from uvicorn's event loop. Bridges HTTP handler coroutines into
|
||||
the isolated BLE loop so that serial I/O (serial_asyncio / HCI) and the
|
||||
audio pipeline are never preempted by HTTP accept/read/write callbacks.
|
||||
|
||||
asyncio.run_coroutine_threadsafe() schedules the coroutine on _ble_loop
|
||||
(thread-safe), returning a concurrent.futures.Future.
|
||||
asyncio.wrap_future() adapts that into an asyncio.Future so the caller
|
||||
can simply `await` it inside uvicorn's loop.
|
||||
"""
|
||||
assert _ble_loop is not None, "BLE loop not yet initialised"
|
||||
future = asyncio.run_coroutine_threadsafe(coro, _ble_loop)
|
||||
return await asyncio.wrap_future(future)
|
||||
|
||||
|
||||
async def _init_i2c_on_startup() -> None:
|
||||
# Ensure i2c-dev kernel module is loaded (required for /dev/i2c-* access)
|
||||
@@ -422,6 +445,11 @@ async def init_radio(transport: str, conf: auracast_config.AuracastConfigGroup,
|
||||
first_source = conf.bigs[0].audio_source if conf.bigs else ''
|
||||
input_device_name = None
|
||||
audio_mode_persist = 'Demo'
|
||||
# Capture original per-BIG device names before transformation
|
||||
original_input_devices = [
|
||||
big.audio_source.split(':', 1)[1] if (isinstance(big.audio_source, str) and big.audio_source.startswith('device:')) else None
|
||||
for big in conf.bigs
|
||||
]
|
||||
if any(isinstance(b.audio_source, str) and b.audio_source.startswith('device:') for b in conf.bigs):
|
||||
if isinstance(first_source, str) and first_source.startswith('device:'):
|
||||
input_device_name = first_source.split(':', 1)[1] if ':' in first_source else None
|
||||
@@ -564,6 +592,13 @@ async def init_radio(transport: str, conf: auracast_config.AuracastConfigGroup,
|
||||
demo_count = sum(1 for big in conf.bigs if isinstance(big.audio_source, str) and big.audio_source.startswith('file:'))
|
||||
demo_rate = int(conf.auracast_sampling_rate_hz or 0)
|
||||
demo_type = None
|
||||
demo_sources = [
|
||||
str(b.audio_source)
|
||||
for b in conf.bigs
|
||||
if isinstance(b.audio_source, str) and b.audio_source.startswith('file:')
|
||||
]
|
||||
is_demo_tone = bool(demo_sources) and all('test_tone_1k_' in src for src in demo_sources)
|
||||
demo_content = '1 kHz test tone' if is_demo_tone else 'Program material'
|
||||
if demo_count > 0 and demo_rate > 0:
|
||||
if demo_rate in (48000, 24000, 16000):
|
||||
demo_type = f"{demo_count} × {demo_rate//1000}kHz"
|
||||
@@ -574,6 +609,7 @@ async def init_radio(transport: str, conf: auracast_config.AuracastConfigGroup,
|
||||
'languages': [big.language for big in conf.bigs],
|
||||
'audio_mode': audio_mode_persist,
|
||||
'input_device': input_device_name,
|
||||
'input_devices': original_input_devices,
|
||||
'program_info': [getattr(big, 'program_info', None) for big in conf.bigs],
|
||||
'gain': [getattr(big, 'input_gain', 1.0) for big in conf.bigs],
|
||||
'auracast_sampling_rate_hz': conf.auracast_sampling_rate_hz,
|
||||
@@ -585,13 +621,15 @@ async def init_radio(transport: str, conf: auracast_config.AuracastConfigGroup,
|
||||
'analog_stereo_mode': getattr(conf.bigs[0], 'analog_stereo_mode', False) if conf.bigs else False,
|
||||
'analog_gain_db_left': getattr(conf, 'analog_gain_db_left', 0.0),
|
||||
'analog_gain_db_right': getattr(conf, 'analog_gain_db_right', 0.0),
|
||||
'advertising_tx_power': getattr(conf, 'advertising_tx_power', 8),
|
||||
'stream_password': (conf.bigs[0].code if conf.bigs and getattr(conf.bigs[0], 'code', None) else None),
|
||||
'big_ids': [getattr(big, 'id', DEFAULT_BIG_ID) for big in conf.bigs],
|
||||
'big_random_addresses': [getattr(big, 'random_address', DEFAULT_RANDOM_ADDRESS) for big in conf.bigs],
|
||||
'demo_total_streams': demo_count,
|
||||
'demo_stream_type': demo_type,
|
||||
'demo_content': demo_content,
|
||||
'is_streaming': auto_started,
|
||||
'demo_sources': [str(b.audio_source) for b in conf.bigs if isinstance(b.audio_source, str) and b.audio_source.startswith('file:')],
|
||||
'demo_sources': demo_sources,
|
||||
}
|
||||
return mc, persisted
|
||||
except HTTPException:
|
||||
@@ -602,7 +640,10 @@ async def init_radio(transport: str, conf: auracast_config.AuracastConfigGroup,
|
||||
|
||||
@app.post("/init")
|
||||
async def initialize(conf: auracast_config.AuracastConfigGroup):
|
||||
"""Initializes the primary broadcaster on the streamer thread."""
|
||||
"""Initializes the primary broadcaster on the BLE loop."""
|
||||
return await _on_ble_loop(_initialize_impl(conf))
|
||||
|
||||
async def _initialize_impl(conf: auracast_config.AuracastConfigGroup):
|
||||
async with _stream_lock:
|
||||
global multicaster1, global_config_group
|
||||
mc, persisted = await init_radio(TRANSPORT1, conf, multicaster1)
|
||||
@@ -612,7 +653,10 @@ async def initialize(conf: auracast_config.AuracastConfigGroup):
|
||||
|
||||
@app.post("/init2")
|
||||
async def initialize2(conf: auracast_config.AuracastConfigGroup):
|
||||
"""Initializes the secondary broadcaster on the streamer thread."""
|
||||
"""Initializes the secondary broadcaster on the BLE loop."""
|
||||
return await _on_ble_loop(_initialize2_impl(conf))
|
||||
|
||||
async def _initialize2_impl(conf: auracast_config.AuracastConfigGroup):
|
||||
async with _stream_lock:
|
||||
global multicaster2
|
||||
mc, persisted = await init_radio(TRANSPORT2, conf, multicaster2)
|
||||
@@ -631,7 +675,11 @@ async def set_led_enabled(body: dict):
|
||||
|
||||
@app.post("/stop_audio")
|
||||
async def stop_audio():
|
||||
"""Stops streaming on both multicaster1 and multicaster2 (worker thread)."""
|
||||
"""Stops streaming on both multicasters via the BLE loop."""
|
||||
return await _on_ble_loop(_stop_audio_impl())
|
||||
|
||||
async def _stop_audio_impl():
|
||||
"""Runs on BLE loop: stops all streamers and persists is_streaming=False."""
|
||||
try:
|
||||
was_running = await _stop_all()
|
||||
|
||||
@@ -681,9 +729,9 @@ async def set_adc_gain(payload: dict):
|
||||
|
||||
@app.post("/stream_lc3")
|
||||
async def send_audio(audio_data: dict[str, str]):
|
||||
"""Sends a block of pre-coded LC3 audio via the worker."""
|
||||
"""Sends a block of pre-coded LC3 audio via the BLE loop."""
|
||||
try:
|
||||
await _stream_lc3(audio_data, list(global_config_group.bigs))
|
||||
await _on_ble_loop(_stream_lc3(audio_data, list(global_config_group.bigs)))
|
||||
return {"status": "audio_sent"}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
@@ -755,11 +803,12 @@ async def _autostart_from_settings():
|
||||
big_ids = settings.get('big_ids') or []
|
||||
big_addrs = settings.get('big_random_addresses') or []
|
||||
stream_password = settings.get('stream_password')
|
||||
tx_power = int(settings.get('advertising_tx_power', 8))
|
||||
original_ts = settings.get('timestamp')
|
||||
previously_streaming = bool(settings.get('is_streaming'))
|
||||
|
||||
log.info(
|
||||
"[AUTOSTART][PRIMARY] loaded settings: previously_streaming=%s audio_mode=%s rate=%s octets=%s pres_delay=%s qos_preset=%s immediate_rendering=%s assisted_listening_stream=%s demo_sources=%s",
|
||||
"[AUTOSTART][PRIMARY] loaded settings: previously_streaming=%s audio_mode=%s rate=%s octets=%s pres_delay=%s qos_preset=%s immediate_rendering=%s assisted_listening_stream=%s tx_power=%+d dBm demo_sources=%s",
|
||||
previously_streaming,
|
||||
audio_mode,
|
||||
rate,
|
||||
@@ -768,6 +817,7 @@ async def _autostart_from_settings():
|
||||
saved_qos_preset,
|
||||
immediate_rendering,
|
||||
assisted_listening_stream,
|
||||
tx_power,
|
||||
(settings.get('demo_sources') or []),
|
||||
)
|
||||
|
||||
@@ -817,6 +867,7 @@ async def _autostart_from_settings():
|
||||
immediate_rendering=immediate_rendering,
|
||||
assisted_listening_stream=assisted_listening_stream,
|
||||
presentation_delay_us=pres_delay if pres_delay is not None else 40000,
|
||||
advertising_tx_power=tx_power,
|
||||
bigs=bigs,
|
||||
)
|
||||
# Set num_bis for stereo mode if needed
|
||||
@@ -886,6 +937,7 @@ async def _autostart_from_settings():
|
||||
presentation_delay_us=pres_delay if pres_delay is not None else 40000,
|
||||
analog_gain_db_left=settings.get('analog_gain_db_left', 0.0),
|
||||
analog_gain_db_right=settings.get('analog_gain_db_right', 0.0),
|
||||
advertising_tx_power=tx_power,
|
||||
bigs=bigs,
|
||||
)
|
||||
# Set num_bis for stereo mode if needed
|
||||
@@ -921,10 +973,11 @@ async def _autostart_from_settings():
|
||||
big_ids = settings.get('big_ids') or []
|
||||
big_addrs = settings.get('big_random_addresses') or []
|
||||
stream_password = settings.get('stream_password')
|
||||
tx_power = int(settings.get('advertising_tx_power', 8))
|
||||
original_ts = settings.get('timestamp')
|
||||
previously_streaming = bool(settings.get('is_streaming'))
|
||||
log.info(
|
||||
"[AUTOSTART][SECONDARY] loaded settings: previously_streaming=%s audio_mode=%s rate=%s octets=%s pres_delay=%s qos_preset=%s immediate_rendering=%s assisted_listening_stream=%s demo_sources=%s",
|
||||
"[AUTOSTART][SECONDARY] loaded settings: previously_streaming=%s audio_mode=%s rate=%s octets=%s pres_delay=%s qos_preset=%s immediate_rendering=%s assisted_listening_stream=%s tx_power=%+d dBm demo_sources=%s",
|
||||
previously_streaming,
|
||||
audio_mode,
|
||||
rate,
|
||||
@@ -933,6 +986,7 @@ async def _autostart_from_settings():
|
||||
saved_qos_preset,
|
||||
immediate_rendering,
|
||||
assisted_listening_stream,
|
||||
tx_power,
|
||||
(settings.get('demo_sources') or []),
|
||||
)
|
||||
if not previously_streaming:
|
||||
@@ -972,6 +1026,7 @@ async def _autostart_from_settings():
|
||||
immediate_rendering=immediate_rendering,
|
||||
assisted_listening_stream=assisted_listening_stream,
|
||||
presentation_delay_us=pres_delay if pres_delay is not None else 40000,
|
||||
advertising_tx_power=tx_power,
|
||||
bigs=bigs,
|
||||
)
|
||||
conf.qos_config = QOS_PRESET_MAP.get(saved_qos_preset, QOS_PRESET_MAP["Fast"])
|
||||
@@ -1041,6 +1096,7 @@ async def _autostart_from_settings():
|
||||
presentation_delay_us=pres_delay if pres_delay is not None else 40000,
|
||||
analog_gain_db_left=settings.get('analog_gain_db_left', 0.0),
|
||||
analog_gain_db_right=settings.get('analog_gain_db_right', 0.0),
|
||||
advertising_tx_power=tx_power,
|
||||
bigs=bigs,
|
||||
)
|
||||
conf.qos_config = QOS_PRESET_MAP.get(saved_qos_preset, QOS_PRESET_MAP["Fast"])
|
||||
@@ -1058,6 +1114,19 @@ async def _autostart_from_settings():
|
||||
await do_primary()
|
||||
await do_secondary()
|
||||
|
||||
async def _ble_startup():
|
||||
"""I2C init, ADC level reset, and autostart task scheduling on the BLE loop.
|
||||
|
||||
Bridged from _startup_autostart_event() so that these async subprocess
|
||||
calls and the long-lived autostart coroutine all run on _ble_loop, never
|
||||
on uvicorn's HTTP loop.
|
||||
"""
|
||||
await _init_i2c_on_startup()
|
||||
await _set_adc_level(0.0, 0.0)
|
||||
log.info("[STARTUP] Scheduling autostart task on BLE loop")
|
||||
asyncio.create_task(_autostart_from_settings())
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def _startup_autostart_event():
|
||||
# Spawn the autostart task without blocking startup
|
||||
@@ -1078,12 +1147,11 @@ async def _startup_autostart_event():
|
||||
# Hydrate settings cache once to avoid disk I/O during /status
|
||||
_load_led_settings()
|
||||
_init_settings_cache_from_disk()
|
||||
await _init_i2c_on_startup()
|
||||
# Ensure ADC mixer level is set at startup (default 0 dB)
|
||||
await _set_adc_level(0.0, 0.0)
|
||||
refresh_pw_cache()
|
||||
log.info("[STARTUP] Scheduling autostart task")
|
||||
asyncio.create_task(_autostart_from_settings())
|
||||
# I2C init, ADC setup and the autostart task must run on the BLE loop so
|
||||
# they share the same event loop as the Bumble HCI transport.
|
||||
log.info("[STARTUP] Bridging I2C init and autostart to BLE loop")
|
||||
asyncio.run_coroutine_threadsafe(_ble_startup(), _ble_loop)
|
||||
|
||||
@app.get("/audio_inputs_pw_usb")
|
||||
async def audio_inputs_pw_usb():
|
||||
@@ -1154,6 +1222,9 @@ async def refresh_audio_devices():
|
||||
@app.post("/shutdown")
|
||||
async def shutdown():
|
||||
"""Stops broadcasting and releases all audio/Bluetooth resources."""
|
||||
return await _on_ble_loop(_shutdown_impl())
|
||||
|
||||
async def _shutdown_impl():
|
||||
try:
|
||||
await _stop_all()
|
||||
return {"status": "stopped"}
|
||||
@@ -1166,6 +1237,9 @@ async def system_reboot():
|
||||
|
||||
Requires the service user to have passwordless sudo permissions to run 'reboot'.
|
||||
"""
|
||||
return await _on_ble_loop(_system_reboot_impl())
|
||||
|
||||
async def _system_reboot_impl():
|
||||
try:
|
||||
# Best-effort: stop any active streaming cleanly WITHOUT persisting state
|
||||
try:
|
||||
@@ -1189,46 +1263,26 @@ async def system_reboot():
|
||||
|
||||
@app.post("/restart_dep")
|
||||
async def restart_dep():
|
||||
"""Restart DEP by running dep.sh stop then dep.sh start in the dep directory.
|
||||
"""Restart DEP via systemctl restart dep.service.
|
||||
|
||||
Requires the service user to have passwordless sudo permissions to run dep.sh.
|
||||
Requires the service user to have passwordless sudo permissions for systemctl.
|
||||
"""
|
||||
try:
|
||||
# Get the dep directory path (dep.sh is in dante_package subdirectory)
|
||||
dep_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'dep', 'dante_package')
|
||||
|
||||
# Run dep.sh stop first
|
||||
log.info("Stopping DEP...")
|
||||
stop_process = await asyncio.create_subprocess_exec(
|
||||
"sudo", "bash", "dep.sh", "stop",
|
||||
cwd=dep_dir,
|
||||
log.info("Restarting DEP via systemctl...")
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
"sudo", "systemctl", "restart", "dep.service",
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE
|
||||
)
|
||||
stop_stdout, stop_stderr = await stop_process.communicate()
|
||||
stdout, stderr = await proc.communicate()
|
||||
|
||||
if stop_process.returncode != 0:
|
||||
error_msg = stop_stderr.decode() if stop_stderr else "Unknown error"
|
||||
log.error(f"Failed to stop DEP: {error_msg}")
|
||||
raise HTTPException(status_code=500, detail=f"Failed to stop DEP: {error_msg}")
|
||||
|
||||
# Run dep.sh start after stop succeeds
|
||||
log.info("Starting DEP...")
|
||||
start_process = await asyncio.create_subprocess_exec(
|
||||
"sudo", "bash", "dep.sh", "start",
|
||||
cwd=dep_dir,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE
|
||||
)
|
||||
start_stdout, start_stderr = await start_process.communicate()
|
||||
|
||||
if start_process.returncode == 0:
|
||||
if proc.returncode == 0:
|
||||
log.info("DEP restarted successfully")
|
||||
return {"status": "success", "message": "DEP restarted successfully"}
|
||||
else:
|
||||
error_msg = start_stderr.decode() if start_stderr else "Unknown error"
|
||||
log.error(f"Failed to start DEP: {error_msg}")
|
||||
raise HTTPException(status_code=500, detail=f"Failed to start DEP: {error_msg}")
|
||||
error_msg = stderr.decode() if stderr else "Unknown error"
|
||||
log.error(f"Failed to restart DEP: {error_msg}")
|
||||
raise HTTPException(status_code=500, detail=f"Failed to restart DEP: {error_msg}")
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
@@ -1322,6 +1376,9 @@ async def check_update():
|
||||
@app.post("/system_update")
|
||||
async def system_update():
|
||||
"""Update application: git pull main branch (latest tag), poetry install, restart services."""
|
||||
return await _on_ble_loop(_system_update_impl())
|
||||
|
||||
async def _system_update_impl():
|
||||
try:
|
||||
# Best-effort: stop any active streaming cleanly
|
||||
try:
|
||||
@@ -1789,5 +1846,170 @@ if __name__ == '__main__':
|
||||
level=os.environ.get('LOG_LEVEL', log.INFO),
|
||||
format='%(module)s.py:%(lineno)d %(levelname)s: %(message)s'
|
||||
)
|
||||
|
||||
# ── GIL switch interval ─────────────────────────────────────────────────
|
||||
# CPython releases the GIL every sys.getswitchinterval() seconds (default
|
||||
# 5 ms). The audio pipeline fires every 10 ms, so a 5 ms granularity
|
||||
# means up to half a frame period can be wasted waiting for the GIL.
|
||||
# Reducing to 1 ms gives the BLE thread much tighter access.
|
||||
import sys
|
||||
sys.setswitchinterval(0.001)
|
||||
log.info("GIL switch interval set to 1 ms")
|
||||
|
||||
# ── BLE / audio event loop ──────────────────────────────────────────────
|
||||
# Bumble (serial_asyncio / HCI) and the audio pipeline run exclusively on
|
||||
# this loop. Uvicorn's HTTP accept/read/write callbacks run on a separate
|
||||
# asyncio loop in the main thread, so they can never stall BLE advertising
|
||||
# or audio encoding.
|
||||
#
|
||||
# Route handlers that touch Bumble objects call _on_ble_loop(), which uses
|
||||
# asyncio.run_coroutine_threadsafe() + asyncio.wrap_future() to submit the
|
||||
# coroutine to _ble_loop and await the result back in uvicorn's loop.
|
||||
# Hot-path read-only endpoints (/status, /audio_level*) access
|
||||
# multicaster state directly – Python's GIL makes attribute reads safe.
|
||||
|
||||
def _pthread_sched_lib():
|
||||
"""Return a ctypes handle with correctly typed pthread scheduling symbols.
|
||||
|
||||
Uses RTLD_DEFAULT (ctypes.CDLL(None)) to resolve symbols from all
|
||||
currently loaded shared libraries. This handles both:
|
||||
- glibc < 2.34: pthread_self/pthread_setschedparam live in libpthread.so.0
|
||||
- glibc >= 2.34: pthreads merged into libc.so.6
|
||||
using find_library("c") would miss libpthread on older glibc and cause
|
||||
a NULL function pointer → SEGV when called.
|
||||
|
||||
Explicit restype/argtypes are mandatory: pthread_t is c_ulong (64-bit
|
||||
on ARM64/x86-64) but ctypes defaults to c_int (32-bit), truncating
|
||||
the thread handle and causing a SEGV inside pthread_setschedparam.
|
||||
"""
|
||||
import ctypes
|
||||
|
||||
SCHED_FIFO = 1
|
||||
SCHED_OTHER = 0
|
||||
|
||||
class SchedParam(ctypes.Structure):
|
||||
_fields_ = [("sched_priority", ctypes.c_int)]
|
||||
|
||||
lib = ctypes.CDLL(None, use_errno=True) # RTLD_DEFAULT
|
||||
|
||||
lib.pthread_self.restype = ctypes.c_ulong
|
||||
lib.pthread_self.argtypes = []
|
||||
|
||||
lib.pthread_getschedparam.restype = ctypes.c_int
|
||||
lib.pthread_getschedparam.argtypes = [
|
||||
ctypes.c_ulong,
|
||||
ctypes.POINTER(ctypes.c_int),
|
||||
ctypes.POINTER(SchedParam),
|
||||
]
|
||||
lib.pthread_setschedparam.restype = ctypes.c_int
|
||||
lib.pthread_setschedparam.argtypes = [
|
||||
ctypes.c_ulong,
|
||||
ctypes.c_int,
|
||||
ctypes.POINTER(SchedParam),
|
||||
]
|
||||
return lib, SchedParam, SCHED_FIFO, SCHED_OTHER
|
||||
|
||||
def _configure_ble_thread_scheduling():
|
||||
"""Confirm or establish SCHED_FIFO for the BLE/audio thread.
|
||||
|
||||
When launched via the systemd unit (CPUSchedulingPolicy=fifo), new
|
||||
threads inherit the process RT policy automatically – just log and
|
||||
return. When run directly (development), attempt to elevate to
|
||||
SCHED_FIFO/30 (requires CAP_SYS_NICE), falling back gracefully.
|
||||
"""
|
||||
import ctypes
|
||||
try:
|
||||
lib, SchedParam, SCHED_FIFO, _ = _pthread_sched_lib()
|
||||
tid = lib.pthread_self()
|
||||
policy = ctypes.c_int(-1)
|
||||
param = SchedParam(0)
|
||||
lib.pthread_getschedparam(tid, ctypes.byref(policy), ctypes.byref(param))
|
||||
|
||||
if policy.value == SCHED_FIFO:
|
||||
log.info("[BLE-LOOP] Already SCHED_FIFO priority=%d (inherited from systemd)",
|
||||
param.sched_priority)
|
||||
return
|
||||
|
||||
param.sched_priority = 30
|
||||
ret = lib.pthread_setschedparam(tid, SCHED_FIFO, ctypes.byref(param))
|
||||
if ret == 0:
|
||||
log.info("[BLE-LOOP] SCHED_FIFO priority=30 set")
|
||||
else:
|
||||
err = ctypes.get_errno()
|
||||
log.warning("[BLE-LOOP] SCHED_FIFO failed (errno=%d: %s) – "
|
||||
"use systemd CPUSchedulingPolicy=fifo or grant CAP_SYS_NICE",
|
||||
err, os.strerror(err))
|
||||
try:
|
||||
os.setpriority(os.PRIO_PROCESS, 0,
|
||||
os.getpriority(os.PRIO_PROCESS, 0) - 5)
|
||||
except PermissionError:
|
||||
pass
|
||||
except Exception as exc:
|
||||
log.warning("[BLE-LOOP] Scheduling setup error: %s", exc)
|
||||
|
||||
def _configure_http_thread_scheduling():
|
||||
"""Demote the HTTP (uvicorn) thread to SCHED_OTHER + nice=+10.
|
||||
|
||||
When systemd sets CPUSchedulingPolicy=fifo, every thread in the
|
||||
process – including uvicorn's main loop – inherits SCHED_FIFO.
|
||||
We demote the HTTP thread back to SCHED_OTHER so the BLE thread
|
||||
always wins CPU arbitration when both are runnable.
|
||||
Lowering scheduling policy never requires special privileges.
|
||||
"""
|
||||
import ctypes
|
||||
try:
|
||||
lib, SchedParam, SCHED_FIFO, SCHED_OTHER = _pthread_sched_lib()
|
||||
tid = lib.pthread_self()
|
||||
policy = ctypes.c_int(-1)
|
||||
param = SchedParam(0)
|
||||
lib.pthread_getschedparam(tid, ctypes.byref(policy), ctypes.byref(param))
|
||||
|
||||
if policy.value == SCHED_FIFO:
|
||||
param.sched_priority = 0
|
||||
ret = lib.pthread_setschedparam(tid, SCHED_OTHER, ctypes.byref(param))
|
||||
if ret == 0:
|
||||
log.info("[HTTP] Demoted SCHED_FIFO → SCHED_OTHER")
|
||||
else:
|
||||
err = ctypes.get_errno()
|
||||
log.warning("[HTTP] Could not demote from SCHED_FIFO (errno=%d)", err)
|
||||
else:
|
||||
log.info("[HTTP] Already SCHED_OTHER, no demotion needed")
|
||||
except Exception as exc:
|
||||
log.warning("[HTTP] Scheduling demotion error: %s", exc)
|
||||
|
||||
try:
|
||||
os.nice(10)
|
||||
log.info("[HTTP] nice=+10 (lower priority)")
|
||||
except Exception as exc:
|
||||
log.debug("[HTTP] os.nice: %s", exc)
|
||||
|
||||
_ble_loop_ready = threading.Event()
|
||||
|
||||
def _run_ble_loop():
|
||||
# Confirm or establish RT scheduling before entering the event loop.
|
||||
_configure_ble_thread_scheduling()
|
||||
|
||||
async def _ble_runner():
|
||||
global _ble_loop
|
||||
_ble_loop = asyncio.get_running_loop()
|
||||
_ble_loop_ready.set()
|
||||
# Keep the loop alive; it is stopped when the process exits because
|
||||
# this is a daemon thread.
|
||||
await asyncio.Event().wait()
|
||||
|
||||
asyncio.run(_ble_runner())
|
||||
|
||||
_ble_thread = threading.Thread(target=_run_ble_loop, name="ble-loop", daemon=True)
|
||||
_ble_thread.start()
|
||||
if not _ble_loop_ready.wait(timeout=5):
|
||||
log.error("BLE event loop failed to start within 5 s – aborting")
|
||||
raise RuntimeError("BLE event loop startup timeout")
|
||||
log.info("BLE event loop started on thread '%s'", _ble_thread.name)
|
||||
|
||||
# ── HTTP / uvicorn event loop (main thread) ─────────────────────────────
|
||||
# Demote the HTTP thread from SCHED_FIFO (if set by systemd) to
|
||||
# SCHED_OTHER + nice=+10 so the BLE thread always preempts it.
|
||||
_configure_http_thread_scheduling()
|
||||
|
||||
# Bind to localhost only for security: prevents network access, only frontend on same machine can connect
|
||||
uvicorn.run(app, host="127.0.0.1", port=5000, access_log=False)
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -21,12 +21,12 @@ def read_lc3_file(filepath):
|
||||
logging.info('frame_duration %s', frame_duration)
|
||||
logging.info('stream_length %s', stream_length)
|
||||
|
||||
lc3_bytes= b''
|
||||
chunks = []
|
||||
while True:
|
||||
b = f_lc3.read(2)
|
||||
if b == b'':
|
||||
break
|
||||
lc3_frame_size = struct.unpack('=H', b)[0]
|
||||
lc3_bytes += f_lc3.read(lc3_frame_size)
|
||||
chunks.append(f_lc3.read(lc3_frame_size))
|
||||
|
||||
return lc3_bytes
|
||||
return b''.join(chunks)
|
||||
@@ -0,0 +1 @@
|
||||
Placeholder file to have the activation folder available, otherwise dante activation script fails with 'Unable to write'.
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"trialMode": true,
|
||||
"trialMode": false,
|
||||
"$schema": "./dante.json_schema.json",
|
||||
"platform":
|
||||
{
|
||||
@@ -16,7 +16,7 @@
|
||||
48000
|
||||
],
|
||||
"samplesPerPeriod" : 16,
|
||||
"periodsPerBuffer" : 300,
|
||||
"periodsPerBuffer" : 150,
|
||||
"networkLatencyMinMs" : 2,
|
||||
"networkLatencyDefaultMs" : 5,
|
||||
"supportedEncodings" :
|
||||
@@ -24,7 +24,10 @@
|
||||
"PCM16"
|
||||
],
|
||||
"defaultEncoding" : "PCM16",
|
||||
"numDepCores" : 1
|
||||
"numDepCores" :
|
||||
[
|
||||
3
|
||||
]
|
||||
},
|
||||
"network" :
|
||||
{
|
||||
@@ -50,31 +53,32 @@
|
||||
"alsaAsrc":
|
||||
{
|
||||
"enableAlsaAsrc": true,
|
||||
"cpuAffinity": 3,
|
||||
"deviceConfigurations": [
|
||||
{
|
||||
"deviceIdentifier": "hw:0,0",
|
||||
"deviceIdentifier": "hw:6,0,0",
|
||||
"direction": "playback",
|
||||
"bitDepth": 16,
|
||||
"numOpenChannels": 6,
|
||||
"alsaChannelRange": "0-5",
|
||||
"danteChannelRange": "0-5",
|
||||
"bufferSize": 4800,
|
||||
"bufferSize": 960,
|
||||
"samplesPerPeriod": 16
|
||||
}
|
||||
]
|
||||
},
|
||||
"product" :
|
||||
{
|
||||
"manfId" : "Audinate",
|
||||
"manfName" : "Audinate Pty Ltd",
|
||||
"modelId" : "OEMDEP",
|
||||
"modelName" : "Linux Dante Embedded Platform",
|
||||
"manfId" : "SummitFC",
|
||||
"manfName" : "Summitwave FlexCo",
|
||||
"modelId" : "TX",
|
||||
"modelName" : "Summitwave TX",
|
||||
"modelVersion" :
|
||||
{
|
||||
"major" : 9,
|
||||
"minor" : 9,
|
||||
"bugfix" : 99
|
||||
"major" : 1,
|
||||
"minor" : 0,
|
||||
"bugfix" : 0
|
||||
},
|
||||
"devicePrefix" : "DEP"
|
||||
"devicePrefix" : "SW-TX"
|
||||
}
|
||||
}
|
||||
|
||||
+13095
-13051
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,8 @@
|
||||
# Provenance of src/openocd/merged.hex — generated by update_firmware.sh. Do not edit by hand.
|
||||
firmware_commit: 52d034e58e42f15449b4d026e056ed99d10999d9
|
||||
firmware_describe: 52d034e
|
||||
firmware_branch: HEAD
|
||||
preset: build_nrf54_radio0_radio1
|
||||
ncs_version: v3.0.2
|
||||
merged_hex_sha256: 4d7779191d08aaefe45f04c2689f3ecbe49688c8e78c7fa9a40550d545df8b17
|
||||
exported_utc: 2026-07-13T12:02:55Z
|
||||
Executable
+161
@@ -0,0 +1,161 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# update_firmware.sh — build (optional) and export the beacon firmware image.
|
||||
#
|
||||
# Copies the sysbuild `merged.hex` produced from the `firmware/` submodule to
|
||||
# src/openocd/merged.hex (the committed artifact the RPi flashes via flash.sh)
|
||||
# and records its provenance in src/openocd/merged.hex.version.
|
||||
#
|
||||
# This runs on a DEV MACHINE that has the nRF Connect SDK (~/ncs) — never on a
|
||||
# beacon device. Devices only ever consume the committed merged.hex.
|
||||
#
|
||||
# Usage:
|
||||
# src/openocd/update_firmware.sh [--build] [--preset NAME] [--ncs-version VER] [--force]
|
||||
#
|
||||
# (default) Export merged.hex from an existing build dir.
|
||||
# --build Configure + build the sysbuild image from scratch (a true
|
||||
# one-shot), then export. Uses the nRF Connect SDK via
|
||||
# `nrfutil toolchain-manager launch` — no manual env setup.
|
||||
# --preset NAME Preset in firmware/CMakePresets.json to build/export
|
||||
# (default: build_nrf54_radio0_radio1). BOARD and the
|
||||
# conf/overlay files are read straight from that preset.
|
||||
# --ncs-version VER nRF Connect SDK version to build with (default: v3.0.2).
|
||||
# West workspace is $HOME/ncs/VER unless $NCS_WORKSPACE set.
|
||||
# --force Export even if the firmware submodule working tree is dirty.
|
||||
#
|
||||
# Example (rebuild the production image from the pinned firmware commit and export):
|
||||
# git submodule update --init firmware
|
||||
# src/openocd/update_firmware.sh --build
|
||||
#
|
||||
# Note: merged.hex is a *sysbuild* output. A plain `cmake --preset` configure
|
||||
# only produces zephyr/zephyr.hex — this script deliberately refuses to fall
|
||||
# back to that, so the exported artifact is always the real merged image.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
PRESET="build_nrf54_radio0_radio1"
|
||||
NCS_VERSION="v3.0.2"
|
||||
DO_BUILD=0
|
||||
FORCE=0
|
||||
|
||||
usage() { awk 'NR>1 && /^#/ {sub(/^# ?/,""); print; next} NR>1 {exit}' "$0"; exit "${1:-1}"; }
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--build) DO_BUILD=1 ;;
|
||||
--preset) shift; PRESET="${1:?--preset needs a value}" ;;
|
||||
--ncs-version) shift; NCS_VERSION="${1:?--ncs-version needs a value}" ;;
|
||||
--force) FORCE=1 ;;
|
||||
-h|--help) usage 0 ;;
|
||||
*) echo "Unknown argument: $1" >&2; usage ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
# Repo root = two levels up from this script (src/openocd/ -> repo root).
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
|
||||
FIRMWARE_DIR="$ROOT/firmware"
|
||||
BUILD_DIR="$FIRMWARE_DIR/$PRESET"
|
||||
SRC_HEX="$BUILD_DIR/merged.hex"
|
||||
DEST_HEX="$ROOT/src/openocd/merged.hex"
|
||||
VERSION_FILE="$ROOT/src/openocd/merged.hex.version"
|
||||
|
||||
die() { echo "[update_firmware] ERROR: $*" >&2; exit 1; }
|
||||
|
||||
# 1. Submodule present and populated?
|
||||
[[ -f "$FIRMWARE_DIR/.git" || -d "$FIRMWARE_DIR/.git" ]] \
|
||||
|| die "firmware submodule not initialised. Run: git submodule update --init firmware"
|
||||
git -C "$FIRMWARE_DIR" rev-parse HEAD >/dev/null 2>&1 \
|
||||
|| die "firmware submodule has no checkout. Run: git submodule update --init firmware"
|
||||
|
||||
# 2. Optional sysbuild build (configure + compile) via the NCS toolchain manager.
|
||||
# BOARD and the conf/overlay files come straight from firmware/CMakePresets.json,
|
||||
# so this stays in sync with the preset the nRF Connect VS Code extension uses.
|
||||
if [[ "$DO_BUILD" == "1" ]]; then
|
||||
command -v nrfutil >/dev/null 2>&1 \
|
||||
|| die "'nrfutil' not found. Install the nRF Connect SDK toolchain manager first."
|
||||
PRESETS_JSON="$FIRMWARE_DIR/CMakePresets.json"
|
||||
[[ -f "$PRESETS_JSON" ]] || die "no CMakePresets.json in $FIRMWARE_DIR"
|
||||
|
||||
# Read BOARD / CONF_FILE / EXTRA_CONF_FILE / DTC_OVERLAY_FILE from the preset.
|
||||
preset_vars="$(python3 - "$PRESETS_JSON" "$PRESET" <<'PY'
|
||||
import json, sys
|
||||
path, preset = sys.argv[1], sys.argv[2]
|
||||
cfgs = {c["name"]: c for c in json.load(open(path)).get("configurePresets", [])}
|
||||
if preset not in cfgs:
|
||||
sys.exit(f"preset '{preset}' not found in {path}")
|
||||
cv = cfgs[preset].get("cacheVariables", {})
|
||||
def g(k):
|
||||
v = cv.get(k)
|
||||
return (v.get("value") if isinstance(v, dict) else v) or ""
|
||||
for k in ("BOARD", "CONF_FILE", "EXTRA_CONF_FILE", "DTC_OVERLAY_FILE"):
|
||||
print(f"{k}={g(k)}")
|
||||
PY
|
||||
)" || die "failed to parse preset '$PRESET' from CMakePresets.json"
|
||||
# Import without eval — values (e.g. EXTRA_CONF_FILE) contain ';'.
|
||||
PRESET_BOARD=""; PRESET_CONF_FILE=""; PRESET_EXTRA_CONF_FILE=""; PRESET_DTC_OVERLAY_FILE=""
|
||||
while IFS='=' read -r _k _v; do
|
||||
case "$_k" in
|
||||
BOARD) PRESET_BOARD="$_v" ;;
|
||||
CONF_FILE) PRESET_CONF_FILE="$_v" ;;
|
||||
EXTRA_CONF_FILE) PRESET_EXTRA_CONF_FILE="$_v" ;;
|
||||
DTC_OVERLAY_FILE) PRESET_DTC_OVERLAY_FILE="$_v" ;;
|
||||
esac
|
||||
done <<< "$preset_vars"
|
||||
[[ -n "$PRESET_BOARD" ]] || die "preset '$PRESET' defines no BOARD"
|
||||
|
||||
WORKSPACE="${NCS_WORKSPACE:-$HOME/ncs/$NCS_VERSION}"
|
||||
[[ -d "$WORKSPACE/.west" ]] \
|
||||
|| die "no west workspace at '$WORKSPACE' (set \$NCS_WORKSPACE or pass --ncs-version)."
|
||||
|
||||
# Assemble the -D flags. CONF_FILE=prj.conf is west's default, so omit it then.
|
||||
DFLAGS=()
|
||||
[[ -n "$PRESET_CONF_FILE" && "$PRESET_CONF_FILE" != "prj.conf" ]] && DFLAGS+=( "-DCONF_FILE=$PRESET_CONF_FILE" )
|
||||
[[ -n "$PRESET_EXTRA_CONF_FILE" ]] && DFLAGS+=( "-DEXTRA_CONF_FILE=$PRESET_EXTRA_CONF_FILE" )
|
||||
[[ -n "$PRESET_DTC_OVERLAY_FILE" ]] && DFLAGS+=( "-DDTC_OVERLAY_FILE=$PRESET_DTC_OVERLAY_FILE" )
|
||||
|
||||
# Build the inner command with each token shell-quoted (conf lists contain ';').
|
||||
inner="cd $(printf %q "$WORKSPACE") && west build --sysbuild -p auto"
|
||||
inner+=" -b $(printf %q "$PRESET_BOARD") -d $(printf %q "$BUILD_DIR") $(printf %q "$FIRMWARE_DIR") --"
|
||||
for f in "${DFLAGS[@]}"; do inner+=" $(printf %q "$f")"; done
|
||||
|
||||
echo "[update_firmware] Building $PRESET (NCS $NCS_VERSION, board $PRESET_BOARD) ..."
|
||||
echo "[update_firmware] west build --sysbuild ${DFLAGS[*]}"
|
||||
nrfutil toolchain-manager launch --ncs-version "$NCS_VERSION" -- bash -c "$inner" \
|
||||
|| die "west build failed."
|
||||
fi
|
||||
|
||||
# 3. Require the sysbuild artifact (no silent zephyr.hex fallback).
|
||||
[[ -f "$SRC_HEX" ]] || die "no merged.hex at '$SRC_HEX'. Build '$PRESET' with sysbuild \
|
||||
(pass --build once the dir is configured), or point --preset at the right build dir."
|
||||
|
||||
# 4. Clean-tree guard so the deployed hex maps to a real firmware commit.
|
||||
FW_DESCRIBE="$(git -C "$FIRMWARE_DIR" describe --always --dirty --tags 2>/dev/null || git -C "$FIRMWARE_DIR" rev-parse --short HEAD)"
|
||||
if [[ "$FW_DESCRIBE" == *-dirty && "$FORCE" != "1" ]]; then
|
||||
die "firmware submodule working tree is dirty ($FW_DESCRIBE). Commit/stash it, or pass --force."
|
||||
fi
|
||||
|
||||
# 5. Export.
|
||||
cp "$SRC_HEX" "$DEST_HEX"
|
||||
|
||||
# 6. Provenance.
|
||||
FW_COMMIT="$(git -C "$FIRMWARE_DIR" rev-parse HEAD)"
|
||||
FW_BRANCH="$(git -C "$FIRMWARE_DIR" rev-parse --abbrev-ref HEAD 2>/dev/null || echo 'detached')"
|
||||
HEX_SHA="$(sha256sum "$DEST_HEX" | awk '{print $1}')"
|
||||
cat > "$VERSION_FILE" <<EOF
|
||||
# Provenance of src/openocd/merged.hex — generated by update_firmware.sh. Do not edit by hand.
|
||||
firmware_commit: $FW_COMMIT
|
||||
firmware_describe: $FW_DESCRIBE
|
||||
firmware_branch: $FW_BRANCH
|
||||
preset: $PRESET
|
||||
ncs_version: $NCS_VERSION
|
||||
merged_hex_sha256: $HEX_SHA
|
||||
exported_utc: $(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
EOF
|
||||
|
||||
echo "[update_firmware] Exported $SRC_HEX"
|
||||
echo "[update_firmware] -> $DEST_HEX"
|
||||
echo "[update_firmware] firmware: $FW_DESCRIBE ($FW_COMMIT)"
|
||||
echo "[update_firmware] sha256: $HEX_SHA"
|
||||
echo "[update_firmware] Now commit: git add src/openocd/merged.hex src/openocd/merged.hex.version firmware"
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/bin/bash
|
||||
# NetworkManager dispatcher script: 10-link-local-mgmt
|
||||
#
|
||||
# Temporarily suppresses IPv4 link-local when a DHCP address is available,
|
||||
# using nmcli device modify (active session only, NOT saved to the profile).
|
||||
# The persistent profile always keeps ipv4.link-local=enabled so that
|
||||
# direct-connect (no DHCP) plug-ins always activate and trigger events.
|
||||
# Avahi is reloaded on each event — no /etc/avahi/hosts file, avahi uses
|
||||
# natural per-interface advertisement so each segment gets the right IP.
|
||||
#
|
||||
# Triggers: up, down, dhcp4-change on ethernet interfaces
|
||||
# Install to: /etc/NetworkManager/dispatcher.d/10-link-local-mgmt
|
||||
# Permissions: root:root 0755
|
||||
|
||||
INTERFACE="$1"
|
||||
ACTION="$2"
|
||||
# Only handle ethernet interfaces
|
||||
if [[ ! "$INTERFACE" =~ ^eth ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
reload_avahi() {
|
||||
systemctl reload avahi-daemon 2>/dev/null || systemctl restart avahi-daemon 2>/dev/null
|
||||
logger -t nm-link-local "[$INTERFACE] $ACTION — avahi reloaded"
|
||||
}
|
||||
|
||||
case "$ACTION" in
|
||||
up)
|
||||
# On 'up' the interface may still carry a stale DHCP address from the previous
|
||||
# session (NM hasn't cleaned it up yet). Reading ip-addr here is unreliable.
|
||||
# Always re-enable link-local as a clean slate; let dhcp4-change suppress it
|
||||
# later if a real DHCP lease is obtained.
|
||||
logger -t nm-link-local "[$INTERFACE] Up — ensuring link-local active (clean slate)"
|
||||
(sleep 2 && nmcli device modify "$INTERFACE" ipv4.link-local enabled 2>/dev/null \
|
||||
&& logger -t nm-link-local "[$INTERFACE] Link-local explicitly enabled on up") &
|
||||
reload_avahi
|
||||
;;
|
||||
|
||||
dhcp4-change)
|
||||
# dhcp4-change fires only when DHCP actually succeeds (new/renewed lease).
|
||||
# At this point the DHCP IP is reliably present — safe to read and suppress link-local.
|
||||
DHCP_IP=$(ip -4 addr show "$INTERFACE" 2>/dev/null \
|
||||
| grep -oP '(?<=inet\s)\d+(\.\d+){3}' \
|
||||
| grep -v '^127\.' \
|
||||
| grep -v '^169\.254\.' \
|
||||
| head -n1)
|
||||
|
||||
if [ -n "$DHCP_IP" ]; then
|
||||
logger -t nm-link-local "[$INTERFACE] DHCP $DHCP_IP confirmed — suppressing link-local (session only)"
|
||||
# Run in background after a delay — nmcli blocks on NM, which is waiting for
|
||||
# this dispatcher to return, causing a deadlock if called synchronously.
|
||||
(sleep 2 && nmcli device modify "$INTERFACE" ipv4.link-local disabled 2>/dev/null \
|
||||
&& logger -t nm-link-local "[$INTERFACE] Link-local suppressed for current session") &
|
||||
fi
|
||||
reload_avahi
|
||||
;;
|
||||
|
||||
down)
|
||||
# NOTE: a carrier-change does NOT fully reset session-level 'device modify' state.
|
||||
# The re-enable is therefore handled in the 'up' handler when no DHCP is detected.
|
||||
logger -t nm-link-local "[$INTERFACE] Down — link-local will be re-enabled on next up without DHCP"
|
||||
reload_avahi
|
||||
;;
|
||||
esac
|
||||
@@ -10,6 +10,8 @@ WorkingDirectory=/home/caster/bumble-auracast/src/auracast/server
|
||||
ExecStart=/home/caster/bumble-auracast/src/auracast/server/start_frontend_https.sh
|
||||
Restart=on-failure
|
||||
Environment=LOG_LEVEL=INFO
|
||||
AllowedCPUs=0
|
||||
CPUAffinity=0
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
||||
@@ -9,6 +9,8 @@ ExecStart=/home/caster/bumble-auracast/.venv/bin/python src/auracast/multicast_s
|
||||
Restart=on-failure
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
Environment=LOG_LEVEL=INFO
|
||||
AllowedCPUs=0
|
||||
CPUAffinity=0
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
[Unit]
|
||||
Description=Auracast Backend Server
|
||||
After=network.target
|
||||
After=network.target dep.service
|
||||
Wants=dep.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
@@ -10,8 +11,10 @@ Restart=on-failure
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
Environment=LOG_LEVEL=INFO
|
||||
CPUSchedulingPolicy=fifo
|
||||
CPUSchedulingPriority=99
|
||||
CPUSchedulingPriority=10
|
||||
LimitRTPRIO=99
|
||||
AllowedCPUs=0,1,2
|
||||
CPUAffinity=0,1,2
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=DEP (Dante Embedded Platform) Container
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
RemainAfterExit=yes
|
||||
WorkingDirectory=/home/caster/bumble-auracast/src/dep/dante_package
|
||||
ExecStart=/bin/bash dep.sh start
|
||||
ExecStop=/bin/bash dep.sh stop
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -9,6 +9,8 @@ ExecStartPre=/bin/sh -lc 'for i in $(seq 1 60); do ip route show default >/dev/n
|
||||
ExecStart=/usr/bin/pipewire-aes67 -c /home/caster/bumble-auracast/src/service/aes67/pipewire-aes67.conf
|
||||
Restart=always
|
||||
RestartSec=5s
|
||||
AllowedCPUs=0
|
||||
CPUAffinity=0
|
||||
# Avoid StartLimitHit on quick failures during boot; let RestartSec handle pacing
|
||||
StartLimitIntervalSec=0
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ After=network.target
|
||||
Type=simple
|
||||
ExecStart=/usr/sbin/ptp4l -i eth0 -f /home/caster/bumble-auracast/src/service/aes67/ptp_aes67_1.conf
|
||||
Restart=on-failure
|
||||
AllowedCPUs=0
|
||||
CPUAffinity=0
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
|
||||
|
||||
@@ -8,30 +8,43 @@ set -e
|
||||
# Enable link-local for all wired ethernet connections
|
||||
while IFS=: read -r name type; do
|
||||
if [[ "$type" == *"ethernet"* ]]; then
|
||||
echo "Enabling IPv4 link-local for connection: $name"
|
||||
echo "Configuring connection: $name"
|
||||
# link-local: always enabled so direct-connect (no DHCP) works immediately
|
||||
sudo nmcli connection modify "$name" ipv4.link-local enabled 2>/dev/null || echo "Failed to modify $name"
|
||||
# may-fail=yes: do NOT tear down the connection when DHCP times out.
|
||||
# Without this, NM declares ip-config-unavailable after the 45s DHCP timeout
|
||||
# and enters a reconnect loop that causes ~1.5 min outages every ~45 seconds.
|
||||
sudo nmcli connection modify "$name" ipv4.may-fail yes 2>/dev/null || echo "Failed to set may-fail on $name"
|
||||
# Infinite DHCP timeout: NM keeps retrying DHCP in the background but never
|
||||
# declares ip-config-unavailable. This prevents the 45s reconnect loop that
|
||||
# kills the link-local address in direct-connect (no DHCP server) scenarios.
|
||||
sudo nmcli connection modify "$name" ipv4.dhcp-timeout infinity 2>/dev/null || echo "Failed to set dhcp-timeout on $name"
|
||||
sudo nmcli connection up "$name" 2>/dev/null || echo "Failed to bring up $name"
|
||||
fi
|
||||
done < <(nmcli -t -f NAME,TYPE connection show)
|
||||
|
||||
# Configure Avahi to prefer DHCP address over static fallback for mDNS
|
||||
# Get the DHCP-assigned IP (first non-localhost, non-192.168.42.10 IP)
|
||||
DHCP_IP=$(ip -4 addr show eth0 2>/dev/null | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | grep -v '^127\.' | grep -v '^169\.254\.' | head -n1)
|
||||
HOSTNAME=$(hostname)
|
||||
|
||||
if [ -n "$DHCP_IP" ]; then
|
||||
echo "DHCP address detected: $DHCP_IP, configuring Avahi to prefer it for mDNS."
|
||||
# Add entry to /etc/avahi/hosts to explicitly map hostname to DHCP IP
|
||||
sudo mkdir -p /etc/avahi
|
||||
echo "$DHCP_IP $HOSTNAME $HOSTNAME.local" | sudo tee /etc/avahi/hosts > /dev/null
|
||||
# Restart avahi to apply the hosts file
|
||||
sudo systemctl restart avahi-daemon
|
||||
else
|
||||
echo "No DHCP address detected, mDNS will use link local"
|
||||
# Remove hosts file to let Avahi advertise all IPs
|
||||
sudo rm -f /etc/avahi/hosts
|
||||
sudo systemctl restart avahi-daemon
|
||||
fi
|
||||
# Remove stale avahi hosts pin — this file overrides per-interface advertisement
|
||||
# and causes mDNS to always resolve to eth0's IP regardless of which interface
|
||||
# the query arrived on, breaking eth1 mDNS entirely.
|
||||
sudo rm -f /etc/avahi/hosts
|
||||
sudo systemctl restart avahi-daemon
|
||||
|
||||
# Ensure Loopback is loaded with a fixed name and index
|
||||
# Needed for dante
|
||||
# TODO image when we create the next image this should be part of it
|
||||
echo "options snd-aloop index=6 id=Loopback pcm_substreams=6" | sudo tee /etc/modprobe.d/snd-aloop.conf
|
||||
echo snd-aloop | sudo tee /etc/modules-load.d/snd-aloop.conf
|
||||
|
||||
|
||||
|
||||
# Install NetworkManager dispatcher script for link-local / Avahi management
|
||||
sudo cp /home/caster/bumble-auracast/src/service/10-link-local-mgmt /etc/NetworkManager/dispatcher.d/10-link-local-mgmt
|
||||
sudo chown root:root /etc/NetworkManager/dispatcher.d/10-link-local-mgmt
|
||||
sudo chmod 755 /etc/NetworkManager/dispatcher.d/10-link-local-mgmt
|
||||
|
||||
# Copy system service file for DEP
|
||||
sudo cp /home/caster/bumble-auracast/src/service/dep.service /etc/systemd/system/dep.service
|
||||
|
||||
# Copy system service file for frontend
|
||||
sudo cp /home/caster/bumble-auracast/src/service/auracast-frontend.service /etc/systemd/system/auracast-frontend.service
|
||||
@@ -40,20 +53,25 @@ sudo cp /home/caster/bumble-auracast/src/service/auracast-frontend.service /etc/
|
||||
mkdir -p /home/caster/.config/systemd/user
|
||||
cp /home/caster/bumble-auracast/src/service/auracast-server.service /home/caster/.config/systemd/user/auracast-server.service
|
||||
|
||||
# Reload systemd for frontend
|
||||
# Reload systemd for frontend and dep
|
||||
sudo systemctl daemon-reload
|
||||
# Reload user systemd for server
|
||||
systemctl --user daemon-reload
|
||||
|
||||
# Enable DEP to start on boot (system)
|
||||
sudo systemctl enable dep.service
|
||||
# Enable frontend to start on boot (system)
|
||||
sudo systemctl enable auracast-frontend.service
|
||||
# Enable server to start on boot (user)
|
||||
systemctl --user enable auracast-server.service
|
||||
|
||||
# Restart both
|
||||
# Restart all
|
||||
sudo systemctl restart dep.service
|
||||
|
||||
sudo systemctl restart auracast-frontend.service
|
||||
systemctl --user restart auracast-server.service
|
||||
|
||||
#print status
|
||||
sudo systemctl status dep.service --no-pager
|
||||
sudo systemctl status auracast-frontend.service --no-pager
|
||||
systemctl --user status auracast-server.service --no-pager
|
||||
|
||||
Reference in New Issue
Block a user