From 6a54cdae71b01a793fb2d6eb1cea3e36bff8ef58 Mon Sep 17 00:00:00 2001 From: Yule Date: Thu, 10 Sep 2026 09:12:12 +0800 Subject: [PATCH] =?UTF-8?q?feat(go):=20=E6=96=B0=E5=A2=9E=20JSON=20API=20?= =?UTF-8?q?=E4=BE=9B=20WebUI=20=E4=BD=BF=E7=94=A8=EF=BC=8Coplock/state=20?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=20JSON?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - internal/api:状态聚合(status)、操作锁读写与自愈、daemon 运行状态、 日志读取解析、module.prop 解析与通道判定 - status 一次调用取代原先 5~6 条 shell 命令;--no-display 跳过 dumpsys/settings - oplock 文件改为 JSON 并带 kind(ramp/boost/restart/manual), WebUI 可显示具体操作文案;兼容旧版裸 PID 格式 - daemon 维护 pid/state.json(模式、最近事件/操作、缓存的比率与亮度) - 新子命令:status / oplock / brightness set / config read|patch(stdin) / log tail|clear|export;config patch 走 stdin 并严格校验类型 - pid/inotifyd.pid → pid/daemon.pid;清理 action.sh 死标记、统一文案 --- action.sh | 6 +- customize.sh | 4 +- go/cmd/luminpro/main.go | 194 +++++++++++++++-- go/internal/api/api_test.go | 343 ++++++++++++++++++++++++++++++ go/internal/api/log.go | 117 ++++++++++ go/internal/api/oplock.go | 149 +++++++++++++ go/internal/api/paths.go | 47 ++++ go/internal/api/state.go | 85 ++++++++ go/internal/api/status.go | 271 +++++++++++++++++++++++ go/internal/config/config.go | 66 ++++-- go/internal/config/config_test.go | 105 +++++++++ go/internal/daemon/daemon.go | 157 +++++++++----- go/internal/daemon/daemon_test.go | 11 +- go/internal/daemon/ops.go | 31 +-- service.sh | 2 +- 15 files changed, 1471 insertions(+), 117 deletions(-) create mode 100644 go/internal/api/api_test.go create mode 100644 go/internal/api/log.go create mode 100644 go/internal/api/oplock.go create mode 100644 go/internal/api/paths.go create mode 100644 go/internal/api/state.go create mode 100644 go/internal/api/status.go diff --git a/action.sh b/action.sh index e12f263..9d920e9 100644 --- a/action.sh +++ b/action.sh @@ -1,18 +1,16 @@ #!/system/bin/sh -# 快速切换脚本 +#shellcheck shell=ash +# 快速启停切换(管理器「操作」按钮 / WebUI 调用) MODDIR="/data/adb/modules/LuminPro" PID_DIR="$MODDIR/pid" STOP_FLAG="$PID_DIR/stop.flag" -UP_FLAG="$PID_DIR/up.flag" -# 切换逻辑 if [ -f "$STOP_FLAG" ]; then rm -f "$STOP_FLAG" echo "LuminPro: 服务已启用" else touch "$STOP_FLAG" - rm -f "$UP_FLAG" echo "LuminPro: 服务已暂停" fi diff --git a/customize.sh b/customize.sh index 5250512..19c0e75 100755 --- a/customize.sh +++ b/customize.sh @@ -246,7 +246,7 @@ CHECK_DEVICE_COMPATIBILITY() { if [ "$prefix" = "25128PNA1" ] || [ "$prefix" = "2512BPNDA" ]; then echo "" echo " ✿ 您可能是 Xiaomi 17 Ultra 用户,建议使用 '0' 事件作为监测对象" - echo " ✿ 是否将 inotifyd 监测事件修改为 '0'? (音量 + 确认,音量 - 跳过)" + echo " ✿ 是否将监听事件修改为 '0'? (音量 + 确认,音量 - 跳过)" if [ "$(btn)" = "0" ]; then "$BIN" config set inotify_events=0 >/dev/null 2>&1 echo " ✦ 已设置为 0 事件监测" @@ -327,7 +327,7 @@ END() { else echo " - 休眠时段: 未配置" fi - echo " - inotifyd 事件: $inotify" + echo " - 监听事件: $inotify" echo " - 当前亮度节点: $now_path" echo " - 最大亮度节点: $max_path" [ ! -f "$now_path" ] && echo " ⚠ 当前亮度节点不存在, 重启后功能将不会启用" diff --git a/go/cmd/luminpro/main.go b/go/cmd/luminpro/main.go index 8b815d9..e0e67aa 100644 --- a/go/cmd/luminpro/main.go +++ b/go/cmd/luminpro/main.go @@ -2,11 +2,19 @@ package main import ( + "encoding/json" + "errors" "fmt" + "io" "os" "path/filepath" "sort" + "strconv" + "strings" + "time" + "github.com/YuleBest/LuminPro/go/internal/api" + "github.com/YuleBest/LuminPro/go/internal/brightness" "github.com/YuleBest/LuminPro/go/internal/config" "github.com/YuleBest/LuminPro/go/internal/daemon" "github.com/YuleBest/LuminPro/go/internal/logging" @@ -28,7 +36,7 @@ func run(args []string) error { if err != nil { return err } - paths := daemon.DefaultPaths(moduleDir) + paths := api.DefaultPaths(moduleDir) log := logging.New(paths.LogFile, config.DefaultLogLevel, config.DefaultLogMaxSize) switch args[0] { @@ -51,8 +59,16 @@ func run(args []string) error { return err } return daemon.Restart(paths, self, log) + case "status": + return runStatus(paths, args[1:]) + case "oplock": + return emitJSON(api.ReadOplock(paths.Oplock)) + case "brightness": + return runBrightness(paths, args[1:]) case "config": return runConfig(paths, args[1:]) + case "log": + return runLog(paths, args[1:]) case "help", "-h", "--help": return usage() default: @@ -64,16 +80,20 @@ func usage() error { fmt.Print(`luminpro - LuminPro 模块守护进程 用法: - luminpro daemon 启动守护进程(监听亮度节点并自动提升) - luminpro boost 一键提升到峰值亮度 / 再次调用恢复 - luminpro restart 重启模块(daemon 未运行时按需拉起) - luminpro config <操作> 配置管理 - init 写入默认配置(已存在则补齐字段) - ensure 补齐缺失字段 - set key=value [...] 写入字段(按字段类型编码) - inspect <旧目录> 输出旧配置字段(key=value 行) - migrate <旧目录> [目标] 迁移旧配置 - remove-old-txt <旧目录> 删除旧版 txt 配置 + luminpro daemon 启动守护进程(监听亮度节点并自动提升) + luminpro boost 一键提升到峰值亮度 / 再次调用恢复 + luminpro restart 重启模块(daemon 未运行时按需拉起) + + luminpro status [--no-display] 聚合状态(JSON) + luminpro oplock 操作锁状态(JSON) + luminpro brightness set <值> 设置亮度(JSON) + + luminpro config <操作> 配置管理(JSON) + read | patch(stdin JSON) | get | set k=v [...] | summary + init | ensure | inspect <旧目录> | migrate <旧目录> [目标] | remove-old-txt <旧目录> + + luminpro log <操作> + tail [-n 行数] [--raw] | clear | export [目录] 模块目录默认由可执行文件位置推导,可用环境变量 LUMINPRO_MODDIR 覆盖(调试用)。 `) @@ -95,7 +115,116 @@ func resolveModuleDir() (string, error) { return filepath.Dir(filepath.Dir(exe)), nil } -func runConfig(paths daemon.Paths, args []string) error { +// emitJSON 输出 JSON(不转义 HTML,供前端直接解析)。 +func emitJSON(v any) error { + enc := json.NewEncoder(os.Stdout) + enc.SetEscapeHTML(false) + return enc.Encode(v) +} + +func runStatus(paths api.Paths, args []string) error { + includeDisplay := true + for _, arg := range args { + if arg == "--no-display" { + includeDisplay = false + } + } + cfg, err := config.Load(paths.ConfigFile) + if err != nil { + return err + } + status := api.BuildStatus(paths, cfg, api.StatusDeps{ + AutoBrightness: system.AutoBrightness{Runner: system.ExecRunner{}}, + HDR: system.HdrRatio{Runner: system.ExecRunner{}}, + Now: time.Now, + }, api.StatusOptions{IncludeDisplay: includeDisplay}) + return emitJSON(status) +} + +func runBrightness(paths api.Paths, args []string) error { + if len(args) < 2 || args[0] != "set" { + return errors.New("用法: luminpro brightness set <值>") + } + value, err := strconv.Atoi(strings.TrimSpace(args[1])) + if err != nil { + return fmt.Errorf("亮度值必须是整数: %q", args[1]) + } + if value < 0 { + return errors.New("亮度值不能为负") + } + cfg, err := config.Load(paths.ConfigFile) + if err != nil { + return err + } + if max, err := brightness.ReadInt(cfg.MaxBriFile); err == nil && max > 0 && value > max { + return fmt.Errorf("亮度值需在 0~%d 之间", max) + } + if !api.FileExists(cfg.NowBriFile) { + return fmt.Errorf("亮度节点不存在: %s", cfg.NowBriFile) + } + + if err := os.MkdirAll(paths.PIDDir, 0o755); err != nil { + return err + } + if err := api.WriteOplock(paths.Oplock, api.KindManual); err != nil { + return err + } + defer api.RemoveOplock(paths.Oplock) + + if err := brightness.WriteInt(cfg.NowBriFile, value); err != nil { + return err + } + return emitJSON(map[string]any{"ok": true, "value": value}) +} + +func runLog(paths api.Paths, args []string) error { + if len(args) == 0 { + return errors.New("用法: luminpro log tail|clear|export") + } + switch args[0] { + case "tail": + lines, raw := 100, false + for i := 1; i < len(args); i++ { + switch { + case args[i] == "--raw": + raw = true + case args[i] == "-n" && i+1 < len(args): + if n, err := strconv.Atoi(args[i+1]); err == nil { + lines = n + } + i++ + case strings.HasPrefix(args[i], "-n="): + if n, err := strconv.Atoi(strings.TrimPrefix(args[i], "-n=")); err == nil { + lines = n + } + } + } + page, err := api.TailLog(paths.LogFile, lines, raw) + if err != nil { + return err + } + return emitJSON(page) + case "clear": + if err := api.ClearLog(paths.LogFile); err != nil { + return err + } + return emitJSON(map[string]any{"ok": true}) + case "export": + dir := "/sdcard" + if len(args) > 1 { + dir = args[1] + } + path, err := api.ExportLog(paths.LogFile, dir) + if err != nil { + return err + } + return emitJSON(map[string]any{"ok": true, "path": path}) + default: + return fmt.Errorf("未知 log 操作: %s", args[0]) + } +} + +func runConfig(paths api.Paths, args []string) error { if len(args) == 0 { return usage() } @@ -104,14 +233,41 @@ func runConfig(paths daemon.Paths, args []string) error { return config.Init(paths.ConfigFile) case "ensure": return config.Ensure(paths.ConfigFile) + case "read": + cfg, err := config.Load(paths.ConfigFile) + if err != nil { + return err + } + data, err := cfg.JSON() + if err != nil { + return err + } + _, err = os.Stdout.Write(append(data, '\n')) + return err + case "patch": + input, err := io.ReadAll(os.Stdin) + if err != nil { + return err + } + var patch map[string]json.RawMessage + if err := json.Unmarshal(input, &patch); err != nil { + return fmt.Errorf("补丁必须是 JSON 对象: %w", err) + } + if err := config.Patch(paths.ConfigFile, patch); err != nil { + return err + } + return emitJSON(map[string]any{"ok": true, "patched": len(patch)}) case "set": if len(args) < 2 { - return fmt.Errorf("set 需要至少一个 key=value") + return errors.New("set 需要至少一个 key=value") } - return config.Set(paths.ConfigFile, args[1:]) + if err := config.Set(paths.ConfigFile, args[1:]); err != nil { + return err + } + return emitJSON(map[string]any{"ok": true}) case "get": if len(args) < 2 { - return fmt.Errorf("get 需要字段名") + return errors.New("get 需要字段名") } cfg, err := config.Load(paths.ConfigFile) if err != nil { @@ -132,17 +288,17 @@ func runConfig(paths daemon.Paths, args []string) error { return nil case "inspect": if len(args) < 2 { - return fmt.Errorf("inspect 需要旧配置目录") + return errors.New("inspect 需要旧配置目录") } old, ok := config.InspectOld(args[1]) if !ok { - return fmt.Errorf("未找到可迁移的旧配置") + return errors.New("未找到可迁移的旧配置") } printOld(old) return nil case "migrate": if len(args) < 2 { - return fmt.Errorf("migrate 需要旧配置目录") + return errors.New("migrate 需要旧配置目录") } target := paths.ConfigFile if len(args) >= 3 { @@ -156,7 +312,7 @@ func runConfig(paths daemon.Paths, args []string) error { return nil case "remove-old-txt": if len(args) < 2 { - return fmt.Errorf("remove-old-txt 需要旧配置目录") + return errors.New("remove-old-txt 需要旧配置目录") } return config.RemoveOldTxt(args[1]) default: diff --git a/go/internal/api/api_test.go b/go/internal/api/api_test.go new file mode 100644 index 0000000..79f5a8d --- /dev/null +++ b/go/internal/api/api_test.go @@ -0,0 +1,343 @@ +package api + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "strconv" + "sync" + "testing" + "time" + + "github.com/YuleBest/LuminPro/go/internal/config" + "github.com/YuleBest/LuminPro/go/internal/system" +) + +// scriptRunner 是可编程的命令假实现。 +type scriptRunner struct { + mu sync.Mutex + outputs map[string]string +} + +func (r *scriptRunner) Output(name string, args ...string) (string, error) { + r.mu.Lock() + defer r.mu.Unlock() + key := name + for _, a := range args { + key += " " + a + } + if v, ok := r.outputs[key]; ok { + return v, nil + } + return "", errors.New("no output") +} + +func TestParseLogLine(t *testing.T) { + cases := []struct { + line string + want LogEntry + }{ + { + "[09-10 12:34:56] [luminpro] [INFO] 触发提升", + LogEntry{Time: "09-10 12:34:56", Tag: "luminpro", Level: "INFO", Message: "触发提升"}, + }, + { + "[09-10 12:34:56] [luminpro] [SUCCESS] 亮度提升完成 (3000)", + LogEntry{Time: "09-10 12:34:56", Tag: "luminpro", Level: "SUCCESS", Message: "亮度提升完成 (3000)"}, + }, + { + "没有格式的一行", + LogEntry{Message: "没有格式的一行"}, + }, + } + for _, tc := range cases { + if got := ParseLogLine(tc.line); got != tc.want { + t.Errorf("ParseLogLine(%q) = %+v, 期望 %+v", tc.line, got, tc.want) + } + } +} + +func TestTailLog(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "service.log") + content := "[09-10 12:00:00] [luminpro] [INFO] 第一条\n" + + "[09-10 12:00:01] [luminpro] [WARN] 第二条\n" + + "[09-10 12:00:02] [luminpro] [ERROR] 第三条\n" + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + + page, err := TailLog(path, 2, false) + if err != nil { + t.Fatal(err) + } + if page.Total != 3 || len(page.Entries) != 2 { + t.Fatalf("应取末 2 条(共 3 条): total=%d len=%d", page.Total, len(page.Entries)) + } + if page.Entries[0].Level != "WARN" || page.Entries[1].Message != "第三条" { + t.Fatalf("条目内容不正确: %+v", page.Entries) + } + + raw, err := TailLog(path, 1, true) + if err != nil { + t.Fatal(err) + } + if raw.Raw == "" || len(raw.Entries) != 0 { + t.Fatalf("--raw 模式应只返回原文: %+v", raw) + } + + missing, err := TailLog(filepath.Join(dir, "不存在.log"), 10, false) + if err != nil || len(missing.Entries) != 0 { + t.Fatalf("缺失文件应返回空页且不报错: %+v %v", missing, err) + } +} + +func TestClearAndExportLog(t *testing.T) { + dir := t.TempDir() + src := filepath.Join(dir, "service.log") + if err := os.WriteFile(src, []byte("data\n"), 0o644); err != nil { + t.Fatal(err) + } + outDir := filepath.Join(dir, "out") + if err := os.Mkdir(outDir, 0o755); err != nil { + t.Fatal(err) + } + + path, err := ExportLog(src, outDir) + if err != nil { + t.Fatal(err) + } + if data, err := os.ReadFile(path); err != nil || string(data) != "data\n" { + t.Fatalf("导出内容不正确: %q %v", string(data), err) + } + if _, err := ExportLog(src, filepath.Join(dir, "缺失目录")); err == nil { + t.Fatal("导出目录不可用时应报错") + } + + if err := ClearLog(src); err != nil { + t.Fatal(err) + } + if data, _ := os.ReadFile(src); len(data) != 0 { + t.Fatalf("清空后应为空文件: %q", string(data)) + } +} + +func TestOplockLifecycle(t *testing.T) { + path := filepath.Join(t.TempDir(), "oplock") + + if got := ReadOplock(path); got.Locked { + t.Fatal("无锁文件应返回未锁定") + } + + if err := WriteOplock(path, KindRamp); err != nil { + t.Fatal(err) + } + got := ReadOplock(path) + if !got.Locked || got.PID != os.Getpid() || got.Kind != KindRamp { + t.Fatalf("锁状态不正确: %+v", got) + } + if got.Label != "正在调整亮度" { + t.Fatalf("锁文案不正确: %q", got.Label) + } + + RemoveOplock(path) + if got := ReadOplock(path); got.Locked { + t.Fatal("释放后应返回未锁定") + } +} + +// 遗留锁(持锁进程已死)应被就地清理。 +func TestOplockSelfHeals(t *testing.T) { + path := filepath.Join(t.TempDir(), "oplock") + if err := os.WriteFile(path, []byte(`{"pid":999999,"kind":"ramp","startedAt":1}`), 0o644); err != nil { + t.Fatal(err) + } + if got := ReadOplock(path); got.Locked { + t.Fatal("进程已死的锁应视为未锁定") + } + if _, err := os.Stat(path); err == nil { + t.Fatal("遗留锁文件应被清理") + } +} + +// 兼容旧版裸 PID 格式的锁文件。 +func TestOplockLegacyFormat(t *testing.T) { + path := filepath.Join(t.TempDir(), "oplock") + if err := os.WriteFile(path, []byte(strconv.Itoa(os.Getpid())), 0o644); err != nil { + t.Fatal(err) + } + got := ReadOplock(path) + if !got.Locked || got.PID != os.Getpid() { + t.Fatalf("旧格式应可识别: %+v", got) + } + + if err := os.WriteFile(path, []byte("garbage"), 0o644); err != nil { + t.Fatal(err) + } + if got := ReadOplock(path); got.Locked { + t.Fatal("无法解析的内容应视为未锁定") + } +} + +func TestChannelOf(t *testing.T) { + cases := map[string]string{ + "V2.5.0": "stable", + "V2.5.0-beta.1": "beta", + "V2.5.0-Beta.2": "beta", + "V2.5.0-dev.3": "dev", + "V2.4-2401": "stable", + } + for version, want := range cases { + if got := ChannelOf(version); got != want { + t.Errorf("ChannelOf(%q) = %q, 期望 %q", version, got, want) + } + } +} + +func TestReadModuleInfo(t *testing.T) { + dir := t.TempDir() + prop := "id=LuminPro\nname=LuminPro丨测试\nversion=V2.5.0-beta.2\nversionCode=2050052\n" + if err := os.WriteFile(filepath.Join(dir, "module.prop"), []byte(prop), 0o644); err != nil { + t.Fatal(err) + } + info := ReadModuleInfo(dir) + if info.ID != "LuminPro" || info.Version != "V2.5.0-beta.2" || info.VersionCode != 2050052 || info.Channel != "beta" { + t.Fatalf("module.prop 解析不正确: %+v", info) + } + // 缺失文件时回退默认值 + if info := ReadModuleInfo(filepath.Join(dir, "不存在")); info.Channel != "stable" { + t.Fatalf("缺失 module.prop 应回退 stable: %+v", info) + } +} + +func TestBuildStatus(t *testing.T) { + dir := t.TempDir() + paths := DefaultPaths(dir) + if err := os.MkdirAll(paths.PIDDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(paths.ConfigFile), 0o755); err != nil { + t.Fatal(err) + } + + node := filepath.Join(dir, "brightness") + maxNode := filepath.Join(dir, "max_brightness") + if err := os.WriteFile(node, []byte("1200"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(maxNode, []byte("4000"), 0o644); err != nil { + t.Fatal(err) + } + + cfg := config.Default() + cfg.NowBriFile = node + cfg.MaxBriFile = maxNode + cfg.UIMaxBri = 1000 + cfg.MaxBri = 3000 + cfg.SleepTime = "2300-0700" + cfg.BlacklistApps = []string{"com.a"} + if err := cfg.Save(paths.ConfigFile); err != nil { + t.Fatal(err) + } + + // daemon 状态 + if err := os.WriteFile(paths.PIDFile, []byte(strconv.Itoa(os.Getpid())), 0o644); err != nil { + t.Fatal(err) + } + if err := WriteState(paths.StateFile, DaemonState{ + PID: os.Getpid(), + StartedAt: time.Now().Add(-90 * time.Second).Unix(), + Mode: "event", + Ratio: &RatioInfo{Value: 1.08, At: time.Now().Unix()}, + HdrSleep: true, + }); err != nil { + t.Fatal(err) + } + if err := WriteOplock(paths.Oplock, KindRamp); err != nil { + t.Fatal(err) + } + + runner := &scriptRunner{outputs: map[string]string{ + "settings get system screen_brightness_mode": "1\n", + "dumpsys display": "hdrSdrRatio 1.02\n", + }} + status := BuildStatus(paths, cfg, StatusDeps{ + AutoBrightness: system.AutoBrightness{Runner: runner}, + HDR: system.HdrRatio{Runner: runner}, + Now: func() time.Time { return time.Date(2026, 9, 10, 12, 0, 0, 0, time.Local) }, + }, StatusOptions{IncludeDisplay: true}) + + if status.Module.Version != "" && status.Module.Channel != "stable" { + t.Fatalf("模块信息不正确: %+v", status.Module) + } + if !status.Daemon.Running || status.Daemon.PID != os.Getpid() || status.Daemon.Mode != "event" { + t.Fatalf("daemon 状态不正确: %+v", status.Daemon) + } + if status.Daemon.UptimeSec < 80 { + t.Fatalf("运行时长计算不正确: %d", status.Daemon.UptimeSec) + } + if status.Brightness.Current != 1200 || status.Brightness.Max != 4000 || status.Brightness.Percent != 30 { + t.Fatalf("亮度信息不正确: %+v", status.Brightness) + } + if status.Sleep.Window != "2300-0700" || status.Sleep.Active { + t.Fatalf("休眠状态不正确: %+v", status.Sleep) + } + if !status.Oplock.Locked || status.Oplock.Kind != KindRamp { + t.Fatalf("操作锁不正确: %+v", status.Oplock) + } + if status.Config.UIMaxBri != 1000 || status.Config.BlacklistCount != 1 { + t.Fatalf("配置摘要不正确: %+v", status.Config) + } + if status.Display == nil || status.Display.HdrRatio != 1.02 || !status.Display.HdrKnown || !status.Display.AutoBrightness || !status.Display.HdrSleep { + t.Fatalf("显示信息不正确: %+v", status.Display) + } + + // --no-display:不调用 dumpsys/settings,改用 daemon 缓存 + light := BuildStatus(paths, cfg, StatusDeps{ + AutoBrightness: system.AutoBrightness{Runner: runner}, + HDR: system.HdrRatio{Runner: runner}, + }, StatusOptions{IncludeDisplay: false}) + if light.Display != nil { + t.Fatalf("--no-display 不应包含显示信息: %+v", light.Display) + } + + // JSON 可序列化 + if _, err := json.Marshal(light); err != nil { + t.Fatalf("状态无法序列化: %v", err) + } +} + +// dumpsys 读取失败时回退到 daemon 缓存并标记 stale。 +func TestBuildStatusFallsBackToCachedRatio(t *testing.T) { + dir := t.TempDir() + paths := DefaultPaths(dir) + if err := os.MkdirAll(paths.PIDDir, 0o755); err != nil { + t.Fatal(err) + } + node := filepath.Join(dir, "brightness") + if err := os.WriteFile(node, []byte("500"), 0o644); err != nil { + t.Fatal(err) + } + cfg := config.Default() + cfg.NowBriFile = node + if err := cfg.Save(paths.ConfigFile); err != nil { + t.Fatal(err) + } + if err := WriteState(paths.StateFile, DaemonState{ + PID: os.Getpid(), + Ratio: &RatioInfo{Value: 1.30, At: time.Now().Unix()}, + }); err != nil { + t.Fatal(err) + } + + runner := &scriptRunner{outputs: map[string]string{}} // 全部失败 + status := BuildStatus(paths, cfg, StatusDeps{ + AutoBrightness: system.AutoBrightness{Runner: runner}, + HDR: system.HdrRatio{Runner: runner}, + }, StatusOptions{IncludeDisplay: true}) + + if status.Display == nil || !status.Display.HdrKnown || !status.Display.HdrStale || status.Display.HdrRatio != 1.30 { + t.Fatalf("应回退到缓存的比率并标记 stale: %+v", status.Display) + } +} diff --git a/go/internal/api/log.go b/go/internal/api/log.go new file mode 100644 index 0000000..1e8b2a3 --- /dev/null +++ b/go/internal/api/log.go @@ -0,0 +1,117 @@ +package api + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "time" +) + +// LogEntry 是一条结构化日志。 +type LogEntry struct { + Time string `json:"time"` + Tag string `json:"tag"` + Level string `json:"level"` + Message string `json:"message"` +} + +// LogPage 是 log tail 的输出。 +type LogPage struct { + Entries []LogEntry `json:"entries"` + Raw string `json:"raw,omitempty"` + SizeKB int `json:"sizeKB"` + Total int `json:"total"` +} + +// ParseLogLine 解析 `[09-10 12:34:56] [luminpro] [INFO] msg`。 +// 不匹配时整行作为 message,level/tag 留空,前端可原样展示。 +func ParseLogLine(line string) LogEntry { + rest := line + var entry LogEntry + + if strings.HasPrefix(rest, "[") { + if end := strings.Index(rest, "]"); end > 0 { + entry.Time = strings.TrimSpace(rest[1:end]) + rest = strings.TrimSpace(rest[end+1:]) + } + } + if strings.HasPrefix(rest, "[") { + if end := strings.Index(rest, "]"); end > 0 { + entry.Tag = strings.TrimSpace(rest[1:end]) + rest = strings.TrimSpace(rest[end+1:]) + } + } + if strings.HasPrefix(rest, "[") { + if end := strings.Index(rest, "]"); end > 0 { + entry.Level = strings.ToUpper(strings.TrimSpace(rest[1:end])) + rest = strings.TrimSpace(rest[end+1:]) + } + } + entry.Message = rest + return entry +} + +// TailLog 读取日志末尾若干行。 +func TailLog(path string, lines int, raw bool) (LogPage, error) { + page := LogPage{Entries: []LogEntry{}} + + data, err := os.ReadFile(path) + if err != nil { + if os.IsNotExist(err) { + return page, nil + } + return page, err + } + page.SizeKB = int(int64(len(data)) / 1024) + + text := strings.TrimRight(string(data), "\n") + if text == "" { + return page, nil + } + all := strings.Split(text, "\n") + page.Total = len(all) + + if lines > 0 && len(all) > lines { + all = all[len(all)-lines:] + } + if raw { + page.Raw = strings.Join(all, "\n") + return page, nil + } + for _, line := range all { + page.Entries = append(page.Entries, ParseLogLine(line)) + } + return page, nil +} + +// ClearLog 清空日志文件。 +func ClearLog(path string) error { + return os.WriteFile(path, nil, 0o644) +} + +// ExportLog 把日志复制到目标目录,返回最终路径。 +func ExportLog(src, dir string) (string, error) { + if dir == "" { + dir = "/sdcard" + } + if info, err := os.Stat(dir); err != nil || !info.IsDir() { + return "", fmt.Errorf("导出目录不可用: %s", dir) + } + name := fmt.Sprintf("LuminPro_%s.log", time.Now().Format("20060102_150405")) + dst := filepath.Join(dir, name) + + data, err := os.ReadFile(src) + if err != nil { + return "", err + } + if err := os.WriteFile(dst, data, 0o644); err != nil { + return "", err + } + return dst, nil +} + +// FormatLogEntry 反向格式化,供需要时使用。 +func FormatLogEntry(e LogEntry) string { + return fmt.Sprintf("[%s] [%s] [%s] %s", e.Time, e.Tag, e.Level, e.Message) +} diff --git a/go/internal/api/oplock.go b/go/internal/api/oplock.go new file mode 100644 index 0000000..5c738c2 --- /dev/null +++ b/go/internal/api/oplock.go @@ -0,0 +1,149 @@ +package api + +import ( + "encoding/json" + "os" + "strconv" + "strings" + "time" +) + +// 操作锁类型,用于前端显示更具体的提示文案。 +const ( + KindRamp = "ramp" // 亮度渐变写入 + KindBoost = "boost" // 一键峰值 / 恢复 + KindRestart = "restart" // 重启模块 + KindManual = "manual" // 前端手动设置亮度 +) + +// OplockFile 是 pid/oplock 的内容。 +type OplockFile struct { + PID int `json:"pid"` + Kind string `json:"kind"` + StartedAt int64 `json:"startedAt"` +} + +// OplockStatus 是给前端的操作锁状态。 +type OplockStatus struct { + Locked bool `json:"locked"` + PID int `json:"pid,omitempty"` + Kind string `json:"kind,omitempty"` + Label string `json:"label,omitempty"` + Seconds int `json:"seconds"` +} + +// KindLabel 返回操作类型的中文说明。 +func KindLabel(kind string) string { + switch kind { + case KindRamp: + return "正在调整亮度" + case KindBoost: + return "正在执行一键提升" + case KindRestart: + return "正在重启模块" + case KindManual: + return "正在设置亮度" + default: + return "正在执行后台操作" + } +} + +// WriteOplock 写入操作锁(持锁进程把自己的 PID 与操作类型写进去)。 +func WriteOplock(path, kind string) error { + info := OplockFile{PID: os.Getpid(), Kind: kind, StartedAt: time.Now().Unix()} + data, err := json.Marshal(info) + if err != nil { + return err + } + return os.WriteFile(path, data, 0o644) +} + +// RemoveOplock 释放操作锁。 +func RemoveOplock(path string) { + _ = os.Remove(path) +} + +// ReadOplock 读取并校验操作锁;持锁进程已不存在时视为遗留锁并就地清理。 +func ReadOplock(path string) OplockStatus { + data, err := os.ReadFile(path) + if err != nil { + return OplockStatus{} + } + text := strings.TrimSpace(string(data)) + if text == "" { + _ = os.Remove(path) + return OplockStatus{} + } + + var info OplockFile + if err := json.Unmarshal([]byte(text), &info); err != nil { + // 兼容旧版裸 PID 格式 + if pid, perr := strconv.Atoi(text); perr == nil { + info = OplockFile{PID: pid} + } else { + _ = os.Remove(path) + return OplockStatus{} + } + } + + if info.PID <= 0 || !ProcessAlive(info.PID) { + _ = os.Remove(path) // 遗留锁:进程已被 SIGKILL 等 + return OplockStatus{} + } + + seconds := 0 + if info.StartedAt > 0 { + if d := time.Now().Unix() - info.StartedAt; d > 0 { + seconds = int(d) + } + } + return OplockStatus{ + Locked: true, + PID: info.PID, + Kind: info.Kind, + Label: KindLabel(info.Kind), + Seconds: seconds, + } +} + +// ProcessAlive 通过 /proc 判断进程是否存活。 +func ProcessAlive(pid int) bool { + if pid <= 0 { + return false + } + _, err := os.Stat("/proc/" + strconv.Itoa(pid)) + return err == nil +} + +// DaemonPID 读取 daemon PID 文件并确认进程存活。 +func DaemonPID(pidFile string) (int, bool) { + data, err := os.ReadFile(pidFile) + if err != nil { + return 0, false + } + pid, err := strconv.Atoi(strings.TrimSpace(string(data))) + if err != nil || pid <= 0 { + return 0, false + } + if !ProcessAlive(pid) { + return 0, false + } + return pid, true +} + +// ProcessState 读取 /proc//status 的状态字符(R/S/D/Z/T/I)。 +func ProcessState(pid int) string { + data, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/status") + if err != nil { + return "" + } + for _, line := range strings.Split(string(data), "\n") { + if strings.HasPrefix(line, "State:") { + fields := strings.Fields(line) + if len(fields) >= 2 { + return fields[1] + } + } + } + return "" +} diff --git a/go/internal/api/paths.go b/go/internal/api/paths.go new file mode 100644 index 0000000..f4ef1f9 --- /dev/null +++ b/go/internal/api/paths.go @@ -0,0 +1,47 @@ +// Package api 提供 WebUI 使用的 JSON API:状态聚合、操作锁、daemon 运行状态与日志读取。 +// +// 设计目标:把过去前端要跑 5~6 条 shell 命令(cat /proc、dumpsys、settings、读节点) +// 才能拿到的信息合并成一次调用,并让所有写操作走 argv/stdin 而不是拼接 shell 字符串。 +package api + +import ( + "os" + "path/filepath" +) + +// Paths 是模块内的文件布局(与 WebUI 的契约)。 +type Paths struct { + ModuleDir string + PIDDir string + ConfigFile string + LogFile string + PIDFile string + StopFlag string + PauseFlag string + Oplock string + BoostFlag string + StateFile string +} + +// DefaultPaths 按模块目录推导全部路径。 +func DefaultPaths(moduleDir string) Paths { + pidDir := filepath.Join(moduleDir, "pid") + return Paths{ + ModuleDir: moduleDir, + PIDDir: pidDir, + ConfigFile: filepath.Join(moduleDir, "config", "config.json"), + LogFile: filepath.Join(moduleDir, "service.log"), + PIDFile: filepath.Join(pidDir, "daemon.pid"), + StopFlag: filepath.Join(pidDir, "stop.flag"), + PauseFlag: filepath.Join(pidDir, "daemon.pause"), + Oplock: filepath.Join(pidDir, "oplock"), + BoostFlag: filepath.Join(pidDir, "boost.flag"), + StateFile: filepath.Join(pidDir, "state.json"), + } +} + +// FileExists 判断普通文件是否存在。 +func FileExists(path string) bool { + info, err := os.Stat(path) + return err == nil && !info.IsDir() +} diff --git a/go/internal/api/state.go b/go/internal/api/state.go new file mode 100644 index 0000000..5d5f60d --- /dev/null +++ b/go/internal/api/state.go @@ -0,0 +1,85 @@ +package api + +import ( + "encoding/json" + "os" +) + +// daemon 运行状态文件的 DTO。daemon 每次判定后刷新,status 直接读取, +// 避免前端高频刷新时反复调用 dumpsys。 + +// EventInfo 最近一次监听到的事件。 +type EventInfo struct { + Letters string `json:"letters"` + At int64 `json:"at"` +} + +// ActionInfo 最近一次亮度操作。 +type ActionInfo struct { + Kind string `json:"kind"` + From int `json:"from"` + To int `json:"to"` + At int64 `json:"at"` +} + +// RatioInfo 最近一次读到的 HDR/SDR 比率。 +type RatioInfo struct { + Value float64 `json:"value"` + At int64 `json:"at"` +} + +// BoolInfo 带时间戳的布尔值。 +type BoolInfo struct { + Value bool `json:"value"` + At int64 `json:"at"` +} + +// IntInfo 带时间戳的整数。 +type IntInfo struct { + Value int `json:"value"` + At int64 `json:"at"` +} + +// DaemonState 是 pid/state.json 的内容。 +type DaemonState struct { + PID int `json:"pid"` + StartedAt int64 `json:"startedAt"` + Mode string `json:"mode"` // event | polling + Node string `json:"node"` + Paused bool `json:"paused"` + HdrSleep bool `json:"hdrSleep"` + LastEvent *EventInfo `json:"lastEvent,omitempty"` + LastAction *ActionInfo `json:"lastAction,omitempty"` + Ratio *RatioInfo `json:"ratio,omitempty"` + AutoBrightness *BoolInfo `json:"autoBrightness,omitempty"` + Brightness *IntInfo `json:"brightness,omitempty"` +} + +// WriteState 原子写入运行状态。 +func WriteState(path string, s DaemonState) error { + data, err := json.Marshal(s) + if err != nil { + return err + } + tmp := path + ".tmp" + if err := os.WriteFile(tmp, data, 0o644); err != nil { + return err + } + return os.Rename(tmp, path) +} + +// ReadState 读取运行状态;文件缺失或损坏时返回 false。 +func ReadState(path string) (DaemonState, bool) { + var s DaemonState + data, err := os.ReadFile(path) + if err != nil { + return s, false + } + if err := json.Unmarshal(data, &s); err != nil { + return s, false + } + if s.PID <= 0 || !ProcessAlive(s.PID) { + return s, false + } + return s, true +} diff --git a/go/internal/api/status.go b/go/internal/api/status.go new file mode 100644 index 0000000..169f4ef --- /dev/null +++ b/go/internal/api/status.go @@ -0,0 +1,271 @@ +package api + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" + "time" + + "github.com/YuleBest/LuminPro/go/internal/config" + "github.com/YuleBest/LuminPro/go/internal/policy" + "github.com/YuleBest/LuminPro/go/internal/system" +) + +// ModuleInfo 来自 module.prop。 +type ModuleInfo struct { + ID string `json:"id"` + Name string `json:"name"` + Version string `json:"version"` + VersionCode int `json:"versionCode"` + Channel string `json:"channel"` +} + +// ReadModuleInfo 解析模块根目录下的 module.prop,并从版本号推导发布通道。 +func ReadModuleInfo(moduleDir string) ModuleInfo { + info := ModuleInfo{ID: "LuminPro", Channel: "stable"} + f, err := os.Open(moduleDir + "/module.prop") + if err != nil { + return info + } + defer f.Close() + + scanner := bufio.NewScanner(f) + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + key, value, ok := strings.Cut(line, "=") + if !ok { + continue + } + value = strings.TrimSpace(value) + switch strings.TrimSpace(key) { + case "id": + info.ID = value + case "name": + info.Name = value + case "version": + info.Version = value + case "versionCode": + if n, err := strconv.Atoi(value); err == nil { + info.VersionCode = n + } + } + } + info.Channel = ChannelOf(info.Version) + return info +} + +// ChannelOf 依据版本号判断发布通道。 +func ChannelOf(version string) string { + v := strings.ToLower(version) + switch { + case strings.Contains(v, "-beta"): + return "beta" + case strings.Contains(v, "-dev"): + return "dev" + default: + return "stable" + } +} + +// DaemonPart 是守护进程状态。 +type DaemonPart struct { + PID int `json:"pid"` + Running bool `json:"running"` + State string `json:"state"` + Mode string `json:"mode"` + Paused bool `json:"paused"` + UptimeSec int `json:"uptimeSec"` +} + +// BrightnessPart 是亮度信息。 +type BrightnessPart struct { + Current int `json:"current"` + Max int `json:"max"` + Percent int `json:"percent"` + Node string `json:"node"` + MaxNode string `json:"maxNode"` + Error string `json:"error,omitempty"` +} + +// DisplayPart 是屏幕相关状态(需要 dumpsys / settings)。 +type DisplayPart struct { + HdrRatio float64 `json:"hdrRatio"` + HdrKnown bool `json:"hdrKnown"` + HdrStale bool `json:"hdrStale"` + HdrSleep bool `json:"hdrSleep"` + AutoBrightness bool `json:"autoBrightness"` +} + +// SleepPart 是休眠时段状态。 +type SleepPart struct { + Window string `json:"window"` + Active bool `json:"active"` +} + +// ConfigPart 是前端展示需要的配置子集。 +type ConfigPart struct { + UIMaxBri int `json:"uiMaxBri"` + MaxBri int `json:"maxBri"` + StepsNum int `json:"stepsNum"` + SleepTime string `json:"sleepTime"` + AutoBriSleep int `json:"autoBriSleep"` + DisplayHdrSleep int `json:"displayHdrSleep"` + HdrEnterRatio float64 `json:"hdrEnterRatio"` + HdrExitRatio float64 `json:"hdrExitRatio"` + CompatibilityMode int `json:"compatibilityMode"` + LogLevel string `json:"logLevel"` + LogMaxSize int `json:"logMaxSize"` + DebugMode int `json:"debugMode"` + NowBriFile string `json:"nowBriFile"` + MaxBriFile string `json:"maxBriFile"` + BlacklistCount int `json:"blacklistCount"` +} + +// LogPart 是日志文件信息。 +type LogPart struct { + Path string `json:"path"` + SizeKB int `json:"sizeKB"` +} + +// Status 是 status 子命令的输出。 +type Status struct { + Module ModuleInfo `json:"module"` + Daemon DaemonPart `json:"daemon"` + Brightness BrightnessPart `json:"brightness"` + Display *DisplayPart `json:"display,omitempty"` + Sleep SleepPart `json:"sleep"` + Oplock OplockStatus `json:"oplock"` + Config ConfigPart `json:"config"` + Log LogPart `json:"log"` +} + +// StatusDeps 是状态聚合用到的系统调用(测试可注入)。 +type StatusDeps struct { + AutoBrightness system.AutoBrightness + HDR system.HdrRatio + Now func() time.Time +} + +// StatusOptions 控制是否读取需要系统调用的字段。 +type StatusOptions struct { + // IncludeDisplay=false 时跳过 dumpsys/settings,仅用 daemon 缓存的数值, + // 供前端高频刷新(例如操作锁轮询)使用。 + IncludeDisplay bool +} + +// BuildStatus 聚合一次完整状态。 +func BuildStatus(p Paths, cfg config.Config, deps StatusDeps, opts StatusOptions) Status { + now := deps.Now + if now == nil { + now = time.Now + } + + st := Status{ + Module: ReadModuleInfo(p.ModuleDir), + Oplock: ReadOplock(p.Oplock), + Sleep: SleepPart{ + Window: cfg.SleepTime, + Active: policy.InSleepWindow(cfg.SleepTime, now()), + }, + Config: ConfigPart{ + UIMaxBri: cfg.UIMaxBri, + MaxBri: cfg.MaxBri, + StepsNum: cfg.StepsNum, + SleepTime: cfg.SleepTime, + AutoBriSleep: cfg.AutoBriSleep, + DisplayHdrSleep: cfg.DisplayHdrSleep, + HdrEnterRatio: cfg.HdrEnterRatio, + HdrExitRatio: cfg.HdrExitRatio, + CompatibilityMode: cfg.CompatibilityMode, + LogLevel: cfg.LogLevel, + LogMaxSize: cfg.LogMaxSize, + DebugMode: cfg.DebugMode, + NowBriFile: cfg.NowBriFile, + MaxBriFile: cfg.MaxBriFile, + BlacklistCount: len(cfg.BlacklistApps), + }, + } + + // 守护进程 + daemonState, hasState := ReadState(p.StateFile) + if pid, alive := DaemonPID(p.PIDFile); alive { + st.Daemon = DaemonPart{ + PID: pid, + Running: true, + State: ProcessState(pid), + } + if hasState { + st.Daemon.Mode = daemonState.Mode + if daemonState.StartedAt > 0 { + if d := now().Unix() - daemonState.StartedAt; d > 0 { + st.Daemon.UptimeSec = int(d) + } + } + } + } + st.Daemon.Paused = FileExists(p.StopFlag) + + // 亮度节点 + st.Brightness = BrightnessPart{Node: cfg.NowBriFile, MaxNode: cfg.MaxBriFile} + current, err := readIntFile(cfg.NowBriFile) + if err != nil { + st.Brightness.Error = err.Error() + } + maxBri, err := readIntFile(cfg.MaxBriFile) + if err != nil && st.Brightness.Error == "" { + st.Brightness.Error = err.Error() + } + st.Brightness.Current = current + st.Brightness.Max = maxBri + if maxBri > 0 { + st.Brightness.Percent = current * 100 / maxBri + } + + // 日志 + st.Log = LogPart{Path: p.LogFile} + if fi, err := os.Stat(p.LogFile); err == nil { + st.Log.SizeKB = int(fi.Size() / 1024) + } + + if !opts.IncludeDisplay { + return st + } + + display := &DisplayPart{} + if deps.HDR.Runner != nil { + if ratio, ok := deps.HDR.Ratio(); ok { + display.HdrRatio = ratio + display.HdrKnown = true + } else if hasState && daemonState.Ratio != nil { + display.HdrRatio = daemonState.Ratio.Value + display.HdrKnown = true + display.HdrStale = true + } + } + if deps.AutoBrightness.Runner != nil { + display.AutoBrightness = deps.AutoBrightness.Enabled() + } else if hasState && daemonState.AutoBrightness != nil { + display.AutoBrightness = daemonState.AutoBrightness.Value + } + display.HdrSleep = hasState && daemonState.HdrSleep + st.Display = display + return st +} + +func readIntFile(path string) (int, error) { + data, err := os.ReadFile(path) + if err != nil { + return 0, err + } + text := strings.TrimSpace(string(data)) + v, err := strconv.Atoi(text) + if err != nil { + return 0, fmt.Errorf("节点内容不是整数: %q", text) + } + return v, nil +} diff --git a/go/internal/config/config.go b/go/internal/config/config.go index 7c75005..98ed851 100644 --- a/go/internal/config/config.go +++ b/go/internal/config/config.go @@ -227,8 +227,38 @@ func parseValue(s string) any { } // applyRaw 用原始键值填充强类型字段,未识别的键留在 extra。 +// 单个字段损坏时保留默认值,不阻断整体加载(与旧 get_cfg 的降级一致)。 func (c *Config) applyRaw(raw map[string]json.RawMessage) { - known := map[string]any{ + _ = c.apply(raw, false) +} + +// apply 填充字段;strict=true 时字段类型不匹配直接报错(用于写路径)。 +func (c *Config) apply(raw map[string]json.RawMessage, strict bool) error { + known := fieldTargets(c) + + c.extra = nil + for key, value := range raw { + dst, ok := known[key] + if !ok { + if c.extra == nil { + c.extra = map[string]json.RawMessage{} + } + c.extra[key] = value + continue + } + if err := json.Unmarshal(value, dst); err != nil && strict { + return fmt.Errorf("字段 %s 的值类型不正确: %w", key, err) + } + } + if c.BlacklistApps == nil { + c.BlacklistApps = []string{} + } + return nil +} + +// fieldTargets 返回已知字段名到目标字段指针的映射。 +func fieldTargets(c *Config) map[string]any { + return map[string]any{ "ui_max_bri": &c.UIMaxBri, "max_bri": &c.MaxBri, "steps_num": &c.StepsNum, @@ -246,22 +276,30 @@ func (c *Config) applyRaw(raw map[string]json.RawMessage) { "debug_mode": &c.DebugMode, "blacklist_apps": &c.BlacklistApps, } +} - c.extra = nil - for key, value := range raw { - if dst, ok := known[key]; ok { - // 单个字段损坏时保留默认值,不阻断整体加载。 - _ = json.Unmarshal(value, dst) - continue - } - if c.extra == nil { - c.extra = map[string]json.RawMessage{} - } - c.extra[key] = value +// JSON 返回完整配置(含全部已知字段,缺失项已补默认值)。 +func (c Config) JSON() ([]byte, error) { + return json.Marshal(c.toRawMap()) +} + +// Patch 用一份 JSON 对象浅合并配置并原子保存。 +// 与 Load 不同,这里对已知字段做严格类型校验,避免写坏配置。 +func Patch(path string, patch map[string]json.RawMessage) error { + c, err := Load(path) + if err != nil { + return err } - if c.BlacklistApps == nil { - c.BlacklistApps = []string{} + raw := c.toRawMap() + for key, value := range patch { + raw[key] = value } + + probe := Default() + if err := probe.apply(raw, true); err != nil { + return err + } + return probe.Save(path) } // toRawMap 导出为原始键值表(含未知键)。 diff --git a/go/internal/config/config_test.go b/go/internal/config/config_test.go index db53128..21a1380 100644 --- a/go/internal/config/config_test.go +++ b/go/internal/config/config_test.go @@ -166,6 +166,111 @@ func TestInitCreatesAndEnsureFills(t *testing.T) { } } +func TestPatchMergesShallowly(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + if err := Set(path, []string{"ui_max_bri=1000", "max_bri=3000", "sleep_time=2200-0700"}); err != nil { + t.Fatal(err) + } + // 注入一个未知字段,验证 patch 后仍保留 + raw, _ := os.ReadFile(path) + var withUnknown map[string]json.RawMessage + _ = json.Unmarshal(raw, &withUnknown) + withUnknown["future_field"] = json.RawMessage(`"keep-me"`) + merged, _ := json.Marshal(withUnknown) + if err := os.WriteFile(path, merged, 0o644); err != nil { + t.Fatal(err) + } + + patch := map[string]json.RawMessage{ + "ui_max_bri": json.RawMessage(`1500`), + "blacklist_apps": json.RawMessage(`["com.a","com.b"]`), + } + if err := Patch(path, patch); err != nil { + t.Fatal(err) + } + + c, err := Load(path) + if err != nil { + t.Fatal(err) + } + if c.UIMaxBri != 1500 { + t.Fatalf("patch 未生效: %d", c.UIMaxBri) + } + if c.MaxBri != 3000 || c.SleepTime != "2200-0700" { + t.Fatalf("未 patch 的字段被改动: %+v", c) + } + if len(c.BlacklistApps) != 2 { + t.Fatalf("数组字段未写入: %v", c.BlacklistApps) + } + + // 未知字段保留 + data, _ := os.ReadFile(path) + var check map[string]json.RawMessage + _ = json.Unmarshal(data, &check) + if _, ok := check["future_field"]; !ok { + t.Fatal("patch 后未知字段丢失") + } +} + +func TestPatchRejectsWrongTypeAndKeepsFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + if err := Set(path, []string{"ui_max_bri=1000"}); err != nil { + t.Fatal(err) + } + before, _ := os.ReadFile(path) + + err := Patch(path, map[string]json.RawMessage{ + "ui_max_bri": json.RawMessage(`"不是数字"`), + }) + if err == nil { + t.Fatal("类型错误应被拒绝") + } + after, _ := os.ReadFile(path) + if string(before) != string(after) { + t.Fatal("校验失败时不应改动配置文件") + } + + if err := Patch(path, map[string]json.RawMessage{ + "blacklist_apps": json.RawMessage(`{"not":"an array"}`), + }); err == nil { + t.Fatal("数组字段类型错误应被拒绝") + } +} + +func TestConfigJSONIsComplete(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + if err := os.WriteFile(path, []byte(`{"ui_max_bri":800}`), 0o644); err != nil { + t.Fatal(err) + } + c, err := Load(path) + if err != nil { + t.Fatal(err) + } + data, err := c.JSON() + if err != nil { + t.Fatal(err) + } + var raw map[string]json.RawMessage + if err := json.Unmarshal(data, &raw); err != nil { + t.Fatal(err) + } + for _, key := range []string{ + "ui_max_bri", "max_bri", "steps_num", "log_max_size", "auto_bri_sleep", + "display_hdr_sleep", "hdr_enter_ratio", "hdr_exit_ratio", "compatibility_mode", + "sleep_time", "inotify_events", "now_bri_file", "max_bri_file", "log_level", + "debug_mode", "blacklist_apps", + } { + if _, ok := raw[key]; !ok { + t.Errorf("JSON 缺少字段 %s", key) + } + } + var ui int + _ = json.Unmarshal(raw["ui_max_bri"], &ui) + if ui != 800 { + t.Fatalf("已有值未保留: %d", ui) + } +} + func TestInspectAndMigrateOldTxt(t *testing.T) { oldDir := t.TempDir() write := func(name, content string) { diff --git a/go/internal/daemon/daemon.go b/go/internal/daemon/daemon.go index 9f3c85c..2510b6d 100644 --- a/go/internal/daemon/daemon.go +++ b/go/internal/daemon/daemon.go @@ -8,13 +8,13 @@ import ( "fmt" "os" "os/signal" - "path/filepath" "strconv" "strings" "sync" "syscall" "time" + "github.com/YuleBest/LuminPro/go/internal/api" "github.com/YuleBest/LuminPro/go/internal/brightness" "github.com/YuleBest/LuminPro/go/internal/config" "github.com/YuleBest/LuminPro/go/internal/inotify" @@ -24,33 +24,10 @@ import ( ) // Paths 是模块内的文件布局(与 WebUI 的契约,不可随意改名)。 -type Paths struct { - ModuleDir string - PIDDir string - ConfigFile string - LogFile string - PIDFile string - StopFlag string - PauseFlag string - Oplock string - BoostFlag string -} +type Paths = api.Paths // DefaultPaths 按模块目录推导全部路径。 -func DefaultPaths(moduleDir string) Paths { - pidDir := filepath.Join(moduleDir, "pid") - return Paths{ - ModuleDir: moduleDir, - PIDDir: pidDir, - ConfigFile: filepath.Join(moduleDir, "config", "config.json"), - LogFile: filepath.Join(moduleDir, "service.log"), - PIDFile: filepath.Join(pidDir, "inotifyd.pid"), - StopFlag: filepath.Join(pidDir, "stop.flag"), - PauseFlag: filepath.Join(pidDir, "daemon.pause"), - Oplock: filepath.Join(pidDir, "oplock"), - BoostFlag: filepath.Join(pidDir, "boost.flag"), - } -} +func DefaultPaths(moduleDir string) Paths { return api.DefaultPaths(moduleDir) } // Deps 是守护进程的外部依赖,测试时可注入假实现。 type Deps struct { @@ -99,17 +76,30 @@ type Daemon struct { ratioCache float64 haveRatioCache bool nodeMissingLogged bool + + // 运行状态(供 WebUI 的 status 读取,避免前端反复调用 dumpsys) + stateMu sync.Mutex + state api.DaemonState } // New 创建守护进程并加载初始配置。 func New(paths Paths, deps Deps) (*Daemon, error) { deps.withDefaults() - d := &Daemon{paths: paths, deps: deps} + d := &Daemon{ + paths: paths, + deps: deps, + state: api.DaemonState{ + PID: os.Getpid(), + StartedAt: time.Now().Unix(), + Mode: "event", + }, + } cfg, err := config.Load(paths.ConfigFile) if err != nil { return nil, err } d.setConfig(cfg) + d.state.Node = cfg.NowBriFile return d, nil } @@ -132,6 +122,7 @@ func (d *Daemon) Run() error { defer d.cleanup() d.log().Info("守护进程已启动") + d.flushState() sigCh := make(chan os.Signal, 4) signal.Notify(sigCh, syscall.SIGHUP, syscall.SIGTERM, syscall.SIGINT) @@ -197,8 +188,10 @@ func (d *Daemon) serve(sigCh chan os.Signal, cfgCh chan struct{}) exitReason { if cfg.CompatibilityMode == 1 { d.log().Warn("兼容模式已开启 (轮询驱动)") + d.setStateMode("polling") go d.compatLoop(stop) } else { + d.setStateMode("event") w, err := inotify.New() if err != nil { d.log().Error("初始化 inotify 失败: " + err.Error()) @@ -223,6 +216,7 @@ func (d *Daemon) serve(sigCh chan os.Signal, cfgCh chan struct{}) exitReason { } return } + d.recordEvent(ev.Letters) d.evaluate() }, runStop) }() @@ -267,16 +261,20 @@ func (d *Daemon) compatLoop(stop <-chan struct{}) { // evaluate 执行一次完整判定;满足条件时执行亮度提升。 func (d *Daemon) evaluate() { + defer d.flushState() + // 服务暂停 / 守护进程挂起:静默跳过(与旧脚本一致) - if fileExists(d.paths.StopFlag) || fileExists(d.paths.PauseFlag) { + if api.FileExists(d.paths.StopFlag) || api.FileExists(d.paths.PauseFlag) { + d.setStatePaused(api.FileExists(d.paths.StopFlag)) return } + d.setStatePaused(false) cfg := d.currentConfig() if cfg.UIMaxBri <= 0 || cfg.MaxBri <= 0 { return // 未校准,等价于旧脚本的 `now >= 0 && now < 0` } - if !fileExists(cfg.NowBriFile) { + if !api.FileExists(cfg.NowBriFile) { return // 节点缺失由外层循环负责记录与重试,这里静默 } @@ -284,9 +282,13 @@ func (d *Daemon) evaluate() { d.log().Info(fmt.Sprintf("处于休眠时段 (%s),跳过提升", cfg.SleepTime)) return } - if cfg.AutoBriSleep == 1 && d.deps.AutoBrightness.Enabled() { - d.log().Info("自动亮度已启用,跳过提升") - return + if cfg.AutoBriSleep == 1 { + autoBri := d.deps.AutoBrightness.Enabled() + d.setStateAutoBrightness(autoBri) + if autoBri { + d.log().Info("自动亮度已启用,跳过提升") + return + } } if len(cfg.BlacklistApps) > 0 { focus := d.deps.Focus.CurrentFocus() @@ -311,6 +313,7 @@ func (d *Daemon) evaluateHdr(cfg config.Config) bool { } if ok { d.ratioCache, d.haveRatioCache = ratio, true + d.setStateRatio(ratio) } decision := d.hdr.Evaluate(ratio, ok, cfg.HdrEnterRatio, cfg.HdrExitRatio) @@ -322,6 +325,7 @@ func (d *Daemon) evaluateHdr(cfg config.Config) bool { case decision.Skip: d.log().Info("HDR 休眠中,跳过提升") } + d.setStateHdrSleep(d.hdr.InSleep()) return !decision.Skip } @@ -337,6 +341,7 @@ func (d *Daemon) boost(cfg config.Config) { d.log().Error("读取亮度节点失败: " + err.Error()) return } + d.setStateBrightness(now) if policy.ShouldBoost(now, cfg.UIMaxBri, cfg.MaxBri) { d.log().Info(fmt.Sprintf("触发提升: 当前亮度 %d ≥ 阈值 %d,目标 %d", now, cfg.UIMaxBri, cfg.MaxBri)) if err := d.ramp(cfg, now); err != nil { @@ -357,11 +362,15 @@ func (d *Daemon) boost(cfg config.Config) { // ramp 执行渐变写入,期间持操作锁。 func (d *Daemon) ramp(cfg config.Config, start int) error { d.log().Info(fmt.Sprintf("开始渐变调整: %d → %d (%d 步)", start, cfg.MaxBri, cfg.StepsNum)) - if err := d.writeOplock(); err != nil { + if err := api.WriteOplock(d.paths.Oplock, api.KindRamp); err != nil { d.log().Warn("写入操作锁失败: " + err.Error()) } - defer d.removeOplock() - return brightness.Ramp(cfg.NowBriFile, start, cfg.MaxBri, cfg.StepsNum, d.deps.StepDelay, nil) + defer api.RemoveOplock(d.paths.Oplock) + + err := brightness.Ramp(cfg.NowBriFile, start, cfg.MaxBri, cfg.StepsNum, d.deps.StepDelay, nil) + d.setStateAction(api.KindRamp, start, cfg.MaxBri) + d.setStateBrightness(cfg.MaxBri) + return err } // pollConfig 定期比对 config.json 的 mtime/大小,变更时通知主循环。 @@ -459,23 +468,73 @@ func (d *Daemon) writePID() error { return os.WriteFile(d.paths.PIDFile, []byte(strconv.Itoa(os.Getpid())), 0o644) } -func (d *Daemon) writeOplock() error { - if err := os.MkdirAll(d.paths.PIDDir, 0o755); err != nil { - return err - } - return os.WriteFile(d.paths.Oplock, []byte(strconv.Itoa(os.Getpid())), 0o644) -} - -func (d *Daemon) removeOplock() { - _ = os.Remove(d.paths.Oplock) -} - func (d *Daemon) cleanup() { _ = os.Remove(d.paths.PIDFile) _ = os.Remove(d.paths.Oplock) + _ = os.Remove(d.paths.StateFile) } -func fileExists(path string) bool { - info, err := os.Stat(path) - return err == nil && !info.IsDir() +// ── 运行状态维护(供 WebUI 的 status 子命令读取)──────────────────────────── + +func (d *Daemon) updateState(fn func(s *api.DaemonState)) { + d.stateMu.Lock() + defer d.stateMu.Unlock() + fn(&d.state) +} + +func (d *Daemon) flushState() { + d.stateMu.Lock() + snapshot := d.state + d.stateMu.Unlock() + if err := api.WriteState(d.paths.StateFile, snapshot); err != nil { + d.log().Warn("写入运行状态失败: " + err.Error()) + } +} + +func (d *Daemon) recordEvent(letters string) { + now := time.Now().Unix() + d.updateState(func(s *api.DaemonState) { + s.LastEvent = &api.EventInfo{Letters: letters, At: now} + }) +} + +func (d *Daemon) setStateMode(mode string) { + d.updateState(func(s *api.DaemonState) { s.Mode = mode }) + d.flushState() +} + +func (d *Daemon) setStatePaused(paused bool) { + d.updateState(func(s *api.DaemonState) { s.Paused = paused }) +} + +func (d *Daemon) setStateRatio(ratio float64) { + now := time.Now().Unix() + d.updateState(func(s *api.DaemonState) { + s.Ratio = &api.RatioInfo{Value: ratio, At: now} + }) +} + +func (d *Daemon) setStateAutoBrightness(on bool) { + now := time.Now().Unix() + d.updateState(func(s *api.DaemonState) { + s.AutoBrightness = &api.BoolInfo{Value: on, At: now} + }) +} + +func (d *Daemon) setStateHdrSleep(asleep bool) { + d.updateState(func(s *api.DaemonState) { s.HdrSleep = asleep }) +} + +func (d *Daemon) setStateBrightness(value int) { + now := time.Now().Unix() + d.updateState(func(s *api.DaemonState) { + s.Brightness = &api.IntInfo{Value: value, At: now} + }) +} + +func (d *Daemon) setStateAction(kind string, from, to int) { + now := time.Now().Unix() + d.updateState(func(s *api.DaemonState) { + s.LastAction = &api.ActionInfo{Kind: kind, From: from, To: to, At: now} + }) } diff --git a/go/internal/daemon/daemon_test.go b/go/internal/daemon/daemon_test.go index 987768e..296de24 100644 --- a/go/internal/daemon/daemon_test.go +++ b/go/internal/daemon/daemon_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "github.com/YuleBest/LuminPro/go/internal/api" "github.com/YuleBest/LuminPro/go/internal/config" "github.com/YuleBest/LuminPro/go/internal/logging" "github.com/YuleBest/LuminPro/go/internal/system" @@ -298,21 +299,21 @@ func TestBoostRejectsMissingNode(t *testing.T) { func TestReadDaemonPID(t *testing.T) { dir := t.TempDir() - pidFile := filepath.Join(dir, "inotifyd.pid") + pidFile := filepath.Join(dir, "daemon.pid") - if _, alive := readDaemonPID(pidFile); alive { + if _, alive := api.DaemonPID(pidFile); alive { t.Fatal("文件不存在应视为未运行") } _ = os.WriteFile(pidFile, []byte("notanumber"), 0o644) - if _, alive := readDaemonPID(pidFile); alive { + if _, alive := api.DaemonPID(pidFile); alive { t.Fatal("非法内容应视为未运行") } _ = os.WriteFile(pidFile, []byte("999999"), 0o644) - if _, alive := readDaemonPID(pidFile); alive { + if _, alive := api.DaemonPID(pidFile); alive { t.Fatal("不存在的 PID 应视为未运行") } _ = os.WriteFile(pidFile, []byte(strconv.Itoa(os.Getpid())), 0o644) - if pid, alive := readDaemonPID(pidFile); !alive || pid != os.Getpid() { + if pid, alive := api.DaemonPID(pidFile); !alive || pid != os.Getpid() { t.Fatal("当前进程 PID 应视为存活") } } diff --git a/go/internal/daemon/ops.go b/go/internal/daemon/ops.go index 98a47e7..fde3b74 100644 --- a/go/internal/daemon/ops.go +++ b/go/internal/daemon/ops.go @@ -10,6 +10,7 @@ import ( "syscall" "time" + "github.com/YuleBest/LuminPro/go/internal/api" "github.com/YuleBest/LuminPro/go/internal/brightness" "github.com/YuleBest/LuminPro/go/internal/config" "github.com/YuleBest/LuminPro/go/internal/logging" @@ -21,7 +22,7 @@ func Boost(paths Paths, log *logging.Logger) error { if err != nil { return err } - if !fileExists(cfg.NowBriFile) { + if !api.FileExists(cfg.NowBriFile) { return fmt.Errorf("亮度节点不存在: %s", cfg.NowBriFile) } @@ -57,10 +58,10 @@ func Boost(paths Paths, log *logging.Logger) error { // writeWithOplock 在持操作锁的前提下写一次亮度节点。 func writeWithOplock(paths Paths, log *logging.Logger, node string, value int) { _ = os.MkdirAll(paths.PIDDir, 0o755) - if err := os.WriteFile(paths.Oplock, []byte(strconv.Itoa(os.Getpid())), 0o644); err != nil && log != nil { + if err := api.WriteOplock(paths.Oplock, api.KindBoost); err != nil && log != nil { log.Warn("写入操作锁失败: " + err.Error()) } - defer func() { _ = os.Remove(paths.Oplock) }() + defer api.RemoveOplock(paths.Oplock) if err := brightness.WriteInt(node, value); err != nil && log != nil { log.Error("写入亮度节点失败: " + err.Error()) } @@ -73,12 +74,12 @@ func Restart(paths Paths, selfPath string, log *logging.Logger) error { return err } // 整个重启窗口持操作锁,WebUI 会据此暂停刷新 - if err := os.WriteFile(paths.Oplock, []byte(strconv.Itoa(os.Getpid())), 0o644); err != nil { + if err := api.WriteOplock(paths.Oplock, api.KindRestart); err != nil { return err } - defer func() { _ = os.Remove(paths.Oplock) }() + defer api.RemoveOplock(paths.Oplock) - if pid, alive := readDaemonPID(paths.PIDFile); alive { + if pid, alive := api.DaemonPID(paths.PIDFile); alive { start := time.Now() if err := syscall.Kill(pid, syscall.SIGHUP); err != nil { return fmt.Errorf("通知守护进程失败: %w", err) @@ -92,7 +93,7 @@ func Restart(paths Paths, selfPath string, log *logging.Logger) error { if err != nil { return err } - if !fileExists(cfg.NowBriFile) { + if !api.FileExists(cfg.NowBriFile) { return fmt.Errorf("亮度节点不存在: %s,无法启动服务,请先在配置页填写正确路径", cfg.NowBriFile) } @@ -105,22 +106,6 @@ func Restart(paths Paths, selfPath string, log *logging.Logger) error { return cmd.Process.Release() } -// readDaemonPID 读取 PID 文件并确认进程存活(/proc 检测,等价于旧脚本的 [ -d /proc/$pid ])。 -func readDaemonPID(pidFile string) (int, bool) { - data, err := os.ReadFile(pidFile) - if err != nil { - return 0, false - } - pid, err := strconv.Atoi(strings.TrimSpace(string(data))) - if err != nil || pid <= 0 { - return 0, false - } - if _, err := os.Stat(fmt.Sprintf("/proc/%d", pid)); err != nil { - return 0, false - } - return pid, true -} - // waitForPIDRewrite 等待 PID 文件在 start 之后被重写。 func waitForPIDRewrite(pidFile string, start time.Time, timeout time.Duration) bool { deadline := time.Now().Add(timeout) diff --git a/service.sh b/service.sh index 85c0930..2eb5672 100755 --- a/service.sh +++ b/service.sh @@ -26,7 +26,7 @@ _log() { sleep 30 # 清理上次遗留的标记文件 -rm -f "$MODDIR/pid/"*.flag "$MODDIR/pid/"*.pause "$MODDIR/pid/"*.lock "$MODDIR/pid/oplock" "$MODDIR/pid/.hdr_ratio_cache" +rm -f "$MODDIR/pid/"*.flag "$MODDIR/pid/"*.pause "$MODDIR/pid/"*.lock "$MODDIR/pid/oplock" "$MODDIR/pid/state.json" "$MODDIR/pid/.hdr_ratio_cache" _log "LuminPro 服务启动" "INFO"