mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-26 09:56:17 -05:00
Controller: move hotspot settings to controller.yaml with WiFi device dropdown.
Hotspot was reported as "not supported" on x86 machines (Ubuntu/Debian PCs) because the Controller only watched the hardcoded default wlan0 device, while predictable interface naming produces names like wlp2s0. The Settings page saved hotspot_device to wrolpi.yaml, which the Controller never read. The Controller now owns hotspot settings in controller.yaml: * New endpoints: GET/POST /api/hotspot/settings, GET /api/hotspot/devices (WiFi interfaces discovered via nmcli). * Legacy hotspot_* values in wrolpi.yaml are migrated into controller.yaml once on startup, unless controller.yaml already sets them. * The Hotspot SSID/password/device fields moved from the Settings page to the Control page next to the Hotspot toggle; the device is now a dropdown of the WiFi devices found on the machine. * The Controller fallback UI gets the same hotspot settings form for parity. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
ebbc60992c
commit
0d2c13e4e7
12 changed files with 586 additions and 89 deletions
|
|
@ -75,6 +75,18 @@ export async function getHotspotStatus() {
|
|||
return controllerFetch('/hotspot/status');
|
||||
}
|
||||
|
||||
export async function getHotspotDevices() {
|
||||
return controllerFetch('/hotspot/devices');
|
||||
}
|
||||
|
||||
export async function getHotspotSettings() {
|
||||
return controllerFetch('/hotspot/settings');
|
||||
}
|
||||
|
||||
export async function updateHotspotSettings(settings) {
|
||||
return controllerFetch('/hotspot/settings', {method: 'POST', body: JSON.stringify(settings)});
|
||||
}
|
||||
|
||||
export async function enableHotspot() {
|
||||
return controllerFetch('/hotspot/enable', {method: 'POST'});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,8 @@ import {
|
|||
enableService,
|
||||
getDisks,
|
||||
getFstabEntries,
|
||||
getHotspotDevices,
|
||||
getHotspotSettings,
|
||||
getSambaStatus,
|
||||
getServiceLogs,
|
||||
getServices,
|
||||
|
|
@ -23,7 +25,9 @@ import {
|
|||
startService,
|
||||
stopService,
|
||||
unmountDisk,
|
||||
updateHotspotSettings,
|
||||
} from "../../api/controller";
|
||||
import QRCode from "react-qr-code";
|
||||
import {toast} from "react-semantic-toasts-2";
|
||||
import {RestartButton, ShutdownButton} from "./Settings";
|
||||
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
|
||||
|
|
@ -1345,6 +1349,100 @@ function SambaSection() {
|
|||
}
|
||||
|
||||
|
||||
function HotspotSettingsForm() {
|
||||
const dockerized = useDockerized();
|
||||
const [devices, setDevices] = React.useState([]);
|
||||
const [form, setForm] = React.useState({device: '', ssid: '', password: ''});
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
const [qrOpen, setQrOpen] = React.useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
const fetchSettings = async () => {
|
||||
try {
|
||||
const [settings, devicesResponse] = await Promise.all([getHotspotSettings(), getHotspotDevices()]);
|
||||
setForm({device: settings.device, ssid: settings.ssid, password: settings.password});
|
||||
setDevices(devicesResponse.devices || []);
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch hotspot settings', e);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
fetchSettings();
|
||||
}, []);
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const settings = await updateHotspotSettings(form);
|
||||
setForm(settings);
|
||||
toast({type: 'success', title: 'Hotspot settings saved', time: 3000});
|
||||
} catch (e) {
|
||||
toast({type: 'error', title: 'Failed to save hotspot settings', description: e.message, time: 5000});
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <Loader active inline size='small'/>;
|
||||
}
|
||||
|
||||
// Keep the saved device selectable even if it is not currently present
|
||||
// (e.g. a USB WiFi dongle is unplugged).
|
||||
const deviceOptions = [...new Set([...devices, form.device].filter(Boolean))]
|
||||
.map(device => ({key: device, value: device, text: device}));
|
||||
|
||||
// Special string which allows a mobile device to connect to a specific Wi-Fi.
|
||||
const qrCodeValue = `WIFI:S:${form.ssid};T:WPA;P:${form.password};;`;
|
||||
|
||||
return <Form style={{marginLeft: '1em', marginBottom: '1em'}}>
|
||||
<Form.Group widths='equal'>
|
||||
<Form.Input
|
||||
label='Hotspot SSID'
|
||||
value={form.ssid}
|
||||
disabled={dockerized || saving}
|
||||
onChange={(e, {value}) => setForm({...form, ssid: value})}
|
||||
/>
|
||||
<Form.Input
|
||||
label='Hotspot Password'
|
||||
value={form.password}
|
||||
disabled={dockerized || saving}
|
||||
onChange={(e, {value}) => setForm({...form, password: value})}
|
||||
/>
|
||||
<Form.Dropdown
|
||||
selection
|
||||
label='Hotspot Device'
|
||||
placeholder='No WiFi devices found'
|
||||
options={deviceOptions}
|
||||
value={form.device}
|
||||
disabled={dockerized || saving}
|
||||
onChange={(e, {value}) => setForm({...form, device: value})}
|
||||
/>
|
||||
</Form.Group>
|
||||
<Button
|
||||
color='violet'
|
||||
disabled={dockerized}
|
||||
loading={saving}
|
||||
onClick={handleSave}
|
||||
>Save</Button>
|
||||
<Modal closeIcon
|
||||
onClose={() => setQrOpen(false)}
|
||||
onOpen={() => setQrOpen(true)}
|
||||
open={qrOpen}
|
||||
trigger={<Button icon='qrcode' color='violet'/>}
|
||||
>
|
||||
<Modal.Header>Scan this code to join the hotspot</Modal.Header>
|
||||
<Modal.Content>
|
||||
<div style={{display: 'inline-block', backgroundColor: '#ffffff', padding: '1em'}}>
|
||||
<QRCode value={qrCodeValue} size={300}/>
|
||||
</div>
|
||||
</Modal.Content>
|
||||
</Modal>
|
||||
</Form>;
|
||||
}
|
||||
|
||||
function AdminControlsSection() {
|
||||
const dockerized = useDockerized();
|
||||
|
||||
|
|
@ -1356,6 +1454,7 @@ function AdminControlsSection() {
|
|||
</Header>
|
||||
|
||||
<HotspotToggle/>
|
||||
<HotspotSettingsForm/>
|
||||
<BluetoothToggle/>
|
||||
<ThrottleToggle/>
|
||||
|
||||
|
|
|
|||
|
|
@ -24,7 +24,6 @@ import {
|
|||
useMessageDismissal,
|
||||
WROLModeMessage
|
||||
} from "../Common";
|
||||
import QRCode from "react-qr-code";
|
||||
import {useConfigs, useDockerized} from "../../hooks/customHooks";
|
||||
import {toast} from "react-semantic-toasts-2";
|
||||
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
|
||||
|
|
@ -296,8 +295,6 @@ function WROLModeSection() {
|
|||
export function SettingsPage() {
|
||||
const [disabled, setDisabled] = React.useState(false);
|
||||
const [editSpecialDirectories, setEditSpecialDirectories] = React.useState(false);
|
||||
const [qrCodeValue, setQrCodeValue] = React.useState('');
|
||||
const [qrOpen, setQrOpen] = React.useState(false);
|
||||
const [ready, setReady] = React.useState(false);
|
||||
const [pendingSave, setPendingSave] = React.useState(false);
|
||||
const {clearAll} = useMessageDismissal();
|
||||
|
|
@ -446,12 +443,6 @@ export function SettingsPage() {
|
|||
setTraceModalOpen(false);
|
||||
}
|
||||
|
||||
const handleHotspotChange = async () => {
|
||||
let {hotspot_ssid, hotspot_encryption, hotspot_password} = state;
|
||||
// Special string which allows a mobile device to connect to a specific Wi-Fi.
|
||||
setQrCodeValue(`WIFI:S:${hotspot_ssid};T:${hotspot_encryption};P:${hotspot_password};;`);
|
||||
}
|
||||
|
||||
React.useEffect(() => {
|
||||
console.debug('settings changed, replacing state...');
|
||||
setReady(settings ? true : undefined);
|
||||
|
|
@ -468,10 +459,6 @@ export function SettingsPage() {
|
|||
download_window_start: settings.download_window_start || '',
|
||||
download_window_end: settings.download_window_end || '',
|
||||
timezone: settings.timezone || '',
|
||||
hotspot_device: settings.hotspot_device,
|
||||
hotspot_on_startup: settings.hotspot_on_startup,
|
||||
hotspot_password: settings.hotspot_password,
|
||||
hotspot_ssid: settings.hotspot_ssid,
|
||||
check_for_upgrades: settings.check_for_upgrades,
|
||||
ignore_outdated_zims: settings.ignore_outdated_zims,
|
||||
log_level: fromApiLogLevel(settings.log_level),
|
||||
|
|
@ -487,10 +474,6 @@ export function SettingsPage() {
|
|||
});
|
||||
}, [JSON.stringify(settings)]);
|
||||
|
||||
React.useEffect(() => {
|
||||
handleHotspotChange();
|
||||
}, [state.hotspot_ssid, state.hotspot_password, state.hotspot_device]);
|
||||
|
||||
const handleInputChange = async (e, name, value) => {
|
||||
if (e) {
|
||||
e.preventDefault()
|
||||
|
|
@ -507,15 +490,6 @@ export function SettingsPage() {
|
|||
setState({...state, [name]: value});
|
||||
}
|
||||
|
||||
const handleQrOpen = async (e) => {
|
||||
e.preventDefault();
|
||||
setQrOpen(true);
|
||||
}
|
||||
|
||||
const qrButton = <Button icon color='violet' style={{marginBottom: '1em'}}>
|
||||
<Icon name='qrcode' size='big'/>
|
||||
</Button>;
|
||||
|
||||
const timezoneOptions = Intl.supportedValuesOf('timeZone').map(tz => (
|
||||
{key: tz, value: tz, text: tz}
|
||||
));
|
||||
|
|
@ -619,54 +593,6 @@ export function SettingsPage() {
|
|||
</ButtonGroup>
|
||||
|
||||
</Grid.Column>
|
||||
<Grid.Column>
|
||||
<Segment>
|
||||
<Header as='h3'>Hotspot Settings</Header>
|
||||
|
||||
<Form.Input
|
||||
label='Hotspot SSID'
|
||||
value={state.hotspot_ssid}
|
||||
disabled={disabled || state.hotspot_ssid === null}
|
||||
onChange={(e, i) => setState({...state, hotspot_ssid: i.value})}
|
||||
style={{marginBottom: '0.5em'}}
|
||||
/>
|
||||
<Form.Input
|
||||
label='Hotspot Password'
|
||||
disabled={disabled || state.hotspot_password === null}
|
||||
value={state.hotspot_password}
|
||||
onChange={(e, i) => setState({...state, hotspot_password: i.value})}
|
||||
style={{marginBottom: '0.5em'}}
|
||||
/>
|
||||
<Form.Input
|
||||
label='Hotspot Device'
|
||||
disabled={disabled || state.hotspot_password === null}
|
||||
value={state.hotspot_device}
|
||||
onChange={(e, i) => handleInputChange(e, 'hotspot_device', i.value)}
|
||||
style={{marginBottom: '0.5em'}}
|
||||
/>
|
||||
|
||||
<Modal closeIcon
|
||||
onClose={() => setQrOpen(false)}
|
||||
onOpen={handleQrOpen}
|
||||
open={qrOpen}
|
||||
trigger={qrButton}
|
||||
>
|
||||
<Modal.Header>
|
||||
Scan this code to join the hotspot
|
||||
</Modal.Header>
|
||||
<Modal.Content>
|
||||
<div style={{
|
||||
display: 'inline-block',
|
||||
backgroundColor: '#ffffff',
|
||||
padding: '1em'
|
||||
}}>
|
||||
<QRCode value={qrCodeValue} size={300}/>
|
||||
</div>
|
||||
</Modal.Content>
|
||||
</Modal>
|
||||
|
||||
</Segment>
|
||||
</Grid.Column>
|
||||
</Grid.Row>
|
||||
</Grid>
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,9 @@ from controller.api.schemas import (
|
|||
BluetoothActionResponse,
|
||||
BluetoothStatusResponse,
|
||||
HotspotActionResponse,
|
||||
HotspotDevicesResponse,
|
||||
HotspotSettingsRequest,
|
||||
HotspotSettingsResponse,
|
||||
HotspotStatusResponse,
|
||||
RestartServicesResponse,
|
||||
SambaShareAddRequest,
|
||||
|
|
@ -30,13 +33,18 @@ from controller.lib.admin import (
|
|||
enable_hotspot,
|
||||
enable_throttle,
|
||||
get_bluetooth_status_dict,
|
||||
get_hotspot_device,
|
||||
get_hotspot_password,
|
||||
get_hotspot_ssid,
|
||||
get_hotspot_status_dict,
|
||||
get_throttle_status_dict,
|
||||
get_timezone_status_dict,
|
||||
get_wifi_devices,
|
||||
reboot_system,
|
||||
restart_all_services,
|
||||
set_timezone,
|
||||
shutdown_system,
|
||||
update_hotspot_settings,
|
||||
)
|
||||
from controller.lib.config import is_docker_mode
|
||||
from controller.lib.samba import (
|
||||
|
|
@ -56,6 +64,33 @@ async def hotspot_status() -> HotspotStatusResponse:
|
|||
return HotspotStatusResponse(**get_hotspot_status_dict())
|
||||
|
||||
|
||||
@router.get("/api/hotspot/devices", response_model=HotspotDevicesResponse)
|
||||
async def hotspot_devices() -> HotspotDevicesResponse:
|
||||
"""List WiFi devices which could host the hotspot."""
|
||||
return HotspotDevicesResponse(devices=get_wifi_devices())
|
||||
|
||||
|
||||
@router.get("/api/hotspot/settings", response_model=HotspotSettingsResponse)
|
||||
async def hotspot_settings() -> HotspotSettingsResponse:
|
||||
"""Get WiFi hotspot settings."""
|
||||
return HotspotSettingsResponse(
|
||||
device=get_hotspot_device(),
|
||||
ssid=get_hotspot_ssid(),
|
||||
password=get_hotspot_password(),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/hotspot/settings", response_model=HotspotSettingsResponse)
|
||||
async def hotspot_settings_update(request: HotspotSettingsRequest) -> HotspotSettingsResponse:
|
||||
"""Update WiFi hotspot settings; they are saved in controller.yaml."""
|
||||
result = update_hotspot_settings(device=request.device, ssid=request.ssid, password=request.password)
|
||||
if not result.get("success"):
|
||||
error = result.get("error", "Failed")
|
||||
status_code = 500 if "Docker" in error else 400
|
||||
raise HTTPException(status_code=status_code, detail=error)
|
||||
return HotspotSettingsResponse(device=result["device"], ssid=result["ssid"], password=result["password"])
|
||||
|
||||
|
||||
@router.post("/api/hotspot/enable", response_model=HotspotActionResponse)
|
||||
async def hotspot_enable() -> HotspotActionResponse:
|
||||
"""Enable WiFi hotspot."""
|
||||
|
|
|
|||
|
|
@ -157,6 +157,28 @@ class HotspotStatusResponse(BaseModel):
|
|||
device: Optional[str] = Field(default=None, description="WiFi device name")
|
||||
|
||||
|
||||
class HotspotDevicesResponse(BaseModel):
|
||||
"""Response model for /api/hotspot/devices endpoint."""
|
||||
|
||||
devices: list[str] = Field(description="Available WiFi device names")
|
||||
|
||||
|
||||
class HotspotSettingsRequest(BaseModel):
|
||||
"""Request model for updating hotspot settings; only provided values are changed."""
|
||||
|
||||
device: Optional[str] = Field(default=None, description="WiFi device name")
|
||||
ssid: Optional[str] = Field(default=None, description="Hotspot SSID")
|
||||
password: Optional[str] = Field(default=None, description="Hotspot password (8 to 63 characters)")
|
||||
|
||||
|
||||
class HotspotSettingsResponse(BaseModel):
|
||||
"""Response model for /api/hotspot/settings endpoint."""
|
||||
|
||||
device: str = Field(description="WiFi device name")
|
||||
ssid: str = Field(description="Hotspot SSID")
|
||||
password: str = Field(description="Hotspot password")
|
||||
|
||||
|
||||
class HotspotActionResponse(BaseModel):
|
||||
"""Response model for hotspot enable/disable actions."""
|
||||
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@ 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_bluetooth_status, get_hotspot_status, get_throttle_status, BluetoothStatus, HotspotStatus
|
||||
from controller.lib.admin import get_bluetooth_status, get_hotspot_ssid, 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,
|
||||
|
|
@ -36,16 +37,12 @@ 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.
|
||||
"""
|
||||
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
|
||||
config = get_config()
|
||||
hotspot_config = config.get("hotspot", {})
|
||||
hotspot_ssid = hotspot_config.get("ssid", "WROLPi") if hotspot_status == HotspotStatus.connected else None
|
||||
hotspot_ssid = get_hotspot_ssid() if hotspot_status == HotspotStatus.connected else None
|
||||
|
||||
return {
|
||||
"dockerized": is_docker_mode(),
|
||||
|
|
|
|||
|
|
@ -49,6 +49,14 @@ async def _noop_status_worker(app, base_sleep: float = 5.0):
|
|||
raise
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_media_directory(tmp_path_factory, monkeypatch):
|
||||
"""Point the media directory at an empty temp dir so tests never read a real
|
||||
/media/wrolpi (e.g. hotspot settings from wrolpi.yaml)."""
|
||||
media_dir = tmp_path_factory.mktemp("media")
|
||||
monkeypatch.setenv("MEDIA_DIRECTORY", str(media_dir))
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _patch_status_worker():
|
||||
"""Replace the real status worker with a no-op for every test.
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ from pathlib import Path
|
|||
|
||||
import yaml
|
||||
|
||||
from controller.lib import config as config_lib
|
||||
from controller.lib.config import is_docker_mode, get_config_value, get_media_directory
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
|
@ -45,13 +46,141 @@ class GovernorStatus(enum.Enum):
|
|||
unknown = enum.auto()
|
||||
|
||||
|
||||
def get_hotspot_device() -> str:
|
||||
return get_config_value('hotspot.device', 'wlan0')
|
||||
|
||||
|
||||
def get_hotspot_ssid() -> str:
|
||||
return get_config_value('hotspot.ssid', 'WROLPi')
|
||||
|
||||
|
||||
def get_hotspot_password() -> str:
|
||||
return get_config_value('hotspot.password', 'wrolpi hotspot')
|
||||
|
||||
|
||||
def update_hotspot_settings(device: str = None, ssid: str = None, password: str = None) -> dict:
|
||||
"""
|
||||
Update hotspot settings in controller.yaml. Only provided values are changed.
|
||||
|
||||
Returns:
|
||||
dict with success status and the current settings
|
||||
"""
|
||||
if is_docker_mode():
|
||||
return {"success": False, "error": "Not available in Docker mode"}
|
||||
|
||||
if device is not None and not device.strip():
|
||||
return {"success": False, "error": "Hotspot device must not be empty"}
|
||||
if ssid is not None and not ssid.strip():
|
||||
return {"success": False, "error": "Hotspot SSID must not be empty"}
|
||||
# nmcli requires a WPA password of 8 to 63 characters.
|
||||
if password is not None and not 8 <= len(password) <= 63:
|
||||
return {"success": False, "error": "Hotspot password must be 8 to 63 characters"}
|
||||
|
||||
if device:
|
||||
config_lib.update_config('hotspot.device', device)
|
||||
if ssid:
|
||||
config_lib.update_config('hotspot.ssid', ssid)
|
||||
if password:
|
||||
config_lib.update_config('hotspot.password', password)
|
||||
|
||||
try:
|
||||
config_lib.save_config()
|
||||
except RuntimeError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
logger.info("Hotspot settings updated (device=%s, ssid=%s)", get_hotspot_device(), get_hotspot_ssid())
|
||||
return {
|
||||
"success": True,
|
||||
"device": get_hotspot_device(),
|
||||
"ssid": get_hotspot_ssid(),
|
||||
"password": get_hotspot_password(),
|
||||
}
|
||||
|
||||
|
||||
def migrate_hotspot_settings_from_wrolpi_config():
|
||||
"""
|
||||
One-time copy of hotspot settings from wrolpi.yaml into controller.yaml.
|
||||
|
||||
Hotspot settings used to be saved in wrolpi.yaml by the Settings page; the
|
||||
Controller now owns them in controller.yaml. Copy any values the user set
|
||||
in wrolpi.yaml unless controller.yaml already sets them explicitly.
|
||||
Called on Controller startup after the primary drive is mounted.
|
||||
"""
|
||||
if not config_lib.CONFIG_PATH_ON_DRIVE.exists():
|
||||
return
|
||||
|
||||
try:
|
||||
with open(config_lib.CONFIG_PATH_ON_DRIVE) as f:
|
||||
controller_config = yaml.safe_load(f) or {}
|
||||
except (IOError, yaml.YAMLError) as e:
|
||||
logger.warning("Failed to read controller.yaml for hotspot migration: %s", e)
|
||||
return
|
||||
|
||||
wrolpi_config_path = get_media_directory() / 'config' / 'wrolpi.yaml'
|
||||
if not wrolpi_config_path.exists():
|
||||
return
|
||||
|
||||
try:
|
||||
with open(wrolpi_config_path) as f:
|
||||
wrolpi_config = yaml.safe_load(f) or {}
|
||||
except (IOError, yaml.YAMLError) as e:
|
||||
logger.warning("Failed to read wrolpi.yaml for hotspot migration: %s", e)
|
||||
return
|
||||
|
||||
explicit = controller_config.get('hotspot') or {}
|
||||
key_map = {'device': 'hotspot_device', 'ssid': 'hotspot_ssid', 'password': 'hotspot_password'}
|
||||
changed = False
|
||||
for controller_key, wrolpi_key in key_map.items():
|
||||
value = wrolpi_config.get(wrolpi_key)
|
||||
if value and controller_key not in explicit and value != get_config_value(f'hotspot.{controller_key}'):
|
||||
config_lib.update_config(f'hotspot.{controller_key}', value)
|
||||
changed = True
|
||||
|
||||
if changed:
|
||||
try:
|
||||
config_lib.save_config()
|
||||
logger.info("Migrated hotspot settings from wrolpi.yaml to controller.yaml")
|
||||
except RuntimeError as e:
|
||||
logger.warning("Could not save migrated hotspot settings: %s", e)
|
||||
|
||||
|
||||
def get_wifi_devices() -> list[str]:
|
||||
"""
|
||||
List WiFi device names (e.g. wlan0, wlp2s0) using nmcli.
|
||||
|
||||
Returns an empty list in Docker mode or when nmcli is unavailable.
|
||||
"""
|
||||
if is_docker_mode():
|
||||
return []
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["nmcli", "-t", "-f", "DEVICE,TYPE", "device"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
return []
|
||||
|
||||
devices = []
|
||||
for line in result.stdout.strip().splitlines():
|
||||
parts = line.split(":")
|
||||
# Exact "wifi" match excludes wifi-p2p devices.
|
||||
if len(parts) >= 2 and parts[1] == "wifi":
|
||||
devices.append(parts[0])
|
||||
return devices
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired, subprocess.SubprocessError):
|
||||
return []
|
||||
|
||||
|
||||
def get_current_ssid(interface: str = None) -> str | None:
|
||||
"""
|
||||
Returns the name of the SSID that is currently connected.
|
||||
Returns None if Hotspot is active, or no Wi-Fi network is being used.
|
||||
"""
|
||||
if interface is None:
|
||||
interface = get_config_value('hotspot.device', 'wlan0')
|
||||
interface = get_hotspot_device()
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['iwgetid', interface, '--raw'],
|
||||
|
|
@ -81,7 +210,7 @@ def get_hotspot_status() -> HotspotStatus:
|
|||
if is_docker_mode():
|
||||
return HotspotStatus.unknown
|
||||
|
||||
device = get_config_value('hotspot.device', 'wlan0')
|
||||
device = get_hotspot_device()
|
||||
|
||||
# Check if device is connected to a Wi-Fi network (not hotspot)
|
||||
if get_current_ssid(device):
|
||||
|
|
@ -128,7 +257,7 @@ def get_hotspot_status_dict() -> dict:
|
|||
ssid: Optional[str] - Hotspot SSID when enabled
|
||||
device: Optional[str] - WiFi device name
|
||||
"""
|
||||
device = get_config_value('hotspot.device', 'wlan0')
|
||||
device = get_hotspot_device()
|
||||
status = get_hotspot_status()
|
||||
|
||||
# Map enum status to enabled/available flags
|
||||
|
|
@ -147,7 +276,7 @@ def get_hotspot_status_dict() -> dict:
|
|||
"enabled": enabled,
|
||||
"available": available,
|
||||
"reason": reason,
|
||||
"ssid": get_config_value('hotspot.ssid', 'WROLPi') if enabled else None,
|
||||
"ssid": get_hotspot_ssid() if enabled else None,
|
||||
"device": device,
|
||||
}
|
||||
|
||||
|
|
@ -162,9 +291,9 @@ def enable_hotspot() -> dict:
|
|||
if is_docker_mode():
|
||||
return {"success": False, "error": "Not available in Docker mode"}
|
||||
|
||||
device = get_config_value('hotspot.device', 'wlan0')
|
||||
ssid = get_config_value('hotspot.ssid', 'WROLPi')
|
||||
password = get_config_value('hotspot.password', 'wrolpi hotspot')
|
||||
device = get_hotspot_device()
|
||||
ssid = get_hotspot_ssid()
|
||||
password = get_hotspot_password()
|
||||
|
||||
try:
|
||||
# First ensure radio is on
|
||||
|
|
|
|||
|
|
@ -87,9 +87,12 @@ async def lifespan(app: FastAPI):
|
|||
logger.info("Using default configuration (no controller.yaml found)")
|
||||
|
||||
# Apply timezone from wrolpi.yaml to the system.
|
||||
from controller.lib.admin import apply_timezone_from_config
|
||||
from controller.lib.admin import apply_timezone_from_config, migrate_hotspot_settings_from_wrolpi_config
|
||||
apply_timezone_from_config()
|
||||
|
||||
# Copy legacy hotspot settings from wrolpi.yaml into controller.yaml.
|
||||
migrate_hotspot_settings_from_wrolpi_config()
|
||||
|
||||
# Apply Samba config if enabled.
|
||||
from controller.lib.samba import apply_samba_from_config
|
||||
apply_samba_from_config()
|
||||
|
|
@ -108,8 +111,9 @@ async def lifespan(app: FastAPI):
|
|||
except RuntimeError as e:
|
||||
logger.warning("Failed to create controller.yaml: %s", e)
|
||||
|
||||
from controller.lib.admin import apply_timezone_from_config
|
||||
from controller.lib.admin import apply_timezone_from_config, migrate_hotspot_settings_from_wrolpi_config
|
||||
apply_timezone_from_config()
|
||||
migrate_hotspot_settings_from_wrolpi_config()
|
||||
|
||||
from controller.lib.samba import apply_samba_from_config
|
||||
apply_samba_from_config()
|
||||
|
|
|
|||
|
|
@ -959,6 +959,23 @@
|
|||
<button id="hotspot-btn" class="btn" onclick="toggleHotspot()" disabled>Loading...</button>
|
||||
<button id="bluetooth-btn" class="btn" onclick="toggleBluetooth()" disabled>Loading...</button>
|
||||
</div>
|
||||
<details style="margin-bottom: 1rem;">
|
||||
<summary style="cursor: pointer;">Hotspot Settings</summary>
|
||||
<div class="modal-form" style="max-width: 24rem; margin-top: 0.5rem;">
|
||||
<label>SSID
|
||||
<input type="text" id="hotspot-ssid">
|
||||
</label>
|
||||
<label>Password
|
||||
<input type="text" id="hotspot-password">
|
||||
</label>
|
||||
<label>Device
|
||||
<select id="hotspot-device"
|
||||
style="width: 100%; padding: 0.5rem; margin-bottom: 1rem; background: #1a1a2e; border: 1px solid #333; border-radius: 4px; color: #fff; font-size: 1rem;">
|
||||
</select>
|
||||
</label>
|
||||
<button class="btn btn-primary" onclick="saveHotspotSettings()">Save Hotspot Settings</button>
|
||||
</div>
|
||||
</details>
|
||||
{% endif %}
|
||||
<div class="action-buttons">
|
||||
<button class="btn btn-warning" onclick="restartServices()">Restart All Services</button>
|
||||
|
|
@ -1372,6 +1389,48 @@
|
|||
await updateHotspotButton();
|
||||
}
|
||||
|
||||
async function loadHotspotSettings() {
|
||||
const ssidInput = document.getElementById('hotspot-ssid');
|
||||
if (!ssidInput) return;
|
||||
try {
|
||||
const [settings, devices] = await Promise.all([
|
||||
apiCall('api/hotspot/settings'),
|
||||
apiCall('api/hotspot/devices'),
|
||||
]);
|
||||
ssidInput.value = settings.ssid;
|
||||
document.getElementById('hotspot-password').value = settings.password;
|
||||
const select = document.getElementById('hotspot-device');
|
||||
select.innerHTML = '';
|
||||
// Keep the saved device selectable even if it is not currently present.
|
||||
const names = [...new Set([...(devices.devices || []), settings.device])].filter(Boolean);
|
||||
for (const name of names) {
|
||||
const option = document.createElement('option');
|
||||
option.value = name;
|
||||
option.textContent = name;
|
||||
option.selected = name === settings.device;
|
||||
select.appendChild(option);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load hotspot settings', e);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveHotspotSettings() {
|
||||
const btn = event.target;
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await apiCall('api/hotspot/settings', 'POST', {
|
||||
ssid: document.getElementById('hotspot-ssid').value,
|
||||
password: document.getElementById('hotspot-password').value,
|
||||
device: document.getElementById('hotspot-device').value,
|
||||
});
|
||||
await updateHotspotButton();
|
||||
} catch (e) {
|
||||
alert(`Failed to save hotspot settings: ${e.message}`);
|
||||
}
|
||||
btn.disabled = false;
|
||||
}
|
||||
|
||||
// --- Bluetooth ---
|
||||
let bluetoothEnabled = null;
|
||||
|
||||
|
|
@ -2759,6 +2818,7 @@
|
|||
// Fetch hardware button status immediately
|
||||
updateHotspotButton();
|
||||
updateBluetoothButton();
|
||||
loadHotspotSettings();
|
||||
|
||||
// Initial update after a short delay (to not overlap with initial load)
|
||||
setTimeout(() => {
|
||||
|
|
|
|||
|
|
@ -5,7 +5,9 @@ Unit tests for controller.lib.admin module.
|
|||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from controller.lib.config import reload_config_from_drive
|
||||
from controller.lib.admin import (
|
||||
apply_timezone_from_config,
|
||||
disable_bluetooth,
|
||||
|
|
@ -19,10 +21,16 @@ from controller.lib.admin import (
|
|||
get_hotspot_status_dict,
|
||||
get_throttle_status,
|
||||
get_timezone_status_dict,
|
||||
get_hotspot_device,
|
||||
get_hotspot_password,
|
||||
get_hotspot_ssid,
|
||||
get_wifi_devices,
|
||||
migrate_hotspot_settings_from_wrolpi_config,
|
||||
reboot_system,
|
||||
restart_all_services,
|
||||
set_timezone,
|
||||
shutdown_system,
|
||||
update_hotspot_settings,
|
||||
BluetoothStatus,
|
||||
HotspotStatus,
|
||||
GovernorStatus,
|
||||
|
|
@ -295,6 +303,155 @@ class TestGetHotspotStatusDict:
|
|||
assert result["enabled"] is True
|
||||
|
||||
|
||||
class TestHotspotSettingsMigration:
|
||||
"""Legacy hotspot settings in wrolpi.yaml are copied into controller.yaml on startup."""
|
||||
|
||||
@staticmethod
|
||||
def _write_wrolpi_yaml(test_config_directory, **values):
|
||||
lines = ''.join(f'{key}: {value}\n' for key, value in values.items())
|
||||
(test_config_directory / 'wrolpi.yaml').write_text(lines)
|
||||
|
||||
def test_migrates_wrolpi_yaml_values(self, test_directory, test_config_directory, mock_config_path,
|
||||
reset_runtime_config):
|
||||
"""wrolpi.yaml hotspot settings should be copied to controller.yaml."""
|
||||
mock_config_path.write_text("{}\n")
|
||||
self._write_wrolpi_yaml(test_config_directory, hotspot_device='wlp2s0', hotspot_ssid='RafaelPi',
|
||||
hotspot_password='password123')
|
||||
|
||||
with mock.patch("controller.lib.admin.get_media_directory", return_value=test_directory):
|
||||
migrate_hotspot_settings_from_wrolpi_config()
|
||||
|
||||
assert get_hotspot_device() == 'wlp2s0'
|
||||
assert get_hotspot_ssid() == 'RafaelPi'
|
||||
assert get_hotspot_password() == 'password123'
|
||||
# The migrated values are persisted in controller.yaml.
|
||||
saved = yaml.safe_load(mock_config_path.read_text())
|
||||
assert saved['hotspot'] == {'device': 'wlp2s0', 'ssid': 'RafaelPi', 'password': 'password123'}
|
||||
|
||||
def test_does_not_overwrite_explicit_controller_values(self, test_directory, test_config_directory,
|
||||
mock_config_path, reset_runtime_config):
|
||||
"""Explicit controller.yaml values win over legacy wrolpi.yaml values."""
|
||||
mock_config_path.write_text("hotspot:\n device: wlan1\n")
|
||||
reload_config_from_drive()
|
||||
self._write_wrolpi_yaml(test_config_directory, hotspot_device='wlp2s0', hotspot_ssid='RafaelPi')
|
||||
|
||||
with mock.patch("controller.lib.admin.get_media_directory", return_value=test_directory):
|
||||
migrate_hotspot_settings_from_wrolpi_config()
|
||||
|
||||
# The explicit device is kept, but the SSID is still migrated.
|
||||
assert get_hotspot_device() == 'wlan1'
|
||||
assert get_hotspot_ssid() == 'RafaelPi'
|
||||
|
||||
def test_noop_without_wrolpi_yaml(self, test_directory, test_config_directory, mock_config_path,
|
||||
reset_runtime_config):
|
||||
"""Nothing happens when wrolpi.yaml does not exist."""
|
||||
mock_config_path.write_text("{}\n")
|
||||
|
||||
with mock.patch("controller.lib.admin.get_media_directory", return_value=test_directory):
|
||||
migrate_hotspot_settings_from_wrolpi_config()
|
||||
|
||||
assert get_hotspot_device() == 'wlan0'
|
||||
assert yaml.safe_load(mock_config_path.read_text()) == {}
|
||||
|
||||
def test_noop_when_drive_not_mounted(self, test_directory, test_config_directory, mock_config_path,
|
||||
reset_runtime_config):
|
||||
"""Nothing happens when controller.yaml does not exist (drive not mounted)."""
|
||||
self._write_wrolpi_yaml(test_config_directory, hotspot_device='wlp2s0')
|
||||
|
||||
with mock.patch("controller.lib.admin.get_media_directory", return_value=test_directory):
|
||||
migrate_hotspot_settings_from_wrolpi_config()
|
||||
|
||||
assert get_hotspot_device() == 'wlan0'
|
||||
|
||||
|
||||
class TestUpdateHotspotSettings:
|
||||
"""Tests for update_hotspot_settings function."""
|
||||
|
||||
def test_updates_and_saves(self, mock_config_path, reset_runtime_config):
|
||||
"""New settings should be applied to the runtime config and saved to controller.yaml."""
|
||||
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
|
||||
result = update_hotspot_settings(device='wlp2s0', ssid='RafaelPi', password='password123')
|
||||
|
||||
assert result["success"] is True
|
||||
assert get_hotspot_device() == 'wlp2s0'
|
||||
saved = yaml.safe_load(mock_config_path.read_text())
|
||||
assert saved['hotspot'] == {'device': 'wlp2s0', 'ssid': 'RafaelPi', 'password': 'password123'}
|
||||
|
||||
def test_partial_update(self, mock_config_path, reset_runtime_config):
|
||||
"""Only provided values are changed."""
|
||||
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
|
||||
result = update_hotspot_settings(device='wlp2s0')
|
||||
|
||||
assert result["success"] is True
|
||||
assert result["device"] == 'wlp2s0'
|
||||
assert result["ssid"] == 'WROLPi'
|
||||
assert result["password"] == 'wrolpi hotspot'
|
||||
|
||||
def test_rejects_short_password(self, mock_config_path, reset_runtime_config):
|
||||
"""nmcli requires a WPA password of 8 to 63 characters."""
|
||||
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
|
||||
result = update_hotspot_settings(password='short')
|
||||
|
||||
assert result["success"] is False
|
||||
assert "8" in result["error"]
|
||||
assert get_hotspot_password() == 'wrolpi hotspot'
|
||||
|
||||
def test_rejects_in_docker_mode(self, reset_runtime_config):
|
||||
"""Hotspot settings cannot be changed in Docker mode."""
|
||||
with mock.patch("controller.lib.admin.is_docker_mode", return_value=True):
|
||||
result = update_hotspot_settings(device='wlp2s0')
|
||||
|
||||
assert result["success"] is False
|
||||
assert "Docker" in result["error"]
|
||||
|
||||
def test_error_when_drive_not_mounted(self, tmp_path, reset_runtime_config):
|
||||
"""Saving fails cleanly when the primary drive is not mounted."""
|
||||
missing_path = tmp_path / 'missing' / 'controller.yaml'
|
||||
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
|
||||
with mock.patch("controller.lib.config.CONFIG_PATH_ON_DRIVE", missing_path):
|
||||
result = update_hotspot_settings(device='wlp2s0')
|
||||
|
||||
assert result["success"] is False
|
||||
assert "not mounted" in result["error"]
|
||||
|
||||
|
||||
class TestGetWifiDevices:
|
||||
"""Tests for get_wifi_devices function."""
|
||||
|
||||
# Real terse nmcli output from an x86 PC: `nmcli -t -f DEVICE,TYPE device`
|
||||
NMCLI_TERSE_DEVICES = (
|
||||
"eno1:ethernet\n"
|
||||
"wlp2s0:wifi\n"
|
||||
"p2p-dev-wlp2s0:wifi-p2p\n"
|
||||
"lo:loopback\n"
|
||||
)
|
||||
|
||||
def test_returns_wifi_devices_only(self):
|
||||
"""Should return only wifi-type devices, excluding wifi-p2p and ethernet."""
|
||||
mock_result = mock.Mock(returncode=0, stdout=self.NMCLI_TERSE_DEVICES)
|
||||
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
|
||||
with mock.patch("subprocess.run", return_value=mock_result):
|
||||
assert get_wifi_devices() == ["wlp2s0"]
|
||||
|
||||
def test_returns_empty_in_docker_mode(self):
|
||||
"""Should return an empty list in Docker mode."""
|
||||
with mock.patch("controller.lib.admin.is_docker_mode", return_value=True):
|
||||
assert get_wifi_devices() == []
|
||||
|
||||
def test_returns_empty_when_nmcli_missing(self):
|
||||
"""Should return an empty list when nmcli is not installed."""
|
||||
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
|
||||
with mock.patch("subprocess.run", side_effect=FileNotFoundError()):
|
||||
assert get_wifi_devices() == []
|
||||
|
||||
def test_returns_empty_when_nmcli_fails(self):
|
||||
"""Should return an empty list when nmcli returns an error."""
|
||||
mock_result = mock.Mock(returncode=8, stdout="")
|
||||
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
|
||||
with mock.patch("subprocess.run", return_value=mock_result):
|
||||
assert get_wifi_devices() == []
|
||||
|
||||
|
||||
class TestDockerModeErrors:
|
||||
"""Admin functions should return an error result when running in Docker mode."""
|
||||
|
||||
|
|
|
|||
|
|
@ -34,6 +34,54 @@ class TestStatusEndpoints:
|
|||
assert data["available"] is False
|
||||
|
||||
|
||||
class TestHotspotDevicesEndpoint:
|
||||
"""GET /api/hotspot/devices lists WiFi interfaces for the Settings dropdown."""
|
||||
|
||||
def test_devices_endpoint_shape(self, test_client):
|
||||
"""Should return the WiFi devices found by nmcli."""
|
||||
from unittest import mock
|
||||
with mock.patch("controller.api.admin.get_wifi_devices", return_value=["wlan0", "wlp2s0"]):
|
||||
response = test_client.get("/api/hotspot/devices")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"devices": ["wlan0", "wlp2s0"]}
|
||||
|
||||
def test_devices_empty_in_docker(self, test_client_docker_mode):
|
||||
"""Should return an empty list in Docker mode."""
|
||||
response = test_client_docker_mode.get("/api/hotspot/devices")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"devices": []}
|
||||
|
||||
|
||||
class TestHotspotSettingsEndpoint:
|
||||
"""GET/POST /api/hotspot/settings manage hotspot settings in controller.yaml."""
|
||||
|
||||
def test_get_settings(self, test_client):
|
||||
"""Should return the current hotspot settings."""
|
||||
response = test_client.get("/api/hotspot/settings")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"device": "wlan0", "ssid": "WROLPi", "password": "wrolpi hotspot"}
|
||||
|
||||
def test_post_settings(self, test_client, mock_config_path):
|
||||
"""Should update settings and persist them to controller.yaml."""
|
||||
response = test_client.post(
|
||||
"/api/hotspot/settings",
|
||||
json={"device": "wlp2s0", "ssid": "RafaelPi", "password": "password123"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"device": "wlp2s0", "ssid": "RafaelPi", "password": "password123"}
|
||||
assert "wlp2s0" in mock_config_path.read_text()
|
||||
|
||||
def test_post_rejects_short_password(self, test_client, mock_config_path):
|
||||
"""Should reject a password shorter than 8 characters."""
|
||||
response = test_client.post("/api/hotspot/settings", json={"password": "short"})
|
||||
assert response.status_code == 400
|
||||
|
||||
def test_post_rejected_in_docker(self, test_client_docker_mode):
|
||||
"""Should reject settings changes in Docker mode."""
|
||||
response = test_client_docker_mode.post("/api/hotspot/settings", json={"device": "wlp2s0"})
|
||||
assert response.status_code == 500
|
||||
|
||||
|
||||
class TestDockerModeRejectsAdminActions:
|
||||
"""Admin action endpoints should reject requests when running in Docker."""
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue