From 28446c570d061e63d0975b362d3a14d359fb0df1 Mon Sep 17 00:00:00 2001 From: Ryan Malloy Date: Sun, 15 Nov 2026 09:36:58 -0700 Subject: [PATCH] Release an idle device so a forgotten connect can't hold the shared radio A client that calls bladerf_connect and never disconnects kept the USB claim until the server exited, blocking every other tool on the shared bladeRF. A watchdog thread now releases the device after MCBLADERF_IDLE_TIMEOUT seconds without a tool call (default 600, 0 disables). Middleware counts tool calls in flight, so a release never lands mid-call, and it also skips while a capture runs. The RX/TX settings are saved first; the next device call reconnects and restores them, sample rate included, since the radio resets that to 4 MHz on open. bladerf_status reports auto_released in between. Version 2026.11.15. --- README.md | 2 +- pyproject.toml | 2 +- src/mcbladerf/__init__.py | 2 +- src/mcbladerf/device.py | 130 ++++++++++++++++++++++++++++++++++++-- src/mcbladerf/server.py | 32 +++++++++- tests/test_idle.py | 120 +++++++++++++++++++++++++++++++++++ uv.lock | 2 +- 7 files changed, 281 insertions(+), 9 deletions(-) create mode 100644 tests/test_idle.py diff --git a/README.md b/README.md index ac3c1ba..d5300dc 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ Write captures to disk, not `/tmp`. On many Linux systems `/tmp` is a tmpfs held Gains you leave out keep whatever the device last had, including values set by another process. The radio is often shared, so set all three RX gains explicitly. -While connected, the server holds the USB device and nothing else can open it. The bladeRF-cli backed tools (probe, calibrate, FPGA load, firmware flash, hardware info) release it for the duration and restore the RX/TX settings afterwards. Call `bladerf_disconnect` when you are done so other tools can use the radio. +While connected, the server holds the USB device and nothing else can open it. The bladeRF-cli backed tools (probe, calibrate, FPGA load, firmware flash, hardware info) release it for the duration and restore the RX/TX settings afterwards. Call `bladerf_disconnect` when you are done so other tools can use the radio. If a client forgets, the server releases an idle connection by itself after `MCBLADERF_IDLE_TIMEOUT` seconds with no tool calls (default 600; `0` disables), never during a call or a capture. `bladerf_status` then reports `auto_released`, and the next device call reconnects and restores the RX/TX settings, sample rate included. ## Troubleshooting diff --git a/pyproject.toml b/pyproject.toml index 9591345..382241b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "mcbladerf" -version = "2026.10.25" +version = "2026.11.15" description = "MCP server for Nuand BladeRF SDR control via SoapySDR" authors = [{name = "Ryan Malloy", email = "ryan@supported.systems"}] readme = "README.md" diff --git a/src/mcbladerf/__init__.py b/src/mcbladerf/__init__.py index d49ac8a..9efd08c 100644 --- a/src/mcbladerf/__init__.py +++ b/src/mcbladerf/__init__.py @@ -1,3 +1,3 @@ """MCP server for Nuand BladeRF SDR control via SoapySDR.""" -__version__ = "2026.10.25" +__version__ = "2026.11.15" diff --git a/src/mcbladerf/device.py b/src/mcbladerf/device.py index d240078..3825c28 100644 --- a/src/mcbladerf/device.py +++ b/src/mcbladerf/device.py @@ -7,8 +7,12 @@ device connection and stream state across MCP tool calls. from __future__ import annotations import asyncio +import os +import sys +import threading +import time from collections.abc import Iterator -from contextlib import contextmanager +from contextlib import contextmanager, suppress from dataclasses import dataclass, field from typing import Any, Literal @@ -95,6 +99,20 @@ class BladeRFState: capture_info: dict[str, Any] = field( default_factory=lambda: {"active": False, "progress": None, "cancelled": False} ) + # Idle auto-release: tool calls in progress, time of the last one, and what + # to restore if the watchdog let go of the device + in_flight: int = 0 + last_activity: float = field(default_factory=time.monotonic) + auto_released_serial: str | None = None + auto_released_config: dict[str, RFConfig] = field(default_factory=dict) + auto_released_at: float | None = None + idle_lock: threading.RLock = field(default_factory=threading.RLock) + + +# Seconds without a tool call before the device is released for other tools. +# 0 disables. The radio is shared, and a client that connects and never +# disconnects would otherwise hold it until the server exits. +IDLE_TIMEOUT_S = float(os.environ.get("MCBLADERF_IDLE_TIMEOUT", "600")) # Global state singleton @@ -146,6 +164,7 @@ def connect(serial: str | None = None, device_index: int | None = None) -> Devic # Close existing connection if any if state.device is not None: disconnect() + _clear_auto_release(state) # Build device arguments string # Note: SoapySDR Python bindings expect a string, not a dict @@ -212,6 +231,7 @@ def disconnect() -> None: if state.device is not None: state.device = None state.serial = None + _clear_auto_release(state) def is_connected() -> bool: @@ -220,9 +240,111 @@ def is_connected() -> bool: def ensure_connected() -> None: - """Raise if no device is connected.""" - if not is_connected(): - raise RuntimeError("No BladeRF device connected. Use bladerf_connect first.") + """Raise if no device is connected. + + A device the idle watchdog released is reopened here, with its RX/TX + settings restored, so callers never see the release. + """ + state = get_state() + if state.device is not None: + return + with state.idle_lock: + if state.device is None and state.auto_released_serial: + _auto_reconnect(state) + return + raise RuntimeError("No BladeRF device connected. Use bladerf_connect first.") + + +def _clear_auto_release(state: BladeRFState) -> None: + state.auto_released_serial = None + state.auto_released_config = {} + state.auto_released_at = None + + +def tool_started() -> None: + """Mark a tool call in progress (called by the server middleware).""" + state = get_state() + with state.idle_lock: + state.in_flight += 1 + state.last_activity = time.monotonic() + + +def tool_finished() -> None: + state = get_state() + with state.idle_lock: + state.in_flight = max(0, state.in_flight - 1) + state.last_activity = time.monotonic() + + +def release_if_idle(timeout_s: float, now: float | None = None) -> bool: + """Release the device if nothing has used it for timeout_s seconds. + + Skipped while a tool call or a capture is running. Returns True if the + device was released. + """ + state = get_state() + now = time.monotonic() if now is None else now + with state.idle_lock: + if ( + state.device is None + or state.in_flight + or state.capture_info["active"] + or now - state.last_activity < timeout_s + ): + return False + serial = state.serial + config = {} + for direction in ("rx", "tx"): + with suppress(Exception): + config[direction] = get_rf_config(direction) + disconnect() + state.auto_released_serial = serial + state.auto_released_config = config + state.auto_released_at = now + print( + f"mcbladerf: released bladeRF {serial} after {now - state.last_activity:.0f} s idle; " + "the next device call reconnects", + file=sys.stderr, + ) + return True + + +def _auto_reconnect(state: BladeRFState) -> None: + serial = state.auto_released_serial + config = state.auto_released_config + released_at = state.auto_released_at + try: + connect(serial=serial) + except RuntimeError as e: + # connect() cleared the record; keep it so a later call can retry + state.auto_released_serial = serial + state.auto_released_config = config + state.auto_released_at = released_at + raise RuntimeError( + f"{e}. The device was released after being idle and could not be " + "reopened; another process is probably using it. Try again later." + ) from e + for direction, cfg in config.items(): + _restore_rf_config(direction, cfg) + + +def start_idle_watchdog(timeout_s: float = IDLE_TIMEOUT_S) -> threading.Thread | None: + """Start the background thread that releases an idle device. 0 disables it.""" + if timeout_s <= 0: + return None + interval = min(30.0, timeout_s / 4) + + def run() -> None: + while True: + time.sleep(interval) + try: + release_if_idle(timeout_s) + except Exception as e: + print(f"mcbladerf: idle watchdog error: {e}", file=sys.stderr) + + thread = threading.Thread(target=run, name="mcbladerf-idle", daemon=True) + thread.start() + return thread @contextmanager diff --git a/src/mcbladerf/server.py b/src/mcbladerf/server.py index 2213fdd..cda7bac 100644 --- a/src/mcbladerf/server.py +++ b/src/mcbladerf/server.py @@ -11,14 +11,28 @@ from collections.abc import Callable from typing import Annotated, Any, Literal from fastmcp import FastMCP +from fastmcp.server.middleware import Middleware from . import __version__, capture, cli_fallback, device + +class _ActivityMiddleware(Middleware): + """Count tool calls in progress so the idle watchdog never releases mid-call.""" + + async def on_call_tool(self, context, call_next): + device.tool_started() + try: + return await call_next(context) + finally: + device.tool_finished() + + # Create FastMCP server instance mcp = FastMCP( "mcbladerf", instructions="MCP server for Nuand BladeRF SDR control via SoapySDR", version=__version__, + middleware=[_ActivityMiddleware()], ) @@ -83,12 +97,25 @@ def bladerf_status() -> dict: """Get comprehensive BladeRF device status. Returns device identification (serial, board name), firmware and FPGA - versions, USB connection speed, and current RF configuration for RX/TX. + versions, and current RF configuration for RX/TX. + + The radio is shared with other tools, so an idle connection is released + after MCBLADERF_IDLE_TIMEOUT seconds (default 600). Status then reports + auto_released; the next device call reconnects and restores settings. Returns: Dict with device info and current configuration. """ if not device.is_connected(): + state = device.get_state() + if state.auto_released_serial: + return { + "connected": False, + "auto_released": True, + "serial": state.auto_released_serial, + "message": "Released after being idle so other tools can use the radio. " + "The next device call reconnects and restores the RX/TX settings.", + } return { "connected": False, "message": "No device connected. Use bladerf_connect first.", @@ -865,6 +892,9 @@ def main(): print(f"📡 mcbladerf v{__version__}", file=sys.stderr) print(" MCP server for Nuand BladeRF SDR control", file=sys.stderr) print(" Using SoapySDR for device access", file=sys.stderr) + if device.start_idle_watchdog(device.IDLE_TIMEOUT_S): + print(f" Idle release after {device.IDLE_TIMEOUT_S:g} s (MCBLADERF_IDLE_TIMEOUT)", + file=sys.stderr) mcp.run(show_banner=False) diff --git a/tests/test_idle.py b/tests/test_idle.py new file mode 100644 index 0000000..93ac5e2 --- /dev/null +++ b/tests/test_idle.py @@ -0,0 +1,120 @@ +import asyncio + +import pytest +from fastmcp import Client + +from mcbladerf import device +from mcbladerf.device import RFConfig + + +class _FakeDevice: + pass + + +@pytest.fixture +def state(monkeypatch): + s = device.BladeRFState() + monkeypatch.setattr(device, "_state", s) + cfg = RFConfig(915e6, 30e6, 28e6, {"lna": 3.0}) + monkeypatch.setattr(device, "get_rf_config", lambda d, channel=0: cfg) + restored = [] + monkeypatch.setattr(device, "_restore_rf_config", lambda d, c: restored.append((d, c))) + s.restored = restored + + def fake_connect(serial=None, device_index=None): + device._clear_auto_release(s) + s.device = _FakeDevice() + s.serial = serial + return None + + monkeypatch.setattr(device, "connect", fake_connect) + s.device = _FakeDevice() + s.serial = "abc123" + return s + + +def test_releases_only_after_timeout(state): + t = state.last_activity + assert not device.release_if_idle(600, now=t + 599) + assert device.is_connected() + + assert device.release_if_idle(600, now=t + 601) + assert not device.is_connected() + assert state.auto_released_serial == "abc123" + assert set(state.auto_released_config) == {"rx", "tx"} + + +def test_never_releases_mid_call(state): + device.tool_started() + assert not device.release_if_idle(0, now=state.last_activity + 1e6) + device.tool_finished() + assert state.in_flight == 0 + assert device.release_if_idle(0, now=state.last_activity + 1) + + +def test_never_releases_during_capture(state): + state.capture_info["active"] = True + assert not device.release_if_idle(0, now=state.last_activity + 1e6) + assert device.is_connected() + + +def test_next_device_call_reconnects_and_restores(state): + device.release_if_idle(0, now=state.last_activity + 1) + + device.ensure_connected() + + assert device.is_connected() + assert state.serial == "abc123" + assert [d for d, _ in state.restored] == ["rx", "tx"] + assert state.auto_released_serial is None + + +def test_failed_reconnect_explains_and_can_retry(state, monkeypatch): + device.release_if_idle(0, now=state.last_activity + 1) + + def busy(serial=None, device_index=None): + device._clear_auto_release(state) + raise RuntimeError("Failed to connect to BladeRF: No device(s) available") + + monkeypatch.setattr(device, "connect", busy) + with pytest.raises(RuntimeError, match="another process is probably using it"): + device.ensure_connected() + assert state.auto_released_serial == "abc123" + + +def test_explicit_disconnect_forgets_auto_release(state): + device.release_if_idle(0, now=state.last_activity + 1) + device.disconnect() + with pytest.raises(RuntimeError, match="Use bladerf_connect first"): + device.ensure_connected() + + +def test_middleware_tracks_tool_calls(monkeypatch): + from mcbladerf.server import mcp + + s = device.BladeRFState() + monkeypatch.setattr(device, "_state", s) + before = s.last_activity + + async def go(): + async with Client(mcp) as c: + await c.call_tool("bladerf_stream_status", {}) + + asyncio.run(go()) + assert s.in_flight == 0 + assert s.last_activity > before + + +def test_status_reports_auto_release(state): + from mcbladerf import server + + device.release_if_idle(0, now=state.last_activity + 1) + st = asyncio.run(_call(server.mcp, "bladerf_status")) + assert st["auto_released"] is True + assert st["serial"] == "abc123" + + +async def _call(mcp, name): + async with Client(mcp) as c: + r = await c.call_tool(name, {}) + return r.structured_content.get("result", r.structured_content) diff --git a/uv.lock b/uv.lock index 3176372..644071e 100644 --- a/uv.lock +++ b/uv.lock @@ -682,7 +682,7 @@ wheels = [ [[package]] name = "mcbladerf" -version = "2026.10.25" +version = "2026.11.15" source = { editable = "." } dependencies = [ { name = "fastmcp" },