# Copyright (C) 2026 Seth Hillbrand # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """Preset management for YoloCam S3 camera settings. Presets are stored as JSON files in ~/.config/yolocam-gui/presets/. Each preset is a dict mapping parameter names to raw protocol values. """ import json import logging import os from pathlib import Path from typing import Any, Dict, List, Optional from yolocam.params import PARAMS, is_readable, is_writable log = logging.getLogger(__name__) PRESETS_DIR = Path(os.path.expanduser("~/.config/yolocam-gui/presets")) # Parameters to include in presets (readable + writable, skip device info and set-only) PRESET_PARAMS = [ name for name, pdef in PARAMS.items() if is_readable(pdef) and is_writable(pdef) ] DEFAULT_PRESET: Dict[str, int] = { "brightness": 50, "sharpness": 0, "contrast": 50, "saturation": 50, "hue": 50, "gamma": 50, "zoom": 50, "exposure-mode": 0, "exposure-ev": 8, "exposure-iso": 400, "exposure-time": 16666, "exposure-aperture": 10, "exposure-lock": 0, "anti-flicker": 0, "dynamic-range": 50, "hdr": 0, "wb-mode": 1, "wb-temp": 5500, "wb-temp-shift": 64, "wb-lock": 0, "focus-mode": 1, "focus-level": 0, "focus-caf": 0, "distortion": 0, "shading": 0, "au-volume": 50, "au-denoise": 0, "au-gain": 0, } class PresetManager: """Save, load, and apply camera parameter presets.""" def __init__(self, presets_dir: Optional[Path] = None): self._dir = presets_dir or PRESETS_DIR self._dir.mkdir(parents=True, exist_ok=True) def _preset_path(self, name: str) -> Path: safe_name = "".join(c if c.isalnum() or c in "-_ " else "_" for c in name) return self._dir / f"{safe_name}.json" def list_presets(self) -> List[str]: """Return sorted list of saved preset names.""" names = [] for p in self._dir.glob("*.json"): try: data = json.loads(p.read_text()) names.append(data.get("name", p.stem)) except (json.JSONDecodeError, OSError): continue return sorted(names) def save_preset(self, name: str, params: Dict[str, Any]) -> None: """Save a preset to disk.""" data = {"name": name, "params": params} path = self._preset_path(name) path.write_text(json.dumps(data, indent=2)) log.info("Saved preset '%s' to %s", name, path) def load_preset(self, name: str) -> Optional[Dict[str, Any]]: """Load a preset by name. Returns the params dict or None.""" path = self._preset_path(name) if not path.exists(): log.warning("Preset '%s' not found at %s", name, path) return None try: data = json.loads(path.read_text()) return data.get("params", {}) except (json.JSONDecodeError, OSError) as exc: log.error("Failed to load preset '%s': %s", name, exc) return None def delete_preset(self, name: str) -> bool: """Delete a saved preset. Returns True if deleted.""" path = self._preset_path(name) if not path.exists(): return False path.unlink() log.info("Deleted preset '%s'", name) return True def get_current_state(self, client: Any) -> Dict[str, Any]: """Read all preset-eligible parameters from the camera. The client argument is a CameraClient instance (import avoided to prevent circular deps). """ state: Dict[str, Any] = {} for name in PRESET_PARAMS: raw = client.get_param_raw(name) if raw is not None: state[name] = raw return state def apply_preset(self, client: Any, name: str) -> bool: """Load a preset and apply all its parameters to the camera. Returns True if the preset was found and applied (individual param failures are logged but do not fail the overall operation). """ params = self.load_preset(name) if params is None: if name == "Default": params = DEFAULT_PRESET else: return False success_count = 0 total = len(params) for param_name, value in params.items(): if param_name not in PARAMS: log.warning("Skipping unknown parameter in preset: %s", param_name) continue if client.set_param(param_name, value): success_count += 1 else: log.warning("Failed to set %s=%s from preset '%s'", param_name, value, name) log.info("Applied preset '%s': %d/%d parameters set", name, success_count, total) return True def save_default(self) -> None: """Write the built-in Default preset to disk.""" self.save_preset("Default", DEFAULT_PRESET)