From 1c557458847059b1b5cf72e34891b06360471d89 Mon Sep 17 00:00:00 2001 From: Roland Date: Sat, 28 Mar 2026 10:09:58 -0600 Subject: [PATCH] Adding bluetooth radio toggle to Controller. Writing controller.yaml to media drive on startup, if it doesn't exist. --- app/src/api/controller.js | 12 ++ app/src/components/Common.js | 16 +- app/src/components/admin/ControllerPage.js | 3 +- .../components/admin/ControllerPage.test.js | 2 + app/src/hooks/customHooks.js | 39 ++++ controller/api/admin.py | 31 ++++ controller/api/schemas.py | 19 ++ controller/api/status.py | 8 +- controller/lib/admin.py | 161 +++++++++++++++++ controller/main.py | 19 +- controller/templates/index.html | 102 ++++++++++- controller/test/test_admin.py | 169 ++++++++++++++++++ controller/test/test_admin_api.py | 50 ++++++ 13 files changed, 624 insertions(+), 7 deletions(-) diff --git a/app/src/api/controller.js b/app/src/api/controller.js index a93399f0..101db4b5 100644 --- a/app/src/api/controller.js +++ b/app/src/api/controller.js @@ -95,6 +95,18 @@ export async function disableThrottle() { return controllerFetch('/throttle/disable', {method: 'POST'}); } +export async function getBluetoothStatus() { + return controllerFetch('/bluetooth/status'); +} + +export async function enableBluetooth() { + return controllerFetch('/bluetooth/enable', {method: 'POST'}); +} + +export async function disableBluetooth() { + return controllerFetch('/bluetooth/disable', {method: 'POST'}); +} + export async function shutdownSystem() { return controllerFetch('/shutdown', {method: 'POST'}); } diff --git a/app/src/components/Common.js b/app/src/components/Common.js index 3b369582..34e27d3f 100644 --- a/app/src/components/Common.js +++ b/app/src/components/Common.js @@ -21,7 +21,7 @@ import { } from 'semantic-ui-react'; import {Link, NavLink, useNavigate} from "react-router"; import Message from "semantic-ui-react/dist/commonjs/collections/Message"; -import {useHotspot, useSearchDirectories, useSearchOrder, useThrottle, useWROLMode} from "../hooks/customHooks"; +import {useBluetooth, useHotspot, useSearchDirectories, useSearchOrder, useThrottle, useWROLMode} from "../hooks/customHooks"; import {Media, SettingsContext, StatusContext, ThemeContext} from "../contexts/contexts"; import { Accordion, @@ -981,6 +981,20 @@ export function ThrottleToggle() { ; } +export function BluetoothToggle() { + let {on, setBluetooth} = useBluetooth(); + const disabled = on === null; + return
+ setBluetooth(checked)} + /> + {disabled && } +
; +} + export function Toggle({label, checked, disabled, onChange, icon, popupContent = null, info = null}) { // Custom toggle because Semantic UI does not handle inverted labels correctly. const {t, inverted} = useContext(ThemeContext); diff --git a/app/src/components/admin/ControllerPage.js b/app/src/components/admin/ControllerPage.js index dbc818ee..671e9351 100644 --- a/app/src/components/admin/ControllerPage.js +++ b/app/src/components/admin/ControllerPage.js @@ -1,7 +1,7 @@ import React from 'react'; import {Checkbox, Container, Dropdown, Form, Icon, Input} from "semantic-ui-react"; import {Button, Confirm, Header, Loader, Modal, Segment, Table} from "../Theme"; -import {APIButton, HandPointMessage, HotspotToggle, InfoMessage, ThrottleToggle, Toggle,} from "../Common"; +import {APIButton, BluetoothToggle, HandPointMessage, HotspotToggle, InfoMessage, ThrottleToggle, Toggle,} from "../Common"; import {useDockerized} from "../../hooks/customHooks"; import {Media} from "../../contexts/contexts"; import { @@ -1064,6 +1064,7 @@ function AdminControlsSection() { + {!dockerized && ( diff --git a/app/src/components/admin/ControllerPage.test.js b/app/src/components/admin/ControllerPage.test.js index 372703c1..920f2e12 100644 --- a/app/src/components/admin/ControllerPage.test.js +++ b/app/src/components/admin/ControllerPage.test.js @@ -40,6 +40,7 @@ jest.mock('../../api/controller', () => ({ // Mock useDockerized hook jest.mock('../../hooks/customHooks', () => ({ useDockerized: jest.fn().mockReturnValue(false), + useBluetooth: jest.fn().mockReturnValue({on: false, setBluetooth: jest.fn()}), useHotspot: jest.fn().mockReturnValue({on: true, setHotspot: jest.fn()}), useThrottle: jest.fn().mockReturnValue({on: false, setThrottle: jest.fn()}), })); @@ -49,6 +50,7 @@ jest.mock('../Common', () => { const actual = jest.requireActual('../Common'); return { ...actual, + BluetoothToggle: () =>
BluetoothToggle
, HotspotToggle: () =>
HotspotToggle
, ThrottleToggle: () =>
ThrottleToggle
, Toggle: ({label, checked, onChange}) => ( diff --git a/app/src/hooks/customHooks.js b/app/src/hooks/customHooks.js index 8bc63e91..ace1aa5e 100644 --- a/app/src/hooks/customHooks.js +++ b/app/src/hooks/customHooks.js @@ -38,6 +38,8 @@ import { updateDomain, } from "../api"; import { + enableBluetooth, + disableBluetooth, enableHotspot, disableHotspot, enableThrottle, @@ -1120,6 +1122,43 @@ export const useThrottle = () => { return {on, setOn, setThrottle: localSetThrottle}; } +export const useBluetooth = () => { + const [on, setOn] = useState(null); + const {status} = useContext(StatusContext); + + useEffect(() => { + const bluetoothStatus = status?.bluetooth_status; + if (bluetoothStatus === 'on') { + setOn(true); + } else if (bluetoothStatus === 'off') { + setOn(false); + } else { + setOn(null); + } + }, [status?.bluetooth_status]); + + const localSetBluetooth = async (enable) => { + setOn(null); + try { + if (enable) { + await enableBluetooth(); + } else { + await disableBluetooth(); + } + } catch (e) { + console.error('Bluetooth error:', e); + toast({ + type: 'error', + title: 'Bluetooth Error', + description: e.message || 'Could not modify Bluetooth. See server logs.', + time: 5000, + }); + } + } + + return {on, setBluetooth: localSetBluetooth}; +} + export const useSearchDirectories = (value) => { const [directoryName, setDirectoryName] = useState(value ?? ''); const [directories, setDirectories] = useState(null); diff --git a/controller/api/admin.py b/controller/api/admin.py index f4ad1594..c30b419c 100644 --- a/controller/api/admin.py +++ b/controller/api/admin.py @@ -5,6 +5,8 @@ Admin API endpoints for WROLPi Controller. from fastapi import APIRouter, HTTPException from controller.api.schemas import ( + BluetoothActionResponse, + BluetoothStatusResponse, HotspotActionResponse, HotspotStatusResponse, RestartServicesResponse, @@ -17,10 +19,13 @@ from controller.api.schemas import ( TimezoneStatusResponse, ) from controller.lib.admin import ( + disable_bluetooth, disable_hotspot, disable_throttle, + enable_bluetooth, enable_hotspot, enable_throttle, + get_bluetooth_status_dict, get_hotspot_status_dict, get_throttle_status_dict, get_timezone_status_dict, @@ -60,6 +65,32 @@ async def hotspot_disable() -> HotspotActionResponse: return HotspotActionResponse(**result) +# --- Bluetooth --- + +@router.get("/api/bluetooth/status", response_model=BluetoothStatusResponse) +async def bluetooth_status() -> BluetoothStatusResponse: + """Get Bluetooth radio status.""" + return BluetoothStatusResponse(**await get_bluetooth_status_dict()) + + +@router.post("/api/bluetooth/enable", response_model=BluetoothActionResponse) +async def bluetooth_enable() -> BluetoothActionResponse: + """Enable Bluetooth radio.""" + result = await enable_bluetooth() + if not result.get("success"): + raise HTTPException(status_code=500, detail=result.get("error", "Failed")) + return BluetoothActionResponse(**result) + + +@router.post("/api/bluetooth/disable", response_model=BluetoothActionResponse) +async def bluetooth_disable() -> BluetoothActionResponse: + """Disable Bluetooth radio.""" + result = await disable_bluetooth() + if not result.get("success"): + raise HTTPException(status_code=500, detail=result.get("error", "Failed")) + return BluetoothActionResponse(**result) + + # --- Throttle --- @router.get("/api/throttle/status", response_model=ThrottleStatusResponse) diff --git a/controller/api/schemas.py b/controller/api/schemas.py index 64e11844..6b3eede2 100644 --- a/controller/api/schemas.py +++ b/controller/api/schemas.py @@ -166,6 +166,25 @@ class HotspotActionResponse(BaseModel): error: Optional[str] = Field(default=None, description="Error message if failed") +# ============================================================================ +# Admin - Bluetooth +# ============================================================================ + +class BluetoothStatusResponse(BaseModel): + """Response model for /api/bluetooth/status endpoint.""" + + enabled: bool = Field(description="Whether Bluetooth radio is currently on") + available: bool = Field(description="Whether Bluetooth functionality is available") + reason: Optional[str] = Field(default=None, description="Reason if unavailable") + + +class BluetoothActionResponse(BaseModel): + """Response model for Bluetooth enable/disable actions.""" + + success: bool = Field(description="Whether the action succeeded") + error: Optional[str] = Field(default=None, description="Error message if failed") + + # ============================================================================ # Admin - Throttle # ============================================================================ diff --git a/controller/api/status.py b/controller/api/status.py index 8a7fdde1..fb53a2d2 100644 --- a/controller/api/status.py +++ b/controller/api/status.py @@ -12,7 +12,7 @@ wrol_mode) remain in the main WROLPi API at /api/status. from fastapi import APIRouter, Request from fastapi.responses import JSONResponse -from controller.lib.admin import get_hotspot_status, get_throttle_status, HotspotStatus +from controller.lib.admin import get_bluetooth_status, get_hotspot_status, get_throttle_status, BluetoothStatus, HotspotStatus from controller.lib.config import is_docker_mode, is_rpi, is_rpi4, is_rpi5 from controller.lib.status import ( get_cpu_status, @@ -31,7 +31,7 @@ def get_cached_status(request: Request) -> dict: return getattr(request.app.state, "cached_status", {}) -def get_system_info() -> dict: +async def get_system_info() -> dict: """ Get static system info that doesn't need frequent updates. These are collected on each request as they rarely change. @@ -39,6 +39,7 @@ def get_system_info() -> dict: from controller.lib.config import get_config hotspot_status = get_hotspot_status() + bluetooth_status = await get_bluetooth_status() throttle_status = get_throttle_status() # Get hotspot SSID from config if hotspot is connected @@ -51,6 +52,7 @@ def get_system_info() -> dict: "is_rpi": is_rpi(), "is_rpi4": is_rpi4(), "is_rpi5": is_rpi5(), + "bluetooth_status": bluetooth_status.name, "hotspot_status": hotspot_status.name, "hotspot_ssid": hotspot_ssid, "throttle_status": throttle_status.name, @@ -78,7 +80,7 @@ async def get_all_stats(request: Request): cached = await collect_all_status() # Add system info to response - response = {**cached, **get_system_info()} + response = {**cached, **await get_system_info()} return JSONResponse(content=response) diff --git a/controller/lib/admin.py b/controller/lib/admin.py index ffbafe17..b9c09ae4 100644 --- a/controller/lib/admin.py +++ b/controller/lib/admin.py @@ -6,6 +6,7 @@ Migrated from wrolpi/admin.py - provides system control functions. import asyncio import enum +import json import logging import subprocess from pathlib import Path @@ -29,6 +30,14 @@ class HotspotStatus(enum.Enum): in_use = enum.auto() # Wi-Fi device is in use for a network connection. +class BluetoothStatus(enum.Enum): + """Bluetooth radio status.""" + on = enum.auto() # Bluetooth radio is on (rfkill unblocked). + off = enum.auto() # Bluetooth radio is off (rfkill blocked). + unavailable = enum.auto() # No Bluetooth hardware or rfkill not installed. + unknown = enum.auto() # Docker mode or cannot determine. + + class GovernorStatus(enum.Enum): """CPU governor status enum matching wrolpi/admin.py""" ondemand = enum.auto() @@ -233,6 +242,158 @@ def disable_hotspot() -> dict: return {"success": False, "error": str(e)} +# --- Bluetooth --- + + +async def get_bluetooth_status() -> BluetoothStatus: + """ + Get current Bluetooth radio status using rfkill. + + Parses JSON output from `rfkill -J` to determine if Bluetooth is blocked. + + Returns: + BluetoothStatus enum value + """ + if is_docker_mode(): + return BluetoothStatus.unknown + + try: + proc = await asyncio.create_subprocess_exec( + "rfkill", "-J", + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=5) + + if proc.returncode != 0: + return BluetoothStatus.unknown + + data = json.loads(stdout.decode()) + bt_devices = [d for d in data.get("rfkilldevices", []) if d.get("type") == "bluetooth"] + + if not bt_devices: + return BluetoothStatus.unavailable + + # If any Bluetooth device is soft or hard blocked, report as off. + for device in bt_devices: + if device.get("soft") == "blocked" or device.get("hard") == "blocked": + return BluetoothStatus.off + + return BluetoothStatus.on + + except (json.JSONDecodeError, KeyError): + return BluetoothStatus.unknown + except asyncio.TimeoutError: + return BluetoothStatus.unknown + except FileNotFoundError: + return BluetoothStatus.unavailable + except OSError: + return BluetoothStatus.unknown + + +async def get_bluetooth_status_dict() -> dict: + """ + Get Bluetooth status as a dict for API responses. + + Returns dict matching BluetoothStatusResponse schema: + enabled: bool - Whether Bluetooth radio is currently on + available: bool - Whether Bluetooth functionality is available + reason: Optional[str] - Reason if unavailable + """ + status = await get_bluetooth_status() + + enabled = status == BluetoothStatus.on + available = status not in (BluetoothStatus.unknown, BluetoothStatus.unavailable) + + reason = None + if status == BluetoothStatus.unknown: + reason = "Bluetooth not supported or rfkill unavailable" + elif status == BluetoothStatus.unavailable: + reason = "No Bluetooth hardware detected" + + return { + "enabled": enabled, + "available": available, + "reason": reason, + } + + +async def enable_bluetooth() -> dict: + """ + Enable Bluetooth radio using rfkill. + + Returns: + dict with success status + """ + if is_docker_mode(): + return {"success": False, "error": "Not available in Docker mode"} + + logger.info("Enabling Bluetooth radio") + try: + proc = await asyncio.create_subprocess_exec( + "rfkill", "unblock", "bluetooth", + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=10) + + if proc.returncode == 0: + logger.info("Bluetooth radio enabled successfully") + return {"success": True} + else: + error_msg = stderr.decode().strip() + logger.warning("Failed to enable Bluetooth: %s", error_msg) + return {"success": False, "error": error_msg or "Unknown error"} + + except asyncio.TimeoutError: + logger.warning("Timeout enabling Bluetooth") + return {"success": False, "error": "Timeout enabling Bluetooth"} + except FileNotFoundError: + logger.warning("rfkill not found, cannot enable Bluetooth") + return {"success": False, "error": "rfkill not found"} + except OSError as e: + logger.warning("Failed to enable Bluetooth: %s", e) + return {"success": False, "error": str(e)} + + +async def disable_bluetooth() -> dict: + """ + Disable Bluetooth radio using rfkill. + + Returns: + dict with success status + """ + if is_docker_mode(): + return {"success": False, "error": "Not available in Docker mode"} + + logger.info("Disabling Bluetooth radio") + try: + proc = await asyncio.create_subprocess_exec( + "rfkill", "block", "bluetooth", + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=10) + + if proc.returncode == 0: + logger.info("Bluetooth radio disabled successfully") + return {"success": True} + else: + error_msg = stderr.decode().strip() + logger.warning("Failed to disable Bluetooth: %s", error_msg) + return {"success": False, "error": error_msg or "Unknown error"} + + except asyncio.TimeoutError: + logger.warning("Timeout disabling Bluetooth") + return {"success": False, "error": "Timeout disabling Bluetooth"} + except FileNotFoundError: + logger.warning("rfkill not found, cannot disable Bluetooth") + return {"success": False, "error": "rfkill not found"} + except OSError as e: + logger.warning("Failed to disable Bluetooth: %s", e) + return {"success": False, "error": str(e)} + + GOVERNOR_MAP = { 'ondemand': GovernorStatus.ondemand, 'powersave': GovernorStatus.powersave, diff --git a/controller/main.py b/controller/main.py index 87454f0d..a5d6e37e 100644 --- a/controller/main.py +++ b/controller/main.py @@ -78,7 +78,24 @@ async def lifespan(app: FastAPI): from controller.lib.admin import apply_timezone_from_config apply_timezone_from_config() else: - logger.info("Primary drive not mounted - using default configuration") + # Drive may be mounted but controller.yaml may not exist yet (e.g., the system + # was set up before the Controller was introduced). Create the marker file. + from controller.lib.config import get_media_directory, save_config + media_dir = get_media_directory() + if media_dir.is_mount(): + logger.info("Primary drive is mounted at %s but controller.yaml is missing, creating it", media_dir) + config_dir = media_dir / "config" + config_dir.mkdir(parents=True, exist_ok=True) + try: + save_config() + reload_config_from_drive() + except RuntimeError as e: + logger.warning("Failed to create controller.yaml: %s", e) + + from controller.lib.admin import apply_timezone_from_config + apply_timezone_from_config() + else: + logger.info("Primary drive not mounted - using default configuration") # Initialize cached status app.state.cached_status = {} diff --git a/controller/templates/index.html b/controller/templates/index.html index d6cde44e..1ebc3d0c 100644 --- a/controller/templates/index.html +++ b/controller/templates/index.html @@ -773,7 +773,7 @@ {% if docker_mode %}
- Running in Docker mode. Disk mounting, hotspot, and shutdown are not available. + Running in Docker mode. Disk mounting, hotspot, Bluetooth, and shutdown are not available.
{% endif %} @@ -904,6 +904,12 @@

System Actions

+ {% if not docker_mode %} +
+ + +
+ {% endif %}
{% if not docker_mode %} @@ -1235,6 +1241,94 @@ } } + // --- Hotspot --- + let hotspotEnabled = null; + + async function updateHotspotButton() { + const btn = document.getElementById('hotspot-btn'); + if (!btn) return; + try { + const data = await apiCall('api/hotspot/status'); + hotspotEnabled = data.enabled; + if (!data.available) { + btn.textContent = 'Hotspot Unavailable'; + btn.disabled = true; + btn.className = 'btn'; + } else if (data.enabled) { + btn.textContent = 'Disable Hotspot'; + btn.disabled = false; + btn.className = 'btn btn-warning'; + } else { + btn.textContent = 'Enable Hotspot'; + btn.disabled = false; + btn.className = 'btn btn-primary'; + } + } catch (e) { + btn.textContent = 'Hotspot Unavailable'; + btn.disabled = true; + } + } + + async function toggleHotspot() { + const btn = document.getElementById('hotspot-btn'); + btn.disabled = true; + btn.innerHTML = ''; + try { + if (hotspotEnabled) { + await apiCall('api/hotspot/disable', 'POST'); + } else { + await apiCall('api/hotspot/enable', 'POST'); + } + } catch (e) { + alert(`Hotspot error: ${e.message}`); + } + await updateHotspotButton(); + } + + // --- Bluetooth --- + let bluetoothEnabled = null; + + async function updateBluetoothButton() { + const btn = document.getElementById('bluetooth-btn'); + if (!btn) return; + try { + const data = await apiCall('api/bluetooth/status'); + bluetoothEnabled = data.enabled; + if (!data.available) { + btn.textContent = 'Bluetooth Unavailable'; + btn.disabled = true; + btn.className = 'btn'; + } else if (data.enabled) { + btn.textContent = 'Disable Bluetooth'; + btn.disabled = false; + btn.className = 'btn btn-warning'; + } else { + btn.textContent = 'Enable Bluetooth'; + btn.disabled = false; + btn.className = 'btn btn-primary'; + } + } catch (e) { + btn.textContent = 'Bluetooth Unavailable'; + btn.disabled = true; + } + } + + async function toggleBluetooth() { + const btn = document.getElementById('bluetooth-btn'); + btn.disabled = true; + btn.innerHTML = ''; + try { + if (bluetoothEnabled) { + await apiCall('api/bluetooth/disable', 'POST'); + } else { + await apiCall('api/bluetooth/enable', 'POST'); + } + } catch (e) { + alert(`Bluetooth error: ${e.message}`); + } + await updateBluetoothButton(); + } + async function waitForController(maxWaitMs = 60000) { const start = Date.now(); while (Date.now() - start < maxWaitMs) { @@ -2471,6 +2565,10 @@ // Update every 10 seconds const updateInterval = 10000; + // Fetch hardware button status immediately + updateHotspotButton(); + updateBluetoothButton(); + // Initial update after a short delay (to not overlap with initial load) setTimeout(() => { updateSystemStatus(); @@ -2485,6 +2583,8 @@ updateServicesTable(); loadDisks(); loadSmart(); + updateHotspotButton(); + updateBluetoothButton(); }, updateInterval); } diff --git a/controller/test/test_admin.py b/controller/test/test_admin.py index 7bb19155..c2d72b22 100644 --- a/controller/test/test_admin.py +++ b/controller/test/test_admin.py @@ -8,10 +8,13 @@ import pytest from controller.lib.admin import ( apply_timezone_from_config, + disable_bluetooth, disable_hotspot, disable_throttle, + enable_bluetooth, enable_hotspot, enable_throttle, + get_bluetooth_status, get_hotspot_status, get_throttle_status, get_timezone_status_dict, @@ -19,11 +22,177 @@ from controller.lib.admin import ( restart_all_services, set_timezone, shutdown_system, + BluetoothStatus, HotspotStatus, GovernorStatus, ) +class TestGetBluetoothStatus: + """Tests for get_bluetooth_status function.""" + + @pytest.mark.asyncio + async def test_returns_bluetooth_status_enum(self): + """Should return a BluetoothStatus enum value.""" + result = await get_bluetooth_status() + assert isinstance(result, BluetoothStatus) + + @pytest.mark.asyncio + async def test_returns_unknown_in_docker_mode(self): + """Should return unknown when in Docker mode.""" + with mock.patch("controller.lib.admin.is_docker_mode", return_value=True): + result = await get_bluetooth_status() + assert result == BluetoothStatus.unknown + + @pytest.mark.asyncio + async def test_returns_unavailable_when_rfkill_not_found(self): + """Should return unavailable when rfkill is not installed.""" + with mock.patch("controller.lib.admin.is_docker_mode", return_value=False): + with mock.patch("asyncio.create_subprocess_exec", side_effect=FileNotFoundError()): + result = await get_bluetooth_status() + assert result == BluetoothStatus.unavailable + + @pytest.mark.asyncio + async def test_returns_on_when_unblocked(self): + """Should return on when Bluetooth is unblocked.""" + rfkill_json = '{"rfkilldevices": [{"id": 0, "type": "bluetooth", "device": "hci0", "soft": "unblocked", "hard": "unblocked"}]}' + mock_proc = mock.AsyncMock() + mock_proc.communicate.return_value = (rfkill_json.encode(), b"") + mock_proc.returncode = 0 + + with mock.patch("controller.lib.admin.is_docker_mode", return_value=False): + with mock.patch("asyncio.create_subprocess_exec", return_value=mock_proc): + result = await get_bluetooth_status() + assert result == BluetoothStatus.on + + @pytest.mark.asyncio + async def test_returns_off_when_soft_blocked(self): + """Should return off when Bluetooth is soft blocked.""" + rfkill_json = '{"rfkilldevices": [{"id": 0, "type": "bluetooth", "device": "hci0", "soft": "blocked", "hard": "unblocked"}]}' + mock_proc = mock.AsyncMock() + mock_proc.communicate.return_value = (rfkill_json.encode(), b"") + mock_proc.returncode = 0 + + with mock.patch("controller.lib.admin.is_docker_mode", return_value=False): + with mock.patch("asyncio.create_subprocess_exec", return_value=mock_proc): + result = await get_bluetooth_status() + assert result == BluetoothStatus.off + + @pytest.mark.asyncio + async def test_returns_off_when_hard_blocked(self): + """Should return off when Bluetooth is hard blocked.""" + rfkill_json = '{"rfkilldevices": [{"id": 0, "type": "bluetooth", "device": "hci0", "soft": "unblocked", "hard": "blocked"}]}' + mock_proc = mock.AsyncMock() + mock_proc.communicate.return_value = (rfkill_json.encode(), b"") + mock_proc.returncode = 0 + + with mock.patch("controller.lib.admin.is_docker_mode", return_value=False): + with mock.patch("asyncio.create_subprocess_exec", return_value=mock_proc): + result = await get_bluetooth_status() + assert result == BluetoothStatus.off + + @pytest.mark.asyncio + async def test_returns_unavailable_when_no_bluetooth_device(self): + """Should return unavailable when no Bluetooth devices exist.""" + rfkill_json = '{"rfkilldevices": [{"id": 0, "type": "wlan", "device": "phy0", "soft": "unblocked", "hard": "unblocked"}]}' + mock_proc = mock.AsyncMock() + mock_proc.communicate.return_value = (rfkill_json.encode(), b"") + mock_proc.returncode = 0 + + with mock.patch("controller.lib.admin.is_docker_mode", return_value=False): + with mock.patch("asyncio.create_subprocess_exec", return_value=mock_proc): + result = await get_bluetooth_status() + assert result == BluetoothStatus.unavailable + + @pytest.mark.asyncio + async def test_handles_timeout(self): + """Should return unknown on timeout.""" + import asyncio + with mock.patch("controller.lib.admin.is_docker_mode", return_value=False): + mock_proc = mock.AsyncMock() + mock_proc.communicate.side_effect = asyncio.TimeoutError() + with mock.patch("asyncio.create_subprocess_exec", return_value=mock_proc): + # wait_for wraps communicate, but we mock at the proc level. + # The timeout is handled by asyncio.wait_for in the function. + result = await get_bluetooth_status() + assert result == BluetoothStatus.unknown + + +class TestEnableBluetooth: + """Tests for enable_bluetooth function.""" + + @pytest.mark.asyncio + async def test_returns_error_in_docker_mode(self): + """Should return error when in Docker mode.""" + with mock.patch("controller.lib.admin.is_docker_mode", return_value=True): + result = await enable_bluetooth() + assert result["success"] is False + assert "Docker" in result.get("error", "") + + @pytest.mark.asyncio + async def test_calls_rfkill_unblock(self): + """Should call rfkill unblock bluetooth.""" + mock_proc = mock.AsyncMock() + mock_proc.communicate.return_value = (b"", b"") + mock_proc.returncode = 0 + + with mock.patch("controller.lib.admin.is_docker_mode", return_value=False): + with mock.patch("asyncio.create_subprocess_exec", return_value=mock_proc) as mock_exec: + result = await enable_bluetooth() + assert result["success"] is True + mock_exec.assert_called_once_with( + "rfkill", "unblock", "bluetooth", + stdout=mock.ANY, + stderr=mock.ANY, + ) + + @pytest.mark.asyncio + async def test_handles_rfkill_not_found(self): + """Should handle rfkill not being available.""" + with mock.patch("controller.lib.admin.is_docker_mode", return_value=False): + with mock.patch("asyncio.create_subprocess_exec", side_effect=FileNotFoundError()): + result = await enable_bluetooth() + assert result["success"] is False + assert "rfkill" in result.get("error", "").lower() + + +class TestDisableBluetooth: + """Tests for disable_bluetooth function.""" + + @pytest.mark.asyncio + async def test_returns_error_in_docker_mode(self): + """Should return error when in Docker mode.""" + with mock.patch("controller.lib.admin.is_docker_mode", return_value=True): + result = await disable_bluetooth() + assert result["success"] is False + assert "Docker" in result.get("error", "") + + @pytest.mark.asyncio + async def test_calls_rfkill_block(self): + """Should call rfkill block bluetooth.""" + mock_proc = mock.AsyncMock() + mock_proc.communicate.return_value = (b"", b"") + mock_proc.returncode = 0 + + with mock.patch("controller.lib.admin.is_docker_mode", return_value=False): + with mock.patch("asyncio.create_subprocess_exec", return_value=mock_proc) as mock_exec: + result = await disable_bluetooth() + assert result["success"] is True + mock_exec.assert_called_once_with( + "rfkill", "block", "bluetooth", + stdout=mock.ANY, + stderr=mock.ANY, + ) + + @pytest.mark.asyncio + async def test_handles_rfkill_not_found(self): + """Should handle rfkill not being available.""" + with mock.patch("controller.lib.admin.is_docker_mode", return_value=False): + with mock.patch("asyncio.create_subprocess_exec", side_effect=FileNotFoundError()): + result = await disable_bluetooth() + assert result["success"] is False + + class TestGetHotspotStatus: """Tests for get_hotspot_status function.""" diff --git a/controller/test/test_admin_api.py b/controller/test/test_admin_api.py index 2f12e0e9..a5ccbcce 100644 --- a/controller/test/test_admin_api.py +++ b/controller/test/test_admin_api.py @@ -45,6 +45,48 @@ class TestHotspotDisableEndpoint: assert "Docker" in response.json()["detail"] +class TestBluetoothStatusEndpoint: + """Tests for /api/bluetooth/status endpoint.""" + + def test_bluetooth_status_returns_200(self, test_client): + """Bluetooth status endpoint should return 200 OK.""" + response = test_client.get("/api/bluetooth/status") + assert response.status_code == 200 + + def test_bluetooth_status_returns_expected_fields(self, test_client): + """Bluetooth status should return enabled and available fields.""" + response = test_client.get("/api/bluetooth/status") + data = response.json() + assert "enabled" in data + assert "available" in data + + def test_bluetooth_status_shows_unavailable_in_docker(self, test_client_docker_mode): + """Bluetooth should be unavailable in Docker mode.""" + response = test_client_docker_mode.get("/api/bluetooth/status") + data = response.json() + assert data["available"] is False + + +class TestBluetoothEnableEndpoint: + """Tests for /api/bluetooth/enable endpoint.""" + + def test_bluetooth_enable_fails_in_docker(self, test_client_docker_mode): + """Bluetooth enable should fail in Docker mode.""" + response = test_client_docker_mode.post("/api/bluetooth/enable") + assert response.status_code == 500 + assert "Docker" in response.json()["detail"] + + +class TestBluetoothDisableEndpoint: + """Tests for /api/bluetooth/disable endpoint.""" + + def test_bluetooth_disable_fails_in_docker(self, test_client_docker_mode): + """Bluetooth disable should fail in Docker mode.""" + response = test_client_docker_mode.post("/api/bluetooth/disable") + assert response.status_code == 500 + assert "Docker" in response.json()["detail"] + + class TestThrottleStatusEndpoint: """Tests for /api/throttle/status endpoint.""" @@ -160,6 +202,14 @@ class TestOpenAPIIncludesAdminEndpoints: assert "/api/hotspot/enable" in data["paths"] assert "/api/hotspot/disable" in data["paths"] + def test_openapi_has_bluetooth_paths(self, test_client): + """OpenAPI schema should include bluetooth paths.""" + response = test_client.get("/openapi.json") + data = response.json() + assert "/api/bluetooth/status" in data["paths"] + assert "/api/bluetooth/enable" in data["paths"] + assert "/api/bluetooth/disable" in data["paths"] + def test_openapi_has_throttle_paths(self, test_client): """OpenAPI schema should include throttle paths.""" response = test_client.get("/openapi.json")