"""gui_core_pkg.config - 配置文件读写。 - CONFIG_PATH config.json 绝对路径 - read_config 读取并返回 dict - write_config 深度合并写回(保留未传字段) - get_last_wifi_target 读上次成功连接的 WiFi 目标(ip:port / ip / 空) - set_last_wifi_target 写入上次成功连接的 WiFi 目标 - clear_last_wifi_target 清除记录 """ from __future__ import annotations import json import os import shutil from douyin.core import path_config CONFIG_PATH = path_config.get_config_path() def read_config() -> dict: if not os.path.exists(CONFIG_PATH): return {} with open(CONFIG_PATH, "r", encoding="utf-8") as f: return json.load(f) def write_config(cfg: dict) -> None: # GUI 表单通常只生成“已知字段”的子集;直接覆盖写会丢失其它键(例如 ROI rect/poly 等扩展配置)。 # 这里做一次 merge:保留原配置中的未知键,再用新 cfg 覆盖同名键。 merged = {} try: merged = read_config() if not isinstance(merged, dict): merged = {} except Exception: merged = {} try: if isinstance(cfg, dict): merged.update(cfg) except Exception: pass with open(CONFIG_PATH, "w", encoding="utf-8") as f: json.dump(merged, f, ensure_ascii=False, indent=4) f.write("\n") # ============================================================ # last_wifi_target 持久化(GUI 扫描成功后保存,下次启动自动重连) # ============================================================ _LAST_WIFI_KEY = "last_wifi_target" def get_last_wifi_target() -> dict: """返回上次成功连接的 WiFi 目标(dict);没有返回空 dict。 存储格式(在 config.json 顶层): "last_wifi_target": { "target": "192.168.5.2:5555", "model": "PEPM00", "saved_at": 1717000000 } """ try: cfg = read_config() except Exception: return {} if not isinstance(cfg, dict): return {} val = cfg.get(_LAST_WIFI_KEY) if isinstance(val, dict) and val.get("target"): return dict(val) return {} def set_last_wifi_target(target: str, model: str = "") -> None: """保存上次成功连接的 WiFi 目标。 target 必须是 ip:port 形式;空字符串等价于 clear_last_wifi_target。 """ target = (target or "").strip() if not target: clear_last_wifi_target() return import time try: write_config( { _LAST_WIFI_KEY: { "target": target, "model": (model or "").strip(), "saved_at": int(time.time()), } } ) except Exception: pass def clear_last_wifi_target() -> None: """从配置里删除 last_wifi_target 记录。""" try: cfg = read_config() except Exception: return if not isinstance(cfg, dict) or _LAST_WIFI_KEY not in cfg: return try: cfg.pop(_LAST_WIFI_KEY, None) # write_config 会做 merge,但 merge 不删键,所以这里直接覆盖写 with open(CONFIG_PATH, "w", encoding="utf-8") as f: json.dump(cfg, f, ensure_ascii=False, indent=4) f.write("\n") except Exception: pass