Pin each SDR service to a dongle by serial; OP25 always opens its SDR by serial
Fixes node-26#11. OP25's generated config said "rtl" (= whichever dongle
enumerates first), so on 2-SDR nodes a decoder could take OP25's dongle
and stop recording. Now:
- sdr_pins: {op25|adsb|ais: serial}, absent = automatic. Every OP25
config generation (op25_client.generate_config) rewrites the device to
rtl=<serial>: the pin, else the first dongle's serial, which is what
"rtl" always opened. Left as "rtl" only for unknown/shared serials.
- secondary-sdr: /secondary/devices lists dongles + serials via librtlsdr
(works while claimed). apply(priority, pins, reserved) never touches
OP25's dongle, gives a pinned service only its own dongle, lets a
higher-priority service take a spare from a lower one, and still runs a
pinned lower-priority service when the top pick has no dongle.
- sdr_settings.py replaces secondary_priority.py: one apply path for the
local dashboard, the new set_sdr_config C2 command (set_secondary_priority
kept as an alias) and config pushes. OP25 restarts only when its own
dongle changes. Checkin reports sdr_devices, sdr_pins, op25_sdr_serial.
- Local dashboard: 'SDRs' card with an OP25 SDR dropdown and a per-service
dongle dropdown, duplicate-serial and double-pin warnings.
Verified: edge-node pytest 194 passed; secondary-sdr tests 7 passed;
flake8 clean; page JS passes node --check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
3ecc7eff1a
commit
9b50ba8114
@@ -1,3 +1,5 @@
|
||||
import ctypes
|
||||
import ctypes.util
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
@@ -141,8 +143,9 @@ def running() -> List[str]:
|
||||
return [m for m in MODES if is_running(m)]
|
||||
|
||||
|
||||
def _start_one(mode: str) -> bool:
|
||||
"""Start one decoder on the first free SDR. False when none is free."""
|
||||
def _start_one(mode: str, candidates: Optional[List[int]] = None) -> bool:
|
||||
"""Start one decoder on the first free SDR among `candidates` (default:
|
||||
every index). False when none is free."""
|
||||
if mode not in _COMMANDS:
|
||||
raise ValueError(f"Unknown secondary SDR mode: {mode!r}")
|
||||
if is_running(mode):
|
||||
@@ -152,7 +155,7 @@ def _start_one(mode: str) -> bool:
|
||||
_ais_vessels.clear()
|
||||
|
||||
needs_stdout = mode == "ais"
|
||||
for index in range(MAX_SDR_INDEX):
|
||||
for index in candidates if candidates is not None else range(MAX_SDR_INDEX):
|
||||
if index in {_indices[m] for m in running() if m in _indices}:
|
||||
continue
|
||||
try:
|
||||
@@ -211,47 +214,95 @@ def stop(mode: Optional[str] = None) -> None:
|
||||
_stop_one(m)
|
||||
|
||||
|
||||
def apply(priority: List[str]) -> List[str]:
|
||||
def _candidates(mode: str, pins: Dict[str, str], reserved: List[str], devs: List[Dict[str, Any]]) -> List[int]:
|
||||
"""SDR indices `mode` may use. A pinned mode gets exactly its dongle; an
|
||||
unpinned one gets any dongle that isn't op25's (reserved) or pinned to
|
||||
another service. Without enumeration, fall back to probing every index."""
|
||||
if not devs:
|
||||
return [] if pins.get(mode) else list(range(MAX_SDR_INDEX))
|
||||
if pins.get(mode):
|
||||
idx = _index_of(pins[mode], devs)
|
||||
return [] if idx is None else [idx]
|
||||
taken = set(reserved) | {s for m, s in pins.items() if m != mode and s}
|
||||
return [d["index"] for d in devs if d["serial"] not in taken]
|
||||
|
||||
|
||||
def apply(priority: List[str], pins: Optional[Dict[str, str]] = None,
|
||||
reserved: Optional[List[str]] = None) -> List[str]:
|
||||
"""Run decoders in priority order until SDRs run out; stop everything else.
|
||||
|
||||
Unchanged when the running set is already the right prefix of the list, so
|
||||
re-applying the same priority (every restart/config push) is a no-op
|
||||
rather than a decoder restart.
|
||||
`pins` maps a mode to the serial of the dongle carrying its antenna;
|
||||
`reserved` lists serials no decoder may touch (op25's). Pins only bind
|
||||
enabled modes — a disabled service's dongle is free for the others.
|
||||
Unchanged when the right decoders already run on allowed dongles, so
|
||||
re-applying the same settings is a no-op rather than a restart.
|
||||
"""
|
||||
for m in priority:
|
||||
if m not in _COMMANDS:
|
||||
raise ValueError(f"Unknown secondary SDR mode: {m!r}")
|
||||
pins = {m: s for m, s in (pins or {}).items() if m in priority and s}
|
||||
reserved = [s for s in (reserved or []) if s]
|
||||
devs = devices()
|
||||
with _lock:
|
||||
live = set(running())
|
||||
if live and live == set(priority[:len(live)]):
|
||||
# Already running the head of the list; only try to extend it.
|
||||
for m in priority[len(live):]:
|
||||
if not _start_one(m):
|
||||
break
|
||||
return running()
|
||||
for m in list(_procs):
|
||||
_stop_one(m)
|
||||
for m in priority:
|
||||
if not _start_one(m):
|
||||
break
|
||||
for m in running():
|
||||
if m not in priority or _indices.get(m) not in _candidates(m, pins, reserved, devs):
|
||||
_stop_one(m)
|
||||
for i, m in enumerate(priority):
|
||||
if m in running():
|
||||
continue
|
||||
cands = _candidates(m, pins, reserved, devs)
|
||||
if _start_one(m, cands):
|
||||
continue
|
||||
# Out of free dongles: take one from the lowest-priority decoder
|
||||
# holding a dongle this mode may use, which then gets its own turn.
|
||||
lower = [x for x in priority[i + 1:] if x in running() and _indices.get(x) in cands]
|
||||
if lower:
|
||||
_stop_one(lower[-1])
|
||||
_start_one(m, cands)
|
||||
return running()
|
||||
|
||||
|
||||
def sdr_count() -> Optional[int]:
|
||||
"""RTL-SDR dongles on USB, same heuristic as install.sh. This container has
|
||||
usbutils; op25's :stable image doesn't, so its /op25/devices can't answer."""
|
||||
def devices() -> List[Dict[str, Any]]:
|
||||
"""Every RTL-SDR on the node with its USB serial — readable even while a
|
||||
dongle is claimed (op25's included), since it doesn't open the device.
|
||||
Cheap dongles often ship with the same serial (00000001); those are
|
||||
flagged, because pinning a service to a shared serial is ambiguous."""
|
||||
try:
|
||||
out = subprocess.run(["lsusb"], capture_output=True, text=True, timeout=5).stdout
|
||||
except Exception:
|
||||
return None
|
||||
return sum(1 for line in out.splitlines() if "0bda:2838" in line or "0bda:2832" in line)
|
||||
lib = ctypes.CDLL(ctypes.util.find_library("rtlsdr") or "librtlsdr.so.0")
|
||||
lib.rtlsdr_get_device_name.restype = ctypes.c_char_p
|
||||
out = []
|
||||
for i in range(lib.rtlsdr_get_device_count()):
|
||||
manufact, product, serial = (ctypes.create_string_buffer(256) for _ in range(3))
|
||||
lib.rtlsdr_get_device_usb_strings(i, manufact, product, serial)
|
||||
out.append({
|
||||
"index": i,
|
||||
"serial": serial.value.decode(errors="replace") or None,
|
||||
"name": (lib.rtlsdr_get_device_name(i) or b"").decode(errors="replace"),
|
||||
})
|
||||
except Exception as e:
|
||||
LOGGER.warning(f"SDR enumeration failed: {e}")
|
||||
return []
|
||||
serials = [d["serial"] for d in out]
|
||||
for d in out:
|
||||
d["duplicate_serial"] = d["serial"] is not None and serials.count(d["serial"]) > 1
|
||||
return out
|
||||
|
||||
|
||||
def _index_of(serial: str, devs: List[Dict[str, Any]]) -> Optional[int]:
|
||||
"""Index of a uniquely-identified serial; None if absent or ambiguous."""
|
||||
matches = [d["index"] for d in devs if d["serial"] == serial]
|
||||
return matches[0] if len(matches) == 1 else None
|
||||
|
||||
|
||||
def status() -> Dict[str, Any]:
|
||||
live = running()
|
||||
devs = devices()
|
||||
by_index = {d["index"]: d["serial"] for d in devs}
|
||||
return {
|
||||
"running": [{"mode": m, "sdr_index": _indices.get(m)} for m in live],
|
||||
"sdr_count": sdr_count(),
|
||||
"running": [
|
||||
{"mode": m, "sdr_index": _indices.get(m), "serial": by_index.get(_indices.get(m))} for m in running()
|
||||
],
|
||||
"sdr_count": len(devs) if devs else None,
|
||||
"devices": devs,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from typing import List, Optional
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from pydantic import BaseModel
|
||||
@@ -19,6 +19,8 @@ class StopBody(BaseModel):
|
||||
|
||||
class ApplyBody(BaseModel):
|
||||
priority: List[str] # ordered, e.g. ["adsb", "ais"]
|
||||
pins: Dict[str, str] = {} # mode -> serial of the dongle with its antenna
|
||||
reserved: List[str] = [] # serials no decoder may touch (op25's)
|
||||
|
||||
|
||||
def create_secondary_router():
|
||||
@@ -27,7 +29,7 @@ def create_secondary_router():
|
||||
@router.post("/apply")
|
||||
async def apply(body: ApplyBody):
|
||||
try:
|
||||
live = decoder_control.apply(body.priority)
|
||||
live = decoder_control.apply(body.priority, body.pins, body.reserved)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
return {"running": live}
|
||||
@@ -51,6 +53,10 @@ def create_secondary_router():
|
||||
async def get_status():
|
||||
return decoder_control.status()
|
||||
|
||||
@router.get("/devices")
|
||||
async def get_devices():
|
||||
return {"devices": decoder_control.devices()}
|
||||
|
||||
@router.get("/data")
|
||||
async def get_data():
|
||||
return decoder_control.data()
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""
|
||||
node-26#11 — which dongle each secondary decoder may use.
|
||||
|
||||
Run from secondary-sdr-container/: PYTHONPATH=app python -m pytest -q tests
|
||||
"""
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from internal import decoder_control as dc
|
||||
|
||||
# radio-box's real pair: op25's dongle and the one with the 1090 antenna.
|
||||
DEVS = [
|
||||
{"index": 0, "serial": "69420", "name": "RTL", "duplicate_serial": False},
|
||||
{"index": 1, "serial": "00000001", "name": "RTL", "duplicate_serial": False},
|
||||
]
|
||||
|
||||
|
||||
def test_unpinned_mode_never_gets_op25s_dongle():
|
||||
assert dc._candidates("adsb", {}, ["00000001"], DEVS) == [0]
|
||||
|
||||
|
||||
def test_pinned_mode_gets_exactly_its_dongle():
|
||||
assert dc._candidates("ais", {"ais": "69420"}, ["00000001"], DEVS) == [0]
|
||||
|
||||
|
||||
def test_unpinned_mode_skips_a_dongle_pinned_to_another_service():
|
||||
assert dc._candidates("ais", {"adsb": "69420"}, ["00000001"], DEVS) == []
|
||||
|
||||
|
||||
def test_missing_or_ambiguous_pin_gets_nothing():
|
||||
assert dc._candidates("adsb", {"adsb": "nope"}, [], DEVS) == []
|
||||
dup = [dict(d, serial="00000001") for d in DEVS]
|
||||
assert dc._candidates("adsb", {"adsb": "00000001"}, [], dup) == []
|
||||
|
||||
|
||||
class FakeDecoders:
|
||||
"""Stands in for real processes: one decoder per free index."""
|
||||
|
||||
def __init__(self):
|
||||
self.live = {}
|
||||
|
||||
def start(self, mode, candidates=None):
|
||||
free = [i for i in candidates if i not in self.live.values()]
|
||||
if not free:
|
||||
return False
|
||||
self.live[mode] = free[0]
|
||||
return True
|
||||
|
||||
def stop(self, mode):
|
||||
self.live.pop(mode, None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake():
|
||||
f = FakeDecoders()
|
||||
with patch.object(dc, "devices", return_value=DEVS), \
|
||||
patch.object(dc, "_start_one", side_effect=f.start), \
|
||||
patch.object(dc, "_stop_one", side_effect=f.stop), \
|
||||
patch.object(dc, "running", side_effect=lambda: [m for m in dc.MODES if m in f.live]), \
|
||||
patch.dict(dc._indices, clear=True):
|
||||
dc._indices.update(f.live)
|
||||
yield f
|
||||
|
||||
|
||||
def _apply(fake, priority, pins=None):
|
||||
dc.apply(priority, pins, ["00000001"])
|
||||
dc._indices.clear()
|
||||
dc._indices.update(fake.live)
|
||||
return fake.live
|
||||
|
||||
|
||||
def test_one_spare_goes_to_the_top_pick(fake):
|
||||
assert _apply(fake, ["ais", "adsb"]) == {"ais": 0}
|
||||
|
||||
|
||||
def test_reordering_hands_the_spare_to_the_new_top_pick(fake):
|
||||
_apply(fake, ["adsb", "ais"])
|
||||
assert _apply(fake, ["ais", "adsb"]) == {"ais": 0}
|
||||
|
||||
|
||||
def test_pinned_lower_priority_still_runs_when_top_pick_has_no_dongle(fake):
|
||||
# AIS ranked first but its only candidate is ADS-B's pinned antenna dongle.
|
||||
assert _apply(fake, ["ais", "adsb"], {"adsb": "69420"}) == {"adsb": 0}
|
||||
Reference in New Issue
Block a user