68 lines
2.4 KiB
Python
68 lines
2.4 KiB
Python
import json
|
|
import os
|
|
import socket
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def _resolve_config_file() -> Path:
|
|
"""Restituisce un percorso persistente e scrivibile per config.json (anche in binary PyInstaller)."""
|
|
if getattr(sys, "frozen", False):
|
|
exe_dir = Path(sys.executable).resolve().parent
|
|
candidate = exe_dir / "config.json"
|
|
if candidate.exists():
|
|
if os.access(candidate, os.W_OK):
|
|
return candidate
|
|
elif os.access(exe_dir, os.W_OK):
|
|
return candidate
|
|
|
|
# Fallback nella directory configurazione utente se la cartella dell'eseguibile è read-only
|
|
if sys.platform == "win32":
|
|
base_dir = Path(os.environ.get("APPDATA", Path.home())) / "BarcodeReaderServer"
|
|
else:
|
|
base_dir = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "barcode_reader_server"
|
|
return base_dir / "config.json"
|
|
|
|
return Path(__file__).resolve().parent / "config.json"
|
|
|
|
|
|
CONFIG_FILE = _resolve_config_file()
|
|
|
|
DEFAULT_CONFIG = {
|
|
"host": "0.0.0.0",
|
|
"port": 8765,
|
|
"udp_discovery_port": 8766,
|
|
"server_name": socket.gethostname(),
|
|
"pin": "", # Empty means no PIN required; or 4-digit code
|
|
"suffix": "enter", # "enter", "tab", "none" or custom string
|
|
"prefix": "",
|
|
"typing_delay": 0.005, # Delay between keystrokes in seconds
|
|
"mode": "type", # "type" or "paste"
|
|
"listening": True, # Whether the server actively processes and types barcodes
|
|
"minimize_to_tray": True, # Close/minimize button hides to system tray
|
|
"log_history": True,
|
|
}
|
|
|
|
|
|
def load_config() -> dict:
|
|
if CONFIG_FILE.exists():
|
|
try:
|
|
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
|
|
data = json.load(f)
|
|
config = {**DEFAULT_CONFIG, **data}
|
|
if not config.get("server_name"):
|
|
config["server_name"] = socket.gethostname()
|
|
return config
|
|
except Exception as e:
|
|
print(f"Avviso: Errore nella lettura di {CONFIG_FILE}: {e}. Uso configurazione predefinita.")
|
|
return DEFAULT_CONFIG.copy()
|
|
|
|
|
|
def save_config(config: dict) -> None:
|
|
try:
|
|
CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
|
json.dump(config, f, indent=4)
|
|
except Exception as e:
|
|
print(f"Errore nel salvataggio della configurazione: {e}")
|