Files
TurboSu/config/settings.py
T
AskaEth 858a5b4b93 feat: UDP data forwarding to multiple downstream devices
- DataForwarder class in listener: sends raw packets to all enabled targets
- REST API: GET/PUT /api/forward for managing targets
- Settings page: add/remove/edit forward targets with host/port/name/enabled
- Status endpoint includes forward_active count
- Config persisted in data/config.json via forward_targets array
2026-07-25 18:07:48 +08:00

70 lines
1.7 KiB
Python

from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Any
from utils.logger import get_logger
logger = get_logger(__name__)
DATA_DIR = Path(__file__).resolve().parent.parent / "data"
CONFIG_FILE = DATA_DIR / "config.json"
DEFAULT_CONFIG: dict[str, Any] = {
"selected_game_id": None,
"theme": "dark",
"sidebar_collapsed": False,
"telemetry_port": 20777,
"telemetry_host": "0.0.0.0",
"server_host": "0.0.0.0",
"server_port": 9527,
"forward_targets": [],
}
def load_config() -> dict[str, Any]:
if CONFIG_FILE.exists():
try:
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
cfg = json.load(f)
merged = {**DEFAULT_CONFIG, **cfg}
logger.info("Config loaded from %s", CONFIG_FILE)
return merged
except Exception as e:
logger.error("Failed to load config: %s", e)
logger.info("No config file found, using defaults")
return DEFAULT_CONFIG.copy()
def save_config(cfg: dict[str, Any]) -> None:
DATA_DIR.mkdir(parents=True, exist_ok=True)
try:
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
json.dump(cfg, f, indent=2, ensure_ascii=False)
logger.info("Config saved to %s", CONFIG_FILE)
except Exception as e:
logger.error("Failed to save config: %s", e)
_config_cache: dict[str, Any] | None = None
def get_config() -> dict[str, Any]:
global _config_cache
if _config_cache is None:
_config_cache = load_config()
return _config_cache
def update_config(key: str, value: Any) -> None:
cfg = get_config()
cfg[key] = value
save_config(cfg)
def reload_config() -> None:
global _config_cache
_config_cache = None